@asaidimu/anansi 3.0.0 → 4.0.1

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.cjs CHANGED
@@ -1,45 +1,45 @@
1
- "use strict";var Qe=Object.create;var Z=Object.defineProperty;var Ze=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var et=Object.getPrototypeOf,tt=Object.prototype.hasOwnProperty;var nt=(t,e)=>{for(var n in e)Z(t,n,{get:e[n],enumerable:!0})},De=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Xe(e))!tt.call(t,r)&&r!==n&&Z(t,r,{get:()=>e[r],enumerable:!(i=Ze(e,r))||i.enumerable});return t};var B=(t,e,n)=>(n=t!=null?Qe(et(t)):{},De(e||!t||!t.__esModule?Z(n,"default",{value:t,enumerable:!0}):n,t)),it=t=>De(Z({},"__esModule",{value:!0}),t);var Ot={};nt(Ot,{JsonPatchError:()=>P,MigrationEngine:()=>Ee,MigrationError:()=>k,MigrationErrorCode:()=>Ge,SchemaRegistry:()=>Y,applyPatch:()=>ie,calculateNextVersion:()=>ve,compareSemanticVersions:()=>O,createGitSchemaRegistry:()=>Ft,createPatch:()=>at,createSchemaMigrationHelper:()=>Je,createStandardSchemaValidator:()=>Pe,deepMerge:()=>pe,docgen:()=>Mt,extractInputFieldGroups:()=>Dt,formResolver:()=>ut,generateSHA256Hash:()=>U,normalizePath:()=>Ae,schemaChangeToPatch:()=>me,schemaDefaults:()=>At,schemaToTypes:()=>Pt,serializeParams:()=>K,sortSemanticVars:()=>Ct,validate:()=>yt,validateMigration:()=>Se,validateSchemaChange:()=>be,validateSchemaDefinition:()=>H});module.exports=it(Ot);var Rt=require("@asaidimu/events");var kt=require("@asaidimu/events"),re=require("@asaidimu/query");var P=class extends Error{constructor(n,i){super(n);this.operation=i;this.name="JsonPatchError"}};function te(t){let e=Ae(t);return e===""?[]:e.substring(1).split("/").map(st)}function Ae(t){return t===""||t==="/"?"":t.startsWith("/")?"/"+t.substring(1).split("/").map(ee).join("/"):"/"+t.split(".").map(ee).join("/")}function ee(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function st(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}var j=new Map;function ne(t,e){let n=t;for(let i of e){if(n===null||typeof n!="object")throw new P(`Invalid path - parent not found at ${i}`);if(Array.isArray(n)){let r=i==="-"?n.length:parseInt(i);if(isNaN(r)||r<0||r>n.length)throw new P(`Invalid array index: ${i}`);n=n[r]}else{if(!n.hasOwnProperty(i))throw new P(`Property ${i} not found`);n=n[i]}}return n}function ue(t,e){let n=j.get(e)||te(e);if(j.set(e,n),n.length===0)return t;let i=ne(t,n.slice(0,-1)),r=n[n.length-1];if(Array.isArray(i)){let a=parseInt(r);if(isNaN(a)||a<0||a>=i.length)throw new P(`Invalid array index: ${r}`);return i[a]}return i[r]}function rt(t,e,n){let i=j.get(e)||te(e);j.set(e,i);let r=ne(t,i.slice(0,-1)),a=i[i.length-1];return Array.isArray(r)?r.splice(0,r.length,...r.filter(s=>s!==n)):r[a]===n&&delete r[a],t}function X(t,e,n){let i=j.get(e)||te(e);if(j.set(e,i),i.length===0)return n;let r=i.slice(0,-1),a=i[i.length-1],s=ne(t,r);if(Array.isArray(s))if(a==="-")s.push(n);else{let o=parseInt(a);if(o<0||o>s.length)throw new P(`Invalid array index: ${a}`);s.splice(o,0,n)}else s[a]=n;return t}function fe(t,e){let n=j.get(e)||te(e);if(j.set(e,n),n.length===0)return;let i=ne(t,n.slice(0,-1)),r=n[n.length-1];if(Array.isArray(i)){let a=parseInt(r);i.splice(a,1)}else delete i[r];return t}function ie(t,e){let n=JSON.parse(JSON.stringify(t));for(let i of e)try{switch(i.op){case"add":n=X(n,i.path,i.value);break;case"remove":n=fe(n,i.path);break;case"removeValue":n=rt(n,i.path,i.value);break;case"replace":n=X(fe(n,i.path),i.path,i.value);break;case"copy":{let r=ue(n,i.from);n=X(n,i.path,JSON.parse(JSON.stringify(r)));break}case"move":{let r=ue(n,i.from);n=X(n,i.path,r),n=fe(n,i.from);break}case"test":{let r=ue(n,i.path);if(JSON.stringify(r)!==JSON.stringify(i.value))throw new P("Test operation failed");break}default:throw new P(`Unsupported operation: ${i.op}`)}}catch(r){throw r instanceof P&&(r.operation=i),r}return n}function at(t,e){let n=[];return le(t,e,"",n),n}function le(t,e,n,i){if(t!==e){if(typeof t!=typeof e||Array.isArray(t)!==Array.isArray(e)){i.push({op:"replace",path:n,value:e});return}typeof t=="object"&&t!==null?Array.isArray(t)?ot(t,e,n,i):ct(t,e,n,i):t!==e&&i.push({op:"replace",path:n,value:e})}}function ot(t,e,n,i){let r=Math.max(t.length,e.length);for(let a=0;a<r;a++){let s=`${n}/${a}`;a>=t.length?i.push({op:"add",path:`${n}/-`,value:e[a]}):a>=e.length?i.push({op:"remove",path:s}):le(t[a],e[a],s,i)}}function ct(t,e,n,i){let r=new Set,a=Object.keys(t),s=Object.keys(e);for(let o of a){let c=ee(o),u=n?`${n}/${c}`:`/${c}`;e.hasOwnProperty(o)?(le(t[o],e[o],u,i),r.add(o)):i.push({op:"remove",path:u})}for(let o of s)if(!r.has(o)){let c=ee(o),u=n?`${n}/${c}`:`/${c}`;i.push({op:"add",path:u,value:e[o]})}}function me(t,e){let n=[];switch(t.type){case"addField":n.push({op:"add",path:`/fields/${t.id}`,value:t.definition});break;case"removeField":n.push({op:"remove",path:`/fields/${t.id}`});break;case"modifyField":{let i=`/fields/${t.id}`;Object.entries(t.changes).forEach(([r,a])=>{typeof a=="object"&&a!==null&&!Array.isArray(a)?n.push({op:"replace",path:`${i}/${r}`,value:a}):n.push({op:"replace",path:`${i}/${r}`,value:a})});break}case"deprecateField":n.push({op:"add",path:`/fields/${t.id}/deprecated`,value:!0});break;case"addIndex":e.indexes||n.push({op:"add",path:"/indexes",value:[]}),n.push({op:"add",path:"/indexes/-",value:t.definition});break;case"removeIndex":{let i=e.indexes?.findIndex(r=>r.name===t.name);i!==void 0&&i>=0&&n.push({op:"remove",path:`/indexes/${i}`});break}case"modifyIndex":{let i=e.indexes?.findIndex(r=>r.name===t.name);i!==void 0&&i>=0&&Object.entries(t.changes).forEach(([r,a])=>{n.push({op:"replace",path:`/indexes/${i}/${r}`,value:a})});break}case"addConstraint":e.constraints||n.push({op:"add",path:"/constraints",value:[]}),Array.isArray(t.constraint)?t.constraint.forEach(i=>{n.push({op:"add",path:"/constraints/-",value:i})}):n.push({op:"add",path:"/constraints/-",value:t.constraint});break;case"removeConstraint":{let i=e.constraints?.findIndex(r=>Array.isArray(r)?r.some(a=>a.name===t.name):r.name===t.name);i!==void 0&&i>=0&&n.push({op:"remove",path:`/constraints/${i}`});break}case"modifyConstraint":{let i=dt(e,t.name);i&&Object.entries(t.changes).forEach(([r,a])=>{n.push({op:"replace",path:`${i}/${r}`,value:a})});break}}return n}function dt(t,e){if(!t.constraints)return null;for(let n=0;n<t.constraints.length;n++){let i=t.constraints[n];if(i.name===e)return`/constraints/${n}`;if(Ie(i)){let r=Fe(i.rules,e);if(r)return`/constraints/${n}${r}`}}return null}function Ie(t){return t&&"operator"in t&&"rules"in t}function Fe(t,e){for(let n=0;n<t.length;n++){let i=t[n];if("name"in i&&i.name===e)return`/rules/${n}`;if(Ie(i)){let r=Fe(i.rules,e);if(r)return`/rules/${n}${r}`}}return null}function pe(t,e){let n={...t};return he(t)&&he(e)&&Object.keys(e).forEach(i=>{he(e[i])?i in t?n[i]=pe(t[i],e[i]):Object.assign(n,{[i]:e[i]}):Object.assign(n,{[i]:e[i]})}),n}function he(t){return t&&typeof t=="object"&&!Array.isArray(t)}function K(t){return t instanceof RegExp?t.toString().slice(1,-1):JSON.stringify(t)}function Pe(t,e){let n=o=>({value:o}),i=o=>({issues:o}),r=(o,c,u,f)=>{switch(c){case"string":return typeof o!="string"?[{message:`Expected string, got ${typeof o}`,path:u}]:[];case"number":return typeof o!="number"||isNaN(o)?[{message:`Expected number, got ${typeof o}`,path:u}]:[];case"boolean":return typeof o!="boolean"?[{message:`Expected boolean, got ${typeof o}`,path:u}]:[];case"array":return Array.isArray(o)?[]:[{message:`Expected array, got ${typeof o}`,path:u}];case"set":return!Array.isArray(o)||new Set(o).size!==o.length?[{message:`Expected unique array, got ${typeof o}`,path:u}]:[];case"enum":return f?.values?f.values.includes(o)?[]:[{message:`Expected one of ${JSON.stringify(f.values)}, got ${o}`,path:u}]:[{message:"Enum type requires 'values' definition",path:u}];case"object":return typeof o!="object"||o===null||Array.isArray(o)?[{message:`Expected object, got ${typeof o}`,path:u}]:[];case"record":return typeof o!="object"||o===null?[{message:`Expected record (object), got ${typeof o}`,path:u}]:[];case"union":return typeof o!="object"||o===null?[{message:`Expected union (object), got ${typeof o}`,path:u}]:[];case"dynamic":return[];default:return[{message:`Unknown type '${c}'`,path:u}]}};function a(o,c,u,f,b){let p=[],E=o.rules.map((m,y)=>{let S=[...f,`rules[${y}]`];if("rules"in m){if(b.has(m.name))return!0;b.add(m.name);let g=a(m,c,u,S,b);return p.push(...g),g.length===0}else{let g=u[m.predicate];if(!g)return p.push({message:`Predicate '${m.predicate}' not found`,path:S}),!1;let $=g({data:c,field:m.field,arguments:m.parameters});if(!$){let h=m.field?` for field '${m.field}'`:"";p.push({message:m.errorMessage||`Constraint '${m.name}' failed${h} with params ${K(m.parameters)}`,path:S})}return $}});return(()=>{switch(o.operator){case"and":return E.every(m=>m);case"or":return E.some(m=>m);case"not":return!E.every(m=>m);case"nor":return!E.some(m=>m);case"xor":return E.filter(m=>m).length===1}})()||p.push({message:`Constraint group '${o.name}' failed`,path:f}),p}function s(o,c,u,f,b,p=new Set){let E=[],T={};if("concrete"in c)if(c.concrete===!0||!Array.isArray(c.fields))T=c.fields;else{let y=c.fields,S=y.find($=>!$.when);S&&Object.assign(T,S.fields);let g=y.find($=>$.when&&o[$.when.field]!==void 0&&o[$.when.field]===$.when.value);if(g)Object.assign(T,g.fields);else if(!S)return E.push({message:"No matching field set found for discriminated schema",path:f}),E}else T=c.fields;let m=new Set(Object.values(T).map(y=>y.name));Object.entries(T).forEach(([y,S])=>{let g=[...f,S.name],$=Object.hasOwnProperty.call(o,S.name)?o[S.name]:void 0;if(S.required&&$==null){E.push({message:`Field '${S.name}' is required`,path:g});let h=S.schema||S.nestedSchema;if(h&&!Array.isArray(h)){let C=b[h.id];C&&E.push(...s({},C,u,g,b,p))}else S.type==="union"&&Array.isArray(S.schema)&&S.schema.forEach(C=>{let d=b[C.id];d&&E.push(...s({},d,u,g,b,p))});return}if($!==void 0){if(E.push(...r($,S.type,g,S)),S.type==="array"||S.type==="set"){S.itemsType&&Array.isArray($)&&$.forEach((C,d)=>E.push(...r(C,S.itemsType,[...g,d.toString()])));let h=S.schema||S.nestedSchema;if(h&&!Array.isArray(h)){let C=b[h.id];C?$.forEach((d,l)=>{typeof d=="object"&&d!==null&&(p.has(h.id)?E.push({message:`Circular reference detected at '${h.id}'`,path:[...g,l.toString()]}):(p.add(h.id),E.push(...s(d,C,u,[...g,l.toString()],b,p)),p.delete(h.id)))}):E.push({message:`Nested schema '${h.id}' not found`,path:g})}}if(S.type==="object"){let h=S.schema||S.nestedSchema;if(h&&!Array.isArray(h)){let C=b[h.id];C?typeof $=="object"&&$!==null&&(p.has(h.id)?E.push({message:`Circular reference detected at '${h.id}'`,path:g}):(p.add(h.id),E.push(...s($,C,u,g,b,p)),h.constraints?.forEach((d,l)=>{if("rules"in d)E.push(...a(d,$,u,[...g,`constraints[${l}]`],p));else{let w=u[d.predicate];w?w({data:$,field:void 0,arguments:d.parameters})||E.push({message:d.errorMessage||`Constraint '${d.name}' failed with params ${K(d.parameters)}`,path:[...g,`constraints[${l}]`]}):E.push({message:`Predicate '${d.predicate}' not found`,path:[...g,`constraints[${l}]`]})}}),p.delete(h.id))):E.push({message:`Nested schema '${h.id}' not found`,path:g})}}if(S.type==="union"){let h=S.schema;!h||!Array.isArray(h)?E.push({message:"Union type requires an array of schema references",path:g}):h.some(d=>{let l=b[d.id];return l?s($,l,u,g,b,new Set(p)).length===0:(E.push({message:`Nested schema '${d.id}' not found`,path:g}),!1)})||E.push({message:"Value does not match any union schema",path:g})}S.constraints?.forEach((h,C)=>{if("rules"in h)E.push(...a(h,o,u,[...g,`constraints[${C}]`],p));else{let d=u[h.predicate];d?d({data:o,field:S.name,arguments:h.parameters})||E.push({message:h.errorMessage||`Constraint '${h.name}' failed for field '${S.name}' with params ${K(h.parameters)}`,path:[...g,`constraints[${C}]`]}):E.push({message:`Predicate '${h.predicate}' not found`,path:[...g,`constraints[${C}]`]})}})}});for(let y in o)Object.hasOwnProperty.call(o,y)&&!m.has(y)&&E.push({message:`Unexpected field '${y}'`,path:[...f,y]});return c.constraints?.forEach((y,S)=>{if("rules"in y)E.push(...a(y,o,u,[...f,`constraints[${S}]`],p));else{let g=u[y.predicate];if(!g)E.push({message:`Predicate '${y.predicate}' not found`,path:[...f,`constraints[${S}]`]});else if(!g({data:o,field:y.field,arguments:y.parameters})){let h=y.field?` for field '${y.field}'`:"";E.push({message:y.errorMessage||`Constraint '${y.name}' failed${h} with params ${K(y.parameters)}`,path:[...f,`constraints[${S}]`]})}}}),E}return{"~standard":{version:1,vendor:"@asaidimu/anansi",validate:o=>{if(typeof o!="object"||o===null)return i([{message:"Input must be an object",path:[]}]);let c=o,u=s(c,t,e,[],t.nestedSchemas||{});return u.length>0?i(u):n(c)},types:{input:{},output:{}}}}}function ut(t){return async e=>{let n=t.validate(e);if(n instanceof Promise&&(n=await n),"value"in n)return{values:n.value,errors:{}};let i={};return n.issues.forEach(r=>{if(!r.path)return;let a=r.path,s=i;for(let o=0;o<a.length;o++){let c=a[o];o===a.length-1?s[c]={type:"validation",message:r.message}:(s[c]=s[c]||{},s=s[c])}}),{values:{},errors:i}}}var _=class extends Error{constructor(n,i){super(n);this.errors=i;this.name="SchemaValidationError"}};var ge=t=>({value:t}),G=t=>({issues:t}),x=(t,e,n=!0)=>t===void 0&&!n?[]:typeof t!="string"||t.trim()===""?[{message:"Must be a non-empty string",path:[e]}]:[],Me=(t,e)=>{let n=["string","number","boolean","array","set","enum","object","record","union","dynamic"];return typeof t!="string"||!n.includes(t)?[{message:`Must be one of ${n.join(", ")}`,path:[e]}]:[]},ft=(t,e)=>{let n=["normal","unique","btree","hash","spatial","fulltext","gi","expression","composite"];return typeof t!="string"||!n.includes(t)?[{message:`Must be one of ${n.join(", ")}`,path:[e]}]:[]},Oe=(t,e)=>{let n=["and","or","not","nor","xor"];return typeof t!="string"||!n.includes(t)?[{message:`Must be one of ${n.join(", ")}`,path:[e]}]:[]},W=(t,e,n=!1)=>t===void 0&&!n?[]:typeof t!="boolean"?[{message:"Must be a boolean",path:[e]}]:[],lt=(t,e,n)=>{if(t===void 0)return[];switch(e){case"string":if(typeof t=="string"||Array.isArray(t)&&t.every(i=>typeof i=="string")||t instanceof RegExp||typeof t=="object"&&t!==null&&"field"in t&&typeof t.field=="string")return[];break;case"number":if(typeof t=="number"||Array.isArray(t)&&t.every(i=>typeof i=="number")||typeof t=="object"&&t!==null&&"precision"in t&&typeof t.precision=="number")return[];break;case"boolean":if(typeof t=="boolean")return[];break;case"array":case"set":if(typeof t=="number"||typeof t=="object"&&t!==null&&"minItems"in t&&typeof t.minItems=="number")return[];break;case"enum":if(Array.isArray(t)&&t.length>0&&t.every(i=>typeof i=="string"||typeof i=="number"))return[];break;case"object":case"record":if(typeof t=="object"&&t!==null&&"schema"in t)return[];break;case"union":if(typeof t=="object"&&t!==null&&"schema"in t)return[];break;case"dynamic":return[]}return[{message:`Invalid parameters for type '${e}'`,path:[n]}]},we=(t,e)=>{let n=[],i=["predicate","name"],r=["type","predicate","field","parameters","name","description","errorMessage"],a=t;return i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`)),n.push(...x(t.predicate,`${e}.predicate`)),t.type!==void 0&&t.type!=="schema"&&n.push({message:"Type must be 'schema' if present",path:[`${e}.type`]}),t.field!==void 0&&typeof t.field!="string"&&n.push({message:"Field must be a string",path:[`${e}.field`]}),t.parameters!==void 0&&(!t.type||t.type!=="schema")&&n.push(...lt(t.parameters,"dynamic",`${e}.parameters`)),n.push(...x(t.description,`${e}.description`,!1)),n.push(...x(t.errorMessage,`${e}.errorMessage`,!1)),n},$e=(t,e)=>{let n=[],i=["name","operator","rules"],r=["name","operator","rules"],a=t;return i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`)),n.push(...Oe(t.operator,`${e}.operator`)),!Array.isArray(t.rules)||t.rules.length===0?n.push({message:"Rules must be a non-empty array",path:[`${e}.rules`]}):t.rules.forEach((s,o)=>{"rules"in s?n.push(...$e(s,`${e}.rules[${o}]`)):n.push(...we(s,`${e}.rules[${o}]`))}),n},q=(t,e)=>{if(!Array.isArray(t))return[{message:"Must be an array",path:[e]}];let n=[];return t.forEach((i,r)=>{"rules"in i?n.push(...$e(i,`${e}[${r}]`)):n.push(...we(i,`${e}[${r}]`))}),n},je=(t,e)=>{let n=[],i=["operator","field"],r=["operator","field","value","conditions"],a=t;return i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...Oe(t.operator,`${e}.operator`)),n.push(...x(t.field,`${e}.field`)),t.conditions!==void 0&&(Array.isArray(t.conditions)?t.conditions.forEach((s,o)=>n.push(...je(s,`${e}.conditions[${o}]`))):n.push({message:"Conditions must be an array",path:[`${e}.conditions`]})),n},Ne=(t,e)=>{let n=[],i=["fields","type","name"],r=["fields","type","unique","partial","description","order","name"],a=t;return i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`)),n.push(...ft(t.type,`${e}.type`)),(!Array.isArray(t.fields)||t.fields.length===0||!t.fields.every(s=>typeof s=="string"))&&n.push({message:"Fields must be a non-empty array of strings",path:[`${e}.fields`]}),n.push(...W(t.unique,`${e}.unique`,!1)),t.partial&&n.push(...je(t.partial,`${e}.partial`)),n.push(...x(t.description,`${e}.description`,!1)),t.order!==void 0&&!["asc","desc"].includes(t.order)&&n.push({message:"Order must be 'asc' or 'desc'",path:[`${e}.order`]}),n},J=(t,e)=>{if(!Array.isArray(t))return[{message:"Must be an array",path:[e]}];let n=[];return t.forEach((i,r)=>n.push(...Ne(i,`${e}[${r}]`))),n},mt=(t,e,n,i,r)=>{let a=[];return t===void 0?[]:(n==="union"&&Array.isArray(t)?(t.length===0&&a.push({message:"Schema array must not be empty for union type",path:[e]}),t.forEach((s,o)=>{let c=`${e}[${o}]`;a.push(...x(s.id,`${c}.id`)),i.includes(s.id)||a.push({message:`Schema ID '${s.id}' must match a nestedSchemas key`,path:[`${c}.id`]}),s.constraints&&a.push(...q(s.constraints,`${c}.constraints`)),s.indexes&&a.push(...J(s.indexes,`${c}.indexes`))})):(n==="object"||n==="array"&&r==="object")&&!Array.isArray(t)?(a.push(...x(t.id,`${e}.id`)),i.includes(t.id)||a.push({message:`Schema ID '${t.id}' must match a nestedSchemas key`,path:[`${e}.id`]}),t.constraints&&a.push(...q(t.constraints,`${e}.constraints`)),t.indexes&&a.push(...J(t.indexes,`${e}.indexes`))):a.push({message:"Schema is only valid for 'object', 'union', or 'array' with itemsType 'object'",path:[e]}),a)},se=(t,e,n)=>{let i=[],r=["name","type"],a=["name","type","required","constraints","default","values","schema","itemsType","nestedSchema","deprecated","reference","description","unique"],s=t;if(r.forEach(o=>{s[o]===void 0&&i.push({message:`${o} is required`,path:[`${e}.${o}`]})}),Object.keys(s).forEach(o=>{a.includes(o)||i.push({message:"Unknown property",path:[`${e}.${o}`]})}),i.push(...x(t.name,`${e}.name`)),i.push(...Me(t.type,`${e}.type`)),i.push(...W(t.required,`${e}.required`,!1)),t.constraints&&i.push(...q(t.constraints,`${e}.constraints`)),t.values!==void 0&&(t.type==="enum"?(!Array.isArray(t.values)||t.values.length===0||!t.values.every(o=>typeof o=="string"||typeof o=="number"))&&i.push({message:"Values must be a non-empty array of strings or numbers",path:[`${e}.values`]}):i.push({message:"Values is only valid for 'enum' type",path:[`${e}.values`]})),t.schema!==void 0&&i.push(...mt(t.schema,`${e}.schema`,t.type,n,t.itemsType)),t.itemsType&&i.push(...Me(t.itemsType,`${e}.itemsType`)),t.nestedSchema){let o=["id"],c=["id","constraints","indexes"],u=t.nestedSchema;o.forEach(f=>{u[f]===void 0&&i.push({message:`${f} is required`,path:[`${e}.nestedSchema.${f}`]})}),Object.keys(u).forEach(f=>{c.includes(f)||i.push({message:"Unknown property",path:[`${e}.nestedSchema.${f}`]})}),i.push(...x(t.nestedSchema.id,`${e}.nestedSchema.id`)),n.includes(t.nestedSchema.id)||i.push({message:`nestedSchema.id '${t.nestedSchema.id}' must match a nestedSchemas key`,path:[`${e}.nestedSchema.id`]}),t.nestedSchema.constraints&&i.push(...q(t.nestedSchema.constraints,`${e}.nestedSchema.constraints`)),t.nestedSchema.indexes&&i.push(...J(t.nestedSchema.indexes,`${e}.nestedSchema.indexes`))}if(i.push(...W(t.deprecated,`${e}.deprecated`,!1)),t.reference){let o=["schema","field"],c=["schema","field"],u=t.reference;o.forEach(f=>{u[f]===void 0&&i.push({message:`${f} is required`,path:[`${e}.reference.${f}`]})}),Object.keys(u).forEach(f=>{c.includes(f)||i.push({message:"Unknown property",path:[`${e}.reference.${f}`]})}),i.push(...x(t.reference.schema,`${e}.reference.schema`)),i.push(...x(t.reference.field,`${e}.reference.field`))}return i.push(...x(t.description,`${e}.description`,!1)),i.push(...W(t.unique,`${e}.unique`,!1)),i},Ve=(t,e,n)=>{let i=[],r=["name","fields"],a=["name","description","concrete","fields","indexes","constraints","metadata"],s=t;return r.forEach(o=>{s[o]===void 0&&i.push({message:`${o} is required`,path:[`${e}.${o}`]})}),Object.keys(s).forEach(o=>{a.includes(o)||i.push({message:"Unknown property",path:[`${e}.${o}`]})}),i.push(...x(t.name,`${e}.name`)),i.push(...W(t.concrete,`${e}.concrete`,!1)),Array.isArray(t.fields)?(t.fields.length===0&&i.push({message:"Fields array must not be empty",path:[`${e}.fields`]}),t.fields.forEach((o,c)=>{let u=`${e}.fields[${c}]`;if(typeof o!="object"||o===null||!("fields"in o))i.push({message:"Each variant must have a 'fields' property",path:[u]});else{let f=o.fields;typeof f!="object"||f===null?i.push({message:"Fields must be a non-empty object",path:[`${u}.fields`]}):Object.entries(f).forEach(([b,p])=>{i.push(...se(p,`${u}.fields.${b}`,n))}),o.when!==void 0&&(typeof o.when!="object"||o.when===null)&&i.push({message:"When must be an object",path:[`${u}.when`]})}})):typeof t.fields=="object"&&t.fields!==null?Object.entries(t.fields).forEach(([o,c])=>{i.push(...se(c,`${e}.fields.${o}`,n))}):i.push({message:"Fields must be a non-empty object or array",path:[`${e}.fields`]}),i.push(...x(t.description,`${e}.description`,!1)),t.indexes&&i.push(...J(t.indexes,`${e}.indexes`)),t.constraints&&i.push(...q(t.constraints,`${e}.constraints`)),t.metadata!==void 0&&(typeof t.metadata!="object"||t.metadata===null)&&i.push({message:"Metadata must be an object",path:[`${e}.metadata`]}),i},ht=t=>{if(typeof t!="object"||t===null)return G([{message:"Schema must be an object",path:[]}]);let e=t,n=[],i=["name","version","fields","nestedSchemas"],r=["name","version","description","fields","nestedSchemas","indexes","constraints","metadata","dependencies","migrations","mock"],a=e;if(i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[s]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[s]})}),n.push(...x(e.name,"name")),n.push(...x(e.version,"version")),typeof e.fields!="object"||e.fields===null)n.push({message:"Fields must be a non-empty object",path:["fields"]});else{let s=Object.keys(e.nestedSchemas||{});Object.entries(e.fields).forEach(([o,c])=>{n.push(...se(c,`fields.${o}`,s))})}if(typeof e.nestedSchemas!="object"||e.nestedSchemas===null)n.push({message:"NestedSchemas must be a non-empty object",path:["nestedSchemas"]});else{let s=Object.keys(e.nestedSchemas);Object.entries(e.nestedSchemas).forEach(([o,c])=>n.push(...Ve(c,`nestedSchemas.${o}`,s)))}return n.push(...x(e.description,"description",!1)),e.indexes&&n.push(...J(e.indexes,"indexes")),e.constraints&&n.push(...q(e.constraints,"constraints")),e.metadata!==void 0&&(typeof e.metadata!="object"||e.metadata===null)&&n.push({message:"Metadata must be an object",path:["metadata"]}),e.dependencies!==void 0&&(!Array.isArray(e.dependencies)||!e.dependencies.every(s=>typeof s=="string"))&&n.push({message:"Dependencies must be an array of strings",path:["dependencies"]}),e.migrations!==void 0&&(Array.isArray(e.migrations)?e.migrations.forEach((s,o)=>n.push(...qe(s,`migrations[${o}]`))):n.push({message:"Migrations must be an array",path:["migrations"]})),e.mock!==void 0&&typeof e.mock!="function"&&n.push({message:"Mock must be a function",path:["mock"]}),n.length>0?G(n):ge(e)},ye=(t,e)=>{let n=[];switch(t.type||n.push({message:"type is required",path:[`${e}.type`]}),t.type){case"modifyProperty":{let i=["type","id","changes"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`)),(t.changes===void 0||typeof t.changes!="object")&&n.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addField":{let i=["type","id","definition"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`)),n.push(...se(t.definition,`${e}.definition`,[]));break}case"removeField":case"deprecateField":{let i=["type","id"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`));break}case"modifyField":{let i=["type","id","changes"],r=["type","id","changes","nestedSchemaChanges"],a=t;if(i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`)),typeof t.changes!="object"&&n.push({message:"Changes must be an object",path:[`${e}.changes`]}),t.nestedSchemaChanges){let s=["id","constraints","indexes"],o=t.nestedSchemaChanges;Object.keys(o).forEach(c=>{s.includes(c)||n.push({message:"Unknown property",path:[`${e}.nestedSchemaChanges.${c}`]})}),n.push(...x(o.id,`${e}.nestedSchemaChanges.id`,!1)),o.constraints&&n.push(...q(o.constraints,`${e}.nestedSchemaChanges.constraints`)),o.indexes&&n.push(...J(o.indexes,`${e}.nestedSchemaChanges.indexes`))}break}case"addIndex":{let i=["type","definition"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...Ne(t.definition,`${e}.definition`));break}case"removeIndex":{let i=["type","name"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`));break}case"modifyIndex":{let i=["type","name","changes"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`)),typeof t.changes!="object"&&n.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addConstraint":{let i=["type","constraint"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),"rules"in t.constraint?n.push(...$e(t.constraint,`${e}.constraint`)):n.push(...we(t.constraint,`${e}.constraint`));break}case"removeConstraint":{let i=["type","name"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`));break}case"modifyConstraint":{let i=["type","name","changes"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`)),typeof t.changes!="object"&&n.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addNestedSchema":{let i=["type","id","definition"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`)),n.push(...Ve(t.definition,`${e}.definition`,[]));break}case"removeNestedSchema":{let i=["type","id"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`));break}case"modifyNestedSchema":{let i=["type","id","changes"],r=i,a=t;i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`)),typeof t.changes!="object"&&n.push({message:"Changes must be an object",path:[`${e}.changes`]});break}default:n.push({message:"Unknown schema change type",path:[`${e}.type`]})}return n},pt=(t,e)=>{let n=[],i=["forward","backward"],r=i,a=t;return i.forEach(s=>{a[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||n.push({message:"Unknown property",path:[`${e}.${s}`]})}),typeof t.forward!="function"&&n.push({message:"Forward must be a function",path:[`${e}.forward`]}),typeof t.backward!="function"&&n.push({message:"Backward must be a function",path:[`${e}.backward`]}),n},qe=(t,e)=>{let n=[],i=["id","schemaVersion","changes","description","status","transform","createdAt","checksum"],r=[...i,"rollback","dependencies"],a=t;i.forEach(o=>{a[o]===void 0&&n.push({message:`${o} is required`,path:[`${e}.${o}`]})}),Object.keys(a).forEach(o=>{r.includes(o)||n.push({message:"Unknown property",path:[`${e}.${o}`]})}),n.push(...x(t.id,`${e}.id`)),n.push(...x(t.schemaVersion,`${e}.schemaVersion`)),n.push(...x(t.description,`${e}.description`));let s=["pending","applied","failed"];return s.includes(t.status)||n.push({message:`Status must be one of ${s.join(", ")}`,path:[`${e}.status`]}),!Array.isArray(t.changes)||t.changes.length===0?n.push({message:"Changes must be a non-empty array",path:[`${e}.changes`]}):t.changes.forEach((o,c)=>n.push(...ye(o,`${e}.changes[${c}]`))),t.rollback!==void 0&&(Array.isArray(t.rollback)?t.rollback.forEach((o,c)=>n.push(...ye(o,`${e}.rollback[${c}]`))):n.push({message:"Rollback must be an array",path:[`${e}.rollback`]})),typeof t.transform=="string"?n.push(...x(t.transform,`${e}.transform`)):typeof t.transform=="object"&&t.transform!==null?n.push(...pt(t.transform,`${e}.transform`)):n.push({message:"Transform must be a string or object",path:[`${e}.transform`]}),n.push(...x(t.createdAt,`${e}.createdAt`)),t.dependencies!==void 0&&(!Array.isArray(t.dependencies)||!t.dependencies.every(o=>typeof o=="string"))&&n.push({message:"Dependencies must be an array of strings",path:[`${e}.dependencies`]}),n.push(...x(t.checksum,`${e}.checksum`)),n},Ue={"~standard":{version:1,vendor:"@asaidimu/anansi",validate:ht,types:{input:{},output:{}}}};var Le={"~standard":{version:1,vendor:"@asaidimu/anansi",validate:t=>{if(typeof t!="object"||t===null)return G([{message:"Migration must be an object",path:[]}]);let e=t,n=qe(e,"");return n.length>0?G(n):ge(e)},types:{input:{},output:{}}}},_e={"~standard":{version:1,vendor:"@asaidimu/anansi",validate:t=>{if(!Array.isArray(t))return G([{message:"SchemaChanges must be an array",path:[]}]);let e=t,n=[];return e.forEach((i,r)=>n.push(...ye(i,`[${r}]`))),n.length>0?G(n):ge(e)},types:{input:[],output:[]}}};function Se(t){try{return!Le["~standard"].validate(t).issues}catch(e){throw new _("Invalid migration definition",e instanceof Error?e:new Error(String(e)))}}function be(t){try{return!_e["~standard"].validate(t).issues}catch(e){throw new _("Invalid schema change definition",e instanceof Error?e:new Error(String(e)))}}function H(t){try{return!Ue["~standard"].validate(t).issues}catch(e){throw new _("Invalid schema definition",e instanceof Error?e:new Error(String(e)))}}var yt=H;var U=async t=>{if(typeof window<"u"&&crypto.subtle){let n=new TextEncoder().encode(t),i=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(i)).map(a=>a.toString(16).padStart(2,"0")).join("")}else{let{createHash:e}=await import("crypto");return e("sha256").update(t).digest("hex")}};function gt(t){let e=t.match(/^(\d+)\.(\d+)\.(\d+)$/);if(!e)throw new Error(`Invalid version format: ${t}. Expected format: major.minor.patch`);return{major:parseInt(e[1],10),minor:parseInt(e[2],10),patch:parseInt(e[3],10)}}function wt(t,e){if(e&&"field"in t&&t.field){let n=e.fields[t.field];if(n)return n.type}if("parameters"in t){let n=t.parameters;if(n instanceof RegExp||Array.isArray(n)&&typeof n[0]=="string")return"string";if(typeof n=="number"||Array.isArray(n)&&typeof n[0]=="number")return"number";if(typeof n=="boolean")return"boolean";if(typeof n=="object"&&n!==null){if("minItems"in n||"maxItems"in n)return"array";if("schema"in n)return"object"}}}function $t(t){return t.required===!0||t.type!==void 0||t.itemsType!==void 0||t.nestedSchema!==void 0||t.reference!==void 0||t.unique===!0}function St(t,e,n){switch(n){case"string":if(t instanceof RegExp&&e instanceof RegExp)return t.source!==e.source;if(Array.isArray(t)&&Array.isArray(e))return e.length<t.length||!t.every(i=>e.includes(i));break;case"number":if(typeof t=="object"&&typeof e=="object"&&"precision"in t&&"precision"in e)return e.precision<t.precision||(e.scale??0)<(t.scale??0);if(Array.isArray(t)&&Array.isArray(e))return e.length<t.length||!t.every(i=>e.includes(i));break;case"array":if(typeof t=="object"&&typeof e=="object"&&"minItems"in t&&"maxItems"in t&&"minItems"in e&&"maxItems"in e)return e.minItems>t.minItems||e.maxItems<t.maxItems;break;case"object":if(typeof t=="object"&&typeof e=="object"&&"schema"in t&&"schema"in e)return Object.keys(e.schema).length>Object.keys(t.schema).length;break}return!1}function bt(t,e){let n={or:1,xor:2,and:3,not:4,nor:4};return!!(e.operator&&n[e.operator]>n[t.operator]||e.rules&&e.rules.length>t.rules.length)}function vt(t,e,n){if(!e)return!0;if("rules"in e&&"rules"in t)return bt(e,t);if("predicate"in t&&t.predicate!==void 0)return!0;if("parameters"in t&&t.parameters!==void 0){let i=wt(e,n);return i?St(e.parameters,t.parameters,i):!0}return!1}function Et(t,e){switch(t.type){case"removeField":case"removeIndex":return"major";case"modifyField":return $t(t.changes)?"major":t.changes.deprecated?"minor":"patch";case"modifyIndex":return t.changes.unique!==void 0||t.changes.fields!==void 0?"major":"minor";case"addConstraint":return"major";case"removeConstraint":return"minor";case"modifyConstraint":let n=e?.constraints?.find(i=>"name"in i&&i.name===t.name);return vt(t.changes,n,e)?"major":"minor";case"addField":case"addIndex":case"deprecateField":return"minor";default:throw new Error(`Unhandled change type: ${JSON.stringify(t)}`)}}function xt(t){let e=new Set,n=new Set,i=new Set,r=new Set;for(let a of t)switch(a.type){case"addField":if(n.has(a.id))throw new Error(`Cannot add previously removed field: ${a.id}`);if(e.has(a.id))throw new Error(`Cannot add already modified field: ${a.id}`);if(r.has(a.id))throw new Error(`Cannot add deprecated field: ${a.id}`);i.add(a.id);break;case"removeField":if(i.has(a.id))throw new Error(`Cannot remove newly added field: ${a.id}`);if(e.has(a.id))throw new Error(`Cannot remove modified field: ${a.id}`);if(r.has(a.id))throw new Error(`Cannot remove field that is being deprecated: ${a.id}`);n.add(a.id);break;case"modifyField":if(n.has(a.id))throw new Error(`Cannot modify removed field: ${a.id}`);if(i.has(a.id))throw new Error(`Cannot modify newly added field: ${a.id}`);if(r.has(a.id))throw new Error(`Cannot modify field that is being deprecated: ${a.id}`);e.add(a.id);break;case"deprecateField":if(n.has(a.id))throw new Error(`Cannot deprecate removed field: ${a.id}`);if(i.has(a.id))throw new Error(`Cannot deprecate newly added field: ${a.id}`);if(e.has(a.id))throw new Error(`Cannot deprecate modified field: ${a.id}`);r.add(a.id);break}}function Tt(t){let e=new Set,n=new Set,i=new Set;for(let r of t)switch(r.type){case"addConstraint":let a=r.constraint,s=("name"in a,a.name);if(n.has(s))throw new Error(`Cannot add previously removed constraint: ${s}`);if(e.has(s))throw new Error(`Cannot add already modified constraint: ${s}`);i.add(s);break;case"removeConstraint":if(i.has(r.name))throw new Error(`Cannot remove newly added constraint: ${r.name}`);if(e.has(r.name))throw new Error(`Cannot remove modified constraint: ${r.name}`);n.add(r.name);break;case"modifyConstraint":if(n.has(r.name))throw new Error(`Cannot modify removed constraint: ${r.name}`);if(i.has(r.name))throw new Error(`Cannot modify newly added constraint: ${r.name}`);e.add(r.name);break}}function ve(t,e,n){if(e.length===0)throw new Error("No changes provided");xt(e),Tt(e);let i=gt(t),r="patch";for(let a of e){let s=Et(a,n);if(s==="major"){r="major";break}else s==="minor"&&r==="patch"&&(r="minor")}switch(r){case"major":return`${i.major+1}.0.0`;case"minor":return`${i.major}.${i.minor+1}.0`;case"patch":return`${i.major}.${i.minor}.${i.patch+1}`}}function O(t,e){let n=u=>u.split(".").map(f=>parseInt(f,10)||0),[i,r,a]=n(t),[s,o,c]=n(e);return i-s||r-o||a-c}function Ct(t){return t.sort(O)}var k=class extends Error{constructor(n,i,r,a){super(n);this.code=i;this.migrationId=r;this.cause=a;this.name="MigrationError"}},Ge=(p=>(p.INVALID_SCHEMA="INVALID_SCHEMA",p.INVALID_MIGRATION="INVALID_MIGRATION",p.CHECKSUM_MISMATCH="CHECKSUM_MISMATCH",p.TIMEOUT="TIMEOUT",p.MEMORY_LIMIT="MEMORY_LIMIT",p.CONCURRENT_OPERATION="CONCURRENT_OPERATION",p.TRANSFORM_ERROR="TRANSFORM_ERROR",p.VERSION_NOT_FOUND="VERSION_NOT_FOUND",p.CIRCULAR_DEPENDENCY="CIRCULAR_DEPENDENCY",p.STREAM_ERROR="STREAM_ERROR",p.ROLLBACK_ERROR="ROLLBACK_ERROR",p.MISSING_TRANSFORM="MISSING_TRANSFORM",p))(Ge||{}),Ee=class t{currentSchema;history=[];migrations=[];isProcessing=!1;constructor(e,n,i){try{if(!H(e))throw new k("Invalid initial schema","INVALID_SCHEMA");if(this.currentSchema=e,n){if(!n.every(r=>Se(r)))throw new k("Invalid migration configuration","INVALID_MIGRATION");this.migrations=n.sort((r,a)=>O(r.schemaVersion,a.schemaVersion))}i&&(this.history=i.sort((r,a)=>O(r.version,a.version)))}catch(r){throw r instanceof k?r:new k("Failed to initialize MigrationEngine","INVALID_SCHEMA",void 0,r)}}data(){return{schema:this.currentSchema,history:this.history,migrations:this.migrations}}async generateChecksum(e){try{let n=JSON.stringify({id:e.id,schemaVersion:e.schemaVersion,changes:e.changes,description:e.description,rollback:e.rollback,createdAt:e.createdAt});return await U(n)}catch(n){throw new k("Checksum generation failed","CHECKSUM_MISMATCH",e.id,n)}}async add(e){if(this.isProcessing)throw new k("Concurrent operation","CONCURRENT_OPERATION");if(!e.changes?.length)throw new k("Migration must include changes","INVALID_MIGRATION");try{e.changes.forEach(i=>be(i))}catch(i){throw new k("Invalid schema changes","INVALID_MIGRATION",void 0,i)}let n={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:""};n.checksum=await this.generateChecksum(n),this.migrations.push(n)}async dryRun(e,n,i){if(this.isProcessing)throw new k("Concurrent operation","CONCURRENT_OPERATION");try{this.isProcessing=!0;let r={...this.currentSchema},a=this.getRelevantMigrations(n,i),s=a.reduce((c,u)=>{let f=n==="forward"?u.changes:u.rollback||[];return this.applySchemaChanges(c,f,u.id)},r),o=await t.processMigrationList(e,n,a);return{newSchema:s,dataPreview:o}}catch(r){throw r instanceof k?r:new k("Dry run failed","INVALID_SCHEMA",void 0,r)}finally{this.isProcessing=!1}}getRelevantMigrations(e,n){return[...this.migrations].filter(i=>{let r=e==="forward"?"pending":"applied",a=n?O(i.schemaVersion,n)>=0:!0;return i.status===r&&a}).sort((i,r)=>e==="forward"?i.id.localeCompare(r.id):r.id.localeCompare(i.id))}applySchemaChanges(e,n,i){try{let r=ve(e.version,n);return n.map(s=>{try{return me(s,e)}catch(o){throw new k("Invalid schema change","INVALID_SCHEMA",i,o)}}).reduce((s,o)=>{try{return ie(s,o)}catch(c){throw new k("Failed to apply patch","INVALID_SCHEMA",i,c)}},{...e,version:r})}catch(r){throw r instanceof k?r:new k("Schema update failed","INVALID_SCHEMA",i,r)}}async prepareMigration(){let e=this.migrations.filter(n=>n.status==="pending");return await this.validateMigrations(e),e}async migrate(e){if(this.isProcessing)throw new k("Concurrent operation","CONCURRENT_OPERATION");let n=await this.prepareMigration();try{this.isProcessing=!0,this.transformSchema("forward");let i=await t.processMigrationList(e,"forward",n);return this.markMigrationsApplied(n),i}finally{this.isProcessing=!1}}async validateMigrations(e){await Promise.all(e.map(async n=>{let i=await this.generateChecksum(n);if(n.checksum!==i)throw new k("Checksum mismatch","CHECKSUM_MISMATCH",n.id)}))}markMigrationsApplied(e){this.migrations=this.migrations.map(n=>e.some(i=>i.id===n.id)?{...n,status:"applied"}:n)}async rollback(e){if(this.isProcessing)throw new k("Concurrent operation","CONCURRENT_OPERATION");return this.migrations.filter(i=>i.status==="applied").slice(-1)[0]?this.rollbackToVersion(this.history[this.history.length-1]?.version||this.currentSchema.version,e):e}async rollbackToVersion(e,n){if(this.isProcessing)throw new k("Concurrent operation","CONCURRENT_OPERATION");try{let i=this.history.findIndex(o=>o.version===e);if(i===-1)throw new Error(`Version ${e} not found in history`);let r=this.migrations.filter(o=>o.schemaVersion===e&&o.status==="applied").sort((o,c)=>c.id.localeCompare(o.id)),a=this.history.length-i;if(a<0)return n;for(let o=0;o<a;o++)this.transformSchema("backward");let s=await t.processMigrationList(n,"backward",r);return this.migrations=this.migrations.map(o=>o.schemaVersion===e&&o.status==="applied"?{...o,status:"pending"}:o),s}finally{this.isProcessing=!1}}static async processMigrationList(e,n,i){return(await Promise.all(i.map(async s=>{try{let o=await this.resolveTransform(s,n);return{migration:s,transform:o}}catch(o){throw new k(`Failed to resolve transform for migration ${s.id}`,"TRANSFORM_ERROR",s.id,o)}}))).filter(s=>!!s.transform).reduce((s,{migration:o,transform:c})=>s.pipeThrough(new TransformStream({async transform(u,f){try{let b=await c(u);f.enqueue(b)}catch(b){f.error(new k(`Data transformation failed for migration ${o.id}`,"TRANSFORM_ERROR",o.id,b))}}})),e)}static async resolveTransform(e,n){return e.transform?typeof e.transform=="string"?e.transform.startsWith("http://")||e.transform.startsWith("https://")?this.resolveRemoteTransform(e.transform,n):this.resolveLocalTransform(e.transform,n):e.transform[n]:null}static async resolveRemoteTransform(e,n){try{let i=await fetch(e);if(!i.ok)throw new k(`Failed to fetch transform module: ${e}`,"TRANSFORM_ERROR",void 0);let r=await i.text();if(typeof window<"u"){let a=new Blob([r],{type:"application/javascript"});return(await import(URL.createObjectURL(a))).default[n]}else{let{runInNewContext:a}=await import("vm"),s={module:{exports:{}},console};return a(r,s,e),s.module.exports[n]}}catch(i){throw new k(`Failed to load remote transform module: ${e}`,"TRANSFORM_ERROR",void 0,i)}}static async resolveLocalTransform(e,n){try{return(await import(e)).default[n]}catch(i){throw new k(`Failed to import local transform module: ${e}`,"TRANSFORM_ERROR",void 0,i)}}transformSchema(e){try{if(e==="backward"){let i=this.history.pop();if(!i)throw new Error("No previous version");this.currentSchema=i;return}let n=this.migrations.filter(i=>i.status==="pending").flatMap(i=>i.changes);if(!n.length)return;this.history.push(structuredClone(this.currentSchema)),this.currentSchema=n.reduce((i,r)=>this.applySchemaChanges(i,[r]),this.currentSchema)}catch(n){throw n instanceof k?n:new k("Schema transformation failed","INVALID_SCHEMA",void 0,n)}}};var Je=t=>{let e=[],n=[];return{addField:(i,r)=>{e.push({type:"addField",id:i,definition:r}),n.push({type:"removeField",id:i})},removeField:i=>{e.push({type:"removeField",id:i});let r=t.fields[i];r&&n.push({type:"addField",id:i,definition:r})},modifyField:(i,r)=>{e.push({type:"modifyField",id:i,changes:r});let a=t.fields[i];a&&n.push({type:"modifyField",id:i,changes:a})},deprecateField:i=>{e.push({type:"deprecateField",id:i}),n.push({type:"modifyField",id:i,changes:{deprecated:!1}})},addIndex:i=>{e.push({type:"addIndex",definition:i}),n.push({type:"removeIndex",name:i.name})},removeIndex:i=>{e.push({type:"removeIndex",name:i});let r=t.indexes?.find(a=>a.name===i);r&&n.push({type:"addIndex",definition:r})},modifyIndex:(i,r)=>{e.push({type:"modifyIndex",name:i,changes:r});let a=t.indexes?.find(s=>s.name===i);a&&n.push({type:"modifyIndex",name:i,changes:a})},addConstraint:i=>{e.push({type:"addConstraint",constraint:i}),n.push({type:"removeConstraint",name:i.name})},removeConstraint:i=>{e.push({type:"removeConstraint",name:i});let r=t.constraints?.find(a=>"name"in a&&a.name===i);r&&n.push({type:"addConstraint",constraint:r})},modifyConstraint:(i,r)=>{e.push({type:"modifyConstraint",name:i,changes:r});let a=t.constraints?.find(s=>"name"in s&&s.name===i);a&&n.push({type:"modifyConstraint",name:i,changes:a})},addNestedSchema:(i,r)=>{e.push({type:"addNestedSchema",id:i,definition:r}),n.push({type:"removeNestedSchema",id:i})},removeNestedSchema:i=>{if(e.push({type:"removeNestedSchema",id:i}),!t.nestedSchemas)return;let r=t.nestedSchemas[i];r&&n.push({type:"addNestedSchema",id:i,definition:r})},modifyNestedSchema:(i,r)=>{if(e.push({type:"modifyNestedSchema",id:i,changes:r}),!t.nestedSchemas)return;let a=t.nestedSchemas[i];a&&n.push({type:"modifyNestedSchema",id:i,changes:a})},changes:()=>({migrate:e,rollback:n})}};var bn=require("@isomorphic-git/lightning-fs"),A=B(require("isomorphic-git"),1),Q=B(require("isomorphic-git/http/web"),1);var Ke=B(require("@isomorphic-git/lightning-fs"),1);function He(t){let e=t.toString(),n=e.substring(e.indexOf("(")+1,e.indexOf(")")),i=e.substring(e.indexOf("{")+1,e.lastIndexOf("}")).trim();return JSON.stringify({params:n,body:i})}function ze(t){let{params:e,body:n}=JSON.parse(t),i=Object.getPrototypeOf(function*(){}).constructor;return new i(e,n)}function xe(t){let e=t.toString(),n=e.match(/\(([^)]*)\)\s*=>\s*(.+)/s),i=e.match(/function\s*\(([^)]*)\)\s*{([\s\S]*)}/),r=e.match(/([^(]*)\(([^)]*)\)\s*{([\s\S]*)}/),a,s;return n?(a=n[1],s=n[2].includes("{")?n[2].substring(1,n[2].length-1).trim():`return ${n[2]}`):i?(a=i[1],s=i[2].trim()):r?(a=r[2],s=r[3].trim()):(a=e.substring(e.indexOf("(")+1,e.indexOf(")")),s=e.substring(e.indexOf("{")+1,e.lastIndexOf("}")).trim()),JSON.stringify({params:a,body:s,type:n?"arrow":i?"function":r?"method":"unknown"})}function Te(t){let{params:e,body:n,type:i}=JSON.parse(t),r=new Function(e,n);return i==="arrow"&&Object.defineProperty(r,"toString",{value:()=>`(${e}) => ${n}`,configurable:!0}),r}function Dt(t){let e={},n={};t.hint?.groups&&t.hint.groups.forEach(r=>{n[r.name]={label:r.label,description:r.description}}),Ce(t.fields,"",t.nestedSchemas||{},e,!0);let i=[];for(let[r,a]of Object.entries(e)){let s=r!=="ungrouped"?n[r]:void 0;i.push({name:r!=="ungrouped"?r:"ungrouped",label:s?.label||"Ungrouped",description:s?.description,fields:a})}return i}function Ce(t,e,n,i,r,a){if(Array.isArray(t))t.forEach(s=>{let o=s.when?e?`${e}.${s.when?.field}`:s.when?.field:void 0;Ce(s.fields,e,n,i,r,o?{[o]:s.when?.value}:void 0)});else for(let[s,o]of Object.entries(t)){if(o.hint?.input.ignore)continue;let c=e?`${e}.${o.name}`:o.name,f=o.required===!0&&r,b={...o,name:c,required:f};if(a&&(b.when=a),o.type!=="object"){let p=o.hint?.input?.group||"ungrouped";i[p]||(i[p]=[]),i[p].push(b)}if(o.schema&&"id"in o.schema&&n[o.schema.id]){let p=n[o.schema.id];Ce(p.fields,c,n,i,f,a)}}}function At(t,e){let n={},i=t.nestedSchemas||{};for(let[r,a]of Object.entries(t.fields))n[r]=ae(a,i,e);return n}function ae(t,e,n){if("default"in t&&t.default!==void 0)return t.default;if(n?.resolver){let i=n.resolver(t);if(i!==void 0)return i}switch(t.type){case"string":return;case"number":return;case"boolean":return!1;case"array":return[];case"set":return[];case"enum":if(!t.values||t.values.length===0)throw new Error(`Enum field "${t.name}" requires non-empty values array`);return t.values[0];case"object":if(!t.schema||!("id"in t.schema)||!e[t.schema.id])throw new Error(`Object field "${t.name}" references invalid nested schema`);return Be(e[t.schema.id],e,n);case"record":return{};case"union":if(!t.schema||!Array.isArray(t.schema)||t.schema.length===0)throw new Error(`Union field "${t.name}" requires non-empty schema array`);let i=n?.discriminator?.[t.name],r=t.schema[0];if(i!==void 0)for(let a of t.schema){let o=e[a.id].fields;if(It(o,i)){r=a;break}}return Be(e[r.id],e,n);case"dynamic":return{};default:throw new Error(`Unsupported field type "${t.type}" for field "${t.name}"`)}}function It(t,e){if(Array.isArray(t)){for(let n of t)for(let i of Object.values(n.fields))if(i.type==="enum"&&i.values?.includes(e)||i.default===e)return i}else for(let n of Object.values(t))if(n.type==="enum"&&n.values?.includes(e)||n.default===e)return n}function Be(t,e,n){let i={},r=n?.discriminator||{};if(Array.isArray(t.fields)){let a=t.fields.filter(o=>!o.when);for(let o of a)for(let[c,u]of Object.entries(o.fields))i[c]=ae(u,e,n);let s=t.fields.filter(o=>o.when);for(let o of s){let c=o.when.field,u=o.when.value;if(r[c]===u)for(let[b,p]of Object.entries(o.fields))i[b]=ae(p,e,n)}}else for(let[a,s]of Object.entries(t.fields))i[a]=ae(s,e,n);return i}var We=require("buffer");window.Buffer=We.Buffer;var Y=class{fs;fsp;rootDir;constructor(e="/registry"){this.fs=new Ke.default(`${e.replace("/","-")}`),this.fsp=this.fs.promises,this.rootDir=e.startsWith("/")?e:`/${e}`}async init(){let e=`${this.rootDir}/registry.json`;(!await this.fileExists(this.rootDir)||!await this.fileExists(e))&&(await this.fsp.mkdir(this.rootDir),await this.fsp.writeFile(e,JSON.stringify({schemas:{},created:new Date().toISOString(),updated:new Date().toISOString()}),"utf8"),await this.fsp.writeFile(`${this.rootDir}/schema-lock.json`,JSON.stringify({updated:new Date().toISOString(),hashes:[]}),"utf8"))}async create({schema:e}){if(!e.name||!e.version||!H(e))throw new Error("Invalid schema");let n=`${this.rootDir}/${e.name}`;if(await this.fileExists(`${n}/schema.json`))throw new Error(`Schema ${e.name} already exists`);return await this.fsp.mkdir(n),await this.fsp.mkdir(`${n}/migrations`),this.saveSchema(e,"create")}async update({schema:e}){if(!e.name||!e.version)throw new Error("Schema must have a name and version");let n=`${this.rootDir}/${e.name}`;if(!await this.fileExists(`${n}/schema.json`))throw new Error(`Schema ${e.name} not found`);return this.saveSchema(e,"update")}async saveSchema(e,n){let i=`${this.rootDir}/${e.name}`,r=await this.processAndStoreMigrations(i,e),a=this.serializeSchema(e);await this.writeSchemaFile(i,a);let s=await U(a);await this.updateIndex(i,e,s,r,n),await this.updateRegistryMetadata(e,n),await this.sync()}async delete({name:e}){let n=`${this.rootDir}/${e}`;if(!await this.fileExists(`${n}/schema.json`))throw new Error(`Schema ${e} not found`);await this.rmdirRecursive(n);let i=await this.readRegistryMetadata();delete i.schemas[e],i.updated=new Date().toISOString(),await this.writeRegistryMetadata(i),await this.sync()}async list(){let e=await this.readRegistryMetadata();return Object.values(e.schemas).map(n=>({name:n.name,version:n.version}))}async schema({name:e,version:n,migrations:i=!1}){let r=`${this.rootDir}/${e}/schema.json`;if(!await this.fileExists(r))return null;let a=this.deserializeSchema(JSON.parse(String(await this.fsp.readFile(r,"utf8")))),s=await this.readSchemaIndex(e);return n&&n!==s.version&&!s.history.some(o=>o.version===n)?null:(i&&(a.migrations=await this.migrations({name:e,version:n})),a)}async stats({schema:e}){return e?this.readSchemaIndex(e):this.readRegistryMetadata()}async sync(){let e={updated:new Date().toISOString(),hashes:[]},n=await this.listFilesRecursive(this.rootDir);for(let i of n)if(i!==`${this.rootDir}/schema-lock.json`&&i.match(new RegExp("/*.git*/"))===null){let r=String(await this.fsp.readFile(i,"utf8"));e.hashes.push([i,await U(r)])}await this.fsp.writeFile(`${this.rootDir}/schema-lock.json`,JSON.stringify(e),"utf8")}async migrations({name:e,version:n}){let i=await this.readSchemaIndex(e),r=n||i.version,a=[];for(let[s,o]of Object.entries(i.migrations)){let c=`${this.rootDir}/${e}/migrations/${o.hash}.json`;if(await this.fileExists(c)){let u=JSON.parse(String(await this.fsp.readFile(c,"utf8")));O(u.schemaVersion,r)<=0&&a.push(this.deserializeMigration(u))}}return a.sort((s,o)=>O(s.schemaVersion,o.schemaVersion))}async history({name:e}){let n=await this.readSchemaIndex(e),i=this.deserializeSchema(JSON.parse(String(await this.fsp.readFile(`${this.rootDir}/${e}/schema.json`,"utf8"))));return Promise.all(n.history.map(async r=>({...i,version:r.version,description:r.description,migrations:await this.migrations({name:e,version:r.version})})))}async processAndStoreMigrations(e,n){return Promise.all((n.migrations||[]).map(async i=>{let r={...i};if(i.transform?.forward){let o=i.transform;r.transform={forward:xe(o.forward),backward:xe(o.backward||(c=>c))}}let a=JSON.stringify(r),s=await U(a);return await this.fsp.writeFile(`${e}/migrations/${s}.json`,a,"utf8"),{id:i.id,hash:s,checksum:i.checksum}}))}serializeSchema(e){return JSON.stringify({...e,migrations:void 0,mock:e.mock?He(e.mock):null})}deserializeSchema(e){return e.mock&&(e.mock=ze(e.mock)),e}deserializeMigration(e){return e.transform?.forward&&(e.transform={forward:Te(e.transform.forward),backward:Te(e.transform.backward)}),e}async writeSchemaFile(e,n){let i=`${e}/schema.json`;return await this.fsp.writeFile(i,n,"utf8"),i}async updateIndex(e,n,i,r,a){let s=`${e}/index.json`,o=a==="create"?{schema:n.name,version:n.version,history:[],migrations:{}}:JSON.parse(String(await this.fsp.readFile(s,"utf8")));o.history.push({version:n.version,hash:i,date:new Date().toISOString(),description:n.description||(a==="create"?"Initial version":"Updated version"),migrations:r.map(c=>c.id),predicates:[],changelog:[]}),o.version=n.version,r.forEach(({id:c,hash:u,checksum:f})=>{o.migrations[c]={hash:u,checksum:f}}),await this.fsp.writeFile(s,JSON.stringify(o),"utf8")}async updateRegistryMetadata(e,n){let i=await this.readRegistryMetadata();i.schemas[e.name]={name:e.name,version:e.version,description:e.description||"",created:n==="create"?new Date().toISOString():i.schemas[e.name]?.created,updated:new Date().toISOString()},i.updated=new Date().toISOString(),await this.writeRegistryMetadata(i)}async readRegistryMetadata(){return JSON.parse(String(await this.fsp.readFile(`${this.rootDir}/registry.json`,"utf8")))}async writeRegistryMetadata(e){await this.fsp.writeFile(`${this.rootDir}/registry.json`,JSON.stringify(e),"utf8")}async readSchemaIndex(e){let n=`${this.rootDir}/${e}/index.json`;if(!await this.fileExists(n))throw new Error(`Schema ${e} not found`);return JSON.parse(String(await this.fsp.readFile(n,"utf8")))}async fileExists(e){try{return await this.fsp.stat(e),!0}catch{return!1}}async rmdirRecursive(e){let n=await this.fsp.readdir(e);for(let i of n){let r=`${e}/${i}`;(await this.fsp.stat(r)).isDirectory()?await this.rmdirRecursive(r):await this.fsp.unlink(r)}await this.fsp.rmdir(e)}async listFilesRecursive(e){let n=[],i=await this.fsp.readdir(e);for(let r of i){let a=`${e}/${r}`;(await this.fsp.stat(a)).isDirectory()?n.push(...await this.listFilesRecursive(a)):n.push(a)}return n}};var ke=class{locks=new Map;async acquire(e){let n,i=new Promise(a=>{n=a}),r=this.locks.get(e)||Promise.resolve();return this.locks.set(e,r.then(()=>i)),await r,n}async withLock(e,n){let i=await this.acquire(e);try{return await n()}finally{i()}}},Re=class{cache=new Map;ttl;constructor(e=3e4){this.ttl=e}get(e){let n=this.cache.get(e);return!n||Date.now()-n.timestamp>this.ttl?(this.cache.delete(e),null):n.schema}set(e,n){this.cache.set(e,{schema:n,timestamp:Date.now()})}invalidate(e){e?this.cache.delete(e):this.cache.clear()}};async function oe(t,e){try{return await t()}catch(n){throw console.error(`${e}:`,n),new Error(`${e}: ${n.message}`)}}async function ce(t,e,n,i,r){await i.init(),await A.default.init({fs:t,dir:e,defaultBranch:n}),await A.default.setConfig({fs:t,dir:e,path:"core.autocrlf",value:"false"}),await A.default.setConfig({fs:t,dir:e,path:"core.eol",value:"lf"}),await A.default.add({fs:t,dir:e,filepath:"."}),await A.default.commit({fs:t,dir:e,message:"chore: initial commit",author:r})}async function Ft(t="/registry",e={}){let n=e.mainBranch||"main",i=e.remote,r=e.createRemote??!1,a=e.author||{name:"SchemaRegistry",email:"system@example.com"},s=e.proxy?[e.proxy]:["https://cors.isomorphic-git.org"],o=0,c=new Y(t),u=c.fs,f=t.startsWith("/")?t:`/${t}`,b=new ke,p=new Re(e.cacheTtl);async function E(d,l){let w=o;do{let v=s[o];try{return await d(v)}catch(D){if(console.warn(`Failed with proxy ${v}: ${D.message}`),o=(o+1)%s.length,o===w)throw new Error(`${l}: All CORS proxies failed`)}}while(!0)}async function T(d,l="."){return oe(async()=>(await A.default.add({fs:u,dir:f,filepath:l}),(await A.default.statusMatrix({fs:u,dir:f})).some(([v,D,R])=>D!==R)?await A.default.commit({fs:u,dir:f,message:d,author:a}):null),"Failed to commit changes")}async function m(d,l,w){return oe(async()=>{if(await y(d))throw new Error(`Tag ${d} already exists`);await A.default.annotatedTag({fs:u,dir:f,ref:d,message:l,tagger:a,object:w})},`Failed to create tag ${d}`)}async function y(d){try{return(await A.default.listTags({fs:u,dir:f})).includes(d)}catch{return!1}}async function S(d){return(await A.default.listTags({fs:u,dir:f})).filter(v=>v.startsWith(d))}async function g(d){return oe(async()=>{let w=(await A.default.listTags({fs:u,dir:f})).filter(v=>v.startsWith(d));for(let v of w)await A.default.deleteTag({fs:u,dir:f,ref:v});return w},`Failed to delete tags with prefix ${d}`)}async function $(d){return oe(async()=>{await A.default.checkout({fs:u,dir:f,ref:d})},`Failed to checkout ${d}`)}async function h(d,{delete:l=!1,force:w=!1}={}){i&&await E(async v=>{await A.default.push({fs:u,http:Q.default,dir:f,ref:d,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:v,delete:l,force:w})},`Failed to push ${d}`)}async function C(d,l=!0){i&&await E(async w=>{try{await A.default.pull({fs:u,http:Q.default,dir:f,ref:d,author:a,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:w,fastForwardOnly:!0})}catch(v){if(!l)console.warn(`Fast-forward pull failed for ${d}, attempting regular pull`),await A.default.pull({fs:u,http:Q.default,dir:f,ref:d,author:a,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:w,fastForwardOnly:!1});else throw v}},`Failed to pull ${d}`)}if(i&&!await c.fileExists(f)){let d=f.slice(1);if(await i.exists({name:d}).catch(()=>!1))await E(async w=>{await A.default.clone({fs:u,http:Q.default,dir:f,url:i.authURL(),ref:n,singleBranch:!0,depth:1,onAuth:()=>i.credentials(),corsProxy:w})},"Failed to clone repository");else if(r)try{i=await i.create({name:d,private:!0}),await ce(u,f,n,c,a),await A.default.addRemote({fs:u,dir:f,remote:"origin",url:i.url()}),await h(n)}catch(w){console.error("Failed to create and push to remote repository:",w),await ce(u,f,n,c,a)}else await ce(u,f,n,c,a)}else await ce(u,f,n,c,a);return{async init(){return b.withLock("init",()=>c.init())},async create(d){let{name:l,version:w}=d.schema;return b.withLock(`schema:${l}`,async()=>{await $(n),await c.create(d);let v=await T(`feat: create schema ${l}`);v&&await m(`${l}-${w}`,`Version ${w}`,v),p.invalidate(l)})},async update(d){let{name:l,version:w}=d.schema;return b.withLock(`schema:${l}`,async()=>{await $(n),await c.update(d);let v=await T(`fix: update schema ${l}`);v&&await m(`${l}-${w}`,`Version ${w}`,v),p.invalidate(l)})},async delete(d){let{name:l}=d;return b.withLock(`schema:${l}`,async()=>{await $(n),await A.default.remove({fs:u,dir:f,filepath:l}),await c.delete(d);let w=await T(`chore: delete schema ${l}`),v=await S(`${l}-`);if(i&&w){await h(n);for(let D of v)await h(D,{delete:!0,force:!0}).catch(R=>console.warn(`Failed to delete remote tag ${D}: ${R.message}`))}await g(`${l}-`),p.invalidate(l)})},async list(){return b.withLock("list",()=>c.list())},async schema(d){let{name:l,version:w}=d,v=`${l}-${w||"latest"}-${d.migrations||!1}`,D=p.get(v);return D||b.withLock(`schema:${l}`,async()=>{if(w){let I=`${l}-${w}`;if(await y(I))await $(I);else throw new Error(`Version ${w} of schema ${l} not found`)}else await $(n);let R=await c.schema(d);return p.set(v,R),R})},async stats(d){return b.withLock("stats",()=>c.stats(d))},async sync(){return b.withLock("sync",async()=>{if(await $(n),await c.sync(),await T("chore: sync local changes"),i){await C(n,!1),await h(n);let d=await A.default.listTags({fs:u,dir:f});for(let w of d)await h(w,{force:!0});let l=await A.default.listTags({fs:u,dir:f});for(let w of l)d.includes(w)||await h(w,{delete:!0})}p.invalidate()})},async migrations(d){let{name:l,version:w}=d,v=`migrations-${l}-${w||"latest"}`,D=p.get(v);return D||b.withLock(`migrations:${l}`,async()=>{if(w){let I=`${l}-${w}`;if(await y(I))await $(I);else throw new Error(`Version ${w} of schema ${l} not found`)}else await $(n);let R=await c.migrations(d);return p.set(v,R),R})},async history(d){let{name:l}=d,w=`history-${l}`,v=p.get(w);return v||b.withLock(`history:${l}`,async()=>{await $(n);let D=await c.history(d);return p.set(w,D),D})}}}function M(t){return"predicate"in t}function Pt(t,e=!0,n=!0){let i="",r=n?"export ":"",a=new Map,s=new Map,o=(T,m=[])=>{if(!e||!T&&!m.length)return"";let y=T?[T]:[];return m.forEach(S=>y.push(S)),`/**
2
- * ${y.join(`
1
+ "use strict";var tt=Object.create;var Z=Object.defineProperty;var nt=Object.getOwnPropertyDescriptor;var it=Object.getOwnPropertyNames;var st=Object.getPrototypeOf,at=Object.prototype.hasOwnProperty;var rt=(t,e)=>{for(var n in e)Z(t,n,{get:e[n],enumerable:!0})},Ie=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of it(e))!at.call(t,a)&&a!==n&&Z(t,a,{get:()=>e[a],enumerable:!(i=nt(e,a))||i.enumerable});return t};var K=(t,e,n)=>(n=t!=null?tt(st(t)):{},Ie(e||!t||!t.__esModule?Z(n,"default",{value:t,enumerable:!0}):n,t)),ot=t=>Ie(Z({},"__esModule",{value:!0}),t);var Vt={};rt(Vt,{JsonPatchError:()=>M,MigrationEngine:()=>xe,MigrationError:()=>A,MigrationErrorCode:()=>Be,SchemaRegistry:()=>Y,applyPatch:()=>ie,calculateNextVersion:()=>Te,compareSemanticVersions:()=>j,createGitSchemaRegistry:()=>Ot,createPatch:()=>ut,createSchemaMigrationHelper:()=>Ke,createStandardSchemaValidator:()=>Oe,deepMerge:()=>ye,docgen:()=>Nt,extractInputFieldGroups:()=>Ft,formResolver:()=>ht,generateSHA256Hash:()=>L,normalizePath:()=>Fe,schemaChangeToPatch:()=>he,schemaDefaults:()=>Pt,schemaToTypes:()=>jt,serializeParams:()=>U,sortSemanticVars:()=>At,validate:()=>wt,validateMigration:()=>ve,validateSchemaChange:()=>Ee,validateSchemaDefinition:()=>z});module.exports=ot(Vt);var It=require("@asaidimu/events");var Rt=require("@asaidimu/events"),re=require("@asaidimu/query");var M=class extends Error{constructor(n,i){super(n);this.operation=i;this.name="JsonPatchError"}};function te(t){let e=Fe(t);return e===""?[]:e.substring(1).split("/").map(ct)}function Fe(t){return t===""||t==="/"?"":t.startsWith("/")?"/"+t.substring(1).split("/").map(ee).join("/"):"/"+t.split(".").map(ee).join("/")}function ee(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function ct(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}var N=new Map;function ne(t,e){let n=t;for(let i of e){if(n===null||typeof n!="object")throw new M(`Invalid path - parent not found at ${i}`);if(Array.isArray(n)){let a=i==="-"?n.length:parseInt(i);if(isNaN(a)||a<0||a>n.length)throw new M(`Invalid array index: ${i}`);n=n[a]}else{if(!n.hasOwnProperty(i))throw new M(`Property ${i} not found`);n=n[i]}}return n}function fe(t,e){let n=N.get(e)||te(e);if(N.set(e,n),n.length===0)return t;let i=ne(t,n.slice(0,-1)),a=n[n.length-1];if(Array.isArray(i)){let r=parseInt(a);if(isNaN(r)||r<0||r>=i.length)throw new M(`Invalid array index: ${a}`);return i[r]}return i[a]}function dt(t,e,n){let i=N.get(e)||te(e);N.set(e,i);let a=ne(t,i.slice(0,-1)),r=i[i.length-1];return Array.isArray(a)?a.splice(0,a.length,...a.filter(s=>s!==n)):a[r]===n&&delete a[r],t}function X(t,e,n){let i=N.get(e)||te(e);if(N.set(e,i),i.length===0)return n;let a=i.slice(0,-1),r=i[i.length-1],s=ne(t,a);if(Array.isArray(s))if(r==="-")s.push(n);else{let o=parseInt(r);if(o<0||o>s.length)throw new M(`Invalid array index: ${r}`);s.splice(o,0,n)}else s[r]=n;return t}function le(t,e){let n=N.get(e)||te(e);if(N.set(e,n),n.length===0)return;let i=ne(t,n.slice(0,-1)),a=n[n.length-1];if(Array.isArray(i)){let r=parseInt(a);i.splice(r,1)}else delete i[a];return t}function ie(t,e){let n=JSON.parse(JSON.stringify(t));for(let i of e)try{switch(i.op){case"add":n=X(n,i.path,i.value);break;case"remove":n=le(n,i.path);break;case"removeValue":n=dt(n,i.path,i.value);break;case"replace":n=X(le(n,i.path),i.path,i.value);break;case"copy":{let a=fe(n,i.from);n=X(n,i.path,JSON.parse(JSON.stringify(a)));break}case"move":{let a=fe(n,i.from);n=X(n,i.path,a),n=le(n,i.from);break}case"test":{let a=fe(n,i.path);if(JSON.stringify(a)!==JSON.stringify(i.value))throw new M("Test operation failed");break}default:throw new M(`Unsupported operation: ${i.op}`)}}catch(a){throw a instanceof M&&(a.operation=i),a}return n}function ut(t,e){let n=[];return me(t,e,"",n),n}function me(t,e,n,i){if(t!==e){if(typeof t!=typeof e||Array.isArray(t)!==Array.isArray(e)){i.push({op:"replace",path:n,value:e});return}typeof t=="object"&&t!==null?Array.isArray(t)?ft(t,e,n,i):lt(t,e,n,i):t!==e&&i.push({op:"replace",path:n,value:e})}}function ft(t,e,n,i){let a=Math.max(t.length,e.length);for(let r=0;r<a;r++){let s=`${n}/${r}`;r>=t.length?i.push({op:"add",path:`${n}/-`,value:e[r]}):r>=e.length?i.push({op:"remove",path:s}):me(t[r],e[r],s,i)}}function lt(t,e,n,i){let a=new Set,r=Object.keys(t),s=Object.keys(e);for(let o of r){let c=ee(o),u=n?`${n}/${c}`:`/${c}`;e.hasOwnProperty(o)?(me(t[o],e[o],u,i),a.add(o)):i.push({op:"remove",path:u})}for(let o of s)if(!a.has(o)){let c=ee(o),u=n?`${n}/${c}`:`/${c}`;i.push({op:"add",path:u,value:e[o]})}}function he(t,e){let n=[];switch(t.type){case"addField":n.push({op:"add",path:`/fields/${t.id}`,value:t.definition});break;case"removeField":n.push({op:"remove",path:`/fields/${t.id}`});break;case"modifyField":{let i=`/fields/${t.id}`;Object.entries(t.changes).forEach(([a,r])=>{typeof r=="object"&&r!==null&&!Array.isArray(r)?n.push({op:"replace",path:`${i}/${a}`,value:r}):n.push({op:"replace",path:`${i}/${a}`,value:r})});break}case"deprecateField":n.push({op:"add",path:`/fields/${t.id}/deprecated`,value:!0});break;case"addIndex":e.indexes||n.push({op:"add",path:"/indexes",value:[]}),n.push({op:"add",path:"/indexes/-",value:t.definition});break;case"removeIndex":{let i=e.indexes?.findIndex(a=>a.name===t.name);i!==void 0&&i>=0&&n.push({op:"remove",path:`/indexes/${i}`});break}case"modifyIndex":{let i=e.indexes?.findIndex(a=>a.name===t.name);i!==void 0&&i>=0&&Object.entries(t.changes).forEach(([a,r])=>{n.push({op:"replace",path:`/indexes/${i}/${a}`,value:r})});break}case"addConstraint":e.constraints||n.push({op:"add",path:"/constraints",value:[]}),Array.isArray(t.constraint)?t.constraint.forEach(i=>{n.push({op:"add",path:"/constraints/-",value:i})}):n.push({op:"add",path:"/constraints/-",value:t.constraint});break;case"removeConstraint":{let i=e.constraints?.findIndex(a=>Array.isArray(a)?a.some(r=>r.name===t.name):a.name===t.name);i!==void 0&&i>=0&&n.push({op:"remove",path:`/constraints/${i}`});break}case"modifyConstraint":{let i=mt(e,t.name);i&&Object.entries(t.changes).forEach(([a,r])=>{n.push({op:"replace",path:`${i}/${a}`,value:r})});break}}return n}function mt(t,e){if(!t.constraints)return null;for(let n=0;n<t.constraints.length;n++){let i=t.constraints[n];if(i.name===e)return`/constraints/${n}`;if(Pe(i)){let a=Me(i.rules,e);if(a)return`/constraints/${n}${a}`}}return null}function Pe(t){return t&&"operator"in t&&"rules"in t}function Me(t,e){for(let n=0;n<t.length;n++){let i=t[n];if("name"in i&&i.name===e)return`/rules/${n}`;if(Pe(i)){let a=Me(i.rules,e);if(a)return`/rules/${n}${a}`}}return null}function ye(t,e){let n={...t};return pe(t)&&pe(e)&&Object.keys(e).forEach(i=>{pe(e[i])?i in t?n[i]=ye(t[i],e[i]):Object.assign(n,{[i]:e[i]}):Object.assign(n,{[i]:e[i]})}),n}function pe(t){return t&&typeof t=="object"&&!Array.isArray(t)}var ge=new Map;function U(t){return t instanceof RegExp?t.toString().slice(1,-1):JSON.stringify(t)}function Oe(t,e){let n=o=>({value:o}),i=o=>({issues:o}),a=(o,c,u,f)=>{switch(c){case"string":return typeof o!="string"?[{message:`Expected string, got ${typeof o}`,path:u}]:[];case"number":return typeof o!="number"||isNaN(o)?[{message:`Expected number, got ${typeof o}`,path:u}]:[];case"boolean":return typeof o!="boolean"?[{message:`Expected boolean, got ${typeof o}`,path:u}]:[];case"array":return Array.isArray(o)?[]:[{message:`Expected array, got ${typeof o}`,path:u}];case"set":return!Array.isArray(o)||new Set(o).size!==o.length?[{message:`Expected unique array, got ${typeof o}`,path:u}]:[];case"enum":return f?.values?f.values.includes(o)?[]:[{message:`Expected one of ${JSON.stringify(f.values)}, got ${o}`,path:u}]:[{message:"Enum type requires 'values' definition",path:u}];case"object":return typeof o!="object"||o===null||Array.isArray(o)?[{message:`Expected object, got ${typeof o}`,path:u}]:[];case"record":return typeof o!="object"||o===null||Array.isArray(o)?[{message:`Expected record (object), got ${typeof o}`,path:u}]:[];case"union":return typeof o!="object"||o===null||Array.isArray(o)?[{message:`Expected union (object), got ${typeof o}`,path:u}]:[];case"dynamic":return console.warn("Deprecated: 'dynamic' type used. Use 'record' instead."),typeof o!="object"||o===null||Array.isArray(o)?[{message:`Expected record (object), got ${typeof o}`,path:u}]:[];default:return[{message:`Unknown type '${c}'`,path:u}]}};function r(o,c,u,f,b){let p=[],v=o.rules.map((m,g)=>{let y=[...f,`rules[${g}]`],$=`${m.name}@${y.join(".")}`;if("rules"in m){if(b.has($))return!0;b.add($);let h=r(m,c,u,y,b);return p.push(...h),b.delete($),h.length===0}else{let h=u[m.predicate];if(!h)return p.push({message:`Predicate '${m.predicate}' not found`,path:y}),!1;let E=`${m.predicate}:${JSON.stringify(m.parameters)}:${JSON.stringify(c[m.field])}`;if(ge.has(E)){let d=ge.get(E);return d||p.push({message:m.errorMessage||`Constraint '${m.name}' failed with params ${U(m.parameters)}`,path:y}),d}let S=h({data:c,field:m.field,arguments:m.parameters});return ge.set(E,S),S||p.push({message:m.errorMessage||`Constraint '${m.name}' failed with params ${U(m.parameters)}`,path:y}),S}});return(()=>{switch(o.operator){case"and":return v.every(m=>m);case"or":return v.some(m=>m);case"not":return!v.every(m=>m);case"nor":return!v.some(m=>m);case"xor":return v.filter(m=>m).length===1}})()||p.push({message:`Constraint group '${o.name}' failed`,path:f}),p}function s(o,c,u,f,b,p=new Set){let v=[];if("type"in c&&!("fields"in c)){let g=f.length>0?o[f[f.length-1]]:o;return v.push(...a(g,c.type,f,{values:c.values})),c.constraints&&c.constraints.forEach((y,$)=>{if("rules"in y)v.push(...r(y,{value:g},u,[...f,`constraints[${$}]`],p));else{let h=u[y.predicate];h?h({data:{value:g},field:"value",arguments:y.parameters})||v.push({message:y.errorMessage||`Constraint '${y.name}' failed with params ${U(y.parameters)}`,path:[...f,`constraints[${$}]`]}):v.push({message:`Predicate '${y.predicate}' not found`,path:[...f,`constraints[${$}]`]})}}),v}let C={};if("concrete"in c)if(c.concrete===!0||!Array.isArray(c.fields))C=c.fields;else{let g=c.fields,y=g.find(h=>!h.when);y&&Object.assign(C,y.fields);let $=g.find(h=>h.when&&o[h.when.field]!==void 0&&o[h.when.field]===h.when.value);if($)Object.assign(C,$.fields);else if(!y)return v.push({message:"No matching field set found for discriminated schema",path:f}),v}else C=c.fields;let m=new Set(Object.values(C).map(g=>g.name));Object.entries(C).forEach(([g,y])=>{let $=[...f,y.name],h=Object.hasOwnProperty.call(o,y.name)?o[y.name]:y.default!==void 0?y.default:void 0;y.required&&h==null&&v.push({message:`Field '${y.name}' is required`,path:$});let E=y.schema||y.nestedSchema;if(y.type==="object"&&E&&!Array.isArray(E)){let S=b[E.id];if(S)if(p.has(E.id))v.push({message:`Circular reference detected at '${E.id}'`,path:$});else{p.add(E.id);let d=h&&typeof h=="object"&&!Array.isArray(h)?h:{};v.push(...s(d,S,u,$,b,p)),E.constraints?.forEach((l,w)=>{if("rules"in l)v.push(...r(l,d,u,[...$,`constraints[${w}]`],p));else{let T=u[l.predicate];T?T({data:d,field:void 0,arguments:l.parameters})||v.push({message:l.errorMessage||`Constraint '${l.name}' failed with params ${U(l.parameters)}`,path:[...$,`constraints[${w}]`]}):v.push({message:`Predicate '${l.predicate}' not found`,path:[...$,`constraints[${w}]`]})}}),p.delete(E.id)}else v.push({message:`Nested schema '${E.id}' not found`,path:$})}if(y.type==="union"&&E&&Array.isArray(E)){let S=!1,d=[];E.forEach((l,w)=>{let T=b[l.id];if(T)if(p.has(l.id))d.push({message:`Circular reference detected at '${l.id}'`,path:[...$,w.toString()]});else{p.add(l.id);let D=h&&typeof h=="object"&&!Array.isArray(h)?h:{},k=s(D,T,u,$,b,new Set(p));k.length===0&&h!==void 0?(S=!0,l.constraints?.forEach((R,F)=>{if("rules"in R){let P=r(R,D,u,[...$,`constraints[${F}]`],p);P.length>0&&(S=!1,d.push(...P))}else{let P=u[R.predicate];P&&!P({data:D,field:void 0,arguments:R.parameters})&&(S=!1,d.push({message:R.errorMessage||`Constraint '${R.name}' failed`,path:[...$,`constraints[${F}]`]}))}})):h===void 0&&d.push(...k.filter(R=>R.message.includes("is required"))),p.delete(l.id)}else d.push({message:`Nested schema '${l.id}' not found`,path:[...$,w.toString()]})}),!S&&h!==void 0?(v.push({message:"Value does not match any union schema",path:$}),v.push(...d)):h===void 0&&v.push(...d)}h!==void 0&&(v.push(...a(h,y.type,$,{values:y.values})),(y.type==="array"||y.type==="set")&&Array.isArray(h)&&(y.constraints?.forEach((S,d)=>{let l=u[S.predicate];l&&!l({data:{[y.name]:h},field:y.name,arguments:S.parameters})&&v.push({message:S.errorMessage||`Constraint '${S.name}' failed for field '${y.name}'`,path:[...$,`constraints[${d}]`]})}),y.itemsType&&h.forEach((S,d)=>v.push(...a(S,y.itemsType,[...$,d.toString()]))),E&&!Array.isArray(E)&&(b[E.id]?h.forEach((S,d)=>{typeof S=="object"&&S!==null&&(p.has(E.id)?v.push({message:`Circular reference detected at '${E.id}'`,path:[...$,d.toString()]}):(p.add(E.id),v.push(...s(S,b[E.id],u,[...$,d.toString()],b,p)),p.delete(E.id)))}):v.push({message:`Nested schema '${E.id}' not found`,path:$}))),y.constraints?.forEach((S,d)=>{if("rules"in S)v.push(...r(S,o,u,[...$,`constraints[${d}]`],p));else{let l=u[S.predicate];l?l({data:o,field:y.name,arguments:S.parameters})||v.push({message:S.errorMessage||`Constraint '${S.name}' failed for field '${y.name}' with params ${U(S.parameters)}`,path:[...$,`constraints[${d}]`]}):v.push({message:`Predicate '${S.predicate}' not found`,path:[...$,`constraints[${d}]`]})}}))});for(let g in o)Object.hasOwnProperty.call(o,g)&&!m.has(g)&&v.push({message:`Unexpected field '${g}'`,path:[...f,g]});return c.constraints?.forEach((g,y)=>{if("rules"in g)v.push(...r(g,o,u,[...f,`constraints[${y}]`],p));else{let $=u[g.predicate];$?$({data:o,field:g.field,arguments:g.parameters})||v.push({message:g.errorMessage||`Constraint '${g.name}' failed with params ${U(g.parameters)}`,path:[...f,`constraints[${y}]`]}):v.push({message:`Predicate '${g.predicate}' not found`,path:[...f,`constraints[${y}]`]})}}),v}return t.version!=="1.0.0"&&console.warn(`Schema version '${t.version}' may require migrations. Validator assumes version 1.0.0.`),{"~standard":{version:1,vendor:"@asaidimu/anansi",validate:o=>{if(typeof o!="object"||o===null)return i([{message:"Input must be an object",path:[]}]);let c=o,u=s(c,t,e,[],t.nestedSchemas||{});return u.length>0?i(u):n(c)},types:{input:{},output:{}}}}}function ht(t){return async e=>{let n=t.validate(e);if(n instanceof Promise&&(n=await n),"value"in n)return{values:n.value,errors:{}};let i={};return n.issues.forEach(a=>{if(!a.path)return;let r=a.path.filter(o=>!o.includes("constraints")),s=i;for(let o=0;o<r.length;o++){let c=r[o];o===r.length-1?s[c]={type:"validation",message:a.message}:(s[c]=s[c]||{},s=s[c])}}),{values:{},errors:i}}}var H=class extends Error{constructor(n,i){super(n);this.errors=i;this.name="SchemaValidationError"}};var we=t=>({value:t}),J=t=>({issues:t}),x=(t,e,n=!0)=>t===void 0&&!n?[]:typeof t!="string"||t.trim()===""?[{message:"Must be a non-empty string",path:[e]}]:[],se=(t,e)=>{let n=["string","number","boolean","array","set","enum","object","record","union","dynamic"];return typeof t!="string"||!n.includes(t)?[{message:`Must be one of ${n.join(", ")}`,path:[e]}]:t==="dynamic"?[{message:"Field type 'dynamic' is deprecated; use 'record' instead",path:[e]}]:[]},pt=(t,e)=>{let n=["normal","unique","btree","hash","spatial","fulltext","gi","expression","composite"];return typeof t!="string"||!n.includes(t)?[{message:`Must be one of ${n.join(", ")}`,path:[e]}]:[]},je=(t,e)=>{let n=["and","or","not","nor","xor"];return typeof t!="string"||!n.includes(t)?[{message:`Must be one of ${n.join(", ")}`,path:[e]}]:[]},W=(t,e,n=!1)=>t===void 0&&!n?[]:typeof t!="boolean"?[{message:"Must be a boolean",path:[e]}]:[],yt=(t,e,n)=>t===void 0?[]:[],Se=(t,e,n)=>{let i=[],a=["predicate","name"],r=["type","predicate","field","parameters","name","description","errorMessage"],s=t;return a.forEach(o=>{s[o]===void 0&&i.push({message:`${o} is required`,path:[`${n}.${o}`]})}),Object.keys(s).forEach(o=>{r.includes(o)||i.push({message:`Unknown property ${o}`,path:[`${n}.${o}`]})}),i.push(...x(t.name,`${n}.name`)),i.push(...x(t.predicate,`${n}.predicate`)),t.field!==void 0&&typeof t.field!="string"&&i.push({message:"Field must be a string",path:[`${n}.field`]}),t.parameters!==void 0&&i.push(...yt(t.parameters,e,`${n}.parameters`)),i.push(...x(t.description,`${n}.description`,!1)),i.push(...x(t.errorMessage,`${n}.errorMessage`,!1)),i},be=(t,e,n)=>{let i=[],a=["name","operator","rules"],r=a,s=t;return a.forEach(o=>{s[o]===void 0&&i.push({message:`${o} is required`,path:[`${n}.${o}`]})}),Object.keys(s).forEach(o=>{r.includes(o)||i.push({message:`Unknown property ${o}`,path:[`${n}.${o}`]})}),i.push(...x(t.name,`${n}.name`)),i.push(...je(t.operator,`${n}.operator`)),!Array.isArray(t.rules)||t.rules.length===0?i.push({message:"Rules must be a non-empty array",path:[`${n}.rules`]}):t.rules.forEach((o,c)=>{"rules"in o?i.push(...be(o,e,`${n}.rules[${c}]`)):i.push(...Se(o,e,`${n}.rules[${c}]`))}),i},V=(t,e,n)=>{if(!Array.isArray(t))return[{message:"Must be an array",path:[n]}];let i=[];return t.forEach((a,r)=>{"rules"in a?i.push(...be(a,e,`${n}[${r}]`)):i.push(...Se(a,e,`${n}[${r}]`))}),i},Ne=(t,e)=>{let n=[],i=["operator","field"],a=["operator","field","value","conditions"],r=t;return i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:`Unknown property ${s}`,path:[`${e}.${s}`]})}),n.push(...je(t.operator,`${e}.operator`)),n.push(...x(t.field,`${e}.field`)),t.conditions!==void 0&&(Array.isArray(t.conditions)?t.conditions.forEach((s,o)=>n.push(...Ne(s,`${e}.conditions[${o}]`))):n.push({message:"Conditions must be an array",path:[`${e}.conditions`]})),n},Ve=(t,e)=>{let n=[],i=["fields","type","name"],a=["fields","type","unique","partial","description","order","name"],r=t;return i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:`Unknown property ${s}`,path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`)),n.push(...pt(t.type,`${e}.type`)),(!Array.isArray(t.fields)||t.fields.length===0||!t.fields.every(s=>typeof s=="string"))&&n.push({message:"Fields must be a non-empty array of strings",path:[`${e}.fields`]}),n.push(...W(t.unique,`${e}.unique`,!1)),t.partial&&n.push(...Ne(t.partial,`${e}.partial`)),n.push(...x(t.description,`${e}.description`,!1)),t.order!==void 0&&!["asc","desc"].includes(t.order)&&n.push({message:"Order must be 'asc' or 'desc'",path:[`${e}.order`]}),n},G=(t,e)=>{if(t===void 0)return[];if(!Array.isArray(t))return[{message:"Must be an array",path:[e]}];let n=[];return t.forEach((i,a)=>n.push(...Ve(i,`${e}[${a}]`))),n},qe=(t,e,n,i,a)=>{let r=[];return t===void 0?[]:(n==="union"&&Array.isArray(t)?(t.length===0&&r.push({message:"Schema array must not be empty for union type",path:[e]}),t.forEach((s,o)=>{let c=`${e}[${o}]`;r.push(...x(s.id,`${c}.id`)),i.includes(s.id)||r.push({message:`Schema ID '${s.id}' must match a nestedSchemas key`,path:[`${c}.id`]}),s.constraints&&r.push(...V(s.constraints,"dynamic",`${c}.constraints`)),s.indexes&&r.push(...G(s.indexes,`${c}.indexes`))})):(n==="object"||n==="array"&&a==="object")&&!Array.isArray(t)?(r.push(...x(t.id,`${e}.id`)),i.includes(t.id)||r.push({message:`Schema ID '${t.id}' must match a nestedSchemas key`,path:[`${e}.id`]}),t.constraints&&r.push(...V(t.constraints,"dynamic",`${e}.constraints`)),t.indexes&&r.push(...G(t.indexes,`${e}.indexes`))):r.push({message:"Schema is only valid for 'object', 'union', or 'array' with itemsType 'object'",path:[e]}),r)},Ue=(t,e,n)=>{if(t===void 0)return[];switch(e){case"string":if(typeof t!="string")return[{message:"Default must be a string",path:[n]}];break;case"number":if(typeof t!="number")return[{message:"Default must be a number",path:[n]}];break;case"boolean":if(typeof t!="boolean")return[{message:"Default must be a boolean",path:[n]}];break;case"array":case"set":if(!Array.isArray(t))return[{message:"Default must be an array",path:[n]}];break;case"enum":if(!Array.isArray(t)||!t.every(i=>typeof i=="string"||typeof i=="number"))return[{message:"Default must be an array of strings or numbers",path:[n]}];break;case"object":case"record":if(typeof t!="object"||t===null)return[{message:"Default must be an object",path:[n]}];break;case"union":case"dynamic":return[]}return[]},Le=(t,e)=>t===void 0?[]:typeof t!="object"||t===null?[{message:"Hint must be an object",path:[e]}]:"input"in t&&typeof t.input!="object"?[{message:"Hint.input must be an object",path:[`${e}.input`]}]:[],ae=(t,e,n)=>{let i=[],a=["name","type"],r=["name","type","required","constraints","default","values","schema","itemsType","nestedSchema","deprecated","reference","description","unique","hint"],s=t;if(a.forEach(o=>{s[o]===void 0&&i.push({message:`${o} is required`,path:[`${e}.${o}`]})}),Object.keys(s).forEach(o=>{r.includes(o)||i.push({message:`Unknown property ${o}`,path:[`${e}.${o}`]})}),i.push(...x(t.name,`${e}.name`)),i.push(...se(t.type,`${e}.type`)),i.push(...W(t.required,`${e}.required`,!1)),t.constraints&&i.push(...V(t.constraints,t.type,`${e}.constraints`)),i.push(...Ue(t.default,t.type,`${e}.default`)),t.values!==void 0&&(t.type==="enum"?(!Array.isArray(t.values)||t.values.length===0||!t.values.every(o=>typeof o=="string"||typeof o=="number"))&&i.push({message:"Values must be a non-empty array of strings or numbers",path:[`${e}.values`]}):i.push({message:"Values is only valid for 'enum' type",path:[`${e}.values`]})),t.schema!==void 0&&i.push(...qe(t.schema,`${e}.schema`,t.type,n,t.itemsType)),t.itemsType&&i.push(...se(t.itemsType,`${e}.itemsType`)),t.nestedSchema){i.push({message:"nestedSchema is deprecated; use schema instead",path:[`${e}.nestedSchema`]});let o=["id"],c=["id","constraints","indexes"],u=t.nestedSchema;o.forEach(f=>{u[f]===void 0&&i.push({message:`${f} is required`,path:[`${e}.nestedSchema.${f}`]})}),Object.keys(u).forEach(f=>{c.includes(f)||i.push({message:`Unknown property ${f}`,path:[`${e}.nestedSchema.${f}`]})}),i.push(...x(t.nestedSchema.id,`${e}.nestedSchema.id`)),n.includes(t.nestedSchema.id)||i.push({message:`nestedSchema.id '${t.nestedSchema.id}' must match a nestedSchemas key`,path:[`${e}.nestedSchema.id`]}),t.nestedSchema.constraints&&i.push(...V(t.nestedSchema.constraints,"dynamic",`${e}.nestedSchema.constraints`)),t.nestedSchema.indexes&&i.push(...G(t.nestedSchema.indexes,`${e}.nestedSchema.indexes`))}if(i.push(...W(t.deprecated,`${e}.deprecated`,!1)),t.reference){i.push({message:"reference is deprecated",path:[`${e}.reference`]});let o=["schema","field"],c=["schema","field"],u=t.reference;o.forEach(f=>{u[f]===void 0&&i.push({message:`${f} is required`,path:[`${e}.reference.${f}`]})}),Object.keys(u).forEach(f=>{c.includes(f)||i.push({message:`Unknown property ${f}`,path:[`${e}.reference.${f}`]})}),i.push(...x(t.reference.schema,`${e}.reference.schema`)),i.push(...x(t.reference.field,`${e}.reference.field`))}return i.push(...x(t.description,`${e}.description`,!1)),i.push(...W(t.unique,`${e}.unique`,!1)),t.hint&&i.push(...Le(t.hint,`${e}.hint`)),i},_e=(t,e,n)=>{let i=[];if("type"in t&&["string","number","boolean","array","set","enum","record"].includes(t.type)){let r=["name","type"],s=["name","type","default","schema","itemsType","constraints","description","metadata"],o=t;r.forEach(c=>{o[c]===void 0&&i.push({message:`${c} is required`,path:[`${e}.${c}`]})}),Object.keys(o).forEach(c=>{s.includes(c)||i.push({message:`Unknown property ${c}`,path:[`${e}.${c}`]})}),i.push(...x(t.name,`${e}.name`)),i.push(...se(t.type,`${e}.type`)),i.push(...Ue(t.default,t.type,`${e}.default`)),t.schema&&i.push(...qe(t.schema,`${e}.schema`,t.type,n,t.itemsType)),t.itemsType&&i.push(...se(t.itemsType,`${e}.itemsType`)),t.constraints&&i.push(...V(t.constraints,t.type,`${e}.constraints`)),i.push(...x(t.description,`${e}.description`,!1)),t.metadata!==void 0&&(typeof t.metadata!="object"||t.metadata===null)&&i.push({message:"Metadata must be an object",path:[`${e}.metadata`]})}else{let r=["name"],s=["name","description","concrete","fields","indexes","constraints","metadata"],o=t;r.forEach(c=>{o[c]===void 0&&i.push({message:`${c} is required`,path:[`${e}.${c}`]})}),Object.keys(o).forEach(c=>{s.includes(c)||i.push({message:`Unknown property ${c}`,path:[`${e}.${c}`]})}),i.push(...x(t.name,`${e}.name`)),i.push(...W(o.concrete,`${e}.concrete`,!1)),o.concrete&&Array.isArray(o.fields)&&i.push({message:"Fields must be an object when concrete is true",path:[`${e}.fields`]}),Array.isArray(o.fields)?(o.fields.length===0&&i.push({message:"Fields array must not be empty",path:[`${e}.fields`]}),o.fields.forEach((c,u)=>{let f=`${e}.fields[${u}]`;if(typeof c!="object"||c===null||!("fields"in c))i.push({message:"Each variant must have a 'fields' property",path:[f]});else{let b=c.fields;typeof b!="object"||b===null?i.push({message:"Fields must be a non-empty object",path:[`${f}.fields`]}):Object.entries(b).forEach(([p,v])=>{i.push(...ae(v,`${f}.fields.${p}`,n))}),c.when!==void 0&&(typeof c.when!="object"||c.when===null?i.push({message:"When must be an object",path:[`${f}.when`]}):i.push(...x(c.when.field,`${f}.when.field`)))}})):o.fields!==void 0&&(typeof o.fields!="object"||o.fields===null?i.push({message:"Fields must be a non-empty object",path:[`${e}.fields`]}):Object.entries(o.fields).forEach(([c,u])=>{i.push(...ae(u,`${e}.fields.${c}`,n))})),i.push(...x(t.description,`${e}.description`,!1)),t.indexes&&i.push(...G(t.indexes,`${e}.indexes`)),t.constraints&&i.push(...V(o.constraints,"dynamic",`${e}.constraints`)),t.metadata!==void 0&&(typeof t.metadata!="object"||t.metadata===null)&&i.push({message:"Metadata must be an object",path:[`${e}.metadata`]})}return i},gt=t=>{if(typeof t!="object"||t===null)return J([{message:"Schema must be an object",path:[]}]);let e=t,n=[],i=["name","version","fields"],a=["name","version","description","fields","nestedSchemas","indexes","constraints","metadata","dependencies","migrations","mock","hint"],r=e;if(i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[s]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:`Unknown property ${s}`,path:[s]})}),n.push(...x(e.name,"name")),n.push(...x(e.version,"version")),typeof e.fields!="object"||e.fields===null)n.push({message:"Fields must be a non-empty object",path:["fields"]});else{let s=Object.keys(e.nestedSchemas||{});Object.entries(e.fields).forEach(([o,c])=>{n.push(...ae(c,`fields.${o}`,s))})}if(e.nestedSchemas!==void 0)if(typeof e.nestedSchemas!="object"||e.nestedSchemas===null)n.push({message:"NestedSchemas must be an object",path:["nestedSchemas"]});else{let s=Object.keys(e.nestedSchemas);Object.entries(e.nestedSchemas).forEach(([o,c])=>n.push(..._e(c,`nestedSchemas.${o}`,s)))}return n.push(...x(e.description,"description",!1)),e.indexes&&n.push(...G(e.indexes,"indexes")),e.constraints&&n.push(...V(e.constraints,"dynamic","constraints")),e.metadata!==void 0&&(typeof e.metadata!="object"||e.metadata===null)&&n.push({message:"Metadata must be an object",path:["metadata"]}),e.dependencies!==void 0&&(n.push({message:"dependencies is deprecated; use DomainModel instead",path:["dependencies"]}),(!Array.isArray(e.dependencies)||!e.dependencies.every(s=>typeof s=="string"))&&n.push({message:"Dependencies must be an array of strings",path:["dependencies"]})),e.migrations!==void 0&&(Array.isArray(e.migrations)?e.migrations.forEach((s,o)=>n.push(...He(s,`migrations[${o}]`))):n.push({message:"Migrations must be an array",path:["migrations"]})),e.mock!==void 0&&typeof e.mock!="function"&&n.push({message:"Mock must be a function",path:["mock"]}),e.hint&&n.push(...Le(e.hint,"hint")),n.length>0?J(n):we(e)},$e=(t,e)=>{let n=[];switch(t.type||n.push({message:"type is required",path:[`${e}.type`]}),t.type){case"modifyProperty":{let i=["type","id","changes"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:`Unknown property ${s}`,path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`)),(t.changes===void 0||typeof t.changes!="object")&&n.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addField":{let i=["type","id","definition"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:`Unknown property ${s}`,path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`)),n.push(...ae(t.definition,`${e}.definition`,[]));break}case"removeField":case"deprecateField":{let i=["type","id"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:`Unknown property ${s}`,path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`));break}case"modifyField":{let i=["type","id","changes"],a=["type","id","changes","nestedSchemaChanges"],r=t;if(i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:`Unknown property ${s}`,path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`)),typeof t.changes!="object"&&n.push({message:"Changes must be an object",path:[`${e}.changes`]}),t.nestedSchemaChanges){let s=["id","constraints","indexes"],o=t.nestedSchemaChanges;Object.keys(o).forEach(c=>{s.includes(c)||n.push({message:`Unknown property ${c}`,path:[`${e}.nestedSchemaChanges.${c}`]})}),n.push(...x(o.id,`${e}.nestedSchemaChanges.id`,!1)),o.constraints&&n.push(...V(o.constraints,"dynamic",`${e}.nestedSchemaChanges.constraints`)),o.indexes&&n.push(...G(o.indexes,`${e}.nestedSchemaChanges.indexes`))}break}case"addIndex":{let i=["type","definition"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:`Unknown property ${s}`,path:[`${e}.${s}`]})}),n.push(...Ve(t.definition,`${e}.definition`));break}case"removeIndex":{let i=["type","name"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:`Unknown property ${s}`,path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`));break}case"modifyIndex":{let i=["type","name","changes"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:`Unknown property ${s}`,path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`)),typeof t.changes!="object"&&n.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addConstraint":{let i=["type","constraint"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:`Unknown property ${s}`,path:[`${e}.${s}`]})}),"rules"in t.constraint?n.push(...be(t.constraint,"dynamic",`${e}.constraint`)):n.push(...Se(t.constraint,"dynamic",`${e}.constraint`));break}case"removeConstraint":{let i=["type","name"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:`Unknown property ${s}`,path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`));break}case"modifyConstraint":{let i=["type","name","changes"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:`Unknown property ${s}`,path:[`${e}.${s}`]})}),n.push(...x(t.name,`${e}.name`)),typeof t.changes!="object"&&n.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addNestedSchema":{let i=["type","id","definition"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:`Unknown property ${s}`,path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`)),n.push(..._e(t.definition,`${e}.definition`,[]));break}case"removeNestedSchema":{let i=["type","id"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:`Unknown property ${s}`,path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`));break}case"modifyNestedSchema":{let i=["type","id","changes"],a=i,r=t;i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:`Unknown property ${s}`,path:[`${e}.${s}`]})}),n.push(...x(t.id,`${e}.id`)),typeof t.changes!="object"&&n.push({message:"Changes must be an object",path:[`${e}.changes`]});break}default:n.push({message:"Unknown schema change type",path:[`${e}.type`]})}return n},$t=(t,e)=>{let n=[],i=["forward","backward"],a=i,r=t;return i.forEach(s=>{r[s]===void 0&&n.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(r).forEach(s=>{a.includes(s)||n.push({message:`Unknown property ${s}`,path:[`${e}.${s}`]})}),typeof t.forward!="function"&&n.push({message:"Forward must be a function",path:[`${e}.forward`]}),typeof t.backward!="function"&&n.push({message:"Backward must be a function",path:[`${e}.backward`]}),n},He=(t,e)=>{let n=[],i=["id","schemaVersion","changes","description","status","transform","createdAt","checksum"],a=[...i,"rollback","dependencies"],r=t;i.forEach(o=>{r[o]===void 0&&n.push({message:`${o} is required`,path:[`${e}.${o}`]})}),Object.keys(r).forEach(o=>{a.includes(o)||n.push({message:`Unknown property ${o}`,path:[`${e}.${o}`]})}),n.push(...x(t.id,`${e}.id`)),n.push(...x(t.schemaVersion,`${e}.schemaVersion`)),n.push(...x(t.description,`${e}.description`));let s=["pending","applied","failed"];return s.includes(t.status)||n.push({message:`Status must be one of ${s.join(", ")}`,path:[`${e}.status`]}),!Array.isArray(t.changes)||t.changes.length===0?n.push({message:"Changes must be a non-empty array",path:[`${e}.changes`]}):t.changes.forEach((o,c)=>{n.push(...$e(o,`${e}.changes[${c}]`))}),t.rollback!==void 0&&(Array.isArray(t.rollback)?t.rollback.forEach((o,c)=>n.push(...$e(o,`${e}.rollback[${c}]`))):n.push({message:"Rollback must be an array",path:[`${e}.rollback`]})),typeof t.transform=="string"?n.push(...x(t.transform,`${e}.transform`)):typeof t.transform=="object"&&t.transform!==null?n.push(...$t(t.transform,`${e}.transform`)):n.push({message:"Transform must be a string or object",path:[`${e}.transform`]}),n.push(...x(t.createdAt,`${e}.createdAt`)),n.push(...x(t.checksum,`${e}.checksum`)),t.dependencies!==void 0&&(n.push({message:"dependencies is deprecated; use DomainModel instead",path:[`${e}.dependencies`]}),(!Array.isArray(t.dependencies)||!t.dependencies.every(o=>typeof o=="string"))&&n.push({message:"Dependencies must be an array of strings",path:[`${e}.dependencies`]})),n},Je={"~standard":{version:1,vendor:"@asaidimu/anansi",validate:gt,types:{input:{},output:{}}}};var Ge={"~standard":{version:1,vendor:"@asaidimu/anansi",validate:t=>{if(typeof t!="object"||t===null)return J([{message:"Migration must be an object",path:[]}]);let e=t,n=He(e,"");return n.length>0?J(n):we(e)},types:{input:{},output:{}}}},ze={"~standard":{version:1,vendor:"@asaidimu/anansi",validate:t=>{if(!Array.isArray(t))return J([{message:"SchemaChanges must be an array",path:[]}]);let e=t,n=[];return e.forEach((i,a)=>n.push(...$e(i,`[${a}]`))),n.length>0?J(n):we(e)},types:{input:[],output:[]}}};function ve(t){try{return!Ge["~standard"].validate(t).issues}catch(e){throw new H("Invalid migration definition",e instanceof Error?e:new Error(String(e)))}}function Ee(t){try{return!ze["~standard"].validate(t).issues}catch(e){throw new H("Invalid schema change definition",e instanceof Error?e:new Error(String(e)))}}function z(t){try{return!Je["~standard"].validate(t).issues}catch(e){throw new H("Invalid schema definition",e instanceof Error?e:new Error(String(e)))}}var wt=z;var L=async t=>{if(typeof window<"u"&&crypto.subtle){let n=new TextEncoder().encode(t),i=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(i)).map(r=>r.toString(16).padStart(2,"0")).join("")}else{let{createHash:e}=await import("crypto");return e("sha256").update(t).digest("hex")}};function St(t){let e=t.match(/^(\d+)\.(\d+)\.(\d+)$/);if(!e)throw new Error(`Invalid version format: ${t}. Expected format: major.minor.patch`);return{major:parseInt(e[1],10),minor:parseInt(e[2],10),patch:parseInt(e[3],10)}}function bt(t,e){if(e&&"field"in t&&t.field){let n=e.fields[t.field];if(n)return n.type}if("parameters"in t){let n=t.parameters;if(n instanceof RegExp||Array.isArray(n)&&typeof n[0]=="string")return"string";if(typeof n=="number"||Array.isArray(n)&&typeof n[0]=="number")return"number";if(typeof n=="boolean")return"boolean";if(typeof n=="object"&&n!==null){if("minItems"in n||"maxItems"in n)return"array";if("schema"in n)return"object"}}}function vt(t){return t.required===!0||t.type!==void 0||t.itemsType!==void 0||t.nestedSchema!==void 0||t.reference!==void 0||t.unique===!0}function Et(t,e,n){switch(n){case"string":if(t instanceof RegExp&&e instanceof RegExp)return t.source!==e.source;if(Array.isArray(t)&&Array.isArray(e))return e.length<t.length||!t.every(i=>e.includes(i));break;case"number":if(typeof t=="object"&&typeof e=="object"&&"precision"in t&&"precision"in e)return e.precision<t.precision||(e.scale??0)<(t.scale??0);if(Array.isArray(t)&&Array.isArray(e))return e.length<t.length||!t.every(i=>e.includes(i));break;case"array":if(typeof t=="object"&&typeof e=="object"&&"minItems"in t&&"maxItems"in t&&"minItems"in e&&"maxItems"in e)return e.minItems>t.minItems||e.maxItems<t.maxItems;break;case"object":if(typeof t=="object"&&typeof e=="object"&&"schema"in t&&"schema"in e)return Object.keys(e.schema).length>Object.keys(t.schema).length;break}return!1}function Tt(t,e){let n={or:1,xor:2,and:3,not:4,nor:4};return!!(e.operator&&n[e.operator]>n[t.operator]||e.rules&&e.rules.length>t.rules.length)}function xt(t,e,n){if(!e)return!0;if("rules"in e&&"rules"in t)return Tt(e,t);if("predicate"in t&&t.predicate!==void 0)return!0;if("parameters"in t&&t.parameters!==void 0){let i=bt(e,n);return i?Et(e.parameters,t.parameters,i):!0}return!1}function Ct(t,e){switch(t.type){case"removeField":case"removeIndex":return"major";case"modifyField":return vt(t.changes)?"major":t.changes.deprecated?"minor":"patch";case"modifyIndex":return t.changes.unique!==void 0||t.changes.fields!==void 0?"major":"minor";case"addConstraint":return"major";case"removeConstraint":return"minor";case"modifyConstraint":let n=e?.constraints?.find(i=>"name"in i&&i.name===t.name);return xt(t.changes,n,e)?"major":"minor";case"addField":case"addIndex":case"deprecateField":return"minor";default:throw new Error(`Unhandled change type: ${JSON.stringify(t)}`)}}function kt(t){let e=new Set,n=new Set,i=new Set,a=new Set;for(let r of t)switch(r.type){case"addField":if(n.has(r.id))throw new Error(`Cannot add previously removed field: ${r.id}`);if(e.has(r.id))throw new Error(`Cannot add already modified field: ${r.id}`);if(a.has(r.id))throw new Error(`Cannot add deprecated field: ${r.id}`);i.add(r.id);break;case"removeField":if(i.has(r.id))throw new Error(`Cannot remove newly added field: ${r.id}`);if(e.has(r.id))throw new Error(`Cannot remove modified field: ${r.id}`);if(a.has(r.id))throw new Error(`Cannot remove field that is being deprecated: ${r.id}`);n.add(r.id);break;case"modifyField":if(n.has(r.id))throw new Error(`Cannot modify removed field: ${r.id}`);if(i.has(r.id))throw new Error(`Cannot modify newly added field: ${r.id}`);if(a.has(r.id))throw new Error(`Cannot modify field that is being deprecated: ${r.id}`);e.add(r.id);break;case"deprecateField":if(n.has(r.id))throw new Error(`Cannot deprecate removed field: ${r.id}`);if(i.has(r.id))throw new Error(`Cannot deprecate newly added field: ${r.id}`);if(e.has(r.id))throw new Error(`Cannot deprecate modified field: ${r.id}`);a.add(r.id);break}}function Dt(t){let e=new Set,n=new Set,i=new Set;for(let a of t)switch(a.type){case"addConstraint":let r=a.constraint,s=("name"in r,r.name);if(n.has(s))throw new Error(`Cannot add previously removed constraint: ${s}`);if(e.has(s))throw new Error(`Cannot add already modified constraint: ${s}`);i.add(s);break;case"removeConstraint":if(i.has(a.name))throw new Error(`Cannot remove newly added constraint: ${a.name}`);if(e.has(a.name))throw new Error(`Cannot remove modified constraint: ${a.name}`);n.add(a.name);break;case"modifyConstraint":if(n.has(a.name))throw new Error(`Cannot modify removed constraint: ${a.name}`);if(i.has(a.name))throw new Error(`Cannot modify newly added constraint: ${a.name}`);e.add(a.name);break}}function Te(t,e,n){if(e.length===0)throw new Error("No changes provided");kt(e),Dt(e);let i=St(t),a="patch";for(let r of e){let s=Ct(r,n);if(s==="major"){a="major";break}else s==="minor"&&a==="patch"&&(a="minor")}switch(a){case"major":return`${i.major+1}.0.0`;case"minor":return`${i.major}.${i.minor+1}.0`;case"patch":return`${i.major}.${i.minor}.${i.patch+1}`}}function j(t,e){let n=u=>u.split(".").map(f=>parseInt(f,10)||0),[i,a,r]=n(t),[s,o,c]=n(e);return i-s||a-o||r-c}function At(t){return t.sort(j)}var A=class extends Error{constructor(n,i,a,r){super(n);this.code=i;this.migrationId=a;this.cause=r;this.name="MigrationError"}},Be=(p=>(p.INVALID_SCHEMA="INVALID_SCHEMA",p.INVALID_MIGRATION="INVALID_MIGRATION",p.CHECKSUM_MISMATCH="CHECKSUM_MISMATCH",p.TIMEOUT="TIMEOUT",p.MEMORY_LIMIT="MEMORY_LIMIT",p.CONCURRENT_OPERATION="CONCURRENT_OPERATION",p.TRANSFORM_ERROR="TRANSFORM_ERROR",p.VERSION_NOT_FOUND="VERSION_NOT_FOUND",p.CIRCULAR_DEPENDENCY="CIRCULAR_DEPENDENCY",p.STREAM_ERROR="STREAM_ERROR",p.ROLLBACK_ERROR="ROLLBACK_ERROR",p.MISSING_TRANSFORM="MISSING_TRANSFORM",p))(Be||{}),xe=class t{currentSchema;history=[];migrations=[];isProcessing=!1;constructor(e,n,i){try{if(!z(e))throw new A("Invalid initial schema","INVALID_SCHEMA");if(this.currentSchema=e,n){if(!n.every(a=>ve(a)))throw new A("Invalid migration configuration","INVALID_MIGRATION");this.migrations=n.sort((a,r)=>j(a.schemaVersion,r.schemaVersion))}i&&(this.history=i.sort((a,r)=>j(a.version,r.version)))}catch(a){throw a instanceof A?a:new A("Failed to initialize MigrationEngine","INVALID_SCHEMA",void 0,a)}}data(){return{schema:this.currentSchema,history:this.history,migrations:this.migrations}}async generateChecksum(e){try{let n=JSON.stringify({id:e.id,schemaVersion:e.schemaVersion,changes:e.changes,description:e.description,rollback:e.rollback,createdAt:e.createdAt});return await L(n)}catch(n){throw new A("Checksum generation failed","CHECKSUM_MISMATCH",e.id,n)}}async add(e){if(this.isProcessing)throw new A("Concurrent operation","CONCURRENT_OPERATION");if(!e.changes?.length)throw new A("Migration must include changes","INVALID_MIGRATION");try{e.changes.forEach(i=>Ee(i))}catch(i){throw new A("Invalid schema changes","INVALID_MIGRATION",void 0,i)}let n={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:""};n.checksum=await this.generateChecksum(n),this.migrations.push(n)}async dryRun(e,n,i){if(this.isProcessing)throw new A("Concurrent operation","CONCURRENT_OPERATION");try{this.isProcessing=!0;let a={...this.currentSchema},r=this.getRelevantMigrations(n,i),s=r.reduce((c,u)=>{let f=n==="forward"?u.changes:u.rollback||[];return this.applySchemaChanges(c,f,u.id)},a),o=await t.processMigrationList(e,n,r);return{newSchema:s,dataPreview:o}}catch(a){throw a instanceof A?a:new A("Dry run failed","INVALID_SCHEMA",void 0,a)}finally{this.isProcessing=!1}}getRelevantMigrations(e,n){return[...this.migrations].filter(i=>{let a=e==="forward"?"pending":"applied",r=n?j(i.schemaVersion,n)>=0:!0;return i.status===a&&r}).sort((i,a)=>e==="forward"?i.id.localeCompare(a.id):a.id.localeCompare(i.id))}applySchemaChanges(e,n,i){try{let a=Te(e.version,n);return n.map(s=>{try{return he(s,e)}catch(o){throw new A("Invalid schema change","INVALID_SCHEMA",i,o)}}).reduce((s,o)=>{try{return ie(s,o)}catch(c){throw new A("Failed to apply patch","INVALID_SCHEMA",i,c)}},{...e,version:a})}catch(a){throw a instanceof A?a:new A("Schema update failed","INVALID_SCHEMA",i,a)}}async prepareMigration(){let e=this.migrations.filter(n=>n.status==="pending");return await this.validateMigrations(e),e}async migrate(e){if(this.isProcessing)throw new A("Concurrent operation","CONCURRENT_OPERATION");let n=await this.prepareMigration();try{this.isProcessing=!0,this.transformSchema("forward");let i=await t.processMigrationList(e,"forward",n);return this.markMigrationsApplied(n),i}finally{this.isProcessing=!1}}async validateMigrations(e){await Promise.all(e.map(async n=>{let i=await this.generateChecksum(n);if(n.checksum!==i)throw new A("Checksum mismatch","CHECKSUM_MISMATCH",n.id)}))}markMigrationsApplied(e){this.migrations=this.migrations.map(n=>e.some(i=>i.id===n.id)?{...n,status:"applied"}:n)}async rollback(e){if(this.isProcessing)throw new A("Concurrent operation","CONCURRENT_OPERATION");return this.migrations.filter(i=>i.status==="applied").slice(-1)[0]?this.rollbackToVersion(this.history[this.history.length-1]?.version||this.currentSchema.version,e):e}async rollbackToVersion(e,n){if(this.isProcessing)throw new A("Concurrent operation","CONCURRENT_OPERATION");try{let i=this.history.findIndex(o=>o.version===e);if(i===-1)throw new Error(`Version ${e} not found in history`);let a=this.migrations.filter(o=>o.schemaVersion===e&&o.status==="applied").sort((o,c)=>c.id.localeCompare(o.id)),r=this.history.length-i;if(r<0)return n;for(let o=0;o<r;o++)this.transformSchema("backward");let s=await t.processMigrationList(n,"backward",a);return this.migrations=this.migrations.map(o=>o.schemaVersion===e&&o.status==="applied"?{...o,status:"pending"}:o),s}finally{this.isProcessing=!1}}static async processMigrationList(e,n,i){return(await Promise.all(i.map(async s=>{try{let o=await this.resolveTransform(s,n);return{migration:s,transform:o}}catch(o){throw new A(`Failed to resolve transform for migration ${s.id}`,"TRANSFORM_ERROR",s.id,o)}}))).filter(s=>!!s.transform).reduce((s,{migration:o,transform:c})=>s.pipeThrough(new TransformStream({async transform(u,f){try{let b=await c(u);f.enqueue(b)}catch(b){f.error(new A(`Data transformation failed for migration ${o.id}`,"TRANSFORM_ERROR",o.id,b))}}})),e)}static async resolveTransform(e,n){return e.transform?typeof e.transform=="string"?e.transform.startsWith("http://")||e.transform.startsWith("https://")?this.resolveRemoteTransform(e.transform,n):this.resolveLocalTransform(e.transform,n):e.transform[n]:null}static async resolveRemoteTransform(e,n){try{let i=await fetch(e);if(!i.ok)throw new A(`Failed to fetch transform module: ${e}`,"TRANSFORM_ERROR",void 0);let a=await i.text();if(typeof window<"u"){let r=new Blob([a],{type:"application/javascript"});return(await import(URL.createObjectURL(r))).default[n]}else{let{runInNewContext:r}=await import("vm"),s={module:{exports:{}},console};return r(a,s,e),s.module.exports[n]}}catch(i){throw new A(`Failed to load remote transform module: ${e}`,"TRANSFORM_ERROR",void 0,i)}}static async resolveLocalTransform(e,n){try{return(await import(e)).default[n]}catch(i){throw new A(`Failed to import local transform module: ${e}`,"TRANSFORM_ERROR",void 0,i)}}transformSchema(e){try{if(e==="backward"){let i=this.history.pop();if(!i)throw new Error("No previous version");this.currentSchema=i;return}let n=this.migrations.filter(i=>i.status==="pending").flatMap(i=>i.changes);if(!n.length)return;this.history.push(structuredClone(this.currentSchema)),this.currentSchema=n.reduce((i,a)=>this.applySchemaChanges(i,[a]),this.currentSchema)}catch(n){throw n instanceof A?n:new A("Schema transformation failed","INVALID_SCHEMA",void 0,n)}}};var Ke=t=>{let e=[],n=[];return{addField:(i,a)=>{e.push({type:"addField",id:i,definition:a}),n.push({type:"removeField",id:i})},removeField:i=>{e.push({type:"removeField",id:i});let a=t.fields[i];a&&n.push({type:"addField",id:i,definition:a})},modifyField:(i,a)=>{e.push({type:"modifyField",id:i,changes:a});let r=t.fields[i];r&&n.push({type:"modifyField",id:i,changes:r})},deprecateField:i=>{e.push({type:"deprecateField",id:i}),n.push({type:"modifyField",id:i,changes:{deprecated:!1}})},addIndex:i=>{e.push({type:"addIndex",definition:i}),n.push({type:"removeIndex",name:i.name})},removeIndex:i=>{e.push({type:"removeIndex",name:i});let a=t.indexes?.find(r=>r.name===i);a&&n.push({type:"addIndex",definition:a})},modifyIndex:(i,a)=>{e.push({type:"modifyIndex",name:i,changes:a});let r=t.indexes?.find(s=>s.name===i);r&&n.push({type:"modifyIndex",name:i,changes:r})},addConstraint:i=>{e.push({type:"addConstraint",constraint:i}),n.push({type:"removeConstraint",name:i.name})},removeConstraint:i=>{e.push({type:"removeConstraint",name:i});let a=t.constraints?.find(r=>"name"in r&&r.name===i);a&&n.push({type:"addConstraint",constraint:a})},modifyConstraint:(i,a)=>{e.push({type:"modifyConstraint",name:i,changes:a});let r=t.constraints?.find(s=>"name"in s&&s.name===i);r&&n.push({type:"modifyConstraint",name:i,changes:r})},addNestedSchema:(i,a)=>{e.push({type:"addNestedSchema",id:i,definition:a}),n.push({type:"removeNestedSchema",id:i})},removeNestedSchema:i=>{if(e.push({type:"removeNestedSchema",id:i}),!t.nestedSchemas)return;let a=t.nestedSchemas[i];a&&n.push({type:"addNestedSchema",id:i,definition:a})},modifyNestedSchema:(i,a)=>{if(e.push({type:"modifyNestedSchema",id:i,changes:a}),!t.nestedSchemas)return;let r=t.nestedSchemas[i];r&&n.push({type:"modifyNestedSchema",id:i,changes:r})},changes:()=>({migrate:e,rollback:n})}};var Tn=require("@isomorphic-git/lightning-fs"),I=K(require("isomorphic-git"),1),Q=K(require("isomorphic-git/http/web"),1);var Ze=K(require("@isomorphic-git/lightning-fs"),1);function We(t){let e=t.toString(),n=e.substring(e.indexOf("(")+1,e.indexOf(")")),i=e.substring(e.indexOf("{")+1,e.lastIndexOf("}")).trim();return JSON.stringify({params:n,body:i})}function Ye(t){let{params:e,body:n}=JSON.parse(t),i=Object.getPrototypeOf(function*(){}).constructor;return new i(e,n)}function Ce(t){let e=t.toString(),n=e.match(/\(([^)]*)\)\s*=>\s*(.+)/s),i=e.match(/function\s*\(([^)]*)\)\s*{([\s\S]*)}/),a=e.match(/([^(]*)\(([^)]*)\)\s*{([\s\S]*)}/),r,s;return n?(r=n[1],s=n[2].includes("{")?n[2].substring(1,n[2].length-1).trim():`return ${n[2]}`):i?(r=i[1],s=i[2].trim()):a?(r=a[2],s=a[3].trim()):(r=e.substring(e.indexOf("(")+1,e.indexOf(")")),s=e.substring(e.indexOf("{")+1,e.lastIndexOf("}")).trim()),JSON.stringify({params:r,body:s,type:n?"arrow":i?"function":a?"method":"unknown"})}function ke(t){let{params:e,body:n,type:i}=JSON.parse(t),a=new Function(e,n);return i==="arrow"&&Object.defineProperty(a,"toString",{value:()=>`(${e}) => ${n}`,configurable:!0}),a}function Ft(t){let e={},n={};t.hint?.groups&&t.hint.groups.forEach(a=>{n[a.name]={label:a.label,description:a.description}}),De(t.fields,"",t.nestedSchemas||{},e,!0);let i=[];for(let[a,r]of Object.entries(e)){let s=a!=="ungrouped"?n[a]:void 0;i.push({name:a!=="ungrouped"?a:"ungrouped",label:s?.label||"Ungrouped",description:s?.description,fields:r})}return i}function De(t,e,n,i,a,r){if(Array.isArray(t))t.forEach(s=>{let o=s.when?e?`${e}.${s.when?.field}`:s.when?.field:void 0;De(s.fields,e,n,i,a,o?{[o]:s.when?.value}:void 0)});else for(let[s,o]of Object.entries(t)){if(o.hint?.input.ignore)continue;let c=e?`${e}.${o.name}`:o.name,f=o.required===!0&&a,b={...o,name:c,required:f};if(r&&(b.when=r),o.type!=="object"){let p=o.hint?.input?.group||"ungrouped";i[p]||(i[p]=[]),i[p].push(b)}if(o.schema&&"id"in o.schema&&n[o.schema.id]){let p=n[o.schema.id];De(p.fields,c,n,i,f,r)}}}function Pt(t,e){let n={},i=t.nestedSchemas||{};for(let[a,r]of Object.entries(t.fields))n[a]=oe(r,i,e);return n}function oe(t,e,n){if("default"in t&&t.default!==void 0)return t.default;if(n?.resolver){let i=n.resolver(t);if(i!==void 0)return i}switch(t.type){case"string":return;case"number":return;case"boolean":return!1;case"array":return[];case"set":return[];case"enum":if(!t.values||t.values.length===0)throw new Error(`Enum field "${t.name}" requires non-empty values array`);return t.values[0];case"object":if(!t.schema||!("id"in t.schema)||!e[t.schema.id])throw new Error(`Object field "${t.name}" references invalid nested schema`);return Qe(e[t.schema.id],e,n);case"record":return{};case"union":if(!t.schema||!Array.isArray(t.schema)||t.schema.length===0)throw new Error(`Union field "${t.name}" requires non-empty schema array`);let i=n?.discriminator?.[t.name],a=t.schema[0];if(i!==void 0)for(let r of t.schema){let o=e[r.id].fields;if(Mt(o,i)){a=r;break}}return Qe(e[a.id],e,n);case"dynamic":return{};default:throw new Error(`Unsupported field type "${t.type}" for field "${t.name}"`)}}function Mt(t,e){if(Array.isArray(t)){for(let n of t)for(let i of Object.values(n.fields))if(i.type==="enum"&&i.values?.includes(e)||i.default===e)return i}else for(let n of Object.values(t))if(n.type==="enum"&&n.values?.includes(e)||n.default===e)return n}function Qe(t,e,n){let i={},a=n?.discriminator||{};if(Array.isArray(t.fields)){let r=t.fields.filter(o=>!o.when);for(let o of r)for(let[c,u]of Object.entries(o.fields))i[c]=oe(u,e,n);let s=t.fields.filter(o=>o.when);for(let o of s){let c=o.when.field,u=o.when.value;if(a[c]===u)for(let[b,p]of Object.entries(o.fields))i[b]=oe(p,e,n)}}else for(let[r,s]of Object.entries(t.fields))i[r]=oe(s,e,n);return i}var Xe=require("buffer");window.Buffer=Xe.Buffer;var Y=class{fs;fsp;rootDir;constructor(e="/registry"){this.fs=new Ze.default(`${e.replace("/","-")}`),this.fsp=this.fs.promises,this.rootDir=e.startsWith("/")?e:`/${e}`}async init(){let e=`${this.rootDir}/registry.json`;(!await this.fileExists(this.rootDir)||!await this.fileExists(e))&&(await this.fsp.mkdir(this.rootDir),await this.fsp.writeFile(e,JSON.stringify({schemas:{},created:new Date().toISOString(),updated:new Date().toISOString()}),"utf8"),await this.fsp.writeFile(`${this.rootDir}/schema-lock.json`,JSON.stringify({updated:new Date().toISOString(),hashes:[]}),"utf8"))}async create({schema:e}){if(!e.name||!e.version||!z(e))throw new Error("Invalid schema");let n=`${this.rootDir}/${e.name}`;if(await this.fileExists(`${n}/schema.json`))throw new Error(`Schema ${e.name} already exists`);return await this.fsp.mkdir(n),await this.fsp.mkdir(`${n}/migrations`),this.saveSchema(e,"create")}async update({schema:e}){if(!e.name||!e.version)throw new Error("Schema must have a name and version");let n=`${this.rootDir}/${e.name}`;if(!await this.fileExists(`${n}/schema.json`))throw new Error(`Schema ${e.name} not found`);return this.saveSchema(e,"update")}async saveSchema(e,n){let i=`${this.rootDir}/${e.name}`,a=await this.processAndStoreMigrations(i,e),r=this.serializeSchema(e);await this.writeSchemaFile(i,r);let s=await L(r);await this.updateIndex(i,e,s,a,n),await this.updateRegistryMetadata(e,n),await this.sync()}async delete({name:e}){let n=`${this.rootDir}/${e}`;if(!await this.fileExists(`${n}/schema.json`))throw new Error(`Schema ${e} not found`);await this.rmdirRecursive(n);let i=await this.readRegistryMetadata();delete i.schemas[e],i.updated=new Date().toISOString(),await this.writeRegistryMetadata(i),await this.sync()}async list(){let e=await this.readRegistryMetadata();return Object.values(e.schemas).map(n=>({name:n.name,version:n.version}))}async schema({name:e,version:n,migrations:i=!1}){let a=`${this.rootDir}/${e}/schema.json`;if(!await this.fileExists(a))return null;let r=this.deserializeSchema(JSON.parse(String(await this.fsp.readFile(a,"utf8")))),s=await this.readSchemaIndex(e);return n&&n!==s.version&&!s.history.some(o=>o.version===n)?null:(i&&(r.migrations=await this.migrations({name:e,version:n})),r)}async stats({schema:e}){return e?this.readSchemaIndex(e):this.readRegistryMetadata()}async sync(){let e={updated:new Date().toISOString(),hashes:[]},n=await this.listFilesRecursive(this.rootDir);for(let i of n)if(i!==`${this.rootDir}/schema-lock.json`&&i.match(new RegExp("/*.git*/"))===null){let a=String(await this.fsp.readFile(i,"utf8"));e.hashes.push([i,await L(a)])}await this.fsp.writeFile(`${this.rootDir}/schema-lock.json`,JSON.stringify(e),"utf8")}async migrations({name:e,version:n}){let i=await this.readSchemaIndex(e),a=n||i.version,r=[];for(let[s,o]of Object.entries(i.migrations)){let c=`${this.rootDir}/${e}/migrations/${o.hash}.json`;if(await this.fileExists(c)){let u=JSON.parse(String(await this.fsp.readFile(c,"utf8")));j(u.schemaVersion,a)<=0&&r.push(this.deserializeMigration(u))}}return r.sort((s,o)=>j(s.schemaVersion,o.schemaVersion))}async history({name:e}){let n=await this.readSchemaIndex(e),i=this.deserializeSchema(JSON.parse(String(await this.fsp.readFile(`${this.rootDir}/${e}/schema.json`,"utf8"))));return Promise.all(n.history.map(async a=>({...i,version:a.version,description:a.description,migrations:await this.migrations({name:e,version:a.version})})))}async processAndStoreMigrations(e,n){return Promise.all((n.migrations||[]).map(async i=>{let a={...i};if(i.transform?.forward){let o=i.transform;a.transform={forward:Ce(o.forward),backward:Ce(o.backward||(c=>c))}}let r=JSON.stringify(a),s=await L(r);return await this.fsp.writeFile(`${e}/migrations/${s}.json`,r,"utf8"),{id:i.id,hash:s,checksum:i.checksum}}))}serializeSchema(e){return JSON.stringify({...e,migrations:void 0,mock:e.mock?We(e.mock):null})}deserializeSchema(e){return e.mock&&(e.mock=Ye(e.mock)),e}deserializeMigration(e){return e.transform?.forward&&(e.transform={forward:ke(e.transform.forward),backward:ke(e.transform.backward)}),e}async writeSchemaFile(e,n){let i=`${e}/schema.json`;return await this.fsp.writeFile(i,n,"utf8"),i}async updateIndex(e,n,i,a,r){let s=`${e}/index.json`,o=r==="create"?{schema:n.name,version:n.version,history:[],migrations:{}}:JSON.parse(String(await this.fsp.readFile(s,"utf8")));o.history.push({version:n.version,hash:i,date:new Date().toISOString(),description:n.description||(r==="create"?"Initial version":"Updated version"),migrations:a.map(c=>c.id),predicates:[],changelog:[]}),o.version=n.version,a.forEach(({id:c,hash:u,checksum:f})=>{o.migrations[c]={hash:u,checksum:f}}),await this.fsp.writeFile(s,JSON.stringify(o),"utf8")}async updateRegistryMetadata(e,n){let i=await this.readRegistryMetadata();i.schemas[e.name]={name:e.name,version:e.version,description:e.description||"",created:n==="create"?new Date().toISOString():i.schemas[e.name]?.created,updated:new Date().toISOString()},i.updated=new Date().toISOString(),await this.writeRegistryMetadata(i)}async readRegistryMetadata(){return JSON.parse(String(await this.fsp.readFile(`${this.rootDir}/registry.json`,"utf8")))}async writeRegistryMetadata(e){await this.fsp.writeFile(`${this.rootDir}/registry.json`,JSON.stringify(e),"utf8")}async readSchemaIndex(e){let n=`${this.rootDir}/${e}/index.json`;if(!await this.fileExists(n))throw new Error(`Schema ${e} not found`);return JSON.parse(String(await this.fsp.readFile(n,"utf8")))}async fileExists(e){try{return await this.fsp.stat(e),!0}catch{return!1}}async rmdirRecursive(e){let n=await this.fsp.readdir(e);for(let i of n){let a=`${e}/${i}`;(await this.fsp.stat(a)).isDirectory()?await this.rmdirRecursive(a):await this.fsp.unlink(a)}await this.fsp.rmdir(e)}async listFilesRecursive(e){let n=[],i=await this.fsp.readdir(e);for(let a of i){let r=`${e}/${a}`;(await this.fsp.stat(r)).isDirectory()?n.push(...await this.listFilesRecursive(r)):n.push(r)}return n}};var Ae=class{locks=new Map;async acquire(e){let n,i=new Promise(r=>{n=r}),a=this.locks.get(e)||Promise.resolve();return this.locks.set(e,a.then(()=>i)),await a,n}async withLock(e,n){let i=await this.acquire(e);try{return await n()}finally{i()}}},Re=class{cache=new Map;ttl;constructor(e=3e4){this.ttl=e}get(e){let n=this.cache.get(e);return!n||Date.now()-n.timestamp>this.ttl?(this.cache.delete(e),null):n.schema}set(e,n){this.cache.set(e,{schema:n,timestamp:Date.now()})}invalidate(e){e?this.cache.delete(e):this.cache.clear()}};async function ce(t,e){try{return await t()}catch(n){throw console.error(`${e}:`,n),new Error(`${e}: ${n.message}`)}}async function de(t,e,n,i,a){await i.init(),await I.default.init({fs:t,dir:e,defaultBranch:n}),await I.default.setConfig({fs:t,dir:e,path:"core.autocrlf",value:"false"}),await I.default.setConfig({fs:t,dir:e,path:"core.eol",value:"lf"}),await I.default.add({fs:t,dir:e,filepath:"."}),await I.default.commit({fs:t,dir:e,message:"chore: initial commit",author:a})}async function Ot(t="/registry",e={}){let n=e.mainBranch||"main",i=e.remote,a=e.createRemote??!1,r=e.author||{name:"SchemaRegistry",email:"system@example.com"},s=e.proxy?[e.proxy]:["https://cors.isomorphic-git.org"],o=0,c=new Y(t),u=c.fs,f=t.startsWith("/")?t:`/${t}`,b=new Ae,p=new Re(e.cacheTtl);async function v(d,l){let w=o;do{let T=s[o];try{return await d(T)}catch(D){if(console.warn(`Failed with proxy ${T}: ${D.message}`),o=(o+1)%s.length,o===w)throw new Error(`${l}: All CORS proxies failed`)}}while(!0)}async function C(d,l="."){return ce(async()=>(await I.default.add({fs:u,dir:f,filepath:l}),(await I.default.statusMatrix({fs:u,dir:f})).some(([T,D,k])=>D!==k)?await I.default.commit({fs:u,dir:f,message:d,author:r}):null),"Failed to commit changes")}async function m(d,l,w){return ce(async()=>{if(await g(d))throw new Error(`Tag ${d} already exists`);await I.default.annotatedTag({fs:u,dir:f,ref:d,message:l,tagger:r,object:w})},`Failed to create tag ${d}`)}async function g(d){try{return(await I.default.listTags({fs:u,dir:f})).includes(d)}catch{return!1}}async function y(d){return(await I.default.listTags({fs:u,dir:f})).filter(T=>T.startsWith(d))}async function $(d){return ce(async()=>{let w=(await I.default.listTags({fs:u,dir:f})).filter(T=>T.startsWith(d));for(let T of w)await I.default.deleteTag({fs:u,dir:f,ref:T});return w},`Failed to delete tags with prefix ${d}`)}async function h(d){return ce(async()=>{await I.default.checkout({fs:u,dir:f,ref:d})},`Failed to checkout ${d}`)}async function E(d,{delete:l=!1,force:w=!1}={}){i&&await v(async T=>{await I.default.push({fs:u,http:Q.default,dir:f,ref:d,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:T,delete:l,force:w})},`Failed to push ${d}`)}async function S(d,l=!0){i&&await v(async w=>{try{await I.default.pull({fs:u,http:Q.default,dir:f,ref:d,author:r,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:w,fastForwardOnly:!0})}catch(T){if(!l)console.warn(`Fast-forward pull failed for ${d}, attempting regular pull`),await I.default.pull({fs:u,http:Q.default,dir:f,ref:d,author:r,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:w,fastForwardOnly:!1});else throw T}},`Failed to pull ${d}`)}if(i&&!await c.fileExists(f)){let d=f.slice(1);if(await i.exists({name:d}).catch(()=>!1))await v(async w=>{await I.default.clone({fs:u,http:Q.default,dir:f,url:i.authURL(),ref:n,singleBranch:!0,depth:1,onAuth:()=>i.credentials(),corsProxy:w})},"Failed to clone repository");else if(a)try{i=await i.create({name:d,private:!0}),await de(u,f,n,c,r),await I.default.addRemote({fs:u,dir:f,remote:"origin",url:i.url()}),await E(n)}catch(w){console.error("Failed to create and push to remote repository:",w),await de(u,f,n,c,r)}else await de(u,f,n,c,r)}else await de(u,f,n,c,r);return{async init(){return b.withLock("init",()=>c.init())},async create(d){let{name:l,version:w}=d.schema;return b.withLock(`schema:${l}`,async()=>{await h(n),await c.create(d);let T=await C(`feat: create schema ${l}`);T&&await m(`${l}-${w}`,`Version ${w}`,T),p.invalidate(l)})},async update(d){let{name:l,version:w}=d.schema;return b.withLock(`schema:${l}`,async()=>{await h(n),await c.update(d);let T=await C(`fix: update schema ${l}`);T&&await m(`${l}-${w}`,`Version ${w}`,T),p.invalidate(l)})},async delete(d){let{name:l}=d;return b.withLock(`schema:${l}`,async()=>{await h(n),await I.default.remove({fs:u,dir:f,filepath:l}),await c.delete(d);let w=await C(`chore: delete schema ${l}`),T=await y(`${l}-`);if(i&&w){await E(n);for(let D of T)await E(D,{delete:!0,force:!0}).catch(k=>console.warn(`Failed to delete remote tag ${D}: ${k.message}`))}await $(`${l}-`),p.invalidate(l)})},async list(){return b.withLock("list",()=>c.list())},async schema(d){let{name:l,version:w}=d,T=`${l}-${w||"latest"}-${d.migrations||!1}`,D=p.get(T);return D||b.withLock(`schema:${l}`,async()=>{if(w){let R=`${l}-${w}`;if(await g(R))await h(R);else throw new Error(`Version ${w} of schema ${l} not found`)}else await h(n);let k=await c.schema(d);return p.set(T,k),k})},async stats(d){return b.withLock("stats",()=>c.stats(d))},async sync(){return b.withLock("sync",async()=>{if(await h(n),await c.sync(),await C("chore: sync local changes"),i){await S(n,!1),await E(n);let d=await I.default.listTags({fs:u,dir:f});for(let w of d)await E(w,{force:!0});let l=await I.default.listTags({fs:u,dir:f});for(let w of l)d.includes(w)||await E(w,{delete:!0})}p.invalidate()})},async migrations(d){let{name:l,version:w}=d,T=`migrations-${l}-${w||"latest"}`,D=p.get(T);return D||b.withLock(`migrations:${l}`,async()=>{if(w){let R=`${l}-${w}`;if(await g(R))await h(R);else throw new Error(`Version ${w} of schema ${l} not found`)}else await h(n);let k=await c.migrations(d);return p.set(T,k),k})},async history(d){let{name:l}=d,w=`history-${l}`,T=p.get(w);return T||b.withLock(`history:${l}`,async()=>{await h(n);let D=await c.history(d);return p.set(w,D),D})}}}function O(t){return"predicate"in t}function jt(t,e=!0,n=!0){let i="",a=n?"export ":"",r=new Map,s=new Map,o=(C,m=[])=>{if(!e||!C&&!m.length)return"";let g=C?[C]:[];return m.forEach(y=>g.push(y)),`/**
2
+ * ${g.join(`
3
3
  * `)}
4
4
  */
5
- `},c=T=>T.charAt(0).toUpperCase()+T.slice(1),u=(T,m)=>{let y=s.get(m)||new Map;for(let[S,g]of Object.entries(T))if(g.type==="enum"&&Array.isArray(g.values)){let $=`${m}${c(g.name)}`,h=g.values.map(C=>String(C));a.set($,h)}else if(g.type==="string"&&g.constraints){let $=g.constraints.find(h=>M(h)&&(h.predicate==="enum"||h.predicate==="oneOf"));if($&&M($)&&Array.isArray($.parameters)){let h=`${m}${c(g.name)}`,C=$.parameters.map(d=>String(d));a.set(h,C)}}else if(g.type==="record"){let $=`${m}${c(g.name)}`;y.set(g.name,$)}y.size>0&&s.set(m,y)};u(t.fields,t.name);for(let[T,m]of Object.entries(t.nestedSchemas||{}))Array.isArray(m.fields)?m.fields.forEach(y=>u(y.fields,c(m.name))):u(m.fields,c(m.name));for(let[T,m]of a){i+=o(`Union type for ${T.toLowerCase()} field values`);let y=m.map(S=>`"${S}"`).join(" | ");i+=`${r}type ${T} = ${y};
5
+ `},c=C=>C.charAt(0).toUpperCase()+C.slice(1),u=(C,m)=>{let g=s.get(m)||new Map;for(let[y,$]of Object.entries(C))if($.type==="enum"&&Array.isArray($.values)){let h=`${m}${c($.name)}`,E=$.values.map(S=>String(S));r.set(h,E)}else if($.type==="string"&&$.constraints){let h=$.constraints.find(E=>O(E)&&(E.predicate==="enum"||E.predicate==="oneOf"));if(h&&O(h)&&Array.isArray(h.parameters)){let E=`${m}${c($.name)}`,S=h.parameters.map(d=>String(d));r.set(E,S)}}else if($.type==="record"){let h=`${m}${c($.name)}`;g.set($.name,h)}g.size>0&&s.set(m,g)};u(t.fields,t.name);for(let[C,m]of Object.entries(t.nestedSchemas||{}))Array.isArray(m.fields)?m.fields.forEach(g=>u(g.fields,c(m.name))):u(m.fields,c(m.name));for(let[C,m]of r){i+=o(`Union type for ${C.toLowerCase()} field values`);let g=m.map(y=>`"${y}"`).join(" | ");i+=`${a}type ${C} = ${g};
6
6
 
7
- `}for(let[T,m]of Object.entries(t.nestedSchemas||{})){let y=c(m.name),S=m.constraints?.map(C=>M(C)?`@constraint ${C.name}: ${C.description||C.predicate}`:`@constraint ${C.name}`)||[];m.concrete&&S.push("@concrete Indicates a concrete schema"),i+=o(m.description,S);let g=s.get(y)||new Map,$=Array.from(g.entries()).map(([C,d])=>`${d} extends Record<string, any> = Record<string, any>`).join(", "),h=g.size>0?`<${$}>`:"";if(Array.isArray(m.fields)){let C=m.fields.filter(v=>!v.when),d=m.fields.filter(v=>v.when),l="";if(C.length>0){l+=`{
8
- `;for(let v of C)for(let[D,R]of Object.entries(v.fields)){let I=R.constraints?.map(V=>M(V)?`@constraint ${V.name}: ${V.description||V.predicate}`:`@constraint ${V.name}`)||[];R.unique&&I.push("@unique Ensures unique values"),R.default!==void 0&&I.push(`@default ${JSON.stringify(R.default)}`),e&&R.description?l+=o(R.description,I):I.length&&(l+=o(void 0,I)),R.deprecated&&(l+=` /** @deprecated */
9
- `);let F=de(R,t,y,g),N=R.required===!1?"?":"";l+=` ${R.name}${N}: ${F};
10
- `}l+="}"}let w="";d.length>0&&(w=d.map(D=>{let R=`{
11
- `;for(let[I,F]of Object.entries(D.fields)){let N=F.constraints?.map(z=>M(z)?`@constraint ${z.name}: ${z.description||z.predicate}`:`@constraint ${z.name}`)||[];F.unique&&N.push("@unique Ensures unique values"),F.default!==void 0&&N.push(`@default ${JSON.stringify(F.default)}`),e&&F.description?R+=o(F.description,N):N.length&&(R+=o(void 0,N)),F.deprecated&&(R+=` /** @deprecated */
12
- `);let V=de(F,t,y,g),Ye=F.required===!1?"?":"";R+=` ${F.name}${Ye}: ${V};
13
- `}if(D.when)for(let[I,F]of Object.entries(D.when))R+=` ${I}: "${F}";
14
- `;return R+="}",R}).join(" | ")),l&&w?i+=`${r}type ${y}${h} = ${l} & (${w});
7
+ `}for(let[C,m]of Object.entries(t.nestedSchemas||{})){let g=c(m.name),y=m.constraints?.map(S=>O(S)?`@constraint ${S.name}: ${S.description||S.predicate}`:`@constraint ${S.name}`)||[];m.concrete&&y.push("@concrete Indicates a concrete schema"),i+=o(m.description,y);let $=s.get(g)||new Map,h=Array.from($.entries()).map(([S,d])=>`${d} extends Record<string, any> = Record<string, any>`).join(", "),E=$.size>0?`<${h}>`:"";if(Array.isArray(m.fields)){let S=m.fields.filter(T=>!T.when),d=m.fields.filter(T=>T.when),l="";if(S.length>0){l+=`{
8
+ `;for(let T of S)for(let[D,k]of Object.entries(T.fields)){let R=k.constraints?.map(q=>O(q)?`@constraint ${q.name}: ${q.description||q.predicate}`:`@constraint ${q.name}`)||[];k.unique&&R.push("@unique Ensures unique values"),k.default!==void 0&&R.push(`@default ${JSON.stringify(k.default)}`),e&&k.description?l+=o(k.description,R):R.length&&(l+=o(void 0,R)),k.deprecated&&(l+=` /** @deprecated */
9
+ `);let F=ue(k,t,g,$),P=k.required===!1?"?":"";l+=` ${k.name}${P}: ${F};
10
+ `}l+="}"}let w="";d.length>0&&(w=d.map(D=>{let k=`{
11
+ `;for(let[R,F]of Object.entries(D.fields)){let P=F.constraints?.map(B=>O(B)?`@constraint ${B.name}: ${B.description||B.predicate}`:`@constraint ${B.name}`)||[];F.unique&&P.push("@unique Ensures unique values"),F.default!==void 0&&P.push(`@default ${JSON.stringify(F.default)}`),e&&F.description?k+=o(F.description,P):P.length&&(k+=o(void 0,P)),F.deprecated&&(k+=` /** @deprecated */
12
+ `);let q=ue(F,t,g,$),et=F.required===!1?"?":"";k+=` ${F.name}${et}: ${q};
13
+ `}if(D.when)for(let[R,F]of Object.entries(D.when))k+=` ${R}: "${F}";
14
+ `;return k+="}",k}).join(" | ")),l&&w?i+=`${a}type ${g}${E} = ${l} & (${w});
15
15
 
16
- `:l?i+=`${r}type ${y}${h} = ${l};
16
+ `:l?i+=`${a}type ${g}${E} = ${l};
17
17
 
18
- `:w&&(i+=`${r}type ${y}${h} = ${w};
18
+ `:w&&(i+=`${a}type ${g}${E} = ${w};
19
19
 
20
- `)}else{i+=`${r}type ${y}${h} = {
21
- `;for(let[C,d]of Object.entries(m.fields)){let l=d.constraints?.map(D=>M(D)?`@constraint ${D.name}: ${D.description||D.predicate}`:`@constraint ${D.name}`)||[];d.unique&&l.push("@unique Ensures unique values"),d.default!==void 0&&l.push(`@default ${JSON.stringify(d.default)}`),e&&d.description?i+=o(d.description,l):l.length&&(i+=o(void 0,l)),d.deprecated&&(i+=` /** @deprecated */
22
- `);let w=de(d,t,y,g),v=d.required===!1?"?":"";i+=` ${d.name}${v}: ${w};
20
+ `)}else{i+=`${a}type ${g}${E} = {
21
+ `;for(let[S,d]of Object.entries(m.fields)){let l=d.constraints?.map(D=>O(D)?`@constraint ${D.name}: ${D.description||D.predicate}`:`@constraint ${D.name}`)||[];d.unique&&l.push("@unique Ensures unique values"),d.default!==void 0&&l.push(`@default ${JSON.stringify(d.default)}`),e&&d.description?i+=o(d.description,l):l.length&&(i+=o(void 0,l)),d.deprecated&&(i+=` /** @deprecated */
22
+ `);let w=ue(d,t,g,$),T=d.required===!1?"?":"";i+=` ${d.name}${T}: ${w};
23
23
  `}m.metadata&&(i+=` metadata: Record<string, any>;
24
24
  `),i+=`};
25
25
 
26
- `}if(m.indexes?.length){i+=o(`Available indexes for ${y}`),i+=`${r}enum ${y}IndexNames {
27
- `;for(let C of m.indexes)i+=` ${C.name} = "${C.name}",
26
+ `}if(m.indexes?.length){i+=o(`Available indexes for ${g}`),i+=`${a}enum ${g}IndexNames {
27
+ `;for(let S of m.indexes)i+=` ${S.name} = "${S.name}",
28
28
  `;i+=`}
29
29
 
30
- `}}let f=t.constraints?.map(T=>M(T)?`@constraint ${T.name}: ${T.description||T.predicate}`:`@constraint ${T.name}`)||[];i+=o(t.description,f);let b=s.get(t.name)||new Map,p=Array.from(b.entries()).map(([T,m])=>`${m} extends Record<string, any> = Record<string, any>`).join(", "),E=b.size>0?`<${p}>`:"";i+=`${r}type ${t.name}${E} = {
31
- `;for(let[T,m]of Object.entries(t.fields)){let y=m.constraints?.map($=>M($)?`@constraint ${$.name}: ${$.description||$.predicate}`:`@constraint ${$.name}`)||[];m.unique&&y.push("@unique Ensures unique values"),m.default!==void 0&&y.push(`@default ${JSON.stringify(m.default)}`),e&&m.description?i+=o(m.description,y):y.length&&(i+=o(void 0,y)),m.deprecated&&(i+=` /** @deprecated */
32
- `);let S=de(m,t,t.name,b),g=m.required===!1?"?":"";i+=` ${m.name}${g}: ${S};
30
+ `}}let f=t.constraints?.map(C=>O(C)?`@constraint ${C.name}: ${C.description||C.predicate}`:`@constraint ${C.name}`)||[];i+=o(t.description,f);let b=s.get(t.name)||new Map,p=Array.from(b.entries()).map(([C,m])=>`${m} extends Record<string, any> = Record<string, any>`).join(", "),v=b.size>0?`<${p}>`:"";i+=`${a}type ${t.name}${v} = {
31
+ `;for(let[C,m]of Object.entries(t.fields)){let g=m.constraints?.map(h=>O(h)?`@constraint ${h.name}: ${h.description||h.predicate}`:`@constraint ${h.name}`)||[];m.unique&&g.push("@unique Ensures unique values"),m.default!==void 0&&g.push(`@default ${JSON.stringify(m.default)}`),e&&m.description?i+=o(m.description,g):g.length&&(i+=o(void 0,g)),m.deprecated&&(i+=` /** @deprecated */
32
+ `);let y=ue(m,t,t.name,b),$=m.required===!1?"?":"";i+=` ${m.name}${$}: ${y};
33
33
  `}if(t.metadata&&(i+=` metadata: Record<string, any>;
34
34
  `),i+=`};
35
35
 
36
- `,t.indexes?.length){i+=o(`Available indexes for ${t.name}`),i+=`${r}enum ${t.name}IndexNames {
37
- `;for(let T of t.indexes)i+=` ${T.name} = "${T.name}",
36
+ `,t.indexes?.length){i+=o(`Available indexes for ${t.name}`),i+=`${a}enum ${t.name}IndexNames {
37
+ `;for(let C of t.indexes)i+=` ${C.name} = "${C.name}",
38
38
  `;i+=`}
39
- `}return i.trim()}function de(t,e,n,i){switch(t.type){case"string":if(t.constraints){let r=t.constraints.find(a=>M(a)&&(a.predicate==="enum"||a.predicate==="oneOf"));if(r&&M(r)&&Array.isArray(r.parameters))return`${n}${L(t.name)}`}return"string";case"number":return"number";case"boolean":return"boolean";case"array":if(t.itemsType){if(t.itemsType==="object"&&t.schema&&!Array.isArray(t.schema)){let r=e.nestedSchemas[t.schema.id];return`${L(r.name)}[]`}return`${t.itemsType}[]`}return"any[]";case"set":if(t.itemsType){if(t.itemsType==="object"&&t.schema&&!Array.isArray(t.schema)){let r=e.nestedSchemas[t.schema.id];return`Set<${L(r.name)}>`}return`Set<${t.itemsType}>`}return"Set<any>";case"enum":return t.values?`${n}${L(t.name)}`:"string";case"object":if(t.schema&&!Array.isArray(t.schema)){let r=e.nestedSchemas[t.schema.id],a=L(r.name);return r.concrete?`string | ${a}`:a}if(t.nestedSchema){let r=e.nestedSchemas[t.nestedSchema.id],a=L(r.name);return r.concrete?`string | ${a}`:a}return t.reference?`${t.reference.schema}${t.required===!1?" | null":""}`:"Record<string, any>";case"record":return i.get(t.name)||"Record<string, any>";case"union":return t.schema&&Array.isArray(t.schema)?t.schema.map(a=>{let s=e.nestedSchemas[a.id];return L(s.name)}).join(" | "):"any";case"dynamic":return"unknown";default:return"any"}}function L(t){return t.charAt(0).toUpperCase()+t.slice(1)}function Mt(t,e){let n=[],i=s=>s===void 0?"`None`":`\`${JSON.stringify(s,null,2)}\``,r=s=>{let o=`**${s.field}** ${s.operator}`;return s.value!==void 0&&(o+=` ${JSON.stringify(s.value)}`),s.conditions&&(o+=` [
40
- ${s.conditions.map(c=>` ${r(c)}`).join(`
39
+ `}return i.trim()}function ue(t,e,n,i){switch(t.type){case"string":if(t.constraints){let a=t.constraints.find(r=>O(r)&&(r.predicate==="enum"||r.predicate==="oneOf"));if(a&&O(a)&&Array.isArray(a.parameters))return`${n}${_(t.name)}`}return"string";case"number":return"number";case"boolean":return"boolean";case"array":if(t.itemsType){if(t.itemsType==="object"&&t.schema&&!Array.isArray(t.schema)){let a=e.nestedSchemas[t.schema.id];return`${_(a.name)}[]`}return`${t.itemsType}[]`}return"any[]";case"set":if(t.itemsType){if(t.itemsType==="object"&&t.schema&&!Array.isArray(t.schema)){let a=e.nestedSchemas[t.schema.id];return`Set<${_(a.name)}>`}return`Set<${t.itemsType}>`}return"Set<any>";case"enum":return t.values?`${n}${_(t.name)}`:"string";case"object":if(t.schema&&!Array.isArray(t.schema)){let a=e.nestedSchemas[t.schema.id],r=_(a.name);return a.concrete?`string | ${r}`:r}if(t.nestedSchema){let a=e.nestedSchemas[t.nestedSchema.id],r=_(a.name);return a.concrete?`string | ${r}`:r}return t.reference?`${t.reference.schema}${t.required===!1?" | null":""}`:"Record<string, any>";case"record":return i.get(t.name)||"Record<string, any>";case"union":return t.schema&&Array.isArray(t.schema)?t.schema.map(r=>{let s=e.nestedSchemas[r.id];return _(s.name)}).join(" | "):"any";case"dynamic":return"unknown";default:return"any"}}function _(t){return t.charAt(0).toUpperCase()+t.slice(1)}function Nt(t,e){let n=[],i=s=>s===void 0?"`None`":`\`${JSON.stringify(s,null,2)}\``,a=s=>{let o=`**${s.field}** ${s.operator}`;return s.value!==void 0&&(o+=` ${JSON.stringify(s.value)}`),s.conditions&&(o+=` [
40
+ ${s.conditions.map(c=>` ${a(c)}`).join(`
41
41
  `)}
42
- ]`),o},a=(s,o=1)=>{let c="#".repeat(o+2);return Object.entries(s).map(([u,f])=>{let b=`${c} ${u} (${f.type})
42
+ ]`),o},r=(s,o=1)=>{let c="#".repeat(o+2);return Object.entries(s).map(([u,f])=>{let b=`${c} ${u} (${f.type})
43
43
 
44
44
  `;return b+=`**Required:** ${f.required?"Yes":"No"}
45
45
 
@@ -47,16 +47,16 @@ ${s.conditions.map(c=>` ${r(c)}`).join(`
47
47
 
48
48
  `),f.itemsType&&(b+=`**Item Type:** ${f.itemsType}
49
49
 
50
- `),f.nestedSchema&&(b+=a(f.nestedSchema,o+1)),b}).join(`
50
+ `),f.nestedSchema&&(b+=r(f.nestedSchema,o+1)),b}).join(`
51
51
  `)};n.push(`# ${t.name} Schema (Version ${t.version})`),t.description&&n.push(`
52
52
  ${t.description}
53
53
  `),n.push("## Metadata"),n.push(`- **Dependencies:** ${t.dependencies?.join(", ")||"None"}`),n.push(`- **Created:** ${new Date().toISOString()}
54
54
  `),n.push(`## Fields
55
55
  `),n.push("| Name | Type | Required | Default | Description | Deprecated | Unique | Constraints |"),n.push("|------|------|----------|---------|-------------|------------|--------|-------------|");for(let[s,o]of Object.entries(t.fields))n.push([s,o.type,o.required?"Yes":"No",i(o.default),o.description?.replace(/\n/g," ")||"",o.deprecated?"Yes":"No",o.unique?"Yes":"No",o.constraints?.length||0].join("|"));Object.entries(t.fields).forEach(([s,o])=>{o.nestedSchema&&(n.push(`
56
56
  ### Nested Schema: ${s}
57
- `),n.push(a(o.nestedSchema)))}),n.push(`
57
+ `),n.push(r(o.nestedSchema)))}),n.push(`
58
58
  ## Indexes
59
- `),n.push("| Name | Type | Fields | Unique | Order | Partial Condition | Description |"),n.push("|------|------|--------|--------|-------|-------------------|-------------|");for(let s of t.indexes||[])n.push([s.name,s.type,s.fields.join(", "),s.unique?"Yes":"No",s.order||"asc",s.partial?r(s.partial):"None",s.description||""].join("|"));n.push(`
59
+ `),n.push("| Name | Type | Fields | Unique | Order | Partial Condition | Description |"),n.push("|------|------|--------|--------|-------|-------------------|-------------|");for(let s of t.indexes||[])n.push([s.name,s.type,s.fields.join(", "),s.unique?"Yes":"No",s.order||"asc",s.partial?a(s.partial):"None",s.description||""].join("|"));n.push(`
60
60
  ## Constraints
61
61
  `),t.constraints&&n.push("### Schema-level Constraints"),n.push(`
62
62
  ## Migrations
package/index.d.cts CHANGED
@@ -417,7 +417,7 @@ interface IndexDefinition {
417
417
  * They facilitate schema reusability, modularity, and the definition of polymorphic structures.
418
418
  *
419
419
  */
420
- type NestedSchemaDefinition<T> = {
420
+ type NestedSchemaDefinition<T = any> = {
421
421
  /**
422
422
  * The unique name or identifier of the nested schema within the parent schema's `nestedSchemas` map.
423
423
  * This `name` is used by `FieldDefinition.schema.id` to reference this nested schema.
@@ -1323,7 +1323,7 @@ interface PersistenceCollection<T, FunctionMap = Record<string, any>> extends Ob
1323
1323
  update(params: {
1324
1324
  data?: Partial<T>;
1325
1325
  patch?: PatchOperation | Array<PatchOperation>;
1326
- query: QueryFilter<T, FunctionMap>;
1326
+ filter: QueryFilter<T, FunctionMap>;
1327
1327
  }): Promise<Array<T>>;
1328
1328
  /**
1329
1329
  * Deletes one or more records from the collection.
@@ -2298,26 +2298,21 @@ declare function schemaToTypes(schema: SchemaDefinition, includeComments?: boole
2298
2298
  /**
2299
2299
  * Serializes constraint parameters for error messages, handling special types like RegExp.
2300
2300
  *
2301
- * @param params - The parameters to serialize, which may include strings, arrays, RegExp, or objects.
2302
- * @returns A string representation of the parameters suitable for inclusion in error messages.
2301
+ * @param params - The parameters to serialize.
2302
+ * @returns A string representation for error messages.
2303
2303
  */
2304
2304
  declare function serializeParams(params: any): string;
2305
2305
  /**
2306
- * Creates a validator conforming to the StandardSchemaV1 interface based on a schema definition
2307
- * and a predicate map for constraint validation.
2306
+ * Creates a validator conforming to StandardSchemaV1 based on a schema definition.
2308
2307
  *
2309
- * @template T - The type of the data object being validated, extending Record<string, any>.
2310
- * @param schema - The schema definition specifying fields, constraints, and nested schemas.
2311
- * @param constraintsMap - A map of predicate names to their validation functions.
2312
- * @returns An object conforming to the StandardSchemaV1 interface with validation logic.
2308
+ * @template T - The type of the data object being validated.
2309
+ * @param schema - The schema definition.
2310
+ * @param constraintsMap - A map of predicate names to validation functions.
2311
+ * @returns A StandardSchemaV1 validator.
2313
2312
  */
2314
2313
  declare function createStandardSchemaValidator<T extends Record<string, any>>(schema: SchemaDefinition, constraintsMap: PredicateMap): StandardSchemaV1<T, T>;
2315
2314
  /**
2316
2315
  * Adapts a StandardSchemaV1 validator to React Hook Form's resolver interface.
2317
- *
2318
- * @template TFieldValues - The type of field values expected by React Hook Form.
2319
- * @param validator - The StandardSchemaV1 validator instance.
2320
- * @returns A resolver function compatible with React Hook Form.
2321
2316
  */
2322
2317
  declare function formResolver<TFieldValues extends FieldValues>(validator: ReturnType<typeof createStandardSchemaValidator>["~standard"]): (values: TFieldValues, context: unknown, options: ResolverOptions<TFieldValues>) => Promise<ResolverResult<TFieldValues>>;
2323
2318
 
package/index.d.ts CHANGED
@@ -417,7 +417,7 @@ interface IndexDefinition {
417
417
  * They facilitate schema reusability, modularity, and the definition of polymorphic structures.
418
418
  *
419
419
  */
420
- type NestedSchemaDefinition<T> = {
420
+ type NestedSchemaDefinition<T = any> = {
421
421
  /**
422
422
  * The unique name or identifier of the nested schema within the parent schema's `nestedSchemas` map.
423
423
  * This `name` is used by `FieldDefinition.schema.id` to reference this nested schema.
@@ -1323,7 +1323,7 @@ interface PersistenceCollection<T, FunctionMap = Record<string, any>> extends Ob
1323
1323
  update(params: {
1324
1324
  data?: Partial<T>;
1325
1325
  patch?: PatchOperation | Array<PatchOperation>;
1326
- query: QueryFilter<T, FunctionMap>;
1326
+ filter: QueryFilter<T, FunctionMap>;
1327
1327
  }): Promise<Array<T>>;
1328
1328
  /**
1329
1329
  * Deletes one or more records from the collection.
@@ -2298,26 +2298,21 @@ declare function schemaToTypes(schema: SchemaDefinition, includeComments?: boole
2298
2298
  /**
2299
2299
  * Serializes constraint parameters for error messages, handling special types like RegExp.
2300
2300
  *
2301
- * @param params - The parameters to serialize, which may include strings, arrays, RegExp, or objects.
2302
- * @returns A string representation of the parameters suitable for inclusion in error messages.
2301
+ * @param params - The parameters to serialize.
2302
+ * @returns A string representation for error messages.
2303
2303
  */
2304
2304
  declare function serializeParams(params: any): string;
2305
2305
  /**
2306
- * Creates a validator conforming to the StandardSchemaV1 interface based on a schema definition
2307
- * and a predicate map for constraint validation.
2306
+ * Creates a validator conforming to StandardSchemaV1 based on a schema definition.
2308
2307
  *
2309
- * @template T - The type of the data object being validated, extending Record<string, any>.
2310
- * @param schema - The schema definition specifying fields, constraints, and nested schemas.
2311
- * @param constraintsMap - A map of predicate names to their validation functions.
2312
- * @returns An object conforming to the StandardSchemaV1 interface with validation logic.
2308
+ * @template T - The type of the data object being validated.
2309
+ * @param schema - The schema definition.
2310
+ * @param constraintsMap - A map of predicate names to validation functions.
2311
+ * @returns A StandardSchemaV1 validator.
2313
2312
  */
2314
2313
  declare function createStandardSchemaValidator<T extends Record<string, any>>(schema: SchemaDefinition, constraintsMap: PredicateMap): StandardSchemaV1<T, T>;
2315
2314
  /**
2316
2315
  * Adapts a StandardSchemaV1 validator to React Hook Form's resolver interface.
2317
- *
2318
- * @template TFieldValues - The type of field values expected by React Hook Form.
2319
- * @param validator - The StandardSchemaV1 validator instance.
2320
- * @returns A resolver function compatible with React Hook Form.
2321
2316
  */
2322
2317
  declare function formResolver<TFieldValues extends FieldValues>(validator: ReturnType<typeof createStandardSchemaValidator>["~standard"]): (values: TFieldValues, context: unknown, options: ResolverOptions<TFieldValues>) => Promise<ResolverResult<TFieldValues>>;
2323
2318