@asaidimu/anansi 1.5.3 → 1.6.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,67 +1,65 @@
1
- "use strict";var Je=Object.create;var J=Object.defineProperty;var He=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var Be=Object.getPrototypeOf,Ke=Object.prototype.hasOwnProperty;var We=(n,e)=>{for(var t in e)J(n,t,{get:e[t],enumerable:!0})},be=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ze(e))!Ke.call(n,s)&&s!==t&&J(n,s,{get:()=>e[s],enumerable:!(i=He(e,s))||i.enumerable});return n};var q=(n,e,t)=>(t=n!=null?Je(Be(n)):{},be(e||!n||!n.__esModule?J(t,"default",{value:n,enumerable:!0}):t,n)),Ye=n=>be(J({},"__esModule",{value:!0}),n);var Ct={};We(Ct,{JsonPatchError:()=>P,MigrationEngine:()=>pe,MigrationError:()=>v,MigrationErrorCode:()=>Fe,SchemaRegistry:()=>_,applyPatch:()=>W,calculateNextVersion:()=>le,compareSemanticVersions:()=>A,createGitSchemaRegistry:()=>$t,createPatch:()=>Xe,createSchemaMigrationHelper:()=>je,createStandardSchemaValidator:()=>Ce,deepMerge:()=>re,docgen:()=>xt,extractInputFieldGroups:()=>Et,generateSHA256Hash:()=>O,generateValidationInterface:()=>vt,normalizePath:()=>ve,schemaChangeToPatch:()=>ae,schemaToTypes:()=>bt,serializeParams:()=>U,sortSemanticVars:()=>gt,validate:()=>ot,validateMigration:()=>me,validateSchemaChange:()=>he,validateSchemaDefinition:()=>N});module.exports=Ye(Ct);var St=require("@asaidimu/events");var wt=require("@asaidimu/events"),Z=require("@asaidimu/query");var P=class extends Error{constructor(t,i){super(t);this.operation=i;this.name="JsonPatchError"}};function B(n){let e=ve(n);return e===""?[]:e.substring(1).split("/").map(Qe)}function ve(n){return n===""||n==="/"?"":n.startsWith("/")?"/"+n.substring(1).split("/").map(z).join("/"):"/"+n.split(".").map(z).join("/")}function z(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}function Qe(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}var M=new Map;function K(n,e){let t=n;for(let i of e){if(t===null||typeof t!="object")throw new P(`Invalid path - parent not found at ${i}`);if(Array.isArray(t)){let s=i==="-"?t.length:parseInt(i);if(isNaN(s)||s<0||s>t.length)throw new P(`Invalid array index: ${i}`);t=t[s]}else{if(!t.hasOwnProperty(i))throw new P(`Property ${i} not found`);t=t[i]}}return t}function te(n,e){let t=M.get(e)||B(e);if(M.set(e,t),t.length===0)return n;let i=K(n,t.slice(0,-1)),s=t[t.length-1];if(Array.isArray(i)){let r=parseInt(s);if(isNaN(r)||r<0||r>=i.length)throw new P(`Invalid array index: ${s}`);return i[r]}return i[s]}function Ze(n,e,t){let i=M.get(e)||B(e);M.set(e,i);let s=K(n,i.slice(0,-1)),r=i[i.length-1];return Array.isArray(s)?s.splice(0,s.length,...s.filter(a=>a!==t)):s[r]===t&&delete s[r],n}function H(n,e,t){let i=M.get(e)||B(e);if(M.set(e,i),i.length===0)return t;let s=i.slice(0,-1),r=i[i.length-1],a=K(n,s);if(Array.isArray(a))if(r==="-")a.push(t);else{let o=parseInt(r);if(o<0||o>a.length)throw new P(`Invalid array index: ${r}`);a.splice(o,0,t)}else a[r]=t;return n}function ne(n,e){let t=M.get(e)||B(e);if(M.set(e,t),t.length===0)return;let i=K(n,t.slice(0,-1)),s=t[t.length-1];if(Array.isArray(i)){let r=parseInt(s);i.splice(r,1)}else delete i[s];return n}function W(n,e){let t=JSON.parse(JSON.stringify(n));for(let i of e)try{switch(i.op){case"add":t=H(t,i.path,i.value);break;case"remove":t=ne(t,i.path);break;case"removeValue":t=Ze(t,i.path,i.value);break;case"replace":t=H(ne(t,i.path),i.path,i.value);break;case"copy":{let s=te(t,i.from);t=H(t,i.path,JSON.parse(JSON.stringify(s)));break}case"move":{let s=te(t,i.from);t=H(t,i.path,s),t=ne(t,i.from);break}case"test":{let s=te(t,i.path);if(JSON.stringify(s)!==JSON.stringify(i.value))throw new P("Test operation failed");break}default:throw new P(`Unsupported operation: ${i.op}`)}}catch(s){throw s instanceof P&&(s.operation=i),s}return t}function Xe(n,e){let t=[];return ie(n,e,"",t),t}function ie(n,e,t,i){if(n!==e){if(typeof n!=typeof e||Array.isArray(n)!==Array.isArray(e)){i.push({op:"replace",path:t,value:e});return}typeof n=="object"&&n!==null?Array.isArray(n)?et(n,e,t,i):tt(n,e,t,i):n!==e&&i.push({op:"replace",path:t,value:e})}}function et(n,e,t,i){let s=Math.max(n.length,e.length);for(let r=0;r<s;r++){let a=`${t}/${r}`;r>=n.length?i.push({op:"add",path:`${t}/-`,value:e[r]}):r>=e.length?i.push({op:"remove",path:a}):ie(n[r],e[r],a,i)}}function tt(n,e,t,i){let s=new Set,r=Object.keys(n),a=Object.keys(e);for(let o of r){let c=z(o),d=t?`${t}/${c}`:`/${c}`;e.hasOwnProperty(o)?(ie(n[o],e[o],d,i),s.add(o)):i.push({op:"remove",path:d})}for(let o of a)if(!s.has(o)){let c=z(o),d=t?`${t}/${c}`:`/${c}`;i.push({op:"add",path:d,value:e[o]})}}function ae(n,e){let t=[];switch(n.type){case"addField":t.push({op:"add",path:`/fields/${n.id}`,value:n.definition});break;case"removeField":t.push({op:"remove",path:`/fields/${n.id}`});break;case"modifyField":{let i=`/fields/${n.id}`;Object.entries(n.changes).forEach(([s,r])=>{typeof r=="object"&&r!==null&&!Array.isArray(r)?t.push({op:"replace",path:`${i}/${s}`,value:r}):t.push({op:"replace",path:`${i}/${s}`,value:r})});break}case"deprecateField":t.push({op:"add",path:`/fields/${n.id}/deprecated`,value:!0});break;case"addIndex":e.indexes||t.push({op:"add",path:"/indexes",value:[]}),t.push({op:"add",path:"/indexes/-",value:n.definition});break;case"removeIndex":{let i=e.indexes?.findIndex(s=>s.name===n.name);i!==void 0&&i>=0&&t.push({op:"remove",path:`/indexes/${i}`});break}case"modifyIndex":{let i=e.indexes?.findIndex(s=>s.name===n.name);i!==void 0&&i>=0&&Object.entries(n.changes).forEach(([s,r])=>{t.push({op:"replace",path:`/indexes/${i}/${s}`,value:r})});break}case"addConstraint":e.constraints||t.push({op:"add",path:"/constraints",value:[]}),Array.isArray(n.constraint)?n.constraint.forEach(i=>{t.push({op:"add",path:"/constraints/-",value:i})}):t.push({op:"add",path:"/constraints/-",value:n.constraint});break;case"removeConstraint":{let i=e.constraints?.findIndex(s=>Array.isArray(s)?s.some(r=>r.name===n.name):s.name===n.name);i!==void 0&&i>=0&&t.push({op:"remove",path:`/constraints/${i}`});break}case"modifyConstraint":{let i=nt(e,n.name);i&&Object.entries(n.changes).forEach(([s,r])=>{t.push({op:"replace",path:`${i}/${s}`,value:r})});break}}return t}function nt(n,e){if(!n.constraints)return null;for(let t=0;t<n.constraints.length;t++){let i=n.constraints[t];if(i.name===e)return`/constraints/${t}`;if(xe(i)){let s=Ee(i.rules,e);if(s)return`/constraints/${t}${s}`}}return null}function xe(n){return n&&"operator"in n&&"rules"in n}function Ee(n,e){for(let t=0;t<n.length;t++){let i=n[t];if("name"in i&&i.name===e)return`/rules/${t}`;if(xe(i)){let s=Ee(i.rules,e);if(s)return`/rules/${t}${s}`}}return null}function re(n,e){let t={...n};return se(n)&&se(e)&&Object.keys(e).forEach(i=>{se(e[i])?i in n?t[i]=re(n[i],e[i]):Object.assign(t,{[i]:e[i]}):Object.assign(t,{[i]:e[i]})}),t}function se(n){return n&&typeof n=="object"&&!Array.isArray(n)}function U(n){return n instanceof RegExp?n.toString().slice(1,-1):JSON.stringify(n)}function Ce(n,e){let t=o=>({value:o}),i=o=>({issues:o}),s=(o,c,d)=>{switch(c){case"string":return typeof o!="string"?[{message:`Expected string, got ${typeof o}`,path:d}]:[];case"number":return typeof o!="number"||isNaN(o)?[{message:`Expected number, got ${typeof o}`,path:d}]:[];case"boolean":return typeof o!="boolean"?[{message:`Expected boolean, got ${typeof o}`,path:d}]:[];case"array":return Array.isArray(o)?[]:[{message:`Expected array, got ${typeof o}`,path:d}];case"set":return!Array.isArray(o)||new Set(o).size!==o.length?[{message:`Expected unique array, got ${typeof o}`,path:d}]:[];case"object":return typeof o!="object"||o===null||Array.isArray(o)?[{message:`Expected object, got ${typeof o}`,path:d}]:[];case"dynamic":return[];default:return[{message:`Unknown type '${c}'`,path:d}]}};function r(o,c,d,u,m){let h=[],g=o.rules.map((f,p)=>{let x=[...u,`rules[${p}]`];if("rules"in f){if(m.has(f.name))return!0;m.add(f.name);let C=r(f,c,d,x,m);return h.push(...C),C.length===0}else{let C=d[f.predicate];if(!C)return h.push({message:`Predicate '${f.predicate}' not found`,path:x}),!1;let $=C({data:c,field:f.field,arguments:f.parameters});if(!$){let E=f.field?` for field '${f.field}'`:"";h.push({message:f.errorMessage||`Constraint '${f.name}' failed${E} with params ${U(f.parameters)}`,path:x})}return $}});return(()=>{switch(o.operator){case"and":return g.every(f=>f);case"or":return g.some(f=>f);case"not":return!g.every(f=>f);case"nor":return!g.some(f=>f);case"xor":return g.filter(f=>f).length===1}})()||h.push({message:`Constraint group '${o.name}' failed`,path:u}),h}function a(o,c,d,u,m,h=new Set){let g=[],D=new Set(Object.values(c.fields).map(f=>f.name));Object.entries(c.fields).forEach(([f,p])=>{let x=[...u,p.name],C=Object.hasOwnProperty.call(o,p.name)?o[p.name]:void 0;if(p.required&&C==null){g.push({message:`Field '${p.name}' is required`,path:x});return}if(C!==void 0){if(g.push(...s(C,p.type,x)),(p.type==="array"||p.type==="set")&&p.itemsType&&Array.isArray(C)&&(C.forEach(($,E)=>g.push(...s($,p.itemsType,[...x,E.toString()]))),p.nestedSchema)){let $=m[p.nestedSchema.id];$?C.forEach((E,I)=>{typeof E=="object"&&E!==null&&(h.has(p.nestedSchema.id)?g.push({message:`Circular reference detected at '${p.nestedSchema.id}'`,path:[...x,I.toString()]}):(h.add(p.nestedSchema.id),g.push(...a(E,$,d,[...x,I.toString()],m,h)),h.delete(p.nestedSchema.id)))}):g.push({message:`Nested schema '${p.nestedSchema.id}' not found`,path:x})}if(p.type==="object"&&p.nestedSchema){let $=m[p.nestedSchema.id];$?typeof C=="object"&&C!==null&&(h.has(p.nestedSchema.id)?g.push({message:`Circular reference detected at '${p.nestedSchema.id}'`,path:x}):(h.add(p.nestedSchema.id),g.push(...a(C,$,d,x,m,h)),p.nestedSchema.constraints?.forEach((E,I)=>{if("rules"in E)g.push(...r(E,C,d,[...x,`constraints[${I}]`],h));else{let l=d[E.predicate];l?l({data:C,field:void 0,arguments:E.parameters})||g.push({message:E.errorMessage||`Constraint '${E.name}' failed with params ${U(E.parameters)}`,path:[...x,`constraints[${I}]`]}):g.push({message:`Predicate '${E.predicate}' not found`,path:[...x,`constraints[${I}]`]})}}),h.delete(p.nestedSchema.id))):g.push({message:`Nested schema '${p.nestedSchema.id}' not found`,path:x})}p.constraints?.forEach(($,E)=>{if("rules"in $)g.push(...r($,o,d,[...x,`constraints[${E}]`],h));else{let I=d[$.predicate];I?I({data:o,field:p.name,arguments:$.parameters})||g.push({message:$.errorMessage||`Constraint '${$.name}' failed for field '${p.name}' with params ${U($.parameters)}`,path:[...x,`constraints[${E}]`]}):g.push({message:`Predicate '${$.predicate}' not found`,path:[...x,`constraints[${E}]`]})}})}});for(let f in o)Object.hasOwnProperty.call(o,f)&&!D.has(f)&&g.push({message:`Unexpected field '${f}'`,path:[...u,f]});return c.constraints?.forEach((f,p)=>{if("rules"in f)g.push(...r(f,o,d,[...u,`constraints[${p}]`],h));else{let x=d[f.predicate];if(!x)g.push({message:`Predicate '${f.predicate}' not found`,path:[...u,`constraints[${p}]`]});else if(!x({data:o,field:f.field,arguments:f.parameters})){let $=f.field?` for field '${f.field}'`:"";g.push({message:f.errorMessage||`Constraint '${f.name}' failed${$} with params ${U(f.parameters)}`,path:[...u,`constraints[${p}]`]})}}}),g}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,d=a(c,n,e,[],n.nestedSchemas||{});return d.length>0?i(d):t(c)},types:{input:{},output:{}}}}}var F=class extends Error{constructor(t,i){super(t);this.errors=i;this.name="SchemaValidationError"}};var ce=n=>({value:n}),j=n=>({issues:n}),S=(n,e,t=!0)=>n===void 0&&!t?[]:typeof n!="string"||n.trim()===""?[{message:"Must be a non-empty string",path:[e]}]:[],Te=(n,e)=>{let t=["string","number","boolean","array","set","object","dynamic"];return typeof n!="string"||!t.includes(n)?[{message:`Must be one of ${t.join(", ")}`,path:[e]}]:[]},it=(n,e)=>{let t=["normal","unique","btree","hash","spatial","fulltext","gi","expression","composite"];return typeof n!="string"||!t.includes(n)?[{message:`Must be one of ${t.join(", ")}`,path:[e]}]:[]},De=(n,e)=>{let t=["and","or","not","nor","xor"];return typeof n!="string"||!t.includes(n)?[{message:`Must be one of ${t.join(", ")}`,path:[e]}]:[]},Y=(n,e,t=!1)=>n===void 0&&!t?[]:typeof n!="boolean"?[{message:"Must be a boolean",path:[e]}]:[],at=(n,e,t)=>{if(n===void 0)return[];switch(e){case"string":if(typeof n=="string"||Array.isArray(n)&&n.every(i=>typeof i=="string")||n instanceof RegExp||typeof n=="object"&&n!==null&&"field"in n&&typeof n.field=="string")return[];break;case"number":if(typeof n=="number"||Array.isArray(n)&&n.every(i=>typeof i=="number")||typeof n=="object"&&n!==null&&"precision"in n&&typeof n.precision=="number")return[];break;case"boolean":if(typeof n=="boolean")return[];break;case"array":case"set":if(typeof n=="number"||typeof n=="object"&&n!==null&&"minItems"in n&&typeof n.minItems=="number")return[];break;case"object":if(typeof n=="object"&&n!==null&&"schema"in n)return[];break;case"dynamic":return[]}return[{message:`Invalid parameters for type '${e}'`,path:[t]}]},de=(n,e)=>{let t=[],i=["predicate","name"],s=["type","predicate","field","parameters","name","description","errorMessage"],r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),t.push(...S(n.predicate,`${e}.predicate`)),n.type!==void 0&&n.type!=="schema"&&t.push({message:"Type must be 'schema' if present",path:[`${e}.type`]}),n.field!==void 0&&typeof n.field!="string"&&t.push({message:"Field must be a string",path:[`${e}.field`]}),n.parameters!==void 0&&(!n.type||n.type!=="schema")&&t.push(...at(n.parameters,"dynamic",`${e}.parameters`)),t.push(...S(n.description,`${e}.description`,!1)),t.push(...S(n.errorMessage,`${e}.errorMessage`,!1)),t},ue=(n,e)=>{let t=[],i=["name","operator","rules"],s=["name","operator","rules"],r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),t.push(...De(n.operator,`${e}.operator`)),!Array.isArray(n.rules)||n.rules.length===0?t.push({message:"Rules must be a non-empty array",path:[`${e}.rules`]}):n.rules.forEach((a,o)=>{"rules"in a?t.push(...ue(a,`${e}.rules[${o}]`)):t.push(...de(a,`${e}.rules[${o}]`))}),t},L=(n,e)=>{if(!Array.isArray(n))return[{message:"Must be an array",path:[e]}];let t=[];return n.forEach((i,s)=>{"rules"in i?t.push(...ue(i,`${e}[${s}]`)):t.push(...de(i,`${e}[${s}]`))}),t},ke=(n,e)=>{let t=[],i=["operator","field"],s=["operator","field","value","conditions"],r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...De(n.operator,`${e}.operator`)),t.push(...S(n.field,`${e}.field`)),n.conditions!==void 0&&(Array.isArray(n.conditions)?n.conditions.forEach((a,o)=>t.push(...ke(a,`${e}.conditions[${o}]`))):t.push({message:"Conditions must be an array",path:[`${e}.conditions`]})),t},Ie=(n,e)=>{let t=[],i=["fields","type","name"],s=["fields","type","unique","partial","description","order","name"],r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),t.push(...it(n.type,`${e}.type`)),(!Array.isArray(n.fields)||n.fields.length===0||!n.fields.every(a=>typeof a=="string"))&&t.push({message:"Fields must be a non-empty array of strings",path:[`${e}.fields`]}),t.push(...Y(n.unique,`${e}.unique`,!1)),n.partial&&t.push(...ke(n.partial,`${e}.partial`)),t.push(...S(n.description,`${e}.description`,!1)),n.order!==void 0&&!["asc","desc"].includes(n.order)&&t.push({message:"Order must be 'asc' or 'desc'",path:[`${e}.order`]}),t},Q=(n,e)=>{if(!Array.isArray(n))return[{message:"Must be an array",path:[e]}];let t=[];return n.forEach((i,s)=>t.push(...Ie(i,`${e}[${s}]`))),t},fe=(n,e)=>{let t=[],i=["name","type"],s=["name","type","required","constraints","default","itemsType","nestedSchema","deprecated","reference","description","unique"],r=n;if(i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),t.push(...Te(n.type,`${e}.type`)),t.push(...Y(n.required,`${e}.required`,!1)),n.constraints&&t.push(...L(n.constraints,`${e}.constraints`)),n.itemsType&&t.push(...Te(n.itemsType,`${e}.itemsType`)),n.nestedSchema){let a=["id"],o=["id","constraints","indexes"],c=n.nestedSchema;a.forEach(d=>{c[d]===void 0&&t.push({message:`${d} is required`,path:[`${e}.nestedSchema.${d}`]})}),Object.keys(c).forEach(d=>{o.includes(d)||t.push({message:"Unknown property",path:[`${e}.nestedSchema.${d}`]})}),t.push(...S(n.nestedSchema.id,`${e}.nestedSchema.id`)),n.nestedSchema.constraints&&t.push(...L(n.nestedSchema.constraints,`${e}.nestedSchema.constraints`)),n.nestedSchema.indexes&&t.push(...Q(n.nestedSchema.indexes,`${e}.nestedSchema.indexes`))}if(t.push(...Y(n.deprecated,`${e}.deprecated`,!1)),n.reference){let a=["schema","field"],o=["schema","field"],c=n.reference;a.forEach(d=>{c[d]===void 0&&t.push({message:`${d} is required`,path:[`${e}.reference.${d}`]})}),Object.keys(c).forEach(d=>{o.includes(d)||t.push({message:"Unknown property",path:[`${e}.reference.${d}`]})}),t.push(...S(n.reference.schema,`${e}.reference.schema`)),t.push(...S(n.reference.field,`${e}.reference.field`))}return t.push(...S(n.description,`${e}.description`,!1)),t.push(...Y(n.unique,`${e}.unique`,!1)),t},Pe=(n,e)=>{let t=[],i=["name","fields"],s=["name","description","fields","indexes","constraints","metadata"],r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),typeof n.fields!="object"?t.push({message:"Fields must be a non-empty object",path:[`${e}.fields`]}):Object.entries(n.fields).forEach(([a,o])=>{t.push(...fe(o,`${e}.fields.${a}`))}),t.push(...S(n.description,`${e}.description`,!1)),n.indexes&&t.push(...Q(n.indexes,`${e}.indexes`)),n.constraints&&t.push(...L(n.constraints,`${e}.constraints`)),n.metadata!==void 0&&(typeof n.metadata!="object"||n.metadata===null)&&t.push({message:"Metadata must be an object",path:[`${e}.metadata`]}),t},st=n=>{if(typeof n!="object"||n===null)return j([{message:"Schema must be an object",path:[]}]);let e=n,t=[],i=["name","version","fields","nestedSchemas"],s=["name","version","description","fields","nestedSchemas","indexes","constraints","metadata","dependencies","migrations","mock"],r=e;if(i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[a]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[a]})}),t.push(...S(e.name,"name")),t.push(...S(e.version,"version")),typeof e.fields!="object"?t.push({message:"Fields must be a non-empty object",path:["fields"]}):Object.entries(e.fields).forEach(([a,o])=>{t.push(...fe(o,`fields.${a}`))}),typeof e.nestedSchemas!="object")t.push({message:"NestedSchemas must be a non-empty object",path:["nestedSchemas"]});else{let a=Object.keys(e.nestedSchemas);Object.entries(e.nestedSchemas).forEach(([o,c])=>t.push(...Pe(c,`nestedSchemas.${o}`))),Object.entries(e.fields).forEach(([o,c])=>{c.nestedSchema&&!a.includes(c.nestedSchema.id)&&t.push({message:`nestedSchema.id '${c.nestedSchema.id}' must match a nestedSchemas key`,path:[`fields.${o}.nestedSchema.id`]})})}return t.push(...S(e.description,"description",!1)),e.indexes&&t.push(...Q(e.indexes,"indexes")),e.constraints&&t.push(...L(e.constraints,"constraints")),e.metadata!==void 0&&(typeof e.metadata!="object"||e.metadata===null)&&t.push({message:"Metadata must be an object",path:["metadata"]}),e.dependencies!==void 0&&(!Array.isArray(e.dependencies)||!e.dependencies.every(a=>typeof a=="string"))&&t.push({message:"Dependencies must be an array of strings",path:["dependencies"]}),e.migrations!==void 0&&(Array.isArray(e.migrations)?e.migrations.forEach((a,o)=>t.push(...Re(a,`migrations[${o}]`))):t.push({message:"Migrations must be an array",path:["migrations"]})),e.mock!==void 0&&typeof e.mock!="function"&&t.push({message:"Mock must be a function",path:["mock"]}),t.length>0?j(t):ce(e)},oe=(n,e)=>{let t=[];switch(n.type||t.push({message:"type is required",path:[`${e}.type`]}),n.type){case"modifyProperty":{let i=["type","id","changes"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`)),(n.changes===void 0||typeof n.changes!="object")&&t.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addField":{let i=["type","id","definition"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`)),t.push(...fe(n.definition,`${e}.definition`));break}case"removeField":case"deprecateField":{let i=["type","id"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`));break}case"modifyField":{let i=["type","id","changes"],s=["type","id","changes","nestedSchemaChanges"],r=n;if(i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`)),typeof n.changes!="object"&&t.push({message:"Changes must be an object",path:[`${e}.changes`]}),n.nestedSchemaChanges){let a=["id","constraints","indexes"],o=n.nestedSchemaChanges;Object.keys(o).forEach(c=>{a.includes(c)||t.push({message:"Unknown property",path:[`${e}.nestedSchemaChanges.${c}`]})}),t.push(...S(o.id,`${e}.nestedSchemaChanges.id`,!1)),o.constraints&&t.push(...L(o.constraints,`${e}.nestedSchemaChanges.constraints`)),o.indexes&&t.push(...Q(o.indexes,`${e}.nestedSchemaChanges.indexes`))}break}case"addIndex":{let i=["type","definition"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...Ie(n.definition,`${e}.definition`));break}case"removeIndex":{let i=["type","name"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`));break}case"modifyIndex":{let i=["type","name","changes"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),typeof n.changes!="object"&&t.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addConstraint":{let i=["type","constraint"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),"rules"in n.constraint?t.push(...ue(n.constraint,`${e}.constraint`)):t.push(...de(n.constraint,`${e}.constraint`));break}case"removeConstraint":{let i=["type","name"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`));break}case"modifyConstraint":{let i=["type","name","changes"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),typeof n.changes!="object"&&t.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addNestedSchema":{let i=["type","id","definition"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`)),t.push(...Pe(n.definition,`${e}.definition`));break}case"removeNestedSchema":{let i=["type","id"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`));break}case"modifyNestedSchema":{let i=["type","id","changes"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`)),typeof n.changes!="object"&&t.push({message:"Changes must be an object",path:[`${e}.changes`]});break}default:t.push({message:"Unknown schema change type",path:[`${e}.type`]})}return t},rt=(n,e)=>{let t=[],i=["forward","backward"],s=i,r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),typeof n.forward!="function"&&t.push({message:"Forward must be a function",path:[`${e}.forward`]}),typeof n.backward!="function"&&t.push({message:"Backward must be a function",path:[`${e}.backward`]}),t},Re=(n,e)=>{let t=[],i=["id","schemaVersion","changes","description","status","transform","createdAt","checksum"],s=[...i,"rollback","dependencies"],r=n;i.forEach(o=>{r[o]===void 0&&t.push({message:`${o} is required`,path:[`${e}.${o}`]})}),Object.keys(r).forEach(o=>{s.includes(o)||t.push({message:"Unknown property",path:[`${e}.${o}`]})}),t.push(...S(n.id,`${e}.id`)),t.push(...S(n.schemaVersion,`${e}.schemaVersion`)),t.push(...S(n.description,`${e}.description`));let a=["pending","applied","failed"];return a.includes(n.status)||t.push({message:`Status must be one of ${a.join(", ")}`,path:[`${e}.status`]}),!Array.isArray(n.changes)||n.changes.length===0?t.push({message:"Changes must be a non-empty array",path:[`${e}.changes`]}):n.changes.forEach((o,c)=>t.push(...oe(o,`${e}.changes[${c}]`))),n.rollback!==void 0&&(Array.isArray(n.rollback)?n.rollback.forEach((o,c)=>t.push(...oe(o,`${e}.rollback[${c}]`))):t.push({message:"Rollback must be an array",path:[`${e}.rollback`]})),typeof n.transform=="string"?t.push(...S(n.transform,`${e}.transform`)):typeof n.transform=="object"&&n.transform!==null?t.push(...rt(n.transform,`${e}.transform`)):t.push({message:"Transform must be a string or object",path:[`${e}.transform`]}),t.push(...S(n.createdAt,`${e}.createdAt`)),n.dependencies!==void 0&&(!Array.isArray(n.dependencies)||!n.dependencies.every(o=>typeof o=="string"))&&t.push({message:"Dependencies must be an array of strings",path:[`${e}.dependencies`]}),t.push(...S(n.checksum,`${e}.checksum`)),t},Ae={"~standard":{version:1,vendor:"xAI",validate:st,types:{input:{},output:{}}}};var Me={"~standard":{version:1,vendor:"xAI",validate:n=>{if(typeof n!="object"||n===null)return j([{message:"Migration must be an object",path:[]}]);let e=n,t=Re(e,"");return t.length>0?j(t):ce(e)},types:{input:{},output:{}}}},Oe={"~standard":{version:1,vendor:"xAI",validate:n=>{if(!Array.isArray(n))return j([{message:"SchemaChanges must be an array",path:[]}]);let e=n,t=[];return e.forEach((i,s)=>t.push(...oe(i,`[${s}]`))),t.length>0?j(t):ce(e)},types:{input:[],output:[]}}};function me(n){try{return!Me["~standard"].validate(n).issues}catch(e){throw new F("Invalid migration definition",e)}}function he(n){try{return!Oe["~standard"].validate(n).issues}catch(e){throw new F("Invalid schema definition",e)}}function N(n){try{return!Ae["~standard"].validate(n).issues}catch(e){throw new F("Invalid schema definition",e)}}var ot=N;var O=async n=>{if(typeof window<"u"&&crypto.subtle){let t=new TextEncoder().encode(n),i=await crypto.subtle.digest("SHA-256",t);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(n).digest("hex")}};function ct(n){let e=n.match(/^(\d+)\.(\d+)\.(\d+)$/);if(!e)throw new Error(`Invalid version format: ${n}. Expected format: major.minor.patch`);return{major:parseInt(e[1],10),minor:parseInt(e[2],10),patch:parseInt(e[3],10)}}function dt(n,e){if(e&&"field"in n&&n.field){let t=e.fields[n.field];if(t)return t.type}if("parameters"in n){let t=n.parameters;if(t instanceof RegExp||Array.isArray(t)&&typeof t[0]=="string")return"string";if(typeof t=="number"||Array.isArray(t)&&typeof t[0]=="number")return"number";if(typeof t=="boolean")return"boolean";if(typeof t=="object"&&t!==null){if("minItems"in t||"maxItems"in t)return"array";if("schema"in t)return"object"}}}function ut(n){return n.required===!0||n.type!==void 0||n.itemsType!==void 0||n.nestedSchema!==void 0||n.reference!==void 0||n.unique===!0}function ft(n,e,t){switch(t){case"string":if(n instanceof RegExp&&e instanceof RegExp)return n.source!==e.source;if(Array.isArray(n)&&Array.isArray(e))return e.length<n.length||!n.every(i=>e.includes(i));break;case"number":if(typeof n=="object"&&typeof e=="object"&&"precision"in n&&"precision"in e)return e.precision<n.precision||(e.scale??0)<(n.scale??0);if(Array.isArray(n)&&Array.isArray(e))return e.length<n.length||!n.every(i=>e.includes(i));break;case"array":if(typeof n=="object"&&typeof e=="object"&&"minItems"in n&&"maxItems"in n&&"minItems"in e&&"maxItems"in e)return e.minItems>n.minItems||e.maxItems<n.maxItems;break;case"object":if(typeof n=="object"&&typeof e=="object"&&"schema"in n&&"schema"in e)return Object.keys(e.schema).length>Object.keys(n.schema).length;break}return!1}function mt(n,e){let t={or:1,xor:2,and:3,not:4,nor:4};return!!(e.operator&&t[e.operator]>t[n.operator]||e.rules&&e.rules.length>n.rules.length)}function ht(n,e,t){if(!e)return!0;if("rules"in e&&"rules"in n)return mt(e,n);if("predicate"in n&&n.predicate!==void 0)return!0;if("parameters"in n&&n.parameters!==void 0){let i=dt(e,t);return i?ft(e.parameters,n.parameters,i):!0}return!1}function lt(n,e){switch(n.type){case"removeField":case"removeIndex":return"major";case"modifyField":return ut(n.changes)?"major":n.changes.deprecated?"minor":"patch";case"modifyIndex":return n.changes.unique!==void 0||n.changes.fields!==void 0?"major":"minor";case"addConstraint":return"major";case"removeConstraint":return"minor";case"modifyConstraint":let t=e?.constraints?.find(i=>"name"in i&&i.name===n.name);return ht(n.changes,t,e)?"major":"minor";case"addField":case"addIndex":case"deprecateField":return"minor";default:throw new Error(`Unhandled change type: ${JSON.stringify(n)}`)}}function pt(n){let e=new Set,t=new Set,i=new Set,s=new Set;for(let r of n)switch(r.type){case"addField":if(t.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(s.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(s.has(r.id))throw new Error(`Cannot remove field that is being deprecated: ${r.id}`);t.add(r.id);break;case"modifyField":if(t.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(s.has(r.id))throw new Error(`Cannot modify field that is being deprecated: ${r.id}`);e.add(r.id);break;case"deprecateField":if(t.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}`);s.add(r.id);break}}function yt(n){let e=new Set,t=new Set,i=new Set;for(let s of n)switch(s.type){case"addConstraint":let r=s.constraint,a=("name"in r,r.name);if(t.has(a))throw new Error(`Cannot add previously removed constraint: ${a}`);if(e.has(a))throw new Error(`Cannot add already modified constraint: ${a}`);i.add(a);break;case"removeConstraint":if(i.has(s.name))throw new Error(`Cannot remove newly added constraint: ${s.name}`);if(e.has(s.name))throw new Error(`Cannot remove modified constraint: ${s.name}`);t.add(s.name);break;case"modifyConstraint":if(t.has(s.name))throw new Error(`Cannot modify removed constraint: ${s.name}`);if(i.has(s.name))throw new Error(`Cannot modify newly added constraint: ${s.name}`);e.add(s.name);break}}function le(n,e,t){if(e.length===0)throw new Error("No changes provided");pt(e),yt(e);let i=ct(n),s="patch";for(let r of e){let a=lt(r,t);if(a==="major"){s="major";break}else a==="minor"&&s==="patch"&&(s="minor")}switch(s){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 A(n,e){let t=d=>d.split(".").map(u=>parseInt(u,10)||0),[i,s,r]=t(n),[a,o,c]=t(e);return i-a||s-o||r-c}function gt(n){return n.sort(A)}var v=class extends Error{constructor(t,i,s,r){super(t);this.code=i;this.migrationId=s;this.cause=r;this.name="MigrationError"}},Fe=(h=>(h.INVALID_SCHEMA="INVALID_SCHEMA",h.INVALID_MIGRATION="INVALID_MIGRATION",h.CHECKSUM_MISMATCH="CHECKSUM_MISMATCH",h.TIMEOUT="TIMEOUT",h.MEMORY_LIMIT="MEMORY_LIMIT",h.CONCURRENT_OPERATION="CONCURRENT_OPERATION",h.TRANSFORM_ERROR="TRANSFORM_ERROR",h.VERSION_NOT_FOUND="VERSION_NOT_FOUND",h.CIRCULAR_DEPENDENCY="CIRCULAR_DEPENDENCY",h.STREAM_ERROR="STREAM_ERROR",h.ROLLBACK_ERROR="ROLLBACK_ERROR",h.MISSING_TRANSFORM="MISSING_TRANSFORM",h))(Fe||{}),pe=class n{currentSchema;history=[];migrations=[];isProcessing=!1;constructor(e,t,i){try{if(!N(e))throw new v("Invalid initial schema","INVALID_SCHEMA");if(this.currentSchema=e,t){if(!t.every(s=>me(s)))throw new v("Invalid migration configuration","INVALID_MIGRATION");this.migrations=t.sort((s,r)=>A(s.schemaVersion,r.schemaVersion))}i&&(this.history=i.sort((s,r)=>A(s.version,r.version)))}catch(s){throw s instanceof v?s:new v("Failed to initialize MigrationEngine","INVALID_SCHEMA",void 0,s)}}data(){return{schema:this.currentSchema,history:this.history,migrations:this.migrations}}async generateChecksum(e){try{let t=JSON.stringify({id:e.id,schemaVersion:e.schemaVersion,changes:e.changes,description:e.description,rollback:e.rollback,createdAt:e.createdAt});return await O(t)}catch(t){throw new v("Checksum generation failed","CHECKSUM_MISMATCH",e.id,t)}}async add(e){if(this.isProcessing)throw new v("Concurrent operation","CONCURRENT_OPERATION");if(!e.changes?.length)throw new v("Migration must include changes","INVALID_MIGRATION");try{e.changes.forEach(i=>he(i))}catch(i){throw new v("Invalid schema changes","INVALID_MIGRATION",void 0,i)}let t={id:Date.now().toString(),schemaVersion:this.currentSchema.version,changes:e.changes,description:e.description,status:"pending",rollback:e.rollback,transform:e.transform,createdAt:new Date().toISOString(),checksum:""};t.checksum=await this.generateChecksum(t),this.migrations.push(t)}async dryRun(e,t,i){if(this.isProcessing)throw new v("Concurrent operation","CONCURRENT_OPERATION");try{this.isProcessing=!0;let s={...this.currentSchema},r=this.getRelevantMigrations(t,i),a=r.reduce((c,d)=>{let u=t==="forward"?d.changes:d.rollback||[];return this.applySchemaChanges(c,u,d.id)},s),o=await n.processMigrationList(e,t,r);return{newSchema:a,dataPreview:o}}catch(s){throw s instanceof v?s:new v("Dry run failed","INVALID_SCHEMA",void 0,s)}finally{this.isProcessing=!1}}getRelevantMigrations(e,t){return[...this.migrations].filter(i=>{let s=e==="forward"?"pending":"applied",r=t?A(i.schemaVersion,t)>=0:!0;return i.status===s&&r}).sort((i,s)=>e==="forward"?i.id.localeCompare(s.id):s.id.localeCompare(i.id))}applySchemaChanges(e,t,i){try{let s=le(e.version,t);return t.map(a=>{try{return ae(a,e)}catch(o){throw new v("Invalid schema change","INVALID_SCHEMA",i,o)}}).reduce((a,o)=>{try{return W(a,o)}catch(c){throw new v("Failed to apply patch","INVALID_SCHEMA",i,c)}},{...e,version:s})}catch(s){throw s instanceof v?s:new v("Schema update failed","INVALID_SCHEMA",i,s)}}async prepareMigration(){let e=this.migrations.filter(t=>t.status==="pending");return await this.validateMigrations(e),e}async migrate(e){if(this.isProcessing)throw new v("Concurrent operation","CONCURRENT_OPERATION");let t=await this.prepareMigration();try{this.isProcessing=!0,this.transformSchema("forward");let i=await n.processMigrationList(e,"forward",t);return this.markMigrationsApplied(t),i}finally{this.isProcessing=!1}}async validateMigrations(e){await Promise.all(e.map(async t=>{let i=await this.generateChecksum(t);if(t.checksum!==i)throw new v("Checksum mismatch","CHECKSUM_MISMATCH",t.id)}))}markMigrationsApplied(e){this.migrations=this.migrations.map(t=>e.some(i=>i.id===t.id)?{...t,status:"applied"}:t)}async rollback(e){if(this.isProcessing)throw new v("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,t){if(this.isProcessing)throw new v("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 s=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 t;for(let o=0;o<r;o++)this.transformSchema("backward");let a=await n.processMigrationList(t,"backward",s);return this.migrations=this.migrations.map(o=>o.schemaVersion===e&&o.status==="applied"?{...o,status:"pending"}:o),a}finally{this.isProcessing=!1}}static async processMigrationList(e,t,i){return(await Promise.all(i.map(async a=>{try{let o=await this.resolveTransform(a,t);return{migration:a,transform:o}}catch(o){throw new v(`Failed to resolve transform for migration ${a.id}`,"TRANSFORM_ERROR",a.id,o)}}))).filter(a=>!!a.transform).reduce((a,{migration:o,transform:c})=>a.pipeThrough(new TransformStream({async transform(d,u){try{let m=await c(d);u.enqueue(m)}catch(m){u.error(new v(`Data transformation failed for migration ${o.id}`,"TRANSFORM_ERROR",o.id,m))}}})),e)}static async resolveTransform(e,t){return e.transform?typeof e.transform=="string"?e.transform.startsWith("http://")||e.transform.startsWith("https://")?this.resolveRemoteTransform(e.transform,t):this.resolveLocalTransform(e.transform,t):e.transform[t]:null}static async resolveRemoteTransform(e,t){try{let i=await fetch(e);if(!i.ok)throw new v(`Failed to fetch transform module: ${e}`,"TRANSFORM_ERROR",void 0);let s=await i.text();if(typeof window<"u"){let r=new Blob([s],{type:"application/javascript"});return(await import(URL.createObjectURL(r))).default[t]}else{let{runInNewContext:r}=await import("vm"),a={module:{exports:{}},console};return r(s,a,e),a.module.exports[t]}}catch(i){throw new v(`Failed to load remote transform module: ${e}`,"TRANSFORM_ERROR",void 0,i)}}static async resolveLocalTransform(e,t){try{return(await import(e)).default[t]}catch(i){throw new v(`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 t=this.migrations.filter(i=>i.status==="pending").flatMap(i=>i.changes);if(!t.length)return;this.history.push(structuredClone(this.currentSchema)),this.currentSchema=t.reduce((i,s)=>this.applySchemaChanges(i,[s]),this.currentSchema)}catch(t){throw t instanceof v?t:new v("Schema transformation failed","INVALID_SCHEMA",void 0,t)}}};var je=n=>{let e=[],t=[];return{addField:(i,s)=>{e.push({type:"addField",id:i,definition:s}),t.push({type:"removeField",id:i})},removeField:i=>{e.push({type:"removeField",id:i});let s=n.fields[i];s&&t.push({type:"addField",id:i,definition:s})},modifyField:(i,s)=>{e.push({type:"modifyField",id:i,changes:s});let r=n.fields[i];r&&t.push({type:"modifyField",id:i,changes:r})},deprecateField:i=>{e.push({type:"deprecateField",id:i}),t.push({type:"modifyField",id:i,changes:{deprecated:!1}})},addIndex:i=>{e.push({type:"addIndex",definition:i}),t.push({type:"removeIndex",name:i.name})},removeIndex:i=>{e.push({type:"removeIndex",name:i});let s=n.indexes?.find(r=>r.name===i);s&&t.push({type:"addIndex",definition:s})},modifyIndex:(i,s)=>{e.push({type:"modifyIndex",name:i,changes:s});let r=n.indexes?.find(a=>a.name===i);r&&t.push({type:"modifyIndex",name:i,changes:r})},addConstraint:i=>{e.push({type:"addConstraint",constraint:i}),t.push({type:"removeConstraint",name:i.name})},removeConstraint:i=>{e.push({type:"removeConstraint",name:i});let s=n.constraints?.find(r=>"name"in r&&r.name===i);s&&t.push({type:"addConstraint",constraint:s})},modifyConstraint:(i,s)=>{e.push({type:"modifyConstraint",name:i,changes:s});let r=n.constraints?.find(a=>"name"in a&&a.name===i);r&&t.push({type:"modifyConstraint",name:i,changes:r})},addNestedSchema:(i,s)=>{e.push({type:"addNestedSchema",id:i,definition:s}),t.push({type:"removeNestedSchema",id:i})},removeNestedSchema:i=>{e.push({type:"removeNestedSchema",id:i});let s=n.nestedSchemas[i];s&&t.push({type:"addNestedSchema",id:i,definition:s})},modifyNestedSchema:(i,s)=>{e.push({type:"modifyNestedSchema",id:i,changes:s});let r=n.nestedSchemas[i];r&&t.push({type:"modifyNestedSchema",id:i,changes:r})},changes:()=>({migrate:e,rollback:t})}};var dn=require("@isomorphic-git/lightning-fs"),T=q(require("isomorphic-git"),1),G=q(require("isomorphic-git/http/web"),1);var qe=q(require("@isomorphic-git/lightning-fs"),1);function Ne(n){let e=n.toString(),t=e.substring(e.indexOf("(")+1,e.indexOf(")")),i=e.substring(e.indexOf("{")+1,e.lastIndexOf("}")).trim();return JSON.stringify({params:t,body:i})}function Ve(n){let{params:e,body:t}=JSON.parse(n),i=Object.getPrototypeOf(function*(){}).constructor;return new i(e,t)}function ye(n){let e=n.toString(),t=e.match(/\(([^)]*)\)\s*=>\s*(.+)/s),i=e.match(/function\s*\(([^)]*)\)\s*{([\s\S]*)}/),s=e.match(/([^(]*)\(([^)]*)\)\s*{([\s\S]*)}/),r,a;return t?(r=t[1],a=t[2].includes("{")?t[2].substring(1,t[2].length-1).trim():`return ${t[2]}`):i?(r=i[1],a=i[2].trim()):s?(r=s[2],a=s[3].trim()):(r=e.substring(e.indexOf("(")+1,e.indexOf(")")),a=e.substring(e.indexOf("{")+1,e.lastIndexOf("}")).trim()),JSON.stringify({params:r,body:a,type:t?"arrow":i?"function":s?"method":"unknown"})}function ge(n){let{params:e,body:t,type:i}=JSON.parse(n),s=new Function(e,t);return i==="arrow"&&Object.defineProperty(s,"toString",{value:()=>`(${e}) => ${t}`,configurable:!0}),s}var Ue=require("buffer");window.Buffer=Ue.Buffer;var _=class{fs;fsp;rootDir;constructor(e="/registry"){this.fs=new qe.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||!N(e))throw new Error("Invalid schema");let t=`${this.rootDir}/${e.name}`;if(await this.fileExists(`${t}/schema.json`))throw new Error(`Schema ${e.name} already exists`);return await this.fsp.mkdir(t),await this.fsp.mkdir(`${t}/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 t=`${this.rootDir}/${e.name}`;if(!await this.fileExists(`${t}/schema.json`))throw new Error(`Schema ${e.name} not found`);return this.saveSchema(e,"update")}async saveSchema(e,t){let i=`${this.rootDir}/${e.name}`,s=await this.processAndStoreMigrations(i,e),r=this.serializeSchema(e);await this.writeSchemaFile(i,r);let a=await O(r);await this.updateIndex(i,e,a,s,t),await this.updateRegistryMetadata(e,t),await this.sync()}async delete({name:e}){let t=`${this.rootDir}/${e}`;if(!await this.fileExists(`${t}/schema.json`))throw new Error(`Schema ${e} not found`);await this.rmdirRecursive(t);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(t=>({name:t.name,version:t.version}))}async schema({name:e,version:t,migrations:i=!1}){let s=`${this.rootDir}/${e}/schema.json`;if(!await this.fileExists(s))return null;let r=this.deserializeSchema(JSON.parse(String(await this.fsp.readFile(s,"utf8")))),a=await this.readSchemaIndex(e);return t&&t!==a.version&&!a.history.some(o=>o.version===t)?null:(i&&(r.migrations=await this.migrations({name:e,version:t})),r)}async stats({schema:e}){return e?this.readSchemaIndex(e):this.readRegistryMetadata()}async sync(){let e={updated:new Date().toISOString(),hashes:[]},t=await this.listFilesRecursive(this.rootDir);for(let i of t)if(i!==`${this.rootDir}/schema-lock.json`&&i.match(new RegExp("/*.git*/"))===null){let s=String(await this.fsp.readFile(i,"utf8"));e.hashes.push([i,await O(s)])}await this.fsp.writeFile(`${this.rootDir}/schema-lock.json`,JSON.stringify(e),"utf8")}async migrations({name:e,version:t}){let i=await this.readSchemaIndex(e),s=t||i.version,r=[];for(let[a,o]of Object.entries(i.migrations)){let c=`${this.rootDir}/${e}/migrations/${o.hash}.json`;if(await this.fileExists(c)){let d=JSON.parse(String(await this.fsp.readFile(c,"utf8")));A(d.schemaVersion,s)<=0&&r.push(this.deserializeMigration(d))}}return r.sort((a,o)=>A(a.schemaVersion,o.schemaVersion))}async history({name:e}){let t=await this.readSchemaIndex(e),i=this.deserializeSchema(JSON.parse(String(await this.fsp.readFile(`${this.rootDir}/${e}/schema.json`,"utf8"))));return Promise.all(t.history.map(async s=>({...i,version:s.version,description:s.description,migrations:await this.migrations({name:e,version:s.version})})))}async processAndStoreMigrations(e,t){return Promise.all((t.migrations||[]).map(async i=>{let s={...i};if(i.transform?.forward){let o=i.transform;s.transform={forward:ye(o.forward),backward:ye(o.backward||(c=>c))}}let r=JSON.stringify(s),a=await O(r);return await this.fsp.writeFile(`${e}/migrations/${a}.json`,r,"utf8"),{id:i.id,hash:a,checksum:i.checksum}}))}serializeSchema(e){return JSON.stringify({...e,migrations:void 0,mock:e.mock?Ne(e.mock):null})}deserializeSchema(e){return e.mock&&(e.mock=Ve(e.mock)),e}deserializeMigration(e){return e.transform?.forward&&(e.transform={forward:ge(e.transform.forward),backward:ge(e.transform.backward)}),e}async writeSchemaFile(e,t){let i=`${e}/schema.json`;return await this.fsp.writeFile(i,t,"utf8"),i}async updateIndex(e,t,i,s,r){let a=`${e}/index.json`,o=r==="create"?{schema:t.name,version:t.version,history:[],migrations:{}}:JSON.parse(String(await this.fsp.readFile(a,"utf8")));o.history.push({version:t.version,hash:i,date:new Date().toISOString(),description:t.description||(r==="create"?"Initial version":"Updated version"),migrations:s.map(c=>c.id),predicates:[],changelog:[]}),o.version=t.version,s.forEach(({id:c,hash:d,checksum:u})=>{o.migrations[c]={hash:d,checksum:u}}),await this.fsp.writeFile(a,JSON.stringify(o),"utf8")}async updateRegistryMetadata(e,t){let i=await this.readRegistryMetadata();i.schemas[e.name]={name:e.name,version:e.version,description:e.description||"",created:t==="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 t=`${this.rootDir}/${e}/index.json`;if(!await this.fileExists(t))throw new Error(`Schema ${e} not found`);return JSON.parse(String(await this.fsp.readFile(t,"utf8")))}async fileExists(e){try{return await this.fsp.stat(e),!0}catch{return!1}}async rmdirRecursive(e){let t=await this.fsp.readdir(e);for(let i of t){let s=`${e}/${i}`;(await this.fsp.stat(s)).isDirectory()?await this.rmdirRecursive(s):await this.fsp.unlink(s)}await this.fsp.rmdir(e)}async listFilesRecursive(e){let t=[],i=await this.fsp.readdir(e);for(let s of i){let r=`${e}/${s}`;(await this.fsp.stat(r)).isDirectory()?t.push(...await this.listFilesRecursive(r)):t.push(r)}return t}};var we=class{locks=new Map;async acquire(e){let t,i=new Promise(r=>{t=r}),s=this.locks.get(e)||Promise.resolve();return this.locks.set(e,s.then(()=>i)),await s,t}async withLock(e,t){let i=await this.acquire(e);try{return await t()}finally{i()}}},Se=class{cache=new Map;ttl;constructor(e=3e4){this.ttl=e}get(e){let t=this.cache.get(e);return!t||Date.now()-t.timestamp>this.ttl?(this.cache.delete(e),null):t.schema}set(e,t){this.cache.set(e,{schema:t,timestamp:Date.now()})}invalidate(e){e?this.cache.delete(e):this.cache.clear()}};async function X(n,e){try{return await n()}catch(t){throw console.error(`${e}:`,t),new Error(`${e}: ${t.message}`)}}async function ee(n,e,t,i,s){await i.init(),await T.default.init({fs:n,dir:e,defaultBranch:t}),await T.default.setConfig({fs:n,dir:e,path:"core.autocrlf",value:"false"}),await T.default.setConfig({fs:n,dir:e,path:"core.eol",value:"lf"}),await T.default.add({fs:n,dir:e,filepath:"."}),await T.default.commit({fs:n,dir:e,message:"chore: initial commit",author:s})}async function $t(n="/registry",e={}){let t=e.mainBranch||"main",i=e.remote,s=e.createRemote??!1,r=e.author||{name:"SchemaRegistry",email:"system@example.com"},a=e.proxy?[e.proxy]:["https://cors.isomorphic-git.org"],o=0,c=new _(n),d=c.fs,u=n.startsWith("/")?n:`/${n}`,m=new we,h=new Se(e.cacheTtl);async function g(l,y){let w=o;do{let b=a[o];try{return await l(b)}catch(k){if(console.warn(`Failed with proxy ${b}: ${k.message}`),o=(o+1)%a.length,o===w)throw new Error(`${y}: All CORS proxies failed`)}}while(!0)}async function D(l,y="."){return X(async()=>(await T.default.add({fs:d,dir:u,filepath:y}),(await T.default.statusMatrix({fs:d,dir:u})).some(([b,k,R])=>k!==R)?await T.default.commit({fs:d,dir:u,message:l,author:r}):null),"Failed to commit changes")}async function f(l,y,w){return X(async()=>{if(await p(l))throw new Error(`Tag ${l} already exists`);await T.default.annotatedTag({fs:d,dir:u,ref:l,message:y,tagger:r,object:w})},`Failed to create tag ${l}`)}async function p(l){try{return(await T.default.listTags({fs:d,dir:u})).includes(l)}catch{return!1}}async function x(l){return(await T.default.listTags({fs:d,dir:u})).filter(b=>b.startsWith(l))}async function C(l){return X(async()=>{let w=(await T.default.listTags({fs:d,dir:u})).filter(b=>b.startsWith(l));for(let b of w)await T.default.deleteTag({fs:d,dir:u,ref:b});return w},`Failed to delete tags with prefix ${l}`)}async function $(l){return X(async()=>{await T.default.checkout({fs:d,dir:u,ref:l})},`Failed to checkout ${l}`)}async function E(l,{delete:y=!1,force:w=!1}={}){i&&await g(async b=>{await T.default.push({fs:d,http:G.default,dir:u,ref:l,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:b,delete:y,force:w})},`Failed to push ${l}`)}async function I(l,y=!0){i&&await g(async w=>{try{await T.default.pull({fs:d,http:G.default,dir:u,ref:l,author:r,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:w,fastForwardOnly:!0})}catch(b){if(!y)console.warn(`Fast-forward pull failed for ${l}, attempting regular pull`),await T.default.pull({fs:d,http:G.default,dir:u,ref:l,author:r,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:w,fastForwardOnly:!1});else throw b}},`Failed to pull ${l}`)}if(i&&!await c.fileExists(u)){let l=u.slice(1);if(await i.exists({name:l}).catch(()=>!1))await g(async w=>{await T.default.clone({fs:d,http:G.default,dir:u,url:i.authURL(),ref:t,singleBranch:!0,depth:1,onAuth:()=>i.credentials(),corsProxy:w})},"Failed to clone repository");else if(s)try{i=await i.create({name:l,private:!0}),await ee(d,u,t,c,r),await T.default.addRemote({fs:d,dir:u,remote:"origin",url:i.url()}),await E(t)}catch(w){console.error("Failed to create and push to remote repository:",w),await ee(d,u,t,c,r)}else await ee(d,u,t,c,r)}else await ee(d,u,t,c,r);return{async init(){return m.withLock("init",()=>c.init())},async create(l){let{name:y,version:w}=l.schema;return m.withLock(`schema:${y}`,async()=>{await $(t),await c.create(l);let b=await D(`feat: create schema ${y}`);b&&await f(`${y}-${w}`,`Version ${w}`,b),h.invalidate(y)})},async update(l){let{name:y,version:w}=l.schema;return m.withLock(`schema:${y}`,async()=>{await $(t),await c.update(l);let b=await D(`fix: update schema ${y}`);b&&await f(`${y}-${w}`,`Version ${w}`,b),h.invalidate(y)})},async delete(l){let{name:y}=l;return m.withLock(`schema:${y}`,async()=>{await $(t),await T.default.remove({fs:d,dir:u,filepath:y}),await c.delete(l);let w=await D(`chore: delete schema ${y}`),b=await x(`${y}-`);if(i&&w){await E(t);for(let k of b)await E(k,{delete:!0,force:!0}).catch(R=>console.warn(`Failed to delete remote tag ${k}: ${R.message}`))}await C(`${y}-`),h.invalidate(y)})},async list(){return m.withLock("list",()=>c.list())},async schema(l){let{name:y,version:w}=l,b=`${y}-${w||"latest"}-${l.migrations||!1}`,k=h.get(b);return k||m.withLock(`schema:${y}`,async()=>{if(w){let V=`${y}-${w}`;if(await p(V))await $(V);else throw new Error(`Version ${w} of schema ${y} not found`)}else await $(t);let R=await c.schema(l);return h.set(b,R),R})},async stats(l){return m.withLock("stats",()=>c.stats(l))},async sync(){return m.withLock("sync",async()=>{if(await $(t),await c.sync(),await D("chore: sync local changes"),i){await I(t,!1),await E(t);let l=await T.default.listTags({fs:d,dir:u});for(let w of l)await E(w,{force:!0});let y=await T.default.listTags({fs:d,dir:u});for(let w of y)l.includes(w)||await E(w,{delete:!0})}h.invalidate()})},async migrations(l){let{name:y,version:w}=l,b=`migrations-${y}-${w||"latest"}`,k=h.get(b);return k||m.withLock(`migrations:${y}`,async()=>{if(w){let V=`${y}-${w}`;if(await p(V))await $(V);else throw new Error(`Version ${w} of schema ${y} not found`)}else await $(t);let R=await c.migrations(l);return h.set(b,R),R})},async history(l){let{name:y}=l,w=`history-${y}`,b=h.get(w);return b||m.withLock(`history:${y}`,async()=>{await $(t);let k=await c.history(l);return h.set(w,k),k})}}}function bt(n,e=!0,t=!0){let i="",s=t?"export ":"",r=new Map,a=(u,m=[])=>{if(!e||!u&&!m.length)return"";let h=u?[u]:[];return m.forEach(g=>h.push(g)),`/**
2
- * ${h.join(`
1
+ "use strict";var We=Object.create;var Z=Object.defineProperty;var Ye=Object.getOwnPropertyDescriptor;var Qe=Object.getOwnPropertyNames;var Ze=Object.getPrototypeOf,Xe=Object.prototype.hasOwnProperty;var et=(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 Qe(e))!Xe.call(t,r)&&r!==n&&Z(t,r,{get:()=>e[r],enumerable:!(i=Ye(e,r))||i.enumerable});return t};var B=(t,e,n)=>(n=t!=null?We(Ze(t)):{},De(e||!t||!t.__esModule?Z(n,"default",{value:t,enumerable:!0}):n,t)),tt=t=>De(Z({},"__esModule",{value:!0}),t);var It={};et(It,{JsonPatchError:()=>F,MigrationEngine:()=>ve,MigrationError:()=>C,MigrationErrorCode:()=>_e,SchemaRegistry:()=>Y,applyPatch:()=>ie,calculateNextVersion:()=>be,compareSemanticVersions:()=>O,createGitSchemaRegistry:()=>kt,createPatch:()=>st,createSchemaMigrationHelper:()=>Ge,createStandardSchemaValidator:()=>Pe,deepMerge:()=>he,docgen:()=>Rt,extractInputFieldGroups:()=>At,formResolver:()=>ct,generateSHA256Hash:()=>L,normalizePath:()=>Re,schemaChangeToPatch:()=>le,schemaToTypes:()=>Dt,serializeParams:()=>K,sortSemanticVars:()=>xt,validate:()=>ht,validateMigration:()=>we,validateSchemaChange:()=>Se,validateSchemaDefinition:()=>H});module.exports=tt(It);var Ct=require("@asaidimu/events");var Tt=require("@asaidimu/events"),re=require("@asaidimu/query");var F=class extends Error{constructor(n,i){super(n);this.operation=i;this.name="JsonPatchError"}};function te(t){let e=Re(t);return e===""?[]:e.substring(1).split("/").map(nt)}function Re(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 nt(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 F(`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 F(`Invalid array index: ${i}`);n=n[r]}else{if(!n.hasOwnProperty(i))throw new F(`Property ${i} not found`);n=n[i]}}return n}function de(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 F(`Invalid array index: ${r}`);return i[a]}return i[r]}function it(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 F(`Invalid array index: ${a}`);s.splice(o,0,n)}else s[a]=n;return t}function ue(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=ue(n,i.path);break;case"removeValue":n=it(n,i.path,i.value);break;case"replace":n=X(ue(n,i.path),i.path,i.value);break;case"copy":{let r=de(n,i.from);n=X(n,i.path,JSON.parse(JSON.stringify(r)));break}case"move":{let r=de(n,i.from);n=X(n,i.path,r),n=ue(n,i.from);break}case"test":{let r=de(n,i.path);if(JSON.stringify(r)!==JSON.stringify(i.value))throw new F("Test operation failed");break}default:throw new F(`Unsupported operation: ${i.op}`)}}catch(r){throw r instanceof F&&(r.operation=i),r}return n}function st(t,e){let n=[];return fe(t,e,"",n),n}function fe(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)?rt(t,e,n,i):at(t,e,n,i):t!==e&&i.push({op:"replace",path:n,value:e})}}function rt(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}):fe(t[a],e[a],s,i)}}function at(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),d=n?`${n}/${c}`:`/${c}`;e.hasOwnProperty(o)?(fe(t[o],e[o],d,i),r.add(o)):i.push({op:"remove",path:d})}for(let o of s)if(!r.has(o)){let c=ee(o),d=n?`${n}/${c}`:`/${c}`;i.push({op:"add",path:d,value:e[o]})}}function le(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=ot(e,t.name);i&&Object.entries(t.changes).forEach(([r,a])=>{n.push({op:"replace",path:`${i}/${r}`,value:a})});break}}return n}function ot(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(Ae(i)){let r=Ie(i.rules,e);if(r)return`/constraints/${n}${r}`}}return null}function Ae(t){return t&&"operator"in t&&"rules"in t}function Ie(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(Ae(i)){let r=Ie(i.rules,e);if(r)return`/rules/${n}${r}`}}return null}function he(t,e){let n={...t};return me(t)&&me(e)&&Object.keys(e).forEach(i=>{me(e[i])?i in t?n[i]=he(t[i],e[i]):Object.assign(n,{[i]:e[i]}):Object.assign(n,{[i]:e[i]})}),n}function me(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,d,l)=>{switch(c){case"string":return typeof o!="string"?[{message:`Expected string, got ${typeof o}`,path:d}]:[];case"number":return typeof o!="number"||isNaN(o)?[{message:`Expected number, got ${typeof o}`,path:d}]:[];case"boolean":return typeof o!="boolean"?[{message:`Expected boolean, got ${typeof o}`,path:d}]:[];case"array":return Array.isArray(o)?[]:[{message:`Expected array, got ${typeof o}`,path:d}];case"set":return!Array.isArray(o)||new Set(o).size!==o.length?[{message:`Expected unique array, got ${typeof o}`,path:d}]:[];case"enum":return l?.values?l.values.includes(o)?[]:[{message:`Expected one of ${JSON.stringify(l.values)}, got ${o}`,path:d}]:[{message:"Enum type requires 'values' definition",path:d}];case"object":return typeof o!="object"||o===null||Array.isArray(o)?[{message:`Expected object, got ${typeof o}`,path:d}]:[];case"record":return typeof o!="object"||o===null?[{message:`Expected record (object), got ${typeof o}`,path:d}]:[];case"union":return typeof o!="object"||o===null?[{message:`Expected union (object), got ${typeof o}`,path:d}]:[];case"dynamic":return[];default:return[{message:`Unknown type '${c}'`,path:d}]}};function a(o,c,d,l,x){let w=[],P=o.rules.map((m,T)=>{let v=[...l,`rules[${T}]`];if("rules"in m){if(x.has(m.name))return!0;x.add(m.name);let p=a(m,c,d,v,x);return w.push(...p),p.length===0}else{let p=d[m.predicate];if(!p)return w.push({message:`Predicate '${m.predicate}' not found`,path:v}),!1;let g=p({data:c,field:m.field,arguments:m.parameters});if(!g){let S=m.field?` for field '${m.field}'`:"";w.push({message:m.errorMessage||`Constraint '${m.name}' failed${S} with params ${K(m.parameters)}`,path:v})}return g}});return(()=>{switch(o.operator){case"and":return P.every(m=>m);case"or":return P.some(m=>m);case"not":return!P.every(m=>m);case"nor":return!P.some(m=>m);case"xor":return P.filter(m=>m).length===1}})()||w.push({message:`Constraint group '${o.name}' failed`,path:l}),w}function s(o,c,d,l,x,w=new Set,P){let y=[],m={};if("concrete"in c)if(c.concrete===!0||!Array.isArray(c.fields))m=c.fields;else{let v=c.fields,p=v.find(S=>!S.when);p&&Object.assign(m,p.fields);let g=v.find(S=>S.when&&o[S.when.field]!==void 0&&o[S.when.field]===S.when.value);if(g)Object.assign(m,g.fields);else if(!p)return y.push({message:"No matching field set found for discriminated schema",path:l}),y}else m=c.fields;let T=new Set(Object.values(m).map(v=>v.name));Object.entries(m).forEach(([v,p])=>{let g=[...l,p.name],S=Object.hasOwnProperty.call(o,p.name)?o[p.name]:void 0;if(p.required&&S==null){y.push({message:`Field '${p.name}' is required`,path:g});return}if(S!==void 0){if(y.push(...r(S,p.type,g,p)),p.type==="array"||p.type==="set"){p.itemsType&&Array.isArray(S)&&S.forEach((u,f)=>y.push(...r(u,p.itemsType,[...g,f.toString()])));let $=p.schema||p.nestedSchema;if($&&!Array.isArray($)){let u=x[$.id];u?S.forEach((f,h)=>{typeof f=="object"&&f!==null&&(w.has($.id)?y.push({message:`Circular reference detected at '${$.id}'`,path:[...g,h.toString()]}):(w.add($.id),y.push(...s(f,u,d,[...g,h.toString()],x,w,o)),w.delete($.id)))}):y.push({message:`Nested schema '${$.id}' not found`,path:g})}}if(p.type==="object"){let $=p.schema||p.nestedSchema;if($&&!Array.isArray($)){let u=x[$.id];u?typeof S=="object"&&S!==null&&(w.has($.id)?y.push({message:`Circular reference detected at '${$.id}'`,path:g}):(w.add($.id),y.push(...s(S,u,d,g,x,w,o)),$.constraints?.forEach((f,h)=>{if("rules"in f)y.push(...a(f,S,d,[...g,`constraints[${h}]`],w));else{let b=d[f.predicate];b?b({data:S,field:void 0,arguments:f.parameters})||y.push({message:f.errorMessage||`Constraint '${f.name}' failed with params ${K(f.parameters)}`,path:[...g,`constraints[${h}]`]}):y.push({message:`Predicate '${f.predicate}' not found`,path:[...g,`constraints[${h}]`]})}}),w.delete($.id))):y.push({message:`Nested schema '${$.id}' not found`,path:g})}}if(p.type==="union"){let $=p.schema;!$||!Array.isArray($)?y.push({message:"Union type requires an array of schema references",path:g}):$.some(f=>{let h=x[f.id];return h?s(S,h,d,g,x,new Set(w),o).length===0:(y.push({message:`Nested schema '${f.id}' not found`,path:g}),!1)})||y.push({message:"Value does not match any union schema",path:g})}p.constraints?.forEach(($,u)=>{if("rules"in $)y.push(...a($,o,d,[...g,`constraints[${u}]`],w));else{let f=d[$.predicate];f?f({data:o,field:p.name,arguments:$.parameters})||y.push({message:$.errorMessage||`Constraint '${$.name}' failed for field '${p.name}' with params ${K($.parameters)}`,path:[...g,`constraints[${u}]`]}):y.push({message:`Predicate '${$.predicate}' not found`,path:[...g,`constraints[${u}]`]})}})}});for(let v in o)Object.hasOwnProperty.call(o,v)&&!T.has(v)&&y.push({message:`Unexpected field '${v}'`,path:[...l,v]});return c.constraints?.forEach((v,p)=>{if("rules"in v)y.push(...a(v,o,d,[...l,`constraints[${p}]`],w));else{let g=d[v.predicate];if(!g)y.push({message:`Predicate '${v.predicate}' not found`,path:[...l,`constraints[${p}]`]});else if(!g({data:o,field:v.field,arguments:v.parameters})){let $=v.field?` for field '${v.field}'`:"";y.push({message:v.errorMessage||`Constraint '${v.name}' failed${$} with params ${K(v.parameters)}`,path:[...l,`constraints[${p}]`]})}}}),y}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,d=s(c,t,e,[],t.nestedSchemas||{});return d.length>0?i(d):n(c)},types:{input:{},output:{}}}}}function ct(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 ye=t=>({value:t}),G=t=>({issues:t}),E=(t,e,n=!0)=>t===void 0&&!n?[]:typeof t!="string"||t.trim()===""?[{message:"Must be a non-empty string",path:[e]}]:[],Fe=(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]}]:[]},dt=(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]}]:[]},Me=(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]}]:[],ut=(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]}]},ge=(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(...E(t.name,`${e}.name`)),n.push(...E(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(...ut(t.parameters,"dynamic",`${e}.parameters`)),n.push(...E(t.description,`${e}.description`,!1)),n.push(...E(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(...E(t.name,`${e}.name`)),n.push(...Me(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(...ge(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(...ge(i,`${e}[${r}]`))}),n},Oe=(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(...Me(t.operator,`${e}.operator`)),n.push(...E(t.field,`${e}.field`)),t.conditions!==void 0&&(Array.isArray(t.conditions)?t.conditions.forEach((s,o)=>n.push(...Oe(s,`${e}.conditions[${o}]`))):n.push({message:"Conditions must be an array",path:[`${e}.conditions`]})),n},je=(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(...E(t.name,`${e}.name`)),n.push(...dt(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(...Oe(t.partial,`${e}.partial`)),n.push(...E(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(...je(i,`${e}[${r}]`))),n},ft=(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(...E(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(...E(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(...E(t.name,`${e}.name`)),i.push(...Fe(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(...ft(t.schema,`${e}.schema`,t.type,n,t.itemsType)),t.itemsType&&i.push(...Fe(t.itemsType,`${e}.itemsType`)),t.nestedSchema){let o=["id"],c=["id","constraints","indexes"],d=t.nestedSchema;o.forEach(l=>{d[l]===void 0&&i.push({message:`${l} is required`,path:[`${e}.nestedSchema.${l}`]})}),Object.keys(d).forEach(l=>{c.includes(l)||i.push({message:"Unknown property",path:[`${e}.nestedSchema.${l}`]})}),i.push(...E(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"],d=t.reference;o.forEach(l=>{d[l]===void 0&&i.push({message:`${l} is required`,path:[`${e}.reference.${l}`]})}),Object.keys(d).forEach(l=>{c.includes(l)||i.push({message:"Unknown property",path:[`${e}.reference.${l}`]})}),i.push(...E(t.reference.schema,`${e}.reference.schema`)),i.push(...E(t.reference.field,`${e}.reference.field`))}return i.push(...E(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(...E(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 d=`${e}.fields[${c}]`;if(typeof o!="object"||o===null||!("fields"in o))i.push({message:"Each variant must have a 'fields' property",path:[d]});else{let l=o.fields;typeof l!="object"||l===null?i.push({message:"Fields must be a non-empty object",path:[`${d}.fields`]}):Object.entries(l).forEach(([x,w])=>{i.push(...se(w,`${d}.fields.${x}`,n))}),o.when!==void 0&&(typeof o.when!="object"||o.when===null)&&i.push({message:"When must be an object",path:[`${d}.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(...E(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},lt=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(...E(e.name,"name")),n.push(...E(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(...E(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(...Ne(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):ye(e)},pe=(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(...E(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(...E(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(...E(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(...E(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(...E(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(...je(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(...E(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(...E(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(...ge(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(...E(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(...E(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(...E(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(...E(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(...E(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},mt=(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},Ne=(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(...E(t.id,`${e}.id`)),n.push(...E(t.schemaVersion,`${e}.schemaVersion`)),n.push(...E(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(...pe(o,`${e}.changes[${c}]`))),t.rollback!==void 0&&(Array.isArray(t.rollback)?t.rollback.forEach((o,c)=>n.push(...pe(o,`${e}.rollback[${c}]`))):n.push({message:"Rollback must be an array",path:[`${e}.rollback`]})),typeof t.transform=="string"?n.push(...E(t.transform,`${e}.transform`)):typeof t.transform=="object"&&t.transform!==null?n.push(...mt(t.transform,`${e}.transform`)):n.push({message:"Transform must be a string or object",path:[`${e}.transform`]}),n.push(...E(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(...E(t.checksum,`${e}.checksum`)),n},qe={"~standard":{version:1,vendor:"@asaidimu/anansi",validate:lt,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=Ne(e,"");return n.length>0?G(n):ye(e)},types:{input:{},output:{}}}},Ue={"~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(...pe(i,`[${r}]`))),n.length>0?G(n):ye(e)},types:{input:[],output:[]}}};function we(t){try{return!Le["~standard"].validate(t).issues}catch(e){throw new _("Invalid migration definition",e instanceof Error?e:new Error(String(e)))}}function Se(t){try{return!Ue["~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!qe["~standard"].validate(t).issues}catch(e){throw new _("Invalid schema definition",e instanceof Error?e:new Error(String(e)))}}var ht=H;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(a=>a.toString(16).padStart(2,"0")).join("")}else{let{createHash:e}=await import("crypto");return e("sha256").update(t).digest("hex")}};function pt(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 yt(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 gt(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 $t(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 wt(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 St(t,e,n){if(!e)return!0;if("rules"in e&&"rules"in t)return wt(e,t);if("predicate"in t&&t.predicate!==void 0)return!0;if("parameters"in t&&t.parameters!==void 0){let i=yt(e,n);return i?$t(e.parameters,t.parameters,i):!0}return!1}function bt(t,e){switch(t.type){case"removeField":case"removeIndex":return"major";case"modifyField":return gt(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 St(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 vt(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 Et(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 be(t,e,n){if(e.length===0)throw new Error("No changes provided");vt(e),Et(e);let i=pt(t),r="patch";for(let a of e){let s=bt(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=d=>d.split(".").map(l=>parseInt(l,10)||0),[i,r,a]=n(t),[s,o,c]=n(e);return i-s||r-o||a-c}function xt(t){return t.sort(O)}var C=class extends Error{constructor(n,i,r,a){super(n);this.code=i;this.migrationId=r;this.cause=a;this.name="MigrationError"}},_e=(w=>(w.INVALID_SCHEMA="INVALID_SCHEMA",w.INVALID_MIGRATION="INVALID_MIGRATION",w.CHECKSUM_MISMATCH="CHECKSUM_MISMATCH",w.TIMEOUT="TIMEOUT",w.MEMORY_LIMIT="MEMORY_LIMIT",w.CONCURRENT_OPERATION="CONCURRENT_OPERATION",w.TRANSFORM_ERROR="TRANSFORM_ERROR",w.VERSION_NOT_FOUND="VERSION_NOT_FOUND",w.CIRCULAR_DEPENDENCY="CIRCULAR_DEPENDENCY",w.STREAM_ERROR="STREAM_ERROR",w.ROLLBACK_ERROR="ROLLBACK_ERROR",w.MISSING_TRANSFORM="MISSING_TRANSFORM",w))(_e||{}),ve=class t{currentSchema;history=[];migrations=[];isProcessing=!1;constructor(e,n,i){try{if(!H(e))throw new C("Invalid initial schema","INVALID_SCHEMA");if(this.currentSchema=e,n){if(!n.every(r=>we(r)))throw new C("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 C?r:new C("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 L(n)}catch(n){throw new C("Checksum generation failed","CHECKSUM_MISMATCH",e.id,n)}}async add(e){if(this.isProcessing)throw new C("Concurrent operation","CONCURRENT_OPERATION");if(!e.changes?.length)throw new C("Migration must include changes","INVALID_MIGRATION");try{e.changes.forEach(i=>Se(i))}catch(i){throw new C("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 C("Concurrent operation","CONCURRENT_OPERATION");try{this.isProcessing=!0;let r={...this.currentSchema},a=this.getRelevantMigrations(n,i),s=a.reduce((c,d)=>{let l=n==="forward"?d.changes:d.rollback||[];return this.applySchemaChanges(c,l,d.id)},r),o=await t.processMigrationList(e,n,a);return{newSchema:s,dataPreview:o}}catch(r){throw r instanceof C?r:new C("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=be(e.version,n);return n.map(s=>{try{return le(s,e)}catch(o){throw new C("Invalid schema change","INVALID_SCHEMA",i,o)}}).reduce((s,o)=>{try{return ie(s,o)}catch(c){throw new C("Failed to apply patch","INVALID_SCHEMA",i,c)}},{...e,version:r})}catch(r){throw r instanceof C?r:new C("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 C("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 C("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 C("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 C("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 C(`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(d,l){try{let x=await c(d);l.enqueue(x)}catch(x){l.error(new C(`Data transformation failed for migration ${o.id}`,"TRANSFORM_ERROR",o.id,x))}}})),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 C(`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 C(`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 C(`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 C?n:new C("Schema transformation failed","INVALID_SCHEMA",void 0,n)}}};var Ge=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=>{e.push({type:"removeNestedSchema",id:i});let r=t.nestedSchemas[i];r&&n.push({type:"addNestedSchema",id:i,definition:r})},modifyNestedSchema:(i,r)=>{e.push({type:"modifyNestedSchema",id:i,changes:r});let a=t.nestedSchemas[i];a&&n.push({type:"modifyNestedSchema",id:i,changes:a})},changes:()=>({migrate:e,rollback:n})}};var pn=require("@isomorphic-git/lightning-fs"),R=B(require("isomorphic-git"),1),Q=B(require("isomorphic-git/http/web"),1);var ze=B(require("@isomorphic-git/lightning-fs"),1);function Je(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 He(t){let{params:e,body:n}=JSON.parse(t),i=Object.getPrototypeOf(function*(){}).constructor;return new i(e,n)}function Ee(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 xe(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}var Be=require("buffer");window.Buffer=Be.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||!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 L(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 L(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 d=JSON.parse(String(await this.fsp.readFile(c,"utf8")));O(d.schemaVersion,r)<=0&&a.push(this.deserializeMigration(d))}}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:Ee(o.forward),backward:Ee(o.backward||(c=>c))}}let a=JSON.stringify(r),s=await L(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?Je(e.mock):null})}deserializeSchema(e){return e.mock&&(e.mock=He(e.mock)),e}deserializeMigration(e){return e.transform?.forward&&(e.transform={forward:xe(e.transform.forward),backward:xe(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:d,checksum:l})=>{o.migrations[c]={hash:d,checksum:l}}),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 Te=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()}}},Ce=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 ae(t,e){try{return await t()}catch(n){throw console.error(`${e}:`,n),new Error(`${e}: ${n.message}`)}}async function oe(t,e,n,i,r){await i.init(),await R.default.init({fs:t,dir:e,defaultBranch:n}),await R.default.setConfig({fs:t,dir:e,path:"core.autocrlf",value:"false"}),await R.default.setConfig({fs:t,dir:e,path:"core.eol",value:"lf"}),await R.default.add({fs:t,dir:e,filepath:"."}),await R.default.commit({fs:t,dir:e,message:"chore: initial commit",author:r})}async function kt(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),d=c.fs,l=t.startsWith("/")?t:`/${t}`,x=new Te,w=new Ce(e.cacheTtl);async function P(u,f){let h=o;do{let b=s[o];try{return await u(b)}catch(D){if(console.warn(`Failed with proxy ${b}: ${D.message}`),o=(o+1)%s.length,o===h)throw new Error(`${f}: All CORS proxies failed`)}}while(!0)}async function y(u,f="."){return ae(async()=>(await R.default.add({fs:d,dir:l,filepath:f}),(await R.default.statusMatrix({fs:d,dir:l})).some(([b,D,k])=>D!==k)?await R.default.commit({fs:d,dir:l,message:u,author:a}):null),"Failed to commit changes")}async function m(u,f,h){return ae(async()=>{if(await T(u))throw new Error(`Tag ${u} already exists`);await R.default.annotatedTag({fs:d,dir:l,ref:u,message:f,tagger:a,object:h})},`Failed to create tag ${u}`)}async function T(u){try{return(await R.default.listTags({fs:d,dir:l})).includes(u)}catch{return!1}}async function v(u){return(await R.default.listTags({fs:d,dir:l})).filter(b=>b.startsWith(u))}async function p(u){return ae(async()=>{let h=(await R.default.listTags({fs:d,dir:l})).filter(b=>b.startsWith(u));for(let b of h)await R.default.deleteTag({fs:d,dir:l,ref:b});return h},`Failed to delete tags with prefix ${u}`)}async function g(u){return ae(async()=>{await R.default.checkout({fs:d,dir:l,ref:u})},`Failed to checkout ${u}`)}async function S(u,{delete:f=!1,force:h=!1}={}){i&&await P(async b=>{await R.default.push({fs:d,http:Q.default,dir:l,ref:u,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:b,delete:f,force:h})},`Failed to push ${u}`)}async function $(u,f=!0){i&&await P(async h=>{try{await R.default.pull({fs:d,http:Q.default,dir:l,ref:u,author:a,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:h,fastForwardOnly:!0})}catch(b){if(!f)console.warn(`Fast-forward pull failed for ${u}, attempting regular pull`),await R.default.pull({fs:d,http:Q.default,dir:l,ref:u,author:a,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:h,fastForwardOnly:!1});else throw b}},`Failed to pull ${u}`)}if(i&&!await c.fileExists(l)){let u=l.slice(1);if(await i.exists({name:u}).catch(()=>!1))await P(async h=>{await R.default.clone({fs:d,http:Q.default,dir:l,url:i.authURL(),ref:n,singleBranch:!0,depth:1,onAuth:()=>i.credentials(),corsProxy:h})},"Failed to clone repository");else if(r)try{i=await i.create({name:u,private:!0}),await oe(d,l,n,c,a),await R.default.addRemote({fs:d,dir:l,remote:"origin",url:i.url()}),await S(n)}catch(h){console.error("Failed to create and push to remote repository:",h),await oe(d,l,n,c,a)}else await oe(d,l,n,c,a)}else await oe(d,l,n,c,a);return{async init(){return x.withLock("init",()=>c.init())},async create(u){let{name:f,version:h}=u.schema;return x.withLock(`schema:${f}`,async()=>{await g(n),await c.create(u);let b=await y(`feat: create schema ${f}`);b&&await m(`${f}-${h}`,`Version ${h}`,b),w.invalidate(f)})},async update(u){let{name:f,version:h}=u.schema;return x.withLock(`schema:${f}`,async()=>{await g(n),await c.update(u);let b=await y(`fix: update schema ${f}`);b&&await m(`${f}-${h}`,`Version ${h}`,b),w.invalidate(f)})},async delete(u){let{name:f}=u;return x.withLock(`schema:${f}`,async()=>{await g(n),await R.default.remove({fs:d,dir:l,filepath:f}),await c.delete(u);let h=await y(`chore: delete schema ${f}`),b=await v(`${f}-`);if(i&&h){await S(n);for(let D of b)await S(D,{delete:!0,force:!0}).catch(k=>console.warn(`Failed to delete remote tag ${D}: ${k.message}`))}await p(`${f}-`),w.invalidate(f)})},async list(){return x.withLock("list",()=>c.list())},async schema(u){let{name:f,version:h}=u,b=`${f}-${h||"latest"}-${u.migrations||!1}`,D=w.get(b);return D||x.withLock(`schema:${f}`,async()=>{if(h){let A=`${f}-${h}`;if(await T(A))await g(A);else throw new Error(`Version ${h} of schema ${f} not found`)}else await g(n);let k=await c.schema(u);return w.set(b,k),k})},async stats(u){return x.withLock("stats",()=>c.stats(u))},async sync(){return x.withLock("sync",async()=>{if(await g(n),await c.sync(),await y("chore: sync local changes"),i){await $(n,!1),await S(n);let u=await R.default.listTags({fs:d,dir:l});for(let h of u)await S(h,{force:!0});let f=await R.default.listTags({fs:d,dir:l});for(let h of f)u.includes(h)||await S(h,{delete:!0})}w.invalidate()})},async migrations(u){let{name:f,version:h}=u,b=`migrations-${f}-${h||"latest"}`,D=w.get(b);return D||x.withLock(`migrations:${f}`,async()=>{if(h){let A=`${f}-${h}`;if(await T(A))await g(A);else throw new Error(`Version ${h} of schema ${f} not found`)}else await g(n);let k=await c.migrations(u);return w.set(b,k),k})},async history(u){let{name:f}=u,h=`history-${f}`,b=w.get(h);return b||x.withLock(`history:${f}`,async()=>{await g(n);let D=await c.history(u);return w.set(h,D),D})}}}function M(t){return"predicate"in t}function Dt(t,e=!0,n=!0){let i="",r=n?"export ":"",a=new Map,s=new Map,o=(y,m=[])=>{if(!e||!y&&!m.length)return"";let T=y?[y]:[];return m.forEach(v=>T.push(v)),`/**
2
+ * ${T.join(`
3
3
  * `)}
4
4
  */
5
- `},o=u=>u.charAt(0).toUpperCase()+u.slice(1),c=(u,m)=>{for(let[h,g]of Object.entries(u))if(g.type==="string"&&g.constraints){let D=g.constraints.find(f=>f.predicate==="enum"||f.predicate==="oneOf");if(D&&Array.isArray(D.parameters)){let f=`${m}${_e(g.name)}`,p=D.parameters.map(x=>String(x));r.set(f,p)}}};c(n.fields,n.name);for(let[u,m]of Object.entries(n.nestedSchemas))c(m.fields,o(m.name));for(let[u,m]of r){i+=a(`Union type for ${u.toLowerCase()} field values`);let h=m.map(g=>`"${g}"`).join(" | ");i+=`${s}type ${u} = ${h};
5
+ `},c=y=>y.charAt(0).toUpperCase()+y.slice(1),d=(y,m)=>{let T=s.get(m)||new Map;for(let[v,p]of Object.entries(y))if(p.type==="enum"&&Array.isArray(p.values)){let g=`${m}${c(p.name)}`,S=p.values.map($=>String($));a.set(g,S)}else if(p.type==="string"&&p.constraints){let g=p.constraints.find(S=>M(S)&&(S.predicate==="enum"||S.predicate==="oneOf"));if(g&&M(g)&&Array.isArray(g.parameters)){let S=`${m}${c(p.name)}`,$=g.parameters.map(u=>String(u));a.set(S,$)}}else if(p.type==="record"){let g=`${m}${c(p.name)}`;T.set(p.name,g)}T.size>0&&s.set(m,T)};d(t.fields,t.name);for(let[y,m]of Object.entries(t.nestedSchemas||{}))Array.isArray(m.fields)?m.fields.forEach(T=>d(T.fields,c(m.name))):d(m.fields,c(m.name));for(let[y,m]of a){i+=o(`Union type for ${y.toLowerCase()} field values`);let T=m.map(v=>`"${v}"`).join(" | ");i+=`${r}type ${y} = ${T};
6
6
 
7
- `}for(let[u,m]of Object.entries(n.nestedSchemas)){let h=o(m.name),g=m.constraints?.map(D=>`@constraint ${D.name}: ${D.description||D.predicate}`)||[];i+=a(m.description,g),i+=`${s}type ${h} = {
8
- `;for(let[D,f]of Object.entries(m.fields)){let p=f.constraints?.map($=>`@constraint ${$.name}: ${$.description||$.predicate}`)||[];f.unique&&p.push("@unique Ensures unique values"),f.default!==void 0&&p.push(`@default ${JSON.stringify(f.default)}`),e&&f.description?i+=a(f.description,p):p.length&&(i+=a(void 0,p)),f.deprecated&&(i+=` /** @deprecated */
9
- `);let x=Le(f,n,h),C=f.required===!1?"?":"";i+=` ${f.name}${C}: ${x};
10
- `}if(m.metadata&&(i+=` metadata: Record<string, any>;
7
+ `}for(let[y,m]of Object.entries(t.nestedSchemas||{})){let T=c(m.name),v=m.constraints?.map($=>M($)?`@constraint ${$.name}: ${$.description||$.predicate}`:`@constraint ${$.name}`)||[];m.concrete&&v.push("@concrete Indicates a concrete schema"),i+=o(m.description,v);let p=s.get(T)||new Map,g=Array.from(p.entries()).map(([$,u])=>`${u} extends Record<string, any> = Record<string, any>`).join(", "),S=p.size>0?`<${g}>`:"";if(Array.isArray(m.fields)){let $=m.fields.filter(b=>!b.when),u=m.fields.filter(b=>b.when),f="";if($.length>0){f+=`{
8
+ `;for(let b of $)for(let[D,k]of Object.entries(b.fields)){let A=k.constraints?.map(N=>M(N)?`@constraint ${N.name}: ${N.description||N.predicate}`:`@constraint ${N.name}`)||[];k.unique&&A.push("@unique Ensures unique values"),k.default!==void 0&&A.push(`@default ${JSON.stringify(k.default)}`),e&&k.description?f+=o(k.description,A):A.length&&(f+=o(void 0,A)),k.deprecated&&(f+=` /** @deprecated */
9
+ `);let I=ce(k,t,T,p),V=k.required===!1?"?":"";f+=` ${k.name}${V}: ${I};
10
+ `}f+="}"}let h="";u.length>0&&(h=u.map(D=>{let k=`{
11
+ `;for(let[A,I]of Object.entries(D.fields)){let V=I.constraints?.map(z=>M(z)?`@constraint ${z.name}: ${z.description||z.predicate}`:`@constraint ${z.name}`)||[];I.unique&&V.push("@unique Ensures unique values"),I.default!==void 0&&V.push(`@default ${JSON.stringify(I.default)}`),e&&I.description?k+=o(I.description,V):V.length&&(k+=o(void 0,V)),I.deprecated&&(k+=` /** @deprecated */
12
+ `);let N=ce(I,t,T,p),Ke=I.required===!1?"?":"";k+=` ${I.name}${Ke}: ${N};
13
+ `}if(D.when)for(let[A,I]of Object.entries(D.when))k+=` ${A}: "${I}";
14
+ `;return k+="}",k}).join(" | ")),f&&h?i+=`${r}type ${T}${S} = ${f} & (${h});
15
+
16
+ `:f?i+=`${r}type ${T}${S} = ${f};
17
+
18
+ `:h&&(i+=`${r}type ${T}${S} = ${h};
19
+
20
+ `)}else{i+=`${r}type ${T}${S} = {
21
+ `;for(let[$,u]of Object.entries(m.fields)){let f=u.constraints?.map(D=>M(D)?`@constraint ${D.name}: ${D.description||D.predicate}`:`@constraint ${D.name}`)||[];u.unique&&f.push("@unique Ensures unique values"),u.default!==void 0&&f.push(`@default ${JSON.stringify(u.default)}`),e&&u.description?i+=o(u.description,f):f.length&&(i+=o(void 0,f)),u.deprecated&&(i+=` /** @deprecated */
22
+ `);let h=ce(u,t,T,p),b=u.required===!1?"?":"";i+=` ${u.name}${b}: ${h};
23
+ `}m.metadata&&(i+=` metadata: Record<string, any>;
11
24
  `),i+=`};
12
25
 
13
- `,m.indexes?.length){i+=a(`Available indexes for ${h}`),i+=`${s}enum ${h}IndexNames {
14
- `;for(let D of m.indexes)i+=` ${D.name} = "${D.name}",
26
+ `}if(m.indexes?.length){i+=o(`Available indexes for ${T}`),i+=`${r}enum ${T}IndexNames {
27
+ `;for(let $ of m.indexes)i+=` ${$.name} = "${$.name}",
15
28
  `;i+=`}
16
29
 
17
- `}}let d=n.constraints?.map(u=>`@constraint ${u.name}: ${u.description||u.predicate}`)||[];i+=a(n.description,d),i+=`${s}type ${n.name} = {
18
- `;for(let[u,m]of Object.entries(n.fields)){let h=m.constraints?.map(f=>`@constraint ${f.name}: ${f.description||f.predicate}`)||[];m.unique&&h.push("@unique Ensures unique values"),m.default!==void 0&&h.push(`@default ${JSON.stringify(m.default)}`),e&&m.description?i+=a(m.description,h):h.length&&(i+=a(void 0,h)),m.deprecated&&(i+=` /** @deprecated */
19
- `);let g=Le(m,n,n.name),D=m.required===!1?"?":"";i+=` ${m.name}${D}: ${g};
20
- `}if(n.metadata&&(i+=` metadata: Record<string, any>;
30
+ `}}let l=t.constraints?.map(y=>M(y)?`@constraint ${y.name}: ${y.description||y.predicate}`:`@constraint ${y.name}`)||[];i+=o(t.description,l);let x=s.get(t.name)||new Map,w=Array.from(x.entries()).map(([y,m])=>`${m} extends Record<string, any> = Record<string, any>`).join(", "),P=x.size>0?`<${w}>`:"";i+=`${r}type ${t.name}${P} = {
31
+ `;for(let[y,m]of Object.entries(t.fields)){let T=m.constraints?.map(g=>M(g)?`@constraint ${g.name}: ${g.description||g.predicate}`:`@constraint ${g.name}`)||[];m.unique&&T.push("@unique Ensures unique values"),m.default!==void 0&&T.push(`@default ${JSON.stringify(m.default)}`),e&&m.description?i+=o(m.description,T):T.length&&(i+=o(void 0,T)),m.deprecated&&(i+=` /** @deprecated */
32
+ `);let v=ce(m,t,t.name,x),p=m.required===!1?"?":"";i+=` ${m.name}${p}: ${v};
33
+ `}if(t.metadata&&(i+=` metadata: Record<string, any>;
21
34
  `),i+=`};
22
35
 
23
- `,n.indexes?.length){i+=a(`Available indexes for ${n.name}`),i+=`${s}enum ${n.name}IndexNames {
24
- `;for(let u of n.indexes)i+=` ${u.name} = "${u.name}",
36
+ `,t.indexes?.length){i+=o(`Available indexes for ${t.name}`),i+=`${r}enum ${t.name}IndexNames {
37
+ `;for(let y of t.indexes)i+=` ${y.name} = "${y.name}",
25
38
  `;i+=`}
26
- `}return i}function Le(n,e,t){switch(n.type){case"string":if(n.constraints){let i=n.constraints.find(s=>s.predicate==="enum"||s.predicate==="oneOf");if(i&&Array.isArray(i.parameters))return`${t}${_e(n.name)}`}return"string";case"number":return"number";case"boolean":return"boolean";case"array":if(n.itemsType){if(n.itemsType==="object"&&n.nestedSchema){let i=e.nestedSchemas[n.nestedSchema.id];return`Array<${$e(i.name)}>`}return`${n.itemsType}[]`}return"any[]";case"set":if(n.itemsType){if(n.itemsType==="object"&&n.nestedSchema){let i=e.nestedSchemas[n.nestedSchema.id];return`Set<${$e(i.name)}>`}return`Set<${n.itemsType}>`}return"Set<any>";case"object":if(n.nestedSchema){let i=e.nestedSchemas[n.nestedSchema.id];return $e(i.name)}return n.reference?`${n.reference.schema}${n.required===!1?" | null":""}`:"Record<string, any>";case"dynamic":return"unknown";default:return"any"}}function _e(n){return n.split(/[-_\s]/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function $e(n){return n.charAt(0).toUpperCase()+n.slice(1)}function vt(n,e=!0){let i=`${e?"export ":""}interface ${n.name}Validator {
27
- `;return i+=` /**
28
- * Validates a ${n.name} object against all schema constraints
29
- * @param data The data to validate
30
- * @returns Validation result with any errors
31
- */
32
- `,i+=` validate(data: ${n.name}): { valid: boolean; errors: Array<{ field: string; message: string }> };
33
-
34
- `,i+=` /**
35
- * Checks if the given object conforms to the ${n.name} type structure
36
- * @param data The object to check
37
- * @returns Whether the object matches the expected structure
38
- */
39
- `,i+=` isType(data: any): data is ${n.name};
40
- `,i+=`}
41
- `,i}function xt(n,e){let t=[],i=a=>a===void 0?"`None`":`\`${JSON.stringify(a,null,2)}\``,s=a=>{let o=`**${a.field}** ${a.operator}`;return a.value!==void 0&&(o+=` ${JSON.stringify(a.value)}`),a.conditions&&(o+=` [
42
- ${a.conditions.map(c=>` ${s(c)}`).join(`
39
+ `}return i.trim()}function ce(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}${U(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`${U(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<${U(r.name)}>`}return`Set<${t.itemsType}>`}return"Set<any>";case"enum":return t.values?`${n}${U(t.name)}`:"string";case"object":if(t.schema&&!Array.isArray(t.schema)){let r=e.nestedSchemas[t.schema.id],a=U(r.name);return r.concrete?`string | ${a}`:a}if(t.nestedSchema){let r=e.nestedSchemas[t.nestedSchema.id],a=U(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 U(s.name)}).join(" | "):"any";case"dynamic":return"unknown";default:return"any"}}function U(t){return t.charAt(0).toUpperCase()+t.slice(1)}function Rt(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(`
43
41
  `)}
44
- ]`),o},r=(a,o=1)=>{let c="#".repeat(o+2);return Object.entries(a).map(([d,u])=>{let m=`${c} ${d} (${u.type})
42
+ ]`),o},a=(s,o=1)=>{let c="#".repeat(o+2);return Object.entries(s).map(([d,l])=>{let x=`${c} ${d} (${l.type})
45
43
 
46
- `;return m+=`**Required:** ${u.required?"Yes":"No"}
44
+ `;return x+=`**Required:** ${l.required?"Yes":"No"}
47
45
 
48
- `,u.description&&(m+=`**Description:** ${u.description}
46
+ `,l.description&&(x+=`**Description:** ${l.description}
49
47
 
50
- `),u.itemsType&&(m+=`**Item Type:** ${u.itemsType}
48
+ `),l.itemsType&&(x+=`**Item Type:** ${l.itemsType}
51
49
 
52
- `),u.nestedSchema&&(m+=r(u.nestedSchema,o+1)),m}).join(`
53
- `)};t.push(`# ${n.name} Schema (Version ${n.version})`),n.description&&t.push(`
54
- ${n.description}
55
- `),t.push("## Metadata"),t.push(`- **Dependencies:** ${n.dependencies?.join(", ")||"None"}`),t.push(`- **Created:** ${new Date().toISOString()}
56
- `),t.push(`## Fields
57
- `),t.push("| Name | Type | Required | Default | Description | Deprecated | Unique | Constraints |"),t.push("|------|------|----------|---------|-------------|------------|--------|-------------|");for(let[a,o]of Object.entries(n.fields))t.push([a,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(n.fields).forEach(([a,o])=>{o.nestedSchema&&(t.push(`
58
- ### Nested Schema: ${a}
59
- `),t.push(r(o.nestedSchema)))}),t.push(`
50
+ `),l.nestedSchema&&(x+=a(l.nestedSchema,o+1)),x}).join(`
51
+ `)};n.push(`# ${t.name} Schema (Version ${t.version})`),t.description&&n.push(`
52
+ ${t.description}
53
+ `),n.push("## Metadata"),n.push(`- **Dependencies:** ${t.dependencies?.join(", ")||"None"}`),n.push(`- **Created:** ${new Date().toISOString()}
54
+ `),n.push(`## Fields
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
+ ### Nested Schema: ${s}
57
+ `),n.push(a(o.nestedSchema)))}),n.push(`
60
58
  ## Indexes
61
- `),t.push("| Name | Type | Fields | Unique | Order | Partial Condition | Description |"),t.push("|------|------|--------|--------|-------|-------------------|-------------|");for(let a of n.indexes||[])t.push([a.name,a.type,a.fields.join(", "),a.unique?"Yes":"No",a.order||"asc",a.partial?s(a.partial):"None",a.description||""].join("|"));t.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?r(s.partial):"None",s.description||""].join("|"));n.push(`
62
60
  ## Constraints
63
- `),n.constraints&&t.push("### Schema-level Constraints"),t.push(`
61
+ `),t.constraints&&n.push("### Schema-level Constraints"),n.push(`
64
62
  ## Migrations
65
- `),t.push("| ID | Description | Status | Changes |"),t.push("|----|-------------|--------|---------|");for(let a of n.migrations||[])t.push([a.id,a.description,a.status,a.changes.length].join("|"));if(n.mock&&e?.faker)try{let a=n.mock(e.faker).next().value;t.push("\n## Example Data\n```json\n"+JSON.stringify(a,null,2)+"\n```")}catch{t.push(`
66
- <!-- Error generating mock data -->`)}return t.join(`
67
- `)}function Et(n){let e={},t={};n.hint?.groups&&n.hint.groups.forEach(s=>{t[s.name]={label:s.label,description:s.description}}),Ge(n.fields,"",n.nestedSchemas||{},e);let i=[];for(let[s,r]of Object.entries(e)){let a=s!=="ungrouped"?t[s]:void 0;i.push({name:s!=="ungrouped"?s:"ungrouped",label:a?.label||"Ungrouped",description:a?.description,fields:r})}return i}function Ge(n,e,t,i){for(let[s,r]of Object.entries(n)){let a=e?`${e}.${r.name}`:r.name,o={...r,name:a};if(!r.hint?.input?.ignore){if(r.type!=="object"){let c=r.hint?.input?.group||"ungrouped";i[c]||(i[c]=[]),i[c].push(o)}if(r.nestedSchema?.id&&t[r.nestedSchema.id]){let c=t[r.nestedSchema.id];Ge(c.fields,a,t,i)}}}}0&&(module.exports={JsonPatchError,MigrationEngine,MigrationError,MigrationErrorCode,SchemaRegistry,applyPatch,calculateNextVersion,compareSemanticVersions,createGitSchemaRegistry,createPatch,createSchemaMigrationHelper,createStandardSchemaValidator,deepMerge,docgen,extractInputFieldGroups,generateSHA256Hash,generateValidationInterface,normalizePath,schemaChangeToPatch,schemaToTypes,serializeParams,sortSemanticVars,validate,validateMigration,validateSchemaChange,validateSchemaDefinition});
63
+ `),n.push("| ID | Description | Status | Changes |"),n.push("|----|-------------|--------|---------|");for(let s of t.migrations||[])n.push([s.id,s.description,s.status,s.changes.length].join("|"));if(t.mock&&e?.faker)try{let s=t.mock(e.faker).next().value;n.push("\n## Example Data\n```json\n"+JSON.stringify(s,null,2)+"\n```")}catch{n.push(`
64
+ <!-- Error generating mock data -->`)}return n.join(`
65
+ `)}function At(t){let e={},n={};t.hint?.groups&&t.hint.groups.forEach(r=>{n[r.name]={label:r.label,description:r.description}}),ke(t.fields,"",t.nestedSchemas||{},e);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 ke(t,e,n,i,r){if(Array.isArray(t))t.forEach(a=>{let s=a.when?e?`${e}.${a.when?.field}`:a.when?.field:void 0;ke(a.fields,e,n,i,s?{[s]:a.when?.value}:void 0)});else for(let[a,s]of Object.entries(t)){if(s.hint?.input.ignore)continue;let o=e?`${e}.${s.name}`:s.name,c={...s,name:o};if(s.type!=="object"){let d=s.hint?.input?.group||"ungrouped";i[d]||(i[d]=[]),i[d].push(c)}if(r&&(c.when=r),s.schema&&"id"in s.schema&&n[s.schema.id]){let d=n[s.schema.id];ke(d.fields,o,n,i,r)}}}0&&(module.exports={JsonPatchError,MigrationEngine,MigrationError,MigrationErrorCode,SchemaRegistry,applyPatch,calculateNextVersion,compareSemanticVersions,createGitSchemaRegistry,createPatch,createSchemaMigrationHelper,createStandardSchemaValidator,deepMerge,docgen,extractInputFieldGroups,formResolver,generateSHA256Hash,normalizePath,schemaChangeToPatch,schemaToTypes,serializeParams,sortSemanticVars,validate,validateMigration,validateSchemaChange,validateSchemaDefinition});
package/index.d.cts CHANGED
@@ -3,6 +3,7 @@ import { Faker } from '@faker-js/faker';
3
3
  import { QueryDSL, QueryFilter } from '@asaidimu/query';
4
4
  import { StandardSchemaV1 } from '@standard-schema/spec';
5
5
  import LightningFS from '@isomorphic-git/lightning-fs';
6
+ import { FieldValues, ResolverOptions, ResolverResult } from 'react-hook-form';
6
7
 
7
8
  /**
8
9
  * hints.ts
@@ -129,10 +130,22 @@ type DynamicHint = {
129
130
  group?: string;
130
131
  ignore?: boolean;
131
132
  };
133
+ /**
134
+ * Hints for generating a date input control.
135
+ */
136
+ type DateHint = {
137
+ type: "date" | "datetime" | "time";
138
+ label?: string;
139
+ placeholder?: string;
140
+ min?: string;
141
+ max?: string;
142
+ group?: string;
143
+ ignore?: boolean;
144
+ };
132
145
  /**
133
146
  * Union type for all possible input hints.
134
147
  */
135
- type InputHint = FileHint | TextHint | SecretHint | NumberHint | BooleanHint | EnumHint | ArrayHint | SetHint | ObjectHint | DynamicHint;
148
+ type InputHint = FileHint | TextHint | SecretHint | NumberHint | BooleanHint | EnumHint | ArrayHint | SetHint | ObjectHint | DynamicHint | DateHint;
136
149
  /**
137
150
  * Defines metadata for a group of inputs at the schema level.
138
151
  */
@@ -239,7 +252,7 @@ interface FieldDefinition<T> {
239
252
  name: string;
240
253
  type: FieldType;
241
254
  required?: boolean;
242
- constraints?: Constraint<any>[];
255
+ constraints?: Array<Constraint<any> | ConstraintGroup<any>>;
243
256
  default?: T;
244
257
  /** For type 'enum', specifies the allowed values. */
245
258
  values?: Array<string | number>;
@@ -1495,9 +1508,32 @@ declare class MigrationEngine {
1495
1508
  */
1496
1509
  declare const createSchemaMigrationHelper: <T>(schema: Readonly<SchemaDefinition>) => SchemaMigrationHelper;
1497
1510
 
1498
- declare function validateMigration<T>(change: any): change is Migration<T>;
1499
- declare function validateSchemaChange<T>(change: any): change is SchemaChange<T>;
1500
- declare function validateSchemaDefinition(schema: any): schema is SchemaDefinition;
1511
+ /**
1512
+ * Validates a migration object against the standard schema.
1513
+ * @template T The expected type of the migration data.
1514
+ * @param change The object to validate.
1515
+ * @returns A type guard indicating whether the object conforms to Migration<T>.
1516
+ * @throws {SchemaValidationError} If validation fails due to an unexpected error.
1517
+ */
1518
+ declare function validateMigration<T>(change: unknown): change is Migration<T>;
1519
+ /**
1520
+ * Validates a schema change object against the standard schema.
1521
+ * @template T The expected type of the schema change data.
1522
+ * @param change The object to validate.
1523
+ * @returns A type guard indicating whether the object conforms to SchemaChange<T>.
1524
+ * @throws {SchemaValidationError} If validation fails due to an unexpected error.
1525
+ */
1526
+ declare function validateSchemaChange<T>(change: unknown): change is SchemaChange<T>;
1527
+ /**
1528
+ * Validates a schema definition object against the standard schema.
1529
+ * @param schema The object to validate.
1530
+ * @returns A type guard indicating whether the object conforms to SchemaDefinition.
1531
+ * @throws {SchemaValidationError} If validation fails due to an unexpected error.
1532
+ */
1533
+ declare function validateSchemaDefinition(schema: unknown): schema is SchemaDefinition;
1534
+ /**
1535
+ * Alias for validateSchemaDefinition, provided for convenience.
1536
+ */
1501
1537
  declare const validate: typeof validateSchemaDefinition;
1502
1538
 
1503
1539
  /**
@@ -1520,9 +1556,11 @@ declare function deepMerge<T extends object>(target: T, update: Partial<T>): T;
1520
1556
  * Converts a SchemaDefinition to TypeScript type definitions
1521
1557
  *
1522
1558
  * Analyzes a schema definition and generates TypeScript type declarations for the main schema,
1523
- * nested schemas, and union types for enum-like constraints. Uses capitalized field.name for field names,
1524
- * capitalized nestedSchema.name for type names, and ignores UUID keys. Handles required/optional fields,
1525
- * union types, primitives, arrays, sets, references, and nested structures with strict type safety.
1559
+ * nested schemas, and union types for enum fields and constraints. Uses field.name as-is for field names,
1560
+ * capitalized nestedSchema.name for type names, and handles required/optional fields, new types (enum,
1561
+ * record, union), discriminated unions with common fields, primitives, arrays, sets, references, and nested
1562
+ * structures with strict type safety. Introduces unique generics for each record field and adjusts object
1563
+ * fields referencing concrete schemas to use a string | NestedType union.
1526
1564
  *
1527
1565
  * @param schema - The schema definition to convert
1528
1566
  * @param includeComments - Whether to include JSDoc comments (default: true)
@@ -1530,10 +1568,6 @@ declare function deepMerge<T extends object>(target: T, update: Partial<T>): T;
1530
1568
  * @returns TypeScript type definitions as a string
1531
1569
  */
1532
1570
  declare function schemaToTypes(schema: SchemaDefinition, includeComments?: boolean, exportTypes?: boolean): string;
1533
- /**
1534
- * Generates a TypeScript interface for validating schema data
1535
- */
1536
- declare function generateValidationInterface(schema: SchemaDefinition, exportType?: boolean): string;
1537
1571
 
1538
1572
  /**
1539
1573
  * Serializes constraint parameters for error messages, handling special types like RegExp.
@@ -1541,22 +1575,14 @@ declare function generateValidationInterface(schema: SchemaDefinition, exportTyp
1541
1575
  declare function serializeParams(params: any): string;
1542
1576
  /**
1543
1577
  * Creates a Standard Schema validator that conforms to the StandardSchemaV1 interface.
1544
- * The validator uses a closure pattern to maintain internal state and avoid prop drilling.
1545
- * Instead of only returning a boolean, the validator collects detailed error issues if validation fails.
1546
- *
1547
- * @template T - The type of the data object to validate
1548
- * @param {SchemaDefinition} schema - The schema definition containing field and constraint rules
1549
- * @param {PredicateMap} constraintsMap - A map of constraint names to predicate functions
1550
- * @returns {StandardSchemaV1<T, T>} An object conforming to the StandardSchemaV1 interface
1551
- *
1552
- * @example
1553
- * const validator = createStandardSchemaValidator(mySchema, myConstraints);
1554
- * const result = validator["~standard"].validate(data);
1555
- * if ('issues' in result) {
1556
- * console.log('Validation failed:', result.issues);
1557
- * }
1558
1578
  */
1559
1579
  declare function createStandardSchemaValidator<T extends Record<string, any>>(schema: SchemaDefinition, constraintsMap: PredicateMap): StandardSchemaV1<T, T>;
1580
+ /**
1581
+ * Adapts a StandardSchemaV1 validator to React Hook Form's resolver interface.
1582
+ * @param validator - The StandardSchemaV1 validator instance.
1583
+ * @returns A resolver function compatible with React Hook Form.
1584
+ */
1585
+ declare function formResolver<TFieldValues extends FieldValues>(validator: ReturnType<typeof createStandardSchemaValidator>["~standard"]): (values: TFieldValues, context: unknown, options: ResolverOptions<TFieldValues>) => Promise<ResolverResult<TFieldValues>>;
1560
1586
 
1561
1587
  /**
1562
1588
  * Calculates the next version number based on schema changes.
@@ -1604,4 +1630,4 @@ interface FieldGroup {
1604
1630
  */
1605
1631
  declare function extractInputFieldGroups(schema: SchemaDefinition): FieldGroup[];
1606
1632
 
1607
- export { type Constraint, type ConstraintGroup, type ConstraintParameters, type ConstraintsMap, type DataTransform, type FieldDefinition, type FieldGroup, type FieldType, type FunctionMap, type IndexDefinition, type IndexType, JsonPatchError, type LogicalOperator, type Migration, MigrationEngine, type MigrationEngineInterface, MigrationError, MigrationErrorCode, type MigrationMetadata, type NestedSchemaDefinition, type PartialIndexCondition, type PatchOperation, type Persistence, type PersistenceCollection, type PersistenceEvent, type PersistenceEventType, type PersistenceTransaction, type Predicate, type PredicateMap, type PredicateName, type PredicateParameters, type RegistryLock, type RegistryMetadata, type RemoteRepository, type Schema, type SchemaChange, type SchemaConstraint, type SchemaDefinition, type SchemaEvent, type SchemaEventType, type SchemaIndex, type SchemaMetadata, type SchemaMigrationHelper, SchemaRegistry, type SchemaRegistryInterface, type SchemaVersion, type TransformFunction, applyPatch, calculateNextVersion, compareSemanticVersions, createGitSchemaRegistry, createPatch, createSchemaMigrationHelper, createStandardSchemaValidator, deepMerge, docgen, extractInputFieldGroups, generateSHA256Hash, generateValidationInterface, normalizePath, schemaChangeToPatch, schemaToTypes, serializeParams, sortSemanticVars, validate, validateMigration, validateSchemaChange, validateSchemaDefinition };
1633
+ export { type ArrayHint, type BooleanHint, type Constraint, type ConstraintGroup, type ConstraintParameters, type ConstraintsMap, type DataTransform, type DateHint, type DynamicHint, type EnumHint, type FieldDefinition, type FieldGroup, type FieldSchema, type FieldType, type FileHint, type FunctionMap, type GroupDefinition, type IndexDefinition, type IndexType, type InputHint, JsonPatchError, type LogicalOperator, type Migration, MigrationEngine, type MigrationEngineInterface, MigrationError, MigrationErrorCode, type MigrationMetadata, type NestedSchemaDefinition, type NumberHint, type ObjectHint, type PartialIndexCondition, type PatchOperation, type Persistence, type PersistenceCollection, type PersistenceEvent, type PersistenceEventType, type PersistenceTransaction, type Predicate, type PredicateMap, type PredicateName, type PredicateParameters, type RegistryLock, type RegistryMetadata, type RemoteRepository, type Schema, type SchemaChange, type SchemaConstraint, type SchemaDefinition, type SchemaEvent, type SchemaEventType, type SchemaHint, type SchemaIndex, type SchemaMetadata, type SchemaMigrationHelper, SchemaRegistry, type SchemaRegistryInterface, type SchemaVersion, type SecretHint, type SetHint, type TextHint, type TransformFunction, applyPatch, calculateNextVersion, compareSemanticVersions, createGitSchemaRegistry, createPatch, createSchemaMigrationHelper, createStandardSchemaValidator, deepMerge, docgen, extractInputFieldGroups, formResolver, generateSHA256Hash, normalizePath, schemaChangeToPatch, schemaToTypes, serializeParams, sortSemanticVars, validate, validateMigration, validateSchemaChange, validateSchemaDefinition };
package/index.d.ts CHANGED
@@ -3,6 +3,7 @@ import { Faker } from '@faker-js/faker';
3
3
  import { QueryDSL, QueryFilter } from '@asaidimu/query';
4
4
  import { StandardSchemaV1 } from '@standard-schema/spec';
5
5
  import LightningFS from '@isomorphic-git/lightning-fs';
6
+ import { FieldValues, ResolverOptions, ResolverResult } from 'react-hook-form';
6
7
 
7
8
  /**
8
9
  * hints.ts
@@ -129,10 +130,22 @@ type DynamicHint = {
129
130
  group?: string;
130
131
  ignore?: boolean;
131
132
  };
133
+ /**
134
+ * Hints for generating a date input control.
135
+ */
136
+ type DateHint = {
137
+ type: "date" | "datetime" | "time";
138
+ label?: string;
139
+ placeholder?: string;
140
+ min?: string;
141
+ max?: string;
142
+ group?: string;
143
+ ignore?: boolean;
144
+ };
132
145
  /**
133
146
  * Union type for all possible input hints.
134
147
  */
135
- type InputHint = FileHint | TextHint | SecretHint | NumberHint | BooleanHint | EnumHint | ArrayHint | SetHint | ObjectHint | DynamicHint;
148
+ type InputHint = FileHint | TextHint | SecretHint | NumberHint | BooleanHint | EnumHint | ArrayHint | SetHint | ObjectHint | DynamicHint | DateHint;
136
149
  /**
137
150
  * Defines metadata for a group of inputs at the schema level.
138
151
  */
@@ -239,7 +252,7 @@ interface FieldDefinition<T> {
239
252
  name: string;
240
253
  type: FieldType;
241
254
  required?: boolean;
242
- constraints?: Constraint<any>[];
255
+ constraints?: Array<Constraint<any> | ConstraintGroup<any>>;
243
256
  default?: T;
244
257
  /** For type 'enum', specifies the allowed values. */
245
258
  values?: Array<string | number>;
@@ -1495,9 +1508,32 @@ declare class MigrationEngine {
1495
1508
  */
1496
1509
  declare const createSchemaMigrationHelper: <T>(schema: Readonly<SchemaDefinition>) => SchemaMigrationHelper;
1497
1510
 
1498
- declare function validateMigration<T>(change: any): change is Migration<T>;
1499
- declare function validateSchemaChange<T>(change: any): change is SchemaChange<T>;
1500
- declare function validateSchemaDefinition(schema: any): schema is SchemaDefinition;
1511
+ /**
1512
+ * Validates a migration object against the standard schema.
1513
+ * @template T The expected type of the migration data.
1514
+ * @param change The object to validate.
1515
+ * @returns A type guard indicating whether the object conforms to Migration<T>.
1516
+ * @throws {SchemaValidationError} If validation fails due to an unexpected error.
1517
+ */
1518
+ declare function validateMigration<T>(change: unknown): change is Migration<T>;
1519
+ /**
1520
+ * Validates a schema change object against the standard schema.
1521
+ * @template T The expected type of the schema change data.
1522
+ * @param change The object to validate.
1523
+ * @returns A type guard indicating whether the object conforms to SchemaChange<T>.
1524
+ * @throws {SchemaValidationError} If validation fails due to an unexpected error.
1525
+ */
1526
+ declare function validateSchemaChange<T>(change: unknown): change is SchemaChange<T>;
1527
+ /**
1528
+ * Validates a schema definition object against the standard schema.
1529
+ * @param schema The object to validate.
1530
+ * @returns A type guard indicating whether the object conforms to SchemaDefinition.
1531
+ * @throws {SchemaValidationError} If validation fails due to an unexpected error.
1532
+ */
1533
+ declare function validateSchemaDefinition(schema: unknown): schema is SchemaDefinition;
1534
+ /**
1535
+ * Alias for validateSchemaDefinition, provided for convenience.
1536
+ */
1501
1537
  declare const validate: typeof validateSchemaDefinition;
1502
1538
 
1503
1539
  /**
@@ -1520,9 +1556,11 @@ declare function deepMerge<T extends object>(target: T, update: Partial<T>): T;
1520
1556
  * Converts a SchemaDefinition to TypeScript type definitions
1521
1557
  *
1522
1558
  * Analyzes a schema definition and generates TypeScript type declarations for the main schema,
1523
- * nested schemas, and union types for enum-like constraints. Uses capitalized field.name for field names,
1524
- * capitalized nestedSchema.name for type names, and ignores UUID keys. Handles required/optional fields,
1525
- * union types, primitives, arrays, sets, references, and nested structures with strict type safety.
1559
+ * nested schemas, and union types for enum fields and constraints. Uses field.name as-is for field names,
1560
+ * capitalized nestedSchema.name for type names, and handles required/optional fields, new types (enum,
1561
+ * record, union), discriminated unions with common fields, primitives, arrays, sets, references, and nested
1562
+ * structures with strict type safety. Introduces unique generics for each record field and adjusts object
1563
+ * fields referencing concrete schemas to use a string | NestedType union.
1526
1564
  *
1527
1565
  * @param schema - The schema definition to convert
1528
1566
  * @param includeComments - Whether to include JSDoc comments (default: true)
@@ -1530,10 +1568,6 @@ declare function deepMerge<T extends object>(target: T, update: Partial<T>): T;
1530
1568
  * @returns TypeScript type definitions as a string
1531
1569
  */
1532
1570
  declare function schemaToTypes(schema: SchemaDefinition, includeComments?: boolean, exportTypes?: boolean): string;
1533
- /**
1534
- * Generates a TypeScript interface for validating schema data
1535
- */
1536
- declare function generateValidationInterface(schema: SchemaDefinition, exportType?: boolean): string;
1537
1571
 
1538
1572
  /**
1539
1573
  * Serializes constraint parameters for error messages, handling special types like RegExp.
@@ -1541,22 +1575,14 @@ declare function generateValidationInterface(schema: SchemaDefinition, exportTyp
1541
1575
  declare function serializeParams(params: any): string;
1542
1576
  /**
1543
1577
  * Creates a Standard Schema validator that conforms to the StandardSchemaV1 interface.
1544
- * The validator uses a closure pattern to maintain internal state and avoid prop drilling.
1545
- * Instead of only returning a boolean, the validator collects detailed error issues if validation fails.
1546
- *
1547
- * @template T - The type of the data object to validate
1548
- * @param {SchemaDefinition} schema - The schema definition containing field and constraint rules
1549
- * @param {PredicateMap} constraintsMap - A map of constraint names to predicate functions
1550
- * @returns {StandardSchemaV1<T, T>} An object conforming to the StandardSchemaV1 interface
1551
- *
1552
- * @example
1553
- * const validator = createStandardSchemaValidator(mySchema, myConstraints);
1554
- * const result = validator["~standard"].validate(data);
1555
- * if ('issues' in result) {
1556
- * console.log('Validation failed:', result.issues);
1557
- * }
1558
1578
  */
1559
1579
  declare function createStandardSchemaValidator<T extends Record<string, any>>(schema: SchemaDefinition, constraintsMap: PredicateMap): StandardSchemaV1<T, T>;
1580
+ /**
1581
+ * Adapts a StandardSchemaV1 validator to React Hook Form's resolver interface.
1582
+ * @param validator - The StandardSchemaV1 validator instance.
1583
+ * @returns A resolver function compatible with React Hook Form.
1584
+ */
1585
+ declare function formResolver<TFieldValues extends FieldValues>(validator: ReturnType<typeof createStandardSchemaValidator>["~standard"]): (values: TFieldValues, context: unknown, options: ResolverOptions<TFieldValues>) => Promise<ResolverResult<TFieldValues>>;
1560
1586
 
1561
1587
  /**
1562
1588
  * Calculates the next version number based on schema changes.
@@ -1604,4 +1630,4 @@ interface FieldGroup {
1604
1630
  */
1605
1631
  declare function extractInputFieldGroups(schema: SchemaDefinition): FieldGroup[];
1606
1632
 
1607
- export { type Constraint, type ConstraintGroup, type ConstraintParameters, type ConstraintsMap, type DataTransform, type FieldDefinition, type FieldGroup, type FieldType, type FunctionMap, type IndexDefinition, type IndexType, JsonPatchError, type LogicalOperator, type Migration, MigrationEngine, type MigrationEngineInterface, MigrationError, MigrationErrorCode, type MigrationMetadata, type NestedSchemaDefinition, type PartialIndexCondition, type PatchOperation, type Persistence, type PersistenceCollection, type PersistenceEvent, type PersistenceEventType, type PersistenceTransaction, type Predicate, type PredicateMap, type PredicateName, type PredicateParameters, type RegistryLock, type RegistryMetadata, type RemoteRepository, type Schema, type SchemaChange, type SchemaConstraint, type SchemaDefinition, type SchemaEvent, type SchemaEventType, type SchemaIndex, type SchemaMetadata, type SchemaMigrationHelper, SchemaRegistry, type SchemaRegistryInterface, type SchemaVersion, type TransformFunction, applyPatch, calculateNextVersion, compareSemanticVersions, createGitSchemaRegistry, createPatch, createSchemaMigrationHelper, createStandardSchemaValidator, deepMerge, docgen, extractInputFieldGroups, generateSHA256Hash, generateValidationInterface, normalizePath, schemaChangeToPatch, schemaToTypes, serializeParams, sortSemanticVars, validate, validateMigration, validateSchemaChange, validateSchemaDefinition };
1633
+ export { type ArrayHint, type BooleanHint, type Constraint, type ConstraintGroup, type ConstraintParameters, type ConstraintsMap, type DataTransform, type DateHint, type DynamicHint, type EnumHint, type FieldDefinition, type FieldGroup, type FieldSchema, type FieldType, type FileHint, type FunctionMap, type GroupDefinition, type IndexDefinition, type IndexType, type InputHint, JsonPatchError, type LogicalOperator, type Migration, MigrationEngine, type MigrationEngineInterface, MigrationError, MigrationErrorCode, type MigrationMetadata, type NestedSchemaDefinition, type NumberHint, type ObjectHint, type PartialIndexCondition, type PatchOperation, type Persistence, type PersistenceCollection, type PersistenceEvent, type PersistenceEventType, type PersistenceTransaction, type Predicate, type PredicateMap, type PredicateName, type PredicateParameters, type RegistryLock, type RegistryMetadata, type RemoteRepository, type Schema, type SchemaChange, type SchemaConstraint, type SchemaDefinition, type SchemaEvent, type SchemaEventType, type SchemaHint, type SchemaIndex, type SchemaMetadata, type SchemaMigrationHelper, SchemaRegistry, type SchemaRegistryInterface, type SchemaVersion, type SecretHint, type SetHint, type TextHint, type TransformFunction, applyPatch, calculateNextVersion, compareSemanticVersions, createGitSchemaRegistry, createPatch, createSchemaMigrationHelper, createStandardSchemaValidator, deepMerge, docgen, extractInputFieldGroups, formResolver, generateSHA256Hash, normalizePath, schemaChangeToPatch, schemaToTypes, serializeParams, sortSemanticVars, validate, validateMigration, validateSchemaChange, validateSchemaDefinition };
package/index.js CHANGED
@@ -1,67 +1,65 @@
1
- import{createEventBus as qt}from"@asaidimu/events";import{createEventBus as Ct}from"@asaidimu/events";import{createMatcher as Dt,createPaginator as kt,createProjector as It,createSorter as Pt}from"@asaidimu/query";var P=class extends Error{constructor(t,i){super(t);this.operation=i;this.name="JsonPatchError"}};function _(n){let e=Oe(n);return e===""?[]:e.substring(1).split("/").map(Fe)}function Oe(n){return n===""||n==="/"?"":n.startsWith("/")?"/"+n.substring(1).split("/").map(L).join("/"):"/"+n.split(".").map(L).join("/")}function L(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}function Fe(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}var A=new Map;function G(n,e){let t=n;for(let i of e){if(t===null||typeof t!="object")throw new P(`Invalid path - parent not found at ${i}`);if(Array.isArray(t)){let s=i==="-"?t.length:parseInt(i);if(isNaN(s)||s<0||s>t.length)throw new P(`Invalid array index: ${i}`);t=t[s]}else{if(!t.hasOwnProperty(i))throw new P(`Property ${i} not found`);t=t[i]}}return t}function Q(n,e){let t=A.get(e)||_(e);if(A.set(e,t),t.length===0)return n;let i=G(n,t.slice(0,-1)),s=t[t.length-1];if(Array.isArray(i)){let r=parseInt(s);if(isNaN(r)||r<0||r>=i.length)throw new P(`Invalid array index: ${s}`);return i[r]}return i[s]}function je(n,e,t){let i=A.get(e)||_(e);A.set(e,i);let s=G(n,i.slice(0,-1)),r=i[i.length-1];return Array.isArray(s)?s.splice(0,s.length,...s.filter(a=>a!==t)):s[r]===t&&delete s[r],n}function U(n,e,t){let i=A.get(e)||_(e);if(A.set(e,i),i.length===0)return t;let s=i.slice(0,-1),r=i[i.length-1],a=G(n,s);if(Array.isArray(a))if(r==="-")a.push(t);else{let o=parseInt(r);if(o<0||o>a.length)throw new P(`Invalid array index: ${r}`);a.splice(o,0,t)}else a[r]=t;return n}function Z(n,e){let t=A.get(e)||_(e);if(A.set(e,t),t.length===0)return;let i=G(n,t.slice(0,-1)),s=t[t.length-1];if(Array.isArray(i)){let r=parseInt(s);i.splice(r,1)}else delete i[s];return n}function X(n,e){let t=JSON.parse(JSON.stringify(n));for(let i of e)try{switch(i.op){case"add":t=U(t,i.path,i.value);break;case"remove":t=Z(t,i.path);break;case"removeValue":t=je(t,i.path,i.value);break;case"replace":t=U(Z(t,i.path),i.path,i.value);break;case"copy":{let s=Q(t,i.from);t=U(t,i.path,JSON.parse(JSON.stringify(s)));break}case"move":{let s=Q(t,i.from);t=U(t,i.path,s),t=Z(t,i.from);break}case"test":{let s=Q(t,i.path);if(JSON.stringify(s)!==JSON.stringify(i.value))throw new P("Test operation failed");break}default:throw new P(`Unsupported operation: ${i.op}`)}}catch(s){throw s instanceof P&&(s.operation=i),s}return t}function at(n,e){let t=[];return ee(n,e,"",t),t}function ee(n,e,t,i){if(n!==e){if(typeof n!=typeof e||Array.isArray(n)!==Array.isArray(e)){i.push({op:"replace",path:t,value:e});return}typeof n=="object"&&n!==null?Array.isArray(n)?Ne(n,e,t,i):Ve(n,e,t,i):n!==e&&i.push({op:"replace",path:t,value:e})}}function Ne(n,e,t,i){let s=Math.max(n.length,e.length);for(let r=0;r<s;r++){let a=`${t}/${r}`;r>=n.length?i.push({op:"add",path:`${t}/-`,value:e[r]}):r>=e.length?i.push({op:"remove",path:a}):ee(n[r],e[r],a,i)}}function Ve(n,e,t,i){let s=new Set,r=Object.keys(n),a=Object.keys(e);for(let o of r){let c=L(o),d=t?`${t}/${c}`:`/${c}`;e.hasOwnProperty(o)?(ee(n[o],e[o],d,i),s.add(o)):i.push({op:"remove",path:d})}for(let o of a)if(!s.has(o)){let c=L(o),d=t?`${t}/${c}`:`/${c}`;i.push({op:"add",path:d,value:e[o]})}}function me(n,e){let t=[];switch(n.type){case"addField":t.push({op:"add",path:`/fields/${n.id}`,value:n.definition});break;case"removeField":t.push({op:"remove",path:`/fields/${n.id}`});break;case"modifyField":{let i=`/fields/${n.id}`;Object.entries(n.changes).forEach(([s,r])=>{typeof r=="object"&&r!==null&&!Array.isArray(r)?t.push({op:"replace",path:`${i}/${s}`,value:r}):t.push({op:"replace",path:`${i}/${s}`,value:r})});break}case"deprecateField":t.push({op:"add",path:`/fields/${n.id}/deprecated`,value:!0});break;case"addIndex":e.indexes||t.push({op:"add",path:"/indexes",value:[]}),t.push({op:"add",path:"/indexes/-",value:n.definition});break;case"removeIndex":{let i=e.indexes?.findIndex(s=>s.name===n.name);i!==void 0&&i>=0&&t.push({op:"remove",path:`/indexes/${i}`});break}case"modifyIndex":{let i=e.indexes?.findIndex(s=>s.name===n.name);i!==void 0&&i>=0&&Object.entries(n.changes).forEach(([s,r])=>{t.push({op:"replace",path:`/indexes/${i}/${s}`,value:r})});break}case"addConstraint":e.constraints||t.push({op:"add",path:"/constraints",value:[]}),Array.isArray(n.constraint)?n.constraint.forEach(i=>{t.push({op:"add",path:"/constraints/-",value:i})}):t.push({op:"add",path:"/constraints/-",value:n.constraint});break;case"removeConstraint":{let i=e.constraints?.findIndex(s=>Array.isArray(s)?s.some(r=>r.name===n.name):s.name===n.name);i!==void 0&&i>=0&&t.push({op:"remove",path:`/constraints/${i}`});break}case"modifyConstraint":{let i=qe(e,n.name);i&&Object.entries(n.changes).forEach(([s,r])=>{t.push({op:"replace",path:`${i}/${s}`,value:r})});break}}return t}function qe(n,e){if(!n.constraints)return null;for(let t=0;t<n.constraints.length;t++){let i=n.constraints[t];if(i.name===e)return`/constraints/${t}`;if(he(i)){let s=le(i.rules,e);if(s)return`/constraints/${t}${s}`}}return null}function he(n){return n&&"operator"in n&&"rules"in n}function le(n,e){for(let t=0;t<n.length;t++){let i=n[t];if("name"in i&&i.name===e)return`/rules/${t}`;if(he(i)){let s=le(i.rules,e);if(s)return`/rules/${t}${s}`}}return null}function pe(n,e){let t={...n};return te(n)&&te(e)&&Object.keys(e).forEach(i=>{te(e[i])?i in n?t[i]=pe(n[i],e[i]):Object.assign(t,{[i]:e[i]}):Object.assign(t,{[i]:e[i]})}),t}function te(n){return n&&typeof n=="object"&&!Array.isArray(n)}function J(n){return n instanceof RegExp?n.toString().slice(1,-1):JSON.stringify(n)}function Ue(n,e){let t=o=>({value:o}),i=o=>({issues:o}),s=(o,c,d)=>{switch(c){case"string":return typeof o!="string"?[{message:`Expected string, got ${typeof o}`,path:d}]:[];case"number":return typeof o!="number"||isNaN(o)?[{message:`Expected number, got ${typeof o}`,path:d}]:[];case"boolean":return typeof o!="boolean"?[{message:`Expected boolean, got ${typeof o}`,path:d}]:[];case"array":return Array.isArray(o)?[]:[{message:`Expected array, got ${typeof o}`,path:d}];case"set":return!Array.isArray(o)||new Set(o).size!==o.length?[{message:`Expected unique array, got ${typeof o}`,path:d}]:[];case"object":return typeof o!="object"||o===null||Array.isArray(o)?[{message:`Expected object, got ${typeof o}`,path:d}]:[];case"dynamic":return[];default:return[{message:`Unknown type '${c}'`,path:d}]}};function r(o,c,d,u,m){let h=[],g=o.rules.map((f,p)=>{let v=[...u,`rules[${p}]`];if("rules"in f){if(m.has(f.name))return!0;m.add(f.name);let C=r(f,c,d,v,m);return h.push(...C),C.length===0}else{let C=d[f.predicate];if(!C)return h.push({message:`Predicate '${f.predicate}' not found`,path:v}),!1;let $=C({data:c,field:f.field,arguments:f.parameters});if(!$){let E=f.field?` for field '${f.field}'`:"";h.push({message:f.errorMessage||`Constraint '${f.name}' failed${E} with params ${J(f.parameters)}`,path:v})}return $}});return(()=>{switch(o.operator){case"and":return g.every(f=>f);case"or":return g.some(f=>f);case"not":return!g.every(f=>f);case"nor":return!g.some(f=>f);case"xor":return g.filter(f=>f).length===1}})()||h.push({message:`Constraint group '${o.name}' failed`,path:u}),h}function a(o,c,d,u,m,h=new Set){let g=[],D=new Set(Object.values(c.fields).map(f=>f.name));Object.entries(c.fields).forEach(([f,p])=>{let v=[...u,p.name],C=Object.hasOwnProperty.call(o,p.name)?o[p.name]:void 0;if(p.required&&C==null){g.push({message:`Field '${p.name}' is required`,path:v});return}if(C!==void 0){if(g.push(...s(C,p.type,v)),(p.type==="array"||p.type==="set")&&p.itemsType&&Array.isArray(C)&&(C.forEach(($,E)=>g.push(...s($,p.itemsType,[...v,E.toString()]))),p.nestedSchema)){let $=m[p.nestedSchema.id];$?C.forEach((E,I)=>{typeof E=="object"&&E!==null&&(h.has(p.nestedSchema.id)?g.push({message:`Circular reference detected at '${p.nestedSchema.id}'`,path:[...v,I.toString()]}):(h.add(p.nestedSchema.id),g.push(...a(E,$,d,[...v,I.toString()],m,h)),h.delete(p.nestedSchema.id)))}):g.push({message:`Nested schema '${p.nestedSchema.id}' not found`,path:v})}if(p.type==="object"&&p.nestedSchema){let $=m[p.nestedSchema.id];$?typeof C=="object"&&C!==null&&(h.has(p.nestedSchema.id)?g.push({message:`Circular reference detected at '${p.nestedSchema.id}'`,path:v}):(h.add(p.nestedSchema.id),g.push(...a(C,$,d,v,m,h)),p.nestedSchema.constraints?.forEach((E,I)=>{if("rules"in E)g.push(...r(E,C,d,[...v,`constraints[${I}]`],h));else{let l=d[E.predicate];l?l({data:C,field:void 0,arguments:E.parameters})||g.push({message:E.errorMessage||`Constraint '${E.name}' failed with params ${J(E.parameters)}`,path:[...v,`constraints[${I}]`]}):g.push({message:`Predicate '${E.predicate}' not found`,path:[...v,`constraints[${I}]`]})}}),h.delete(p.nestedSchema.id))):g.push({message:`Nested schema '${p.nestedSchema.id}' not found`,path:v})}p.constraints?.forEach(($,E)=>{if("rules"in $)g.push(...r($,o,d,[...v,`constraints[${E}]`],h));else{let I=d[$.predicate];I?I({data:o,field:p.name,arguments:$.parameters})||g.push({message:$.errorMessage||`Constraint '${$.name}' failed for field '${p.name}' with params ${J($.parameters)}`,path:[...v,`constraints[${E}]`]}):g.push({message:`Predicate '${$.predicate}' not found`,path:[...v,`constraints[${E}]`]})}})}});for(let f in o)Object.hasOwnProperty.call(o,f)&&!D.has(f)&&g.push({message:`Unexpected field '${f}'`,path:[...u,f]});return c.constraints?.forEach((f,p)=>{if("rules"in f)g.push(...r(f,o,d,[...u,`constraints[${p}]`],h));else{let v=d[f.predicate];if(!v)g.push({message:`Predicate '${f.predicate}' not found`,path:[...u,`constraints[${p}]`]});else if(!v({data:o,field:f.field,arguments:f.parameters})){let $=f.field?` for field '${f.field}'`:"";g.push({message:f.errorMessage||`Constraint '${f.name}' failed${$} with params ${J(f.parameters)}`,path:[...u,`constraints[${p}]`]})}}}),g}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,d=a(c,n,e,[],n.nestedSchemas||{});return d.length>0?i(d):t(c)},types:{input:{},output:{}}}}}var O=class extends Error{constructor(t,i){super(t);this.errors=i;this.name="SchemaValidationError"}};var ie=n=>({value:n}),F=n=>({issues:n}),S=(n,e,t=!0)=>n===void 0&&!t?[]:typeof n!="string"||n.trim()===""?[{message:"Must be a non-empty string",path:[e]}]:[],ye=(n,e)=>{let t=["string","number","boolean","array","set","object","dynamic"];return typeof n!="string"||!t.includes(n)?[{message:`Must be one of ${t.join(", ")}`,path:[e]}]:[]},Le=(n,e)=>{let t=["normal","unique","btree","hash","spatial","fulltext","gi","expression","composite"];return typeof n!="string"||!t.includes(n)?[{message:`Must be one of ${t.join(", ")}`,path:[e]}]:[]},ge=(n,e)=>{let t=["and","or","not","nor","xor"];return typeof n!="string"||!t.includes(n)?[{message:`Must be one of ${t.join(", ")}`,path:[e]}]:[]},H=(n,e,t=!1)=>n===void 0&&!t?[]:typeof n!="boolean"?[{message:"Must be a boolean",path:[e]}]:[],_e=(n,e,t)=>{if(n===void 0)return[];switch(e){case"string":if(typeof n=="string"||Array.isArray(n)&&n.every(i=>typeof i=="string")||n instanceof RegExp||typeof n=="object"&&n!==null&&"field"in n&&typeof n.field=="string")return[];break;case"number":if(typeof n=="number"||Array.isArray(n)&&n.every(i=>typeof i=="number")||typeof n=="object"&&n!==null&&"precision"in n&&typeof n.precision=="number")return[];break;case"boolean":if(typeof n=="boolean")return[];break;case"array":case"set":if(typeof n=="number"||typeof n=="object"&&n!==null&&"minItems"in n&&typeof n.minItems=="number")return[];break;case"object":if(typeof n=="object"&&n!==null&&"schema"in n)return[];break;case"dynamic":return[]}return[{message:`Invalid parameters for type '${e}'`,path:[t]}]},ae=(n,e)=>{let t=[],i=["predicate","name"],s=["type","predicate","field","parameters","name","description","errorMessage"],r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),t.push(...S(n.predicate,`${e}.predicate`)),n.type!==void 0&&n.type!=="schema"&&t.push({message:"Type must be 'schema' if present",path:[`${e}.type`]}),n.field!==void 0&&typeof n.field!="string"&&t.push({message:"Field must be a string",path:[`${e}.field`]}),n.parameters!==void 0&&(!n.type||n.type!=="schema")&&t.push(..._e(n.parameters,"dynamic",`${e}.parameters`)),t.push(...S(n.description,`${e}.description`,!1)),t.push(...S(n.errorMessage,`${e}.errorMessage`,!1)),t},se=(n,e)=>{let t=[],i=["name","operator","rules"],s=["name","operator","rules"],r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),t.push(...ge(n.operator,`${e}.operator`)),!Array.isArray(n.rules)||n.rules.length===0?t.push({message:"Rules must be a non-empty array",path:[`${e}.rules`]}):n.rules.forEach((a,o)=>{"rules"in a?t.push(...se(a,`${e}.rules[${o}]`)):t.push(...ae(a,`${e}.rules[${o}]`))}),t},V=(n,e)=>{if(!Array.isArray(n))return[{message:"Must be an array",path:[e]}];let t=[];return n.forEach((i,s)=>{"rules"in i?t.push(...se(i,`${e}[${s}]`)):t.push(...ae(i,`${e}[${s}]`))}),t},we=(n,e)=>{let t=[],i=["operator","field"],s=["operator","field","value","conditions"],r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...ge(n.operator,`${e}.operator`)),t.push(...S(n.field,`${e}.field`)),n.conditions!==void 0&&(Array.isArray(n.conditions)?n.conditions.forEach((a,o)=>t.push(...we(a,`${e}.conditions[${o}]`))):t.push({message:"Conditions must be an array",path:[`${e}.conditions`]})),t},Se=(n,e)=>{let t=[],i=["fields","type","name"],s=["fields","type","unique","partial","description","order","name"],r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),t.push(...Le(n.type,`${e}.type`)),(!Array.isArray(n.fields)||n.fields.length===0||!n.fields.every(a=>typeof a=="string"))&&t.push({message:"Fields must be a non-empty array of strings",path:[`${e}.fields`]}),t.push(...H(n.unique,`${e}.unique`,!1)),n.partial&&t.push(...we(n.partial,`${e}.partial`)),t.push(...S(n.description,`${e}.description`,!1)),n.order!==void 0&&!["asc","desc"].includes(n.order)&&t.push({message:"Order must be 'asc' or 'desc'",path:[`${e}.order`]}),t},z=(n,e)=>{if(!Array.isArray(n))return[{message:"Must be an array",path:[e]}];let t=[];return n.forEach((i,s)=>t.push(...Se(i,`${e}[${s}]`))),t},re=(n,e)=>{let t=[],i=["name","type"],s=["name","type","required","constraints","default","itemsType","nestedSchema","deprecated","reference","description","unique"],r=n;if(i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),t.push(...ye(n.type,`${e}.type`)),t.push(...H(n.required,`${e}.required`,!1)),n.constraints&&t.push(...V(n.constraints,`${e}.constraints`)),n.itemsType&&t.push(...ye(n.itemsType,`${e}.itemsType`)),n.nestedSchema){let a=["id"],o=["id","constraints","indexes"],c=n.nestedSchema;a.forEach(d=>{c[d]===void 0&&t.push({message:`${d} is required`,path:[`${e}.nestedSchema.${d}`]})}),Object.keys(c).forEach(d=>{o.includes(d)||t.push({message:"Unknown property",path:[`${e}.nestedSchema.${d}`]})}),t.push(...S(n.nestedSchema.id,`${e}.nestedSchema.id`)),n.nestedSchema.constraints&&t.push(...V(n.nestedSchema.constraints,`${e}.nestedSchema.constraints`)),n.nestedSchema.indexes&&t.push(...z(n.nestedSchema.indexes,`${e}.nestedSchema.indexes`))}if(t.push(...H(n.deprecated,`${e}.deprecated`,!1)),n.reference){let a=["schema","field"],o=["schema","field"],c=n.reference;a.forEach(d=>{c[d]===void 0&&t.push({message:`${d} is required`,path:[`${e}.reference.${d}`]})}),Object.keys(c).forEach(d=>{o.includes(d)||t.push({message:"Unknown property",path:[`${e}.reference.${d}`]})}),t.push(...S(n.reference.schema,`${e}.reference.schema`)),t.push(...S(n.reference.field,`${e}.reference.field`))}return t.push(...S(n.description,`${e}.description`,!1)),t.push(...H(n.unique,`${e}.unique`,!1)),t},$e=(n,e)=>{let t=[],i=["name","fields"],s=["name","description","fields","indexes","constraints","metadata"],r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),typeof n.fields!="object"?t.push({message:"Fields must be a non-empty object",path:[`${e}.fields`]}):Object.entries(n.fields).forEach(([a,o])=>{t.push(...re(o,`${e}.fields.${a}`))}),t.push(...S(n.description,`${e}.description`,!1)),n.indexes&&t.push(...z(n.indexes,`${e}.indexes`)),n.constraints&&t.push(...V(n.constraints,`${e}.constraints`)),n.metadata!==void 0&&(typeof n.metadata!="object"||n.metadata===null)&&t.push({message:"Metadata must be an object",path:[`${e}.metadata`]}),t},Ge=n=>{if(typeof n!="object"||n===null)return F([{message:"Schema must be an object",path:[]}]);let e=n,t=[],i=["name","version","fields","nestedSchemas"],s=["name","version","description","fields","nestedSchemas","indexes","constraints","metadata","dependencies","migrations","mock"],r=e;if(i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[a]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[a]})}),t.push(...S(e.name,"name")),t.push(...S(e.version,"version")),typeof e.fields!="object"?t.push({message:"Fields must be a non-empty object",path:["fields"]}):Object.entries(e.fields).forEach(([a,o])=>{t.push(...re(o,`fields.${a}`))}),typeof e.nestedSchemas!="object")t.push({message:"NestedSchemas must be a non-empty object",path:["nestedSchemas"]});else{let a=Object.keys(e.nestedSchemas);Object.entries(e.nestedSchemas).forEach(([o,c])=>t.push(...$e(c,`nestedSchemas.${o}`))),Object.entries(e.fields).forEach(([o,c])=>{c.nestedSchema&&!a.includes(c.nestedSchema.id)&&t.push({message:`nestedSchema.id '${c.nestedSchema.id}' must match a nestedSchemas key`,path:[`fields.${o}.nestedSchema.id`]})})}return t.push(...S(e.description,"description",!1)),e.indexes&&t.push(...z(e.indexes,"indexes")),e.constraints&&t.push(...V(e.constraints,"constraints")),e.metadata!==void 0&&(typeof e.metadata!="object"||e.metadata===null)&&t.push({message:"Metadata must be an object",path:["metadata"]}),e.dependencies!==void 0&&(!Array.isArray(e.dependencies)||!e.dependencies.every(a=>typeof a=="string"))&&t.push({message:"Dependencies must be an array of strings",path:["dependencies"]}),e.migrations!==void 0&&(Array.isArray(e.migrations)?e.migrations.forEach((a,o)=>t.push(...be(a,`migrations[${o}]`))):t.push({message:"Migrations must be an array",path:["migrations"]})),e.mock!==void 0&&typeof e.mock!="function"&&t.push({message:"Mock must be a function",path:["mock"]}),t.length>0?F(t):ie(e)},ne=(n,e)=>{let t=[];switch(n.type||t.push({message:"type is required",path:[`${e}.type`]}),n.type){case"modifyProperty":{let i=["type","id","changes"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`)),(n.changes===void 0||typeof n.changes!="object")&&t.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addField":{let i=["type","id","definition"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`)),t.push(...re(n.definition,`${e}.definition`));break}case"removeField":case"deprecateField":{let i=["type","id"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`));break}case"modifyField":{let i=["type","id","changes"],s=["type","id","changes","nestedSchemaChanges"],r=n;if(i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`)),typeof n.changes!="object"&&t.push({message:"Changes must be an object",path:[`${e}.changes`]}),n.nestedSchemaChanges){let a=["id","constraints","indexes"],o=n.nestedSchemaChanges;Object.keys(o).forEach(c=>{a.includes(c)||t.push({message:"Unknown property",path:[`${e}.nestedSchemaChanges.${c}`]})}),t.push(...S(o.id,`${e}.nestedSchemaChanges.id`,!1)),o.constraints&&t.push(...V(o.constraints,`${e}.nestedSchemaChanges.constraints`)),o.indexes&&t.push(...z(o.indexes,`${e}.nestedSchemaChanges.indexes`))}break}case"addIndex":{let i=["type","definition"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...Se(n.definition,`${e}.definition`));break}case"removeIndex":{let i=["type","name"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`));break}case"modifyIndex":{let i=["type","name","changes"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),typeof n.changes!="object"&&t.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addConstraint":{let i=["type","constraint"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),"rules"in n.constraint?t.push(...se(n.constraint,`${e}.constraint`)):t.push(...ae(n.constraint,`${e}.constraint`));break}case"removeConstraint":{let i=["type","name"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`));break}case"modifyConstraint":{let i=["type","name","changes"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.name,`${e}.name`)),typeof n.changes!="object"&&t.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addNestedSchema":{let i=["type","id","definition"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`)),t.push(...$e(n.definition,`${e}.definition`));break}case"removeNestedSchema":{let i=["type","id"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`));break}case"modifyNestedSchema":{let i=["type","id","changes"],s=i,r=n;i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),t.push(...S(n.id,`${e}.id`)),typeof n.changes!="object"&&t.push({message:"Changes must be an object",path:[`${e}.changes`]});break}default:t.push({message:"Unknown schema change type",path:[`${e}.type`]})}return t},Je=(n,e)=>{let t=[],i=["forward","backward"],s=i,r=n;return i.forEach(a=>{r[a]===void 0&&t.push({message:`${a} is required`,path:[`${e}.${a}`]})}),Object.keys(r).forEach(a=>{s.includes(a)||t.push({message:"Unknown property",path:[`${e}.${a}`]})}),typeof n.forward!="function"&&t.push({message:"Forward must be a function",path:[`${e}.forward`]}),typeof n.backward!="function"&&t.push({message:"Backward must be a function",path:[`${e}.backward`]}),t},be=(n,e)=>{let t=[],i=["id","schemaVersion","changes","description","status","transform","createdAt","checksum"],s=[...i,"rollback","dependencies"],r=n;i.forEach(o=>{r[o]===void 0&&t.push({message:`${o} is required`,path:[`${e}.${o}`]})}),Object.keys(r).forEach(o=>{s.includes(o)||t.push({message:"Unknown property",path:[`${e}.${o}`]})}),t.push(...S(n.id,`${e}.id`)),t.push(...S(n.schemaVersion,`${e}.schemaVersion`)),t.push(...S(n.description,`${e}.description`));let a=["pending","applied","failed"];return a.includes(n.status)||t.push({message:`Status must be one of ${a.join(", ")}`,path:[`${e}.status`]}),!Array.isArray(n.changes)||n.changes.length===0?t.push({message:"Changes must be a non-empty array",path:[`${e}.changes`]}):n.changes.forEach((o,c)=>t.push(...ne(o,`${e}.changes[${c}]`))),n.rollback!==void 0&&(Array.isArray(n.rollback)?n.rollback.forEach((o,c)=>t.push(...ne(o,`${e}.rollback[${c}]`))):t.push({message:"Rollback must be an array",path:[`${e}.rollback`]})),typeof n.transform=="string"?t.push(...S(n.transform,`${e}.transform`)):typeof n.transform=="object"&&n.transform!==null?t.push(...Je(n.transform,`${e}.transform`)):t.push({message:"Transform must be a string or object",path:[`${e}.transform`]}),t.push(...S(n.createdAt,`${e}.createdAt`)),n.dependencies!==void 0&&(!Array.isArray(n.dependencies)||!n.dependencies.every(o=>typeof o=="string"))&&t.push({message:"Dependencies must be an array of strings",path:[`${e}.dependencies`]}),t.push(...S(n.checksum,`${e}.checksum`)),t},ve={"~standard":{version:1,vendor:"xAI",validate:Ge,types:{input:{},output:{}}}};var xe={"~standard":{version:1,vendor:"xAI",validate:n=>{if(typeof n!="object"||n===null)return F([{message:"Migration must be an object",path:[]}]);let e=n,t=be(e,"");return t.length>0?F(t):ie(e)},types:{input:{},output:{}}}},Ee={"~standard":{version:1,vendor:"xAI",validate:n=>{if(!Array.isArray(n))return F([{message:"SchemaChanges must be an array",path:[]}]);let e=n,t=[];return e.forEach((i,s)=>t.push(...ne(i,`[${s}]`))),t.length>0?F(t):ie(e)},types:{input:[],output:[]}}};function Ce(n){try{return!xe["~standard"].validate(n).issues}catch(e){throw new O("Invalid migration definition",e)}}function Te(n){try{return!Ee["~standard"].validate(n).issues}catch(e){throw new O("Invalid schema definition",e)}}function q(n){try{return!ve["~standard"].validate(n).issues}catch(e){throw new O("Invalid schema definition",e)}}var mt=q;var j=async n=>{if(typeof window<"u"&&crypto.subtle){let t=new TextEncoder().encode(n),i=await crypto.subtle.digest("SHA-256",t);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(n).digest("hex")}};function He(n){let e=n.match(/^(\d+)\.(\d+)\.(\d+)$/);if(!e)throw new Error(`Invalid version format: ${n}. Expected format: major.minor.patch`);return{major:parseInt(e[1],10),minor:parseInt(e[2],10),patch:parseInt(e[3],10)}}function ze(n,e){if(e&&"field"in n&&n.field){let t=e.fields[n.field];if(t)return t.type}if("parameters"in n){let t=n.parameters;if(t instanceof RegExp||Array.isArray(t)&&typeof t[0]=="string")return"string";if(typeof t=="number"||Array.isArray(t)&&typeof t[0]=="number")return"number";if(typeof t=="boolean")return"boolean";if(typeof t=="object"&&t!==null){if("minItems"in t||"maxItems"in t)return"array";if("schema"in t)return"object"}}}function Be(n){return n.required===!0||n.type!==void 0||n.itemsType!==void 0||n.nestedSchema!==void 0||n.reference!==void 0||n.unique===!0}function Ke(n,e,t){switch(t){case"string":if(n instanceof RegExp&&e instanceof RegExp)return n.source!==e.source;if(Array.isArray(n)&&Array.isArray(e))return e.length<n.length||!n.every(i=>e.includes(i));break;case"number":if(typeof n=="object"&&typeof e=="object"&&"precision"in n&&"precision"in e)return e.precision<n.precision||(e.scale??0)<(n.scale??0);if(Array.isArray(n)&&Array.isArray(e))return e.length<n.length||!n.every(i=>e.includes(i));break;case"array":if(typeof n=="object"&&typeof e=="object"&&"minItems"in n&&"maxItems"in n&&"minItems"in e&&"maxItems"in e)return e.minItems>n.minItems||e.maxItems<n.maxItems;break;case"object":if(typeof n=="object"&&typeof e=="object"&&"schema"in n&&"schema"in e)return Object.keys(e.schema).length>Object.keys(n.schema).length;break}return!1}function We(n,e){let t={or:1,xor:2,and:3,not:4,nor:4};return!!(e.operator&&t[e.operator]>t[n.operator]||e.rules&&e.rules.length>n.rules.length)}function Ye(n,e,t){if(!e)return!0;if("rules"in e&&"rules"in n)return We(e,n);if("predicate"in n&&n.predicate!==void 0)return!0;if("parameters"in n&&n.parameters!==void 0){let i=ze(e,t);return i?Ke(e.parameters,n.parameters,i):!0}return!1}function Qe(n,e){switch(n.type){case"removeField":case"removeIndex":return"major";case"modifyField":return Be(n.changes)?"major":n.changes.deprecated?"minor":"patch";case"modifyIndex":return n.changes.unique!==void 0||n.changes.fields!==void 0?"major":"minor";case"addConstraint":return"major";case"removeConstraint":return"minor";case"modifyConstraint":let t=e?.constraints?.find(i=>"name"in i&&i.name===n.name);return Ye(n.changes,t,e)?"major":"minor";case"addField":case"addIndex":case"deprecateField":return"minor";default:throw new Error(`Unhandled change type: ${JSON.stringify(n)}`)}}function Ze(n){let e=new Set,t=new Set,i=new Set,s=new Set;for(let r of n)switch(r.type){case"addField":if(t.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(s.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(s.has(r.id))throw new Error(`Cannot remove field that is being deprecated: ${r.id}`);t.add(r.id);break;case"modifyField":if(t.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(s.has(r.id))throw new Error(`Cannot modify field that is being deprecated: ${r.id}`);e.add(r.id);break;case"deprecateField":if(t.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}`);s.add(r.id);break}}function Xe(n){let e=new Set,t=new Set,i=new Set;for(let s of n)switch(s.type){case"addConstraint":let r=s.constraint,a=("name"in r,r.name);if(t.has(a))throw new Error(`Cannot add previously removed constraint: ${a}`);if(e.has(a))throw new Error(`Cannot add already modified constraint: ${a}`);i.add(a);break;case"removeConstraint":if(i.has(s.name))throw new Error(`Cannot remove newly added constraint: ${s.name}`);if(e.has(s.name))throw new Error(`Cannot remove modified constraint: ${s.name}`);t.add(s.name);break;case"modifyConstraint":if(t.has(s.name))throw new Error(`Cannot modify removed constraint: ${s.name}`);if(i.has(s.name))throw new Error(`Cannot modify newly added constraint: ${s.name}`);e.add(s.name);break}}function De(n,e,t){if(e.length===0)throw new Error("No changes provided");Ze(e),Xe(e);let i=He(n),s="patch";for(let r of e){let a=Qe(r,t);if(a==="major"){s="major";break}else a==="minor"&&s==="patch"&&(s="minor")}switch(s){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 M(n,e){let t=d=>d.split(".").map(u=>parseInt(u,10)||0),[i,s,r]=t(n),[a,o,c]=t(e);return i-a||s-o||r-c}function pt(n){return n.sort(M)}var x=class extends Error{constructor(t,i,s,r){super(t);this.code=i;this.migrationId=s;this.cause=r;this.name="MigrationError"}},et=(h=>(h.INVALID_SCHEMA="INVALID_SCHEMA",h.INVALID_MIGRATION="INVALID_MIGRATION",h.CHECKSUM_MISMATCH="CHECKSUM_MISMATCH",h.TIMEOUT="TIMEOUT",h.MEMORY_LIMIT="MEMORY_LIMIT",h.CONCURRENT_OPERATION="CONCURRENT_OPERATION",h.TRANSFORM_ERROR="TRANSFORM_ERROR",h.VERSION_NOT_FOUND="VERSION_NOT_FOUND",h.CIRCULAR_DEPENDENCY="CIRCULAR_DEPENDENCY",h.STREAM_ERROR="STREAM_ERROR",h.ROLLBACK_ERROR="ROLLBACK_ERROR",h.MISSING_TRANSFORM="MISSING_TRANSFORM",h))(et||{}),ke=class n{currentSchema;history=[];migrations=[];isProcessing=!1;constructor(e,t,i){try{if(!q(e))throw new x("Invalid initial schema","INVALID_SCHEMA");if(this.currentSchema=e,t){if(!t.every(s=>Ce(s)))throw new x("Invalid migration configuration","INVALID_MIGRATION");this.migrations=t.sort((s,r)=>M(s.schemaVersion,r.schemaVersion))}i&&(this.history=i.sort((s,r)=>M(s.version,r.version)))}catch(s){throw s instanceof x?s:new x("Failed to initialize MigrationEngine","INVALID_SCHEMA",void 0,s)}}data(){return{schema:this.currentSchema,history:this.history,migrations:this.migrations}}async generateChecksum(e){try{let t=JSON.stringify({id:e.id,schemaVersion:e.schemaVersion,changes:e.changes,description:e.description,rollback:e.rollback,createdAt:e.createdAt});return await j(t)}catch(t){throw new x("Checksum generation failed","CHECKSUM_MISMATCH",e.id,t)}}async add(e){if(this.isProcessing)throw new x("Concurrent operation","CONCURRENT_OPERATION");if(!e.changes?.length)throw new x("Migration must include changes","INVALID_MIGRATION");try{e.changes.forEach(i=>Te(i))}catch(i){throw new x("Invalid schema changes","INVALID_MIGRATION",void 0,i)}let t={id:Date.now().toString(),schemaVersion:this.currentSchema.version,changes:e.changes,description:e.description,status:"pending",rollback:e.rollback,transform:e.transform,createdAt:new Date().toISOString(),checksum:""};t.checksum=await this.generateChecksum(t),this.migrations.push(t)}async dryRun(e,t,i){if(this.isProcessing)throw new x("Concurrent operation","CONCURRENT_OPERATION");try{this.isProcessing=!0;let s={...this.currentSchema},r=this.getRelevantMigrations(t,i),a=r.reduce((c,d)=>{let u=t==="forward"?d.changes:d.rollback||[];return this.applySchemaChanges(c,u,d.id)},s),o=await n.processMigrationList(e,t,r);return{newSchema:a,dataPreview:o}}catch(s){throw s instanceof x?s:new x("Dry run failed","INVALID_SCHEMA",void 0,s)}finally{this.isProcessing=!1}}getRelevantMigrations(e,t){return[...this.migrations].filter(i=>{let s=e==="forward"?"pending":"applied",r=t?M(i.schemaVersion,t)>=0:!0;return i.status===s&&r}).sort((i,s)=>e==="forward"?i.id.localeCompare(s.id):s.id.localeCompare(i.id))}applySchemaChanges(e,t,i){try{let s=De(e.version,t);return t.map(a=>{try{return me(a,e)}catch(o){throw new x("Invalid schema change","INVALID_SCHEMA",i,o)}}).reduce((a,o)=>{try{return X(a,o)}catch(c){throw new x("Failed to apply patch","INVALID_SCHEMA",i,c)}},{...e,version:s})}catch(s){throw s instanceof x?s:new x("Schema update failed","INVALID_SCHEMA",i,s)}}async prepareMigration(){let e=this.migrations.filter(t=>t.status==="pending");return await this.validateMigrations(e),e}async migrate(e){if(this.isProcessing)throw new x("Concurrent operation","CONCURRENT_OPERATION");let t=await this.prepareMigration();try{this.isProcessing=!0,this.transformSchema("forward");let i=await n.processMigrationList(e,"forward",t);return this.markMigrationsApplied(t),i}finally{this.isProcessing=!1}}async validateMigrations(e){await Promise.all(e.map(async t=>{let i=await this.generateChecksum(t);if(t.checksum!==i)throw new x("Checksum mismatch","CHECKSUM_MISMATCH",t.id)}))}markMigrationsApplied(e){this.migrations=this.migrations.map(t=>e.some(i=>i.id===t.id)?{...t,status:"applied"}:t)}async rollback(e){if(this.isProcessing)throw new x("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,t){if(this.isProcessing)throw new x("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 s=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 t;for(let o=0;o<r;o++)this.transformSchema("backward");let a=await n.processMigrationList(t,"backward",s);return this.migrations=this.migrations.map(o=>o.schemaVersion===e&&o.status==="applied"?{...o,status:"pending"}:o),a}finally{this.isProcessing=!1}}static async processMigrationList(e,t,i){return(await Promise.all(i.map(async a=>{try{let o=await this.resolveTransform(a,t);return{migration:a,transform:o}}catch(o){throw new x(`Failed to resolve transform for migration ${a.id}`,"TRANSFORM_ERROR",a.id,o)}}))).filter(a=>!!a.transform).reduce((a,{migration:o,transform:c})=>a.pipeThrough(new TransformStream({async transform(d,u){try{let m=await c(d);u.enqueue(m)}catch(m){u.error(new x(`Data transformation failed for migration ${o.id}`,"TRANSFORM_ERROR",o.id,m))}}})),e)}static async resolveTransform(e,t){return e.transform?typeof e.transform=="string"?e.transform.startsWith("http://")||e.transform.startsWith("https://")?this.resolveRemoteTransform(e.transform,t):this.resolveLocalTransform(e.transform,t):e.transform[t]:null}static async resolveRemoteTransform(e,t){try{let i=await fetch(e);if(!i.ok)throw new x(`Failed to fetch transform module: ${e}`,"TRANSFORM_ERROR",void 0);let s=await i.text();if(typeof window<"u"){let r=new Blob([s],{type:"application/javascript"});return(await import(URL.createObjectURL(r))).default[t]}else{let{runInNewContext:r}=await import("vm"),a={module:{exports:{}},console};return r(s,a,e),a.module.exports[t]}}catch(i){throw new x(`Failed to load remote transform module: ${e}`,"TRANSFORM_ERROR",void 0,i)}}static async resolveLocalTransform(e,t){try{return(await import(e)).default[t]}catch(i){throw new x(`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 t=this.migrations.filter(i=>i.status==="pending").flatMap(i=>i.changes);if(!t.length)return;this.history.push(structuredClone(this.currentSchema)),this.currentSchema=t.reduce((i,s)=>this.applySchemaChanges(i,[s]),this.currentSchema)}catch(t){throw t instanceof x?t:new x("Schema transformation failed","INVALID_SCHEMA",void 0,t)}}};var tt=n=>{let e=[],t=[];return{addField:(i,s)=>{e.push({type:"addField",id:i,definition:s}),t.push({type:"removeField",id:i})},removeField:i=>{e.push({type:"removeField",id:i});let s=n.fields[i];s&&t.push({type:"addField",id:i,definition:s})},modifyField:(i,s)=>{e.push({type:"modifyField",id:i,changes:s});let r=n.fields[i];r&&t.push({type:"modifyField",id:i,changes:r})},deprecateField:i=>{e.push({type:"deprecateField",id:i}),t.push({type:"modifyField",id:i,changes:{deprecated:!1}})},addIndex:i=>{e.push({type:"addIndex",definition:i}),t.push({type:"removeIndex",name:i.name})},removeIndex:i=>{e.push({type:"removeIndex",name:i});let s=n.indexes?.find(r=>r.name===i);s&&t.push({type:"addIndex",definition:s})},modifyIndex:(i,s)=>{e.push({type:"modifyIndex",name:i,changes:s});let r=n.indexes?.find(a=>a.name===i);r&&t.push({type:"modifyIndex",name:i,changes:r})},addConstraint:i=>{e.push({type:"addConstraint",constraint:i}),t.push({type:"removeConstraint",name:i.name})},removeConstraint:i=>{e.push({type:"removeConstraint",name:i});let s=n.constraints?.find(r=>"name"in r&&r.name===i);s&&t.push({type:"addConstraint",constraint:s})},modifyConstraint:(i,s)=>{e.push({type:"modifyConstraint",name:i,changes:s});let r=n.constraints?.find(a=>"name"in a&&a.name===i);r&&t.push({type:"modifyConstraint",name:i,changes:r})},addNestedSchema:(i,s)=>{e.push({type:"addNestedSchema",id:i,definition:s}),t.push({type:"removeNestedSchema",id:i})},removeNestedSchema:i=>{e.push({type:"removeNestedSchema",id:i});let s=n.nestedSchemas[i];s&&t.push({type:"addNestedSchema",id:i,definition:s})},modifyNestedSchema:(i,s)=>{e.push({type:"modifyNestedSchema",id:i,changes:s});let r=n.nestedSchemas[i];r&&t.push({type:"modifyNestedSchema",id:i,changes:r})},changes:()=>({migrate:e,rollback:t})}};import"@isomorphic-git/lightning-fs";import T from"isomorphic-git";import K from"isomorphic-git/http/web";import nt from"@isomorphic-git/lightning-fs";function Ie(n){let e=n.toString(),t=e.substring(e.indexOf("(")+1,e.indexOf(")")),i=e.substring(e.indexOf("{")+1,e.lastIndexOf("}")).trim();return JSON.stringify({params:t,body:i})}function Pe(n){let{params:e,body:t}=JSON.parse(n),i=Object.getPrototypeOf(function*(){}).constructor;return new i(e,t)}function oe(n){let e=n.toString(),t=e.match(/\(([^)]*)\)\s*=>\s*(.+)/s),i=e.match(/function\s*\(([^)]*)\)\s*{([\s\S]*)}/),s=e.match(/([^(]*)\(([^)]*)\)\s*{([\s\S]*)}/),r,a;return t?(r=t[1],a=t[2].includes("{")?t[2].substring(1,t[2].length-1).trim():`return ${t[2]}`):i?(r=i[1],a=i[2].trim()):s?(r=s[2],a=s[3].trim()):(r=e.substring(e.indexOf("(")+1,e.indexOf(")")),a=e.substring(e.indexOf("{")+1,e.lastIndexOf("}")).trim()),JSON.stringify({params:r,body:a,type:t?"arrow":i?"function":s?"method":"unknown"})}function ce(n){let{params:e,body:t,type:i}=JSON.parse(n),s=new Function(e,t);return i==="arrow"&&Object.defineProperty(s,"toString",{value:()=>`(${e}) => ${t}`,configurable:!0}),s}import{Buffer as it}from"buffer";window.Buffer=it;var B=class{fs;fsp;rootDir;constructor(e="/registry"){this.fs=new nt(`${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||!q(e))throw new Error("Invalid schema");let t=`${this.rootDir}/${e.name}`;if(await this.fileExists(`${t}/schema.json`))throw new Error(`Schema ${e.name} already exists`);return await this.fsp.mkdir(t),await this.fsp.mkdir(`${t}/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 t=`${this.rootDir}/${e.name}`;if(!await this.fileExists(`${t}/schema.json`))throw new Error(`Schema ${e.name} not found`);return this.saveSchema(e,"update")}async saveSchema(e,t){let i=`${this.rootDir}/${e.name}`,s=await this.processAndStoreMigrations(i,e),r=this.serializeSchema(e);await this.writeSchemaFile(i,r);let a=await j(r);await this.updateIndex(i,e,a,s,t),await this.updateRegistryMetadata(e,t),await this.sync()}async delete({name:e}){let t=`${this.rootDir}/${e}`;if(!await this.fileExists(`${t}/schema.json`))throw new Error(`Schema ${e} not found`);await this.rmdirRecursive(t);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(t=>({name:t.name,version:t.version}))}async schema({name:e,version:t,migrations:i=!1}){let s=`${this.rootDir}/${e}/schema.json`;if(!await this.fileExists(s))return null;let r=this.deserializeSchema(JSON.parse(String(await this.fsp.readFile(s,"utf8")))),a=await this.readSchemaIndex(e);return t&&t!==a.version&&!a.history.some(o=>o.version===t)?null:(i&&(r.migrations=await this.migrations({name:e,version:t})),r)}async stats({schema:e}){return e?this.readSchemaIndex(e):this.readRegistryMetadata()}async sync(){let e={updated:new Date().toISOString(),hashes:[]},t=await this.listFilesRecursive(this.rootDir);for(let i of t)if(i!==`${this.rootDir}/schema-lock.json`&&i.match(new RegExp("/*.git*/"))===null){let s=String(await this.fsp.readFile(i,"utf8"));e.hashes.push([i,await j(s)])}await this.fsp.writeFile(`${this.rootDir}/schema-lock.json`,JSON.stringify(e),"utf8")}async migrations({name:e,version:t}){let i=await this.readSchemaIndex(e),s=t||i.version,r=[];for(let[a,o]of Object.entries(i.migrations)){let c=`${this.rootDir}/${e}/migrations/${o.hash}.json`;if(await this.fileExists(c)){let d=JSON.parse(String(await this.fsp.readFile(c,"utf8")));M(d.schemaVersion,s)<=0&&r.push(this.deserializeMigration(d))}}return r.sort((a,o)=>M(a.schemaVersion,o.schemaVersion))}async history({name:e}){let t=await this.readSchemaIndex(e),i=this.deserializeSchema(JSON.parse(String(await this.fsp.readFile(`${this.rootDir}/${e}/schema.json`,"utf8"))));return Promise.all(t.history.map(async s=>({...i,version:s.version,description:s.description,migrations:await this.migrations({name:e,version:s.version})})))}async processAndStoreMigrations(e,t){return Promise.all((t.migrations||[]).map(async i=>{let s={...i};if(i.transform?.forward){let o=i.transform;s.transform={forward:oe(o.forward),backward:oe(o.backward||(c=>c))}}let r=JSON.stringify(s),a=await j(r);return await this.fsp.writeFile(`${e}/migrations/${a}.json`,r,"utf8"),{id:i.id,hash:a,checksum:i.checksum}}))}serializeSchema(e){return JSON.stringify({...e,migrations:void 0,mock:e.mock?Ie(e.mock):null})}deserializeSchema(e){return e.mock&&(e.mock=Pe(e.mock)),e}deserializeMigration(e){return e.transform?.forward&&(e.transform={forward:ce(e.transform.forward),backward:ce(e.transform.backward)}),e}async writeSchemaFile(e,t){let i=`${e}/schema.json`;return await this.fsp.writeFile(i,t,"utf8"),i}async updateIndex(e,t,i,s,r){let a=`${e}/index.json`,o=r==="create"?{schema:t.name,version:t.version,history:[],migrations:{}}:JSON.parse(String(await this.fsp.readFile(a,"utf8")));o.history.push({version:t.version,hash:i,date:new Date().toISOString(),description:t.description||(r==="create"?"Initial version":"Updated version"),migrations:s.map(c=>c.id),predicates:[],changelog:[]}),o.version=t.version,s.forEach(({id:c,hash:d,checksum:u})=>{o.migrations[c]={hash:d,checksum:u}}),await this.fsp.writeFile(a,JSON.stringify(o),"utf8")}async updateRegistryMetadata(e,t){let i=await this.readRegistryMetadata();i.schemas[e.name]={name:e.name,version:e.version,description:e.description||"",created:t==="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 t=`${this.rootDir}/${e}/index.json`;if(!await this.fileExists(t))throw new Error(`Schema ${e} not found`);return JSON.parse(String(await this.fsp.readFile(t,"utf8")))}async fileExists(e){try{return await this.fsp.stat(e),!0}catch{return!1}}async rmdirRecursive(e){let t=await this.fsp.readdir(e);for(let i of t){let s=`${e}/${i}`;(await this.fsp.stat(s)).isDirectory()?await this.rmdirRecursive(s):await this.fsp.unlink(s)}await this.fsp.rmdir(e)}async listFilesRecursive(e){let t=[],i=await this.fsp.readdir(e);for(let s of i){let r=`${e}/${s}`;(await this.fsp.stat(r)).isDirectory()?t.push(...await this.listFilesRecursive(r)):t.push(r)}return t}};var de=class{locks=new Map;async acquire(e){let t,i=new Promise(r=>{t=r}),s=this.locks.get(e)||Promise.resolve();return this.locks.set(e,s.then(()=>i)),await s,t}async withLock(e,t){let i=await this.acquire(e);try{return await t()}finally{i()}}},ue=class{cache=new Map;ttl;constructor(e=3e4){this.ttl=e}get(e){let t=this.cache.get(e);return!t||Date.now()-t.timestamp>this.ttl?(this.cache.delete(e),null):t.schema}set(e,t){this.cache.set(e,{schema:t,timestamp:Date.now()})}invalidate(e){e?this.cache.delete(e):this.cache.clear()}};async function W(n,e){try{return await n()}catch(t){throw console.error(`${e}:`,t),new Error(`${e}: ${t.message}`)}}async function Y(n,e,t,i,s){await i.init(),await T.init({fs:n,dir:e,defaultBranch:t}),await T.setConfig({fs:n,dir:e,path:"core.autocrlf",value:"false"}),await T.setConfig({fs:n,dir:e,path:"core.eol",value:"lf"}),await T.add({fs:n,dir:e,filepath:"."}),await T.commit({fs:n,dir:e,message:"chore: initial commit",author:s})}async function sn(n="/registry",e={}){let t=e.mainBranch||"main",i=e.remote,s=e.createRemote??!1,r=e.author||{name:"SchemaRegistry",email:"system@example.com"},a=e.proxy?[e.proxy]:["https://cors.isomorphic-git.org"],o=0,c=new B(n),d=c.fs,u=n.startsWith("/")?n:`/${n}`,m=new de,h=new ue(e.cacheTtl);async function g(l,y){let w=o;do{let b=a[o];try{return await l(b)}catch(k){if(console.warn(`Failed with proxy ${b}: ${k.message}`),o=(o+1)%a.length,o===w)throw new Error(`${y}: All CORS proxies failed`)}}while(!0)}async function D(l,y="."){return W(async()=>(await T.add({fs:d,dir:u,filepath:y}),(await T.statusMatrix({fs:d,dir:u})).some(([b,k,R])=>k!==R)?await T.commit({fs:d,dir:u,message:l,author:r}):null),"Failed to commit changes")}async function f(l,y,w){return W(async()=>{if(await p(l))throw new Error(`Tag ${l} already exists`);await T.annotatedTag({fs:d,dir:u,ref:l,message:y,tagger:r,object:w})},`Failed to create tag ${l}`)}async function p(l){try{return(await T.listTags({fs:d,dir:u})).includes(l)}catch{return!1}}async function v(l){return(await T.listTags({fs:d,dir:u})).filter(b=>b.startsWith(l))}async function C(l){return W(async()=>{let w=(await T.listTags({fs:d,dir:u})).filter(b=>b.startsWith(l));for(let b of w)await T.deleteTag({fs:d,dir:u,ref:b});return w},`Failed to delete tags with prefix ${l}`)}async function $(l){return W(async()=>{await T.checkout({fs:d,dir:u,ref:l})},`Failed to checkout ${l}`)}async function E(l,{delete:y=!1,force:w=!1}={}){i&&await g(async b=>{await T.push({fs:d,http:K,dir:u,ref:l,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:b,delete:y,force:w})},`Failed to push ${l}`)}async function I(l,y=!0){i&&await g(async w=>{try{await T.pull({fs:d,http:K,dir:u,ref:l,author:r,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:w,fastForwardOnly:!0})}catch(b){if(!y)console.warn(`Fast-forward pull failed for ${l}, attempting regular pull`),await T.pull({fs:d,http:K,dir:u,ref:l,author:r,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:w,fastForwardOnly:!1});else throw b}},`Failed to pull ${l}`)}if(i&&!await c.fileExists(u)){let l=u.slice(1);if(await i.exists({name:l}).catch(()=>!1))await g(async w=>{await T.clone({fs:d,http:K,dir:u,url:i.authURL(),ref:t,singleBranch:!0,depth:1,onAuth:()=>i.credentials(),corsProxy:w})},"Failed to clone repository");else if(s)try{i=await i.create({name:l,private:!0}),await Y(d,u,t,c,r),await T.addRemote({fs:d,dir:u,remote:"origin",url:i.url()}),await E(t)}catch(w){console.error("Failed to create and push to remote repository:",w),await Y(d,u,t,c,r)}else await Y(d,u,t,c,r)}else await Y(d,u,t,c,r);return{async init(){return m.withLock("init",()=>c.init())},async create(l){let{name:y,version:w}=l.schema;return m.withLock(`schema:${y}`,async()=>{await $(t),await c.create(l);let b=await D(`feat: create schema ${y}`);b&&await f(`${y}-${w}`,`Version ${w}`,b),h.invalidate(y)})},async update(l){let{name:y,version:w}=l.schema;return m.withLock(`schema:${y}`,async()=>{await $(t),await c.update(l);let b=await D(`fix: update schema ${y}`);b&&await f(`${y}-${w}`,`Version ${w}`,b),h.invalidate(y)})},async delete(l){let{name:y}=l;return m.withLock(`schema:${y}`,async()=>{await $(t),await T.remove({fs:d,dir:u,filepath:y}),await c.delete(l);let w=await D(`chore: delete schema ${y}`),b=await v(`${y}-`);if(i&&w){await E(t);for(let k of b)await E(k,{delete:!0,force:!0}).catch(R=>console.warn(`Failed to delete remote tag ${k}: ${R.message}`))}await C(`${y}-`),h.invalidate(y)})},async list(){return m.withLock("list",()=>c.list())},async schema(l){let{name:y,version:w}=l,b=`${y}-${w||"latest"}-${l.migrations||!1}`,k=h.get(b);return k||m.withLock(`schema:${y}`,async()=>{if(w){let N=`${y}-${w}`;if(await p(N))await $(N);else throw new Error(`Version ${w} of schema ${y} not found`)}else await $(t);let R=await c.schema(l);return h.set(b,R),R})},async stats(l){return m.withLock("stats",()=>c.stats(l))},async sync(){return m.withLock("sync",async()=>{if(await $(t),await c.sync(),await D("chore: sync local changes"),i){await I(t,!1),await E(t);let l=await T.listTags({fs:d,dir:u});for(let w of l)await E(w,{force:!0});let y=await T.listTags({fs:d,dir:u});for(let w of y)l.includes(w)||await E(w,{delete:!0})}h.invalidate()})},async migrations(l){let{name:y,version:w}=l,b=`migrations-${y}-${w||"latest"}`,k=h.get(b);return k||m.withLock(`migrations:${y}`,async()=>{if(w){let N=`${y}-${w}`;if(await p(N))await $(N);else throw new Error(`Version ${w} of schema ${y} not found`)}else await $(t);let R=await c.migrations(l);return h.set(b,R),R})},async history(l){let{name:y}=l,w=`history-${y}`,b=h.get(w);return b||m.withLock(`history:${y}`,async()=>{await $(t);let k=await c.history(l);return h.set(w,k),k})}}}function fn(n,e=!0,t=!0){let i="",s=t?"export ":"",r=new Map,a=(u,m=[])=>{if(!e||!u&&!m.length)return"";let h=u?[u]:[];return m.forEach(g=>h.push(g)),`/**
2
- * ${h.join(`
1
+ import{createEventBus as zt}from"@asaidimu/events";import{createEventBus as Pt}from"@asaidimu/events";import{createMatcher as Mt,createPaginator as Ot,createProjector as jt,createSorter as Vt}from"@asaidimu/query";var F=class extends Error{constructor(t,i){super(t);this.operation=i;this.name="JsonPatchError"}};function Y(n){let e=qe(n);return e===""?[]:e.substring(1).split("/").map(Le)}function qe(n){return n===""||n==="/"?"":n.startsWith("/")?"/"+n.substring(1).split("/").map(W).join("/"):"/"+n.split(".").map(W).join("/")}function W(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}function Le(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}var O=new Map;function Q(n,e){let t=n;for(let i of e){if(t===null||typeof t!="object")throw new F(`Invalid path - parent not found at ${i}`);if(Array.isArray(t)){let r=i==="-"?t.length:parseInt(i);if(isNaN(r)||r<0||r>t.length)throw new F(`Invalid array index: ${i}`);t=t[r]}else{if(!t.hasOwnProperty(i))throw new F(`Property ${i} not found`);t=t[i]}}return t}function re(n,e){let t=O.get(e)||Y(e);if(O.set(e,t),t.length===0)return n;let i=Q(n,t.slice(0,-1)),r=t[t.length-1];if(Array.isArray(i)){let a=parseInt(r);if(isNaN(a)||a<0||a>=i.length)throw new F(`Invalid array index: ${r}`);return i[a]}return i[r]}function Ue(n,e,t){let i=O.get(e)||Y(e);O.set(e,i);let r=Q(n,i.slice(0,-1)),a=i[i.length-1];return Array.isArray(r)?r.splice(0,r.length,...r.filter(s=>s!==t)):r[a]===t&&delete r[a],n}function K(n,e,t){let i=O.get(e)||Y(e);if(O.set(e,i),i.length===0)return t;let r=i.slice(0,-1),a=i[i.length-1],s=Q(n,r);if(Array.isArray(s))if(a==="-")s.push(t);else{let o=parseInt(a);if(o<0||o>s.length)throw new F(`Invalid array index: ${a}`);s.splice(o,0,t)}else s[a]=t;return n}function ae(n,e){let t=O.get(e)||Y(e);if(O.set(e,t),t.length===0)return;let i=Q(n,t.slice(0,-1)),r=t[t.length-1];if(Array.isArray(i)){let a=parseInt(r);i.splice(a,1)}else delete i[r];return n}function oe(n,e){let t=JSON.parse(JSON.stringify(n));for(let i of e)try{switch(i.op){case"add":t=K(t,i.path,i.value);break;case"remove":t=ae(t,i.path);break;case"removeValue":t=Ue(t,i.path,i.value);break;case"replace":t=K(ae(t,i.path),i.path,i.value);break;case"copy":{let r=re(t,i.from);t=K(t,i.path,JSON.parse(JSON.stringify(r)));break}case"move":{let r=re(t,i.from);t=K(t,i.path,r),t=ae(t,i.from);break}case"test":{let r=re(t,i.path);if(JSON.stringify(r)!==JSON.stringify(i.value))throw new F("Test operation failed");break}default:throw new F(`Unsupported operation: ${i.op}`)}}catch(r){throw r instanceof F&&(r.operation=i),r}return t}function ut(n,e){let t=[];return ce(n,e,"",t),t}function ce(n,e,t,i){if(n!==e){if(typeof n!=typeof e||Array.isArray(n)!==Array.isArray(e)){i.push({op:"replace",path:t,value:e});return}typeof n=="object"&&n!==null?Array.isArray(n)?_e(n,e,t,i):Ge(n,e,t,i):n!==e&&i.push({op:"replace",path:t,value:e})}}function _e(n,e,t,i){let r=Math.max(n.length,e.length);for(let a=0;a<r;a++){let s=`${t}/${a}`;a>=n.length?i.push({op:"add",path:`${t}/-`,value:e[a]}):a>=e.length?i.push({op:"remove",path:s}):ce(n[a],e[a],s,i)}}function Ge(n,e,t,i){let r=new Set,a=Object.keys(n),s=Object.keys(e);for(let o of a){let c=W(o),d=t?`${t}/${c}`:`/${c}`;e.hasOwnProperty(o)?(ce(n[o],e[o],d,i),r.add(o)):i.push({op:"remove",path:d})}for(let o of s)if(!r.has(o)){let c=W(o),d=t?`${t}/${c}`:`/${c}`;i.push({op:"add",path:d,value:e[o]})}}function we(n,e){let t=[];switch(n.type){case"addField":t.push({op:"add",path:`/fields/${n.id}`,value:n.definition});break;case"removeField":t.push({op:"remove",path:`/fields/${n.id}`});break;case"modifyField":{let i=`/fields/${n.id}`;Object.entries(n.changes).forEach(([r,a])=>{typeof a=="object"&&a!==null&&!Array.isArray(a)?t.push({op:"replace",path:`${i}/${r}`,value:a}):t.push({op:"replace",path:`${i}/${r}`,value:a})});break}case"deprecateField":t.push({op:"add",path:`/fields/${n.id}/deprecated`,value:!0});break;case"addIndex":e.indexes||t.push({op:"add",path:"/indexes",value:[]}),t.push({op:"add",path:"/indexes/-",value:n.definition});break;case"removeIndex":{let i=e.indexes?.findIndex(r=>r.name===n.name);i!==void 0&&i>=0&&t.push({op:"remove",path:`/indexes/${i}`});break}case"modifyIndex":{let i=e.indexes?.findIndex(r=>r.name===n.name);i!==void 0&&i>=0&&Object.entries(n.changes).forEach(([r,a])=>{t.push({op:"replace",path:`/indexes/${i}/${r}`,value:a})});break}case"addConstraint":e.constraints||t.push({op:"add",path:"/constraints",value:[]}),Array.isArray(n.constraint)?n.constraint.forEach(i=>{t.push({op:"add",path:"/constraints/-",value:i})}):t.push({op:"add",path:"/constraints/-",value:n.constraint});break;case"removeConstraint":{let i=e.constraints?.findIndex(r=>Array.isArray(r)?r.some(a=>a.name===n.name):r.name===n.name);i!==void 0&&i>=0&&t.push({op:"remove",path:`/constraints/${i}`});break}case"modifyConstraint":{let i=Je(e,n.name);i&&Object.entries(n.changes).forEach(([r,a])=>{t.push({op:"replace",path:`${i}/${r}`,value:a})});break}}return t}function Je(n,e){if(!n.constraints)return null;for(let t=0;t<n.constraints.length;t++){let i=n.constraints[t];if(i.name===e)return`/constraints/${t}`;if(Se(i)){let r=be(i.rules,e);if(r)return`/constraints/${t}${r}`}}return null}function Se(n){return n&&"operator"in n&&"rules"in n}function be(n,e){for(let t=0;t<n.length;t++){let i=n[t];if("name"in i&&i.name===e)return`/rules/${t}`;if(Se(i)){let r=be(i.rules,e);if(r)return`/rules/${t}${r}`}}return null}function ve(n,e){let t={...n};return de(n)&&de(e)&&Object.keys(e).forEach(i=>{de(e[i])?i in n?t[i]=ve(n[i],e[i]):Object.assign(t,{[i]:e[i]}):Object.assign(t,{[i]:e[i]})}),t}function de(n){return n&&typeof n=="object"&&!Array.isArray(n)}function Z(n){return n instanceof RegExp?n.toString().slice(1,-1):JSON.stringify(n)}function He(n,e){let t=o=>({value:o}),i=o=>({issues:o}),r=(o,c,d,l)=>{switch(c){case"string":return typeof o!="string"?[{message:`Expected string, got ${typeof o}`,path:d}]:[];case"number":return typeof o!="number"||isNaN(o)?[{message:`Expected number, got ${typeof o}`,path:d}]:[];case"boolean":return typeof o!="boolean"?[{message:`Expected boolean, got ${typeof o}`,path:d}]:[];case"array":return Array.isArray(o)?[]:[{message:`Expected array, got ${typeof o}`,path:d}];case"set":return!Array.isArray(o)||new Set(o).size!==o.length?[{message:`Expected unique array, got ${typeof o}`,path:d}]:[];case"enum":return l?.values?l.values.includes(o)?[]:[{message:`Expected one of ${JSON.stringify(l.values)}, got ${o}`,path:d}]:[{message:"Enum type requires 'values' definition",path:d}];case"object":return typeof o!="object"||o===null||Array.isArray(o)?[{message:`Expected object, got ${typeof o}`,path:d}]:[];case"record":return typeof o!="object"||o===null?[{message:`Expected record (object), got ${typeof o}`,path:d}]:[];case"union":return typeof o!="object"||o===null?[{message:`Expected union (object), got ${typeof o}`,path:d}]:[];case"dynamic":return[];default:return[{message:`Unknown type '${c}'`,path:d}]}};function a(o,c,d,l,x){let w=[],P=o.rules.map((m,T)=>{let v=[...l,`rules[${T}]`];if("rules"in m){if(x.has(m.name))return!0;x.add(m.name);let p=a(m,c,d,v,x);return w.push(...p),p.length===0}else{let p=d[m.predicate];if(!p)return w.push({message:`Predicate '${m.predicate}' not found`,path:v}),!1;let g=p({data:c,field:m.field,arguments:m.parameters});if(!g){let S=m.field?` for field '${m.field}'`:"";w.push({message:m.errorMessage||`Constraint '${m.name}' failed${S} with params ${Z(m.parameters)}`,path:v})}return g}});return(()=>{switch(o.operator){case"and":return P.every(m=>m);case"or":return P.some(m=>m);case"not":return!P.every(m=>m);case"nor":return!P.some(m=>m);case"xor":return P.filter(m=>m).length===1}})()||w.push({message:`Constraint group '${o.name}' failed`,path:l}),w}function s(o,c,d,l,x,w=new Set,P){let y=[],m={};if("concrete"in c)if(c.concrete===!0||!Array.isArray(c.fields))m=c.fields;else{let v=c.fields,p=v.find(S=>!S.when);p&&Object.assign(m,p.fields);let g=v.find(S=>S.when&&o[S.when.field]!==void 0&&o[S.when.field]===S.when.value);if(g)Object.assign(m,g.fields);else if(!p)return y.push({message:"No matching field set found for discriminated schema",path:l}),y}else m=c.fields;let T=new Set(Object.values(m).map(v=>v.name));Object.entries(m).forEach(([v,p])=>{let g=[...l,p.name],S=Object.hasOwnProperty.call(o,p.name)?o[p.name]:void 0;if(p.required&&S==null){y.push({message:`Field '${p.name}' is required`,path:g});return}if(S!==void 0){if(y.push(...r(S,p.type,g,p)),p.type==="array"||p.type==="set"){p.itemsType&&Array.isArray(S)&&S.forEach((u,f)=>y.push(...r(u,p.itemsType,[...g,f.toString()])));let $=p.schema||p.nestedSchema;if($&&!Array.isArray($)){let u=x[$.id];u?S.forEach((f,h)=>{typeof f=="object"&&f!==null&&(w.has($.id)?y.push({message:`Circular reference detected at '${$.id}'`,path:[...g,h.toString()]}):(w.add($.id),y.push(...s(f,u,d,[...g,h.toString()],x,w,o)),w.delete($.id)))}):y.push({message:`Nested schema '${$.id}' not found`,path:g})}}if(p.type==="object"){let $=p.schema||p.nestedSchema;if($&&!Array.isArray($)){let u=x[$.id];u?typeof S=="object"&&S!==null&&(w.has($.id)?y.push({message:`Circular reference detected at '${$.id}'`,path:g}):(w.add($.id),y.push(...s(S,u,d,g,x,w,o)),$.constraints?.forEach((f,h)=>{if("rules"in f)y.push(...a(f,S,d,[...g,`constraints[${h}]`],w));else{let b=d[f.predicate];b?b({data:S,field:void 0,arguments:f.parameters})||y.push({message:f.errorMessage||`Constraint '${f.name}' failed with params ${Z(f.parameters)}`,path:[...g,`constraints[${h}]`]}):y.push({message:`Predicate '${f.predicate}' not found`,path:[...g,`constraints[${h}]`]})}}),w.delete($.id))):y.push({message:`Nested schema '${$.id}' not found`,path:g})}}if(p.type==="union"){let $=p.schema;!$||!Array.isArray($)?y.push({message:"Union type requires an array of schema references",path:g}):$.some(f=>{let h=x[f.id];return h?s(S,h,d,g,x,new Set(w),o).length===0:(y.push({message:`Nested schema '${f.id}' not found`,path:g}),!1)})||y.push({message:"Value does not match any union schema",path:g})}p.constraints?.forEach(($,u)=>{if("rules"in $)y.push(...a($,o,d,[...g,`constraints[${u}]`],w));else{let f=d[$.predicate];f?f({data:o,field:p.name,arguments:$.parameters})||y.push({message:$.errorMessage||`Constraint '${$.name}' failed for field '${p.name}' with params ${Z($.parameters)}`,path:[...g,`constraints[${u}]`]}):y.push({message:`Predicate '${$.predicate}' not found`,path:[...g,`constraints[${u}]`]})}})}});for(let v in o)Object.hasOwnProperty.call(o,v)&&!T.has(v)&&y.push({message:`Unexpected field '${v}'`,path:[...l,v]});return c.constraints?.forEach((v,p)=>{if("rules"in v)y.push(...a(v,o,d,[...l,`constraints[${p}]`],w));else{let g=d[v.predicate];if(!g)y.push({message:`Predicate '${v.predicate}' not found`,path:[...l,`constraints[${p}]`]});else if(!g({data:o,field:v.field,arguments:v.parameters})){let $=v.field?` for field '${v.field}'`:"";y.push({message:v.errorMessage||`Constraint '${v.name}' failed${$} with params ${Z(v.parameters)}`,path:[...l,`constraints[${p}]`]})}}}),y}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,d=s(c,n,e,[],n.nestedSchemas||{});return d.length>0?i(d):t(c)},types:{input:{},output:{}}}}}function mt(n){return async e=>{let t=n.validate(e);if(t instanceof Promise&&(t=await t),"value"in t)return{values:t.value,errors:{}};let i={};return t.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 U=class extends Error{constructor(t,i){super(t);this.errors=i;this.name="SchemaValidationError"}};var fe=n=>({value:n}),_=n=>({issues:n}),E=(n,e,t=!0)=>n===void 0&&!t?[]:typeof n!="string"||n.trim()===""?[{message:"Must be a non-empty string",path:[e]}]:[],Ee=(n,e)=>{let t=["string","number","boolean","array","set","enum","object","record","union","dynamic"];return typeof n!="string"||!t.includes(n)?[{message:`Must be one of ${t.join(", ")}`,path:[e]}]:[]},ze=(n,e)=>{let t=["normal","unique","btree","hash","spatial","fulltext","gi","expression","composite"];return typeof n!="string"||!t.includes(n)?[{message:`Must be one of ${t.join(", ")}`,path:[e]}]:[]},xe=(n,e)=>{let t=["and","or","not","nor","xor"];return typeof n!="string"||!t.includes(n)?[{message:`Must be one of ${t.join(", ")}`,path:[e]}]:[]},z=(n,e,t=!1)=>n===void 0&&!t?[]:typeof n!="boolean"?[{message:"Must be a boolean",path:[e]}]:[],Be=(n,e,t)=>{if(n===void 0)return[];switch(e){case"string":if(typeof n=="string"||Array.isArray(n)&&n.every(i=>typeof i=="string")||n instanceof RegExp||typeof n=="object"&&n!==null&&"field"in n&&typeof n.field=="string")return[];break;case"number":if(typeof n=="number"||Array.isArray(n)&&n.every(i=>typeof i=="number")||typeof n=="object"&&n!==null&&"precision"in n&&typeof n.precision=="number")return[];break;case"boolean":if(typeof n=="boolean")return[];break;case"array":case"set":if(typeof n=="number"||typeof n=="object"&&n!==null&&"minItems"in n&&typeof n.minItems=="number")return[];break;case"enum":if(Array.isArray(n)&&n.length>0&&n.every(i=>typeof i=="string"||typeof i=="number"))return[];break;case"object":case"record":if(typeof n=="object"&&n!==null&&"schema"in n)return[];break;case"union":if(typeof n=="object"&&n!==null&&"schema"in n)return[];break;case"dynamic":return[]}return[{message:`Invalid parameters for type '${e}'`,path:[t]}]},le=(n,e)=>{let t=[],i=["predicate","name"],r=["type","predicate","field","parameters","name","description","errorMessage"],a=n;return i.forEach(s=>{a[s]===void 0&&t.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||t.push({message:"Unknown property",path:[`${e}.${s}`]})}),t.push(...E(n.name,`${e}.name`)),t.push(...E(n.predicate,`${e}.predicate`)),n.type!==void 0&&n.type!=="schema"&&t.push({message:"Type must be 'schema' if present",path:[`${e}.type`]}),n.field!==void 0&&typeof n.field!="string"&&t.push({message:"Field must be a string",path:[`${e}.field`]}),n.parameters!==void 0&&(!n.type||n.type!=="schema")&&t.push(...Be(n.parameters,"dynamic",`${e}.parameters`)),t.push(...E(n.description,`${e}.description`,!1)),t.push(...E(n.errorMessage,`${e}.errorMessage`,!1)),t},me=(n,e)=>{let t=[],i=["name","operator","rules"],r=["name","operator","rules"],a=n;return i.forEach(s=>{a[s]===void 0&&t.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||t.push({message:"Unknown property",path:[`${e}.${s}`]})}),t.push(...E(n.name,`${e}.name`)),t.push(...xe(n.operator,`${e}.operator`)),!Array.isArray(n.rules)||n.rules.length===0?t.push({message:"Rules must be a non-empty array",path:[`${e}.rules`]}):n.rules.forEach((s,o)=>{"rules"in s?t.push(...me(s,`${e}.rules[${o}]`)):t.push(...le(s,`${e}.rules[${o}]`))}),t},q=(n,e)=>{if(!Array.isArray(n))return[{message:"Must be an array",path:[e]}];let t=[];return n.forEach((i,r)=>{"rules"in i?t.push(...me(i,`${e}[${r}]`)):t.push(...le(i,`${e}[${r}]`))}),t},Te=(n,e)=>{let t=[],i=["operator","field"],r=["operator","field","value","conditions"],a=n;return i.forEach(s=>{a[s]===void 0&&t.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||t.push({message:"Unknown property",path:[`${e}.${s}`]})}),t.push(...xe(n.operator,`${e}.operator`)),t.push(...E(n.field,`${e}.field`)),n.conditions!==void 0&&(Array.isArray(n.conditions)?n.conditions.forEach((s,o)=>t.push(...Te(s,`${e}.conditions[${o}]`))):t.push({message:"Conditions must be an array",path:[`${e}.conditions`]})),t},Ce=(n,e)=>{let t=[],i=["fields","type","name"],r=["fields","type","unique","partial","description","order","name"],a=n;return i.forEach(s=>{a[s]===void 0&&t.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||t.push({message:"Unknown property",path:[`${e}.${s}`]})}),t.push(...E(n.name,`${e}.name`)),t.push(...ze(n.type,`${e}.type`)),(!Array.isArray(n.fields)||n.fields.length===0||!n.fields.every(s=>typeof s=="string"))&&t.push({message:"Fields must be a non-empty array of strings",path:[`${e}.fields`]}),t.push(...z(n.unique,`${e}.unique`,!1)),n.partial&&t.push(...Te(n.partial,`${e}.partial`)),t.push(...E(n.description,`${e}.description`,!1)),n.order!==void 0&&!["asc","desc"].includes(n.order)&&t.push({message:"Order must be 'asc' or 'desc'",path:[`${e}.order`]}),t},G=(n,e)=>{if(!Array.isArray(n))return[{message:"Must be an array",path:[e]}];let t=[];return n.forEach((i,r)=>t.push(...Ce(i,`${e}[${r}]`))),t},Ke=(n,e,t,i,r)=>{let a=[];return n===void 0?[]:(t==="union"&&Array.isArray(n)?(n.length===0&&a.push({message:"Schema array must not be empty for union type",path:[e]}),n.forEach((s,o)=>{let c=`${e}[${o}]`;a.push(...E(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(...G(s.indexes,`${c}.indexes`))})):(t==="object"||t==="array"&&r==="object")&&!Array.isArray(n)?(a.push(...E(n.id,`${e}.id`)),i.includes(n.id)||a.push({message:`Schema ID '${n.id}' must match a nestedSchemas key`,path:[`${e}.id`]}),n.constraints&&a.push(...q(n.constraints,`${e}.constraints`)),n.indexes&&a.push(...G(n.indexes,`${e}.indexes`))):a.push({message:"Schema is only valid for 'object', 'union', or 'array' with itemsType 'object'",path:[e]}),a)},X=(n,e,t)=>{let i=[],r=["name","type"],a=["name","type","required","constraints","default","values","schema","itemsType","nestedSchema","deprecated","reference","description","unique"],s=n;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(...E(n.name,`${e}.name`)),i.push(...Ee(n.type,`${e}.type`)),i.push(...z(n.required,`${e}.required`,!1)),n.constraints&&i.push(...q(n.constraints,`${e}.constraints`)),n.values!==void 0&&(n.type==="enum"?(!Array.isArray(n.values)||n.values.length===0||!n.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`]})),n.schema!==void 0&&i.push(...Ke(n.schema,`${e}.schema`,n.type,t,n.itemsType)),n.itemsType&&i.push(...Ee(n.itemsType,`${e}.itemsType`)),n.nestedSchema){let o=["id"],c=["id","constraints","indexes"],d=n.nestedSchema;o.forEach(l=>{d[l]===void 0&&i.push({message:`${l} is required`,path:[`${e}.nestedSchema.${l}`]})}),Object.keys(d).forEach(l=>{c.includes(l)||i.push({message:"Unknown property",path:[`${e}.nestedSchema.${l}`]})}),i.push(...E(n.nestedSchema.id,`${e}.nestedSchema.id`)),t.includes(n.nestedSchema.id)||i.push({message:`nestedSchema.id '${n.nestedSchema.id}' must match a nestedSchemas key`,path:[`${e}.nestedSchema.id`]}),n.nestedSchema.constraints&&i.push(...q(n.nestedSchema.constraints,`${e}.nestedSchema.constraints`)),n.nestedSchema.indexes&&i.push(...G(n.nestedSchema.indexes,`${e}.nestedSchema.indexes`))}if(i.push(...z(n.deprecated,`${e}.deprecated`,!1)),n.reference){let o=["schema","field"],c=["schema","field"],d=n.reference;o.forEach(l=>{d[l]===void 0&&i.push({message:`${l} is required`,path:[`${e}.reference.${l}`]})}),Object.keys(d).forEach(l=>{c.includes(l)||i.push({message:"Unknown property",path:[`${e}.reference.${l}`]})}),i.push(...E(n.reference.schema,`${e}.reference.schema`)),i.push(...E(n.reference.field,`${e}.reference.field`))}return i.push(...E(n.description,`${e}.description`,!1)),i.push(...z(n.unique,`${e}.unique`,!1)),i},ke=(n,e,t)=>{let i=[],r=["name","fields"],a=["name","description","concrete","fields","indexes","constraints","metadata"],s=n;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(...E(n.name,`${e}.name`)),i.push(...z(n.concrete,`${e}.concrete`,!1)),Array.isArray(n.fields)?(n.fields.length===0&&i.push({message:"Fields array must not be empty",path:[`${e}.fields`]}),n.fields.forEach((o,c)=>{let d=`${e}.fields[${c}]`;if(typeof o!="object"||o===null||!("fields"in o))i.push({message:"Each variant must have a 'fields' property",path:[d]});else{let l=o.fields;typeof l!="object"||l===null?i.push({message:"Fields must be a non-empty object",path:[`${d}.fields`]}):Object.entries(l).forEach(([x,w])=>{i.push(...X(w,`${d}.fields.${x}`,t))}),o.when!==void 0&&(typeof o.when!="object"||o.when===null)&&i.push({message:"When must be an object",path:[`${d}.when`]})}})):typeof n.fields=="object"&&n.fields!==null?Object.entries(n.fields).forEach(([o,c])=>{i.push(...X(c,`${e}.fields.${o}`,t))}):i.push({message:"Fields must be a non-empty object or array",path:[`${e}.fields`]}),i.push(...E(n.description,`${e}.description`,!1)),n.indexes&&i.push(...G(n.indexes,`${e}.indexes`)),n.constraints&&i.push(...q(n.constraints,`${e}.constraints`)),n.metadata!==void 0&&(typeof n.metadata!="object"||n.metadata===null)&&i.push({message:"Metadata must be an object",path:[`${e}.metadata`]}),i},We=n=>{if(typeof n!="object"||n===null)return _([{message:"Schema must be an object",path:[]}]);let e=n,t=[],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&&t.push({message:`${s} is required`,path:[s]})}),Object.keys(a).forEach(s=>{r.includes(s)||t.push({message:"Unknown property",path:[s]})}),t.push(...E(e.name,"name")),t.push(...E(e.version,"version")),typeof e.fields!="object"||e.fields===null)t.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])=>{t.push(...X(c,`fields.${o}`,s))})}if(typeof e.nestedSchemas!="object"||e.nestedSchemas===null)t.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])=>t.push(...ke(c,`nestedSchemas.${o}`,s)))}return t.push(...E(e.description,"description",!1)),e.indexes&&t.push(...G(e.indexes,"indexes")),e.constraints&&t.push(...q(e.constraints,"constraints")),e.metadata!==void 0&&(typeof e.metadata!="object"||e.metadata===null)&&t.push({message:"Metadata must be an object",path:["metadata"]}),e.dependencies!==void 0&&(!Array.isArray(e.dependencies)||!e.dependencies.every(s=>typeof s=="string"))&&t.push({message:"Dependencies must be an array of strings",path:["dependencies"]}),e.migrations!==void 0&&(Array.isArray(e.migrations)?e.migrations.forEach((s,o)=>t.push(...De(s,`migrations[${o}]`))):t.push({message:"Migrations must be an array",path:["migrations"]})),e.mock!==void 0&&typeof e.mock!="function"&&t.push({message:"Mock must be a function",path:["mock"]}),t.length>0?_(t):fe(e)},ue=(n,e)=>{let t=[];switch(n.type||t.push({message:"type is required",path:[`${e}.type`]}),n.type){case"modifyProperty":{let i=["type","id","changes"],r=i,a=n;i.forEach(s=>{a[s]===void 0&&t.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||t.push({message:"Unknown property",path:[`${e}.${s}`]})}),t.push(...E(n.id,`${e}.id`)),(n.changes===void 0||typeof n.changes!="object")&&t.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addField":{let i=["type","id","definition"],r=i,a=n;i.forEach(s=>{a[s]===void 0&&t.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||t.push({message:"Unknown property",path:[`${e}.${s}`]})}),t.push(...E(n.id,`${e}.id`)),t.push(...X(n.definition,`${e}.definition`,[]));break}case"removeField":case"deprecateField":{let i=["type","id"],r=i,a=n;i.forEach(s=>{a[s]===void 0&&t.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||t.push({message:"Unknown property",path:[`${e}.${s}`]})}),t.push(...E(n.id,`${e}.id`));break}case"modifyField":{let i=["type","id","changes"],r=["type","id","changes","nestedSchemaChanges"],a=n;if(i.forEach(s=>{a[s]===void 0&&t.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||t.push({message:"Unknown property",path:[`${e}.${s}`]})}),t.push(...E(n.id,`${e}.id`)),typeof n.changes!="object"&&t.push({message:"Changes must be an object",path:[`${e}.changes`]}),n.nestedSchemaChanges){let s=["id","constraints","indexes"],o=n.nestedSchemaChanges;Object.keys(o).forEach(c=>{s.includes(c)||t.push({message:"Unknown property",path:[`${e}.nestedSchemaChanges.${c}`]})}),t.push(...E(o.id,`${e}.nestedSchemaChanges.id`,!1)),o.constraints&&t.push(...q(o.constraints,`${e}.nestedSchemaChanges.constraints`)),o.indexes&&t.push(...G(o.indexes,`${e}.nestedSchemaChanges.indexes`))}break}case"addIndex":{let i=["type","definition"],r=i,a=n;i.forEach(s=>{a[s]===void 0&&t.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||t.push({message:"Unknown property",path:[`${e}.${s}`]})}),t.push(...Ce(n.definition,`${e}.definition`));break}case"removeIndex":{let i=["type","name"],r=i,a=n;i.forEach(s=>{a[s]===void 0&&t.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||t.push({message:"Unknown property",path:[`${e}.${s}`]})}),t.push(...E(n.name,`${e}.name`));break}case"modifyIndex":{let i=["type","name","changes"],r=i,a=n;i.forEach(s=>{a[s]===void 0&&t.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||t.push({message:"Unknown property",path:[`${e}.${s}`]})}),t.push(...E(n.name,`${e}.name`)),typeof n.changes!="object"&&t.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addConstraint":{let i=["type","constraint"],r=i,a=n;i.forEach(s=>{a[s]===void 0&&t.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||t.push({message:"Unknown property",path:[`${e}.${s}`]})}),"rules"in n.constraint?t.push(...me(n.constraint,`${e}.constraint`)):t.push(...le(n.constraint,`${e}.constraint`));break}case"removeConstraint":{let i=["type","name"],r=i,a=n;i.forEach(s=>{a[s]===void 0&&t.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||t.push({message:"Unknown property",path:[`${e}.${s}`]})}),t.push(...E(n.name,`${e}.name`));break}case"modifyConstraint":{let i=["type","name","changes"],r=i,a=n;i.forEach(s=>{a[s]===void 0&&t.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||t.push({message:"Unknown property",path:[`${e}.${s}`]})}),t.push(...E(n.name,`${e}.name`)),typeof n.changes!="object"&&t.push({message:"Changes must be an object",path:[`${e}.changes`]});break}case"addNestedSchema":{let i=["type","id","definition"],r=i,a=n;i.forEach(s=>{a[s]===void 0&&t.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||t.push({message:"Unknown property",path:[`${e}.${s}`]})}),t.push(...E(n.id,`${e}.id`)),t.push(...ke(n.definition,`${e}.definition`,[]));break}case"removeNestedSchema":{let i=["type","id"],r=i,a=n;i.forEach(s=>{a[s]===void 0&&t.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||t.push({message:"Unknown property",path:[`${e}.${s}`]})}),t.push(...E(n.id,`${e}.id`));break}case"modifyNestedSchema":{let i=["type","id","changes"],r=i,a=n;i.forEach(s=>{a[s]===void 0&&t.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||t.push({message:"Unknown property",path:[`${e}.${s}`]})}),t.push(...E(n.id,`${e}.id`)),typeof n.changes!="object"&&t.push({message:"Changes must be an object",path:[`${e}.changes`]});break}default:t.push({message:"Unknown schema change type",path:[`${e}.type`]})}return t},Ye=(n,e)=>{let t=[],i=["forward","backward"],r=i,a=n;return i.forEach(s=>{a[s]===void 0&&t.push({message:`${s} is required`,path:[`${e}.${s}`]})}),Object.keys(a).forEach(s=>{r.includes(s)||t.push({message:"Unknown property",path:[`${e}.${s}`]})}),typeof n.forward!="function"&&t.push({message:"Forward must be a function",path:[`${e}.forward`]}),typeof n.backward!="function"&&t.push({message:"Backward must be a function",path:[`${e}.backward`]}),t},De=(n,e)=>{let t=[],i=["id","schemaVersion","changes","description","status","transform","createdAt","checksum"],r=[...i,"rollback","dependencies"],a=n;i.forEach(o=>{a[o]===void 0&&t.push({message:`${o} is required`,path:[`${e}.${o}`]})}),Object.keys(a).forEach(o=>{r.includes(o)||t.push({message:"Unknown property",path:[`${e}.${o}`]})}),t.push(...E(n.id,`${e}.id`)),t.push(...E(n.schemaVersion,`${e}.schemaVersion`)),t.push(...E(n.description,`${e}.description`));let s=["pending","applied","failed"];return s.includes(n.status)||t.push({message:`Status must be one of ${s.join(", ")}`,path:[`${e}.status`]}),!Array.isArray(n.changes)||n.changes.length===0?t.push({message:"Changes must be a non-empty array",path:[`${e}.changes`]}):n.changes.forEach((o,c)=>t.push(...ue(o,`${e}.changes[${c}]`))),n.rollback!==void 0&&(Array.isArray(n.rollback)?n.rollback.forEach((o,c)=>t.push(...ue(o,`${e}.rollback[${c}]`))):t.push({message:"Rollback must be an array",path:[`${e}.rollback`]})),typeof n.transform=="string"?t.push(...E(n.transform,`${e}.transform`)):typeof n.transform=="object"&&n.transform!==null?t.push(...Ye(n.transform,`${e}.transform`)):t.push({message:"Transform must be a string or object",path:[`${e}.transform`]}),t.push(...E(n.createdAt,`${e}.createdAt`)),n.dependencies!==void 0&&(!Array.isArray(n.dependencies)||!n.dependencies.every(o=>typeof o=="string"))&&t.push({message:"Dependencies must be an array of strings",path:[`${e}.dependencies`]}),t.push(...E(n.checksum,`${e}.checksum`)),t},Re={"~standard":{version:1,vendor:"@asaidimu/anansi",validate:We,types:{input:{},output:{}}}};var Ae={"~standard":{version:1,vendor:"@asaidimu/anansi",validate:n=>{if(typeof n!="object"||n===null)return _([{message:"Migration must be an object",path:[]}]);let e=n,t=De(e,"");return t.length>0?_(t):fe(e)},types:{input:{},output:{}}}},Ie={"~standard":{version:1,vendor:"@asaidimu/anansi",validate:n=>{if(!Array.isArray(n))return _([{message:"SchemaChanges must be an array",path:[]}]);let e=n,t=[];return e.forEach((i,r)=>t.push(...ue(i,`[${r}]`))),t.length>0?_(t):fe(e)},types:{input:[],output:[]}}};function Pe(n){try{return!Ae["~standard"].validate(n).issues}catch(e){throw new U("Invalid migration definition",e instanceof Error?e:new Error(String(e)))}}function Fe(n){try{return!Ie["~standard"].validate(n).issues}catch(e){throw new U("Invalid schema change definition",e instanceof Error?e:new Error(String(e)))}}function B(n){try{return!Re["~standard"].validate(n).issues}catch(e){throw new U("Invalid schema definition",e instanceof Error?e:new Error(String(e)))}}var wt=B;var J=async n=>{if(typeof window<"u"&&crypto.subtle){let t=new TextEncoder().encode(n),i=await crypto.subtle.digest("SHA-256",t);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(n).digest("hex")}};function Qe(n){let e=n.match(/^(\d+)\.(\d+)\.(\d+)$/);if(!e)throw new Error(`Invalid version format: ${n}. Expected format: major.minor.patch`);return{major:parseInt(e[1],10),minor:parseInt(e[2],10),patch:parseInt(e[3],10)}}function Ze(n,e){if(e&&"field"in n&&n.field){let t=e.fields[n.field];if(t)return t.type}if("parameters"in n){let t=n.parameters;if(t instanceof RegExp||Array.isArray(t)&&typeof t[0]=="string")return"string";if(typeof t=="number"||Array.isArray(t)&&typeof t[0]=="number")return"number";if(typeof t=="boolean")return"boolean";if(typeof t=="object"&&t!==null){if("minItems"in t||"maxItems"in t)return"array";if("schema"in t)return"object"}}}function Xe(n){return n.required===!0||n.type!==void 0||n.itemsType!==void 0||n.nestedSchema!==void 0||n.reference!==void 0||n.unique===!0}function et(n,e,t){switch(t){case"string":if(n instanceof RegExp&&e instanceof RegExp)return n.source!==e.source;if(Array.isArray(n)&&Array.isArray(e))return e.length<n.length||!n.every(i=>e.includes(i));break;case"number":if(typeof n=="object"&&typeof e=="object"&&"precision"in n&&"precision"in e)return e.precision<n.precision||(e.scale??0)<(n.scale??0);if(Array.isArray(n)&&Array.isArray(e))return e.length<n.length||!n.every(i=>e.includes(i));break;case"array":if(typeof n=="object"&&typeof e=="object"&&"minItems"in n&&"maxItems"in n&&"minItems"in e&&"maxItems"in e)return e.minItems>n.minItems||e.maxItems<n.maxItems;break;case"object":if(typeof n=="object"&&typeof e=="object"&&"schema"in n&&"schema"in e)return Object.keys(e.schema).length>Object.keys(n.schema).length;break}return!1}function tt(n,e){let t={or:1,xor:2,and:3,not:4,nor:4};return!!(e.operator&&t[e.operator]>t[n.operator]||e.rules&&e.rules.length>n.rules.length)}function nt(n,e,t){if(!e)return!0;if("rules"in e&&"rules"in n)return tt(e,n);if("predicate"in n&&n.predicate!==void 0)return!0;if("parameters"in n&&n.parameters!==void 0){let i=Ze(e,t);return i?et(e.parameters,n.parameters,i):!0}return!1}function it(n,e){switch(n.type){case"removeField":case"removeIndex":return"major";case"modifyField":return Xe(n.changes)?"major":n.changes.deprecated?"minor":"patch";case"modifyIndex":return n.changes.unique!==void 0||n.changes.fields!==void 0?"major":"minor";case"addConstraint":return"major";case"removeConstraint":return"minor";case"modifyConstraint":let t=e?.constraints?.find(i=>"name"in i&&i.name===n.name);return nt(n.changes,t,e)?"major":"minor";case"addField":case"addIndex":case"deprecateField":return"minor";default:throw new Error(`Unhandled change type: ${JSON.stringify(n)}`)}}function st(n){let e=new Set,t=new Set,i=new Set,r=new Set;for(let a of n)switch(a.type){case"addField":if(t.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}`);t.add(a.id);break;case"modifyField":if(t.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(t.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 rt(n){let e=new Set,t=new Set,i=new Set;for(let r of n)switch(r.type){case"addConstraint":let a=r.constraint,s=("name"in a,a.name);if(t.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}`);t.add(r.name);break;case"modifyConstraint":if(t.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 Me(n,e,t){if(e.length===0)throw new Error("No changes provided");st(e),rt(e);let i=Qe(n),r="patch";for(let a of e){let s=it(a,t);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 j(n,e){let t=d=>d.split(".").map(l=>parseInt(l,10)||0),[i,r,a]=t(n),[s,o,c]=t(e);return i-s||r-o||a-c}function vt(n){return n.sort(j)}var k=class extends Error{constructor(t,i,r,a){super(t);this.code=i;this.migrationId=r;this.cause=a;this.name="MigrationError"}},at=(w=>(w.INVALID_SCHEMA="INVALID_SCHEMA",w.INVALID_MIGRATION="INVALID_MIGRATION",w.CHECKSUM_MISMATCH="CHECKSUM_MISMATCH",w.TIMEOUT="TIMEOUT",w.MEMORY_LIMIT="MEMORY_LIMIT",w.CONCURRENT_OPERATION="CONCURRENT_OPERATION",w.TRANSFORM_ERROR="TRANSFORM_ERROR",w.VERSION_NOT_FOUND="VERSION_NOT_FOUND",w.CIRCULAR_DEPENDENCY="CIRCULAR_DEPENDENCY",w.STREAM_ERROR="STREAM_ERROR",w.ROLLBACK_ERROR="ROLLBACK_ERROR",w.MISSING_TRANSFORM="MISSING_TRANSFORM",w))(at||{}),Oe=class n{currentSchema;history=[];migrations=[];isProcessing=!1;constructor(e,t,i){try{if(!B(e))throw new k("Invalid initial schema","INVALID_SCHEMA");if(this.currentSchema=e,t){if(!t.every(r=>Pe(r)))throw new k("Invalid migration configuration","INVALID_MIGRATION");this.migrations=t.sort((r,a)=>j(r.schemaVersion,a.schemaVersion))}i&&(this.history=i.sort((r,a)=>j(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 t=JSON.stringify({id:e.id,schemaVersion:e.schemaVersion,changes:e.changes,description:e.description,rollback:e.rollback,createdAt:e.createdAt});return await J(t)}catch(t){throw new k("Checksum generation failed","CHECKSUM_MISMATCH",e.id,t)}}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=>Fe(i))}catch(i){throw new k("Invalid schema changes","INVALID_MIGRATION",void 0,i)}let t={id:Date.now().toString(),schemaVersion:this.currentSchema.version,changes:e.changes,description:e.description,status:"pending",rollback:e.rollback,transform:e.transform,createdAt:new Date().toISOString(),checksum:""};t.checksum=await this.generateChecksum(t),this.migrations.push(t)}async dryRun(e,t,i){if(this.isProcessing)throw new k("Concurrent operation","CONCURRENT_OPERATION");try{this.isProcessing=!0;let r={...this.currentSchema},a=this.getRelevantMigrations(t,i),s=a.reduce((c,d)=>{let l=t==="forward"?d.changes:d.rollback||[];return this.applySchemaChanges(c,l,d.id)},r),o=await n.processMigrationList(e,t,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,t){return[...this.migrations].filter(i=>{let r=e==="forward"?"pending":"applied",a=t?j(i.schemaVersion,t)>=0:!0;return i.status===r&&a}).sort((i,r)=>e==="forward"?i.id.localeCompare(r.id):r.id.localeCompare(i.id))}applySchemaChanges(e,t,i){try{let r=Me(e.version,t);return t.map(s=>{try{return we(s,e)}catch(o){throw new k("Invalid schema change","INVALID_SCHEMA",i,o)}}).reduce((s,o)=>{try{return oe(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(t=>t.status==="pending");return await this.validateMigrations(e),e}async migrate(e){if(this.isProcessing)throw new k("Concurrent operation","CONCURRENT_OPERATION");let t=await this.prepareMigration();try{this.isProcessing=!0,this.transformSchema("forward");let i=await n.processMigrationList(e,"forward",t);return this.markMigrationsApplied(t),i}finally{this.isProcessing=!1}}async validateMigrations(e){await Promise.all(e.map(async t=>{let i=await this.generateChecksum(t);if(t.checksum!==i)throw new k("Checksum mismatch","CHECKSUM_MISMATCH",t.id)}))}markMigrationsApplied(e){this.migrations=this.migrations.map(t=>e.some(i=>i.id===t.id)?{...t,status:"applied"}:t)}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,t){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 t;for(let o=0;o<a;o++)this.transformSchema("backward");let s=await n.processMigrationList(t,"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,t,i){return(await Promise.all(i.map(async s=>{try{let o=await this.resolveTransform(s,t);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(d,l){try{let x=await c(d);l.enqueue(x)}catch(x){l.error(new k(`Data transformation failed for migration ${o.id}`,"TRANSFORM_ERROR",o.id,x))}}})),e)}static async resolveTransform(e,t){return e.transform?typeof e.transform=="string"?e.transform.startsWith("http://")||e.transform.startsWith("https://")?this.resolveRemoteTransform(e.transform,t):this.resolveLocalTransform(e.transform,t):e.transform[t]:null}static async resolveRemoteTransform(e,t){try{let 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[t]}else{let{runInNewContext:a}=await import("vm"),s={module:{exports:{}},console};return a(r,s,e),s.module.exports[t]}}catch(i){throw new k(`Failed to load remote transform module: ${e}`,"TRANSFORM_ERROR",void 0,i)}}static async resolveLocalTransform(e,t){try{return(await import(e)).default[t]}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 t=this.migrations.filter(i=>i.status==="pending").flatMap(i=>i.changes);if(!t.length)return;this.history.push(structuredClone(this.currentSchema)),this.currentSchema=t.reduce((i,r)=>this.applySchemaChanges(i,[r]),this.currentSchema)}catch(t){throw t instanceof k?t:new k("Schema transformation failed","INVALID_SCHEMA",void 0,t)}}};var ot=n=>{let e=[],t=[];return{addField:(i,r)=>{e.push({type:"addField",id:i,definition:r}),t.push({type:"removeField",id:i})},removeField:i=>{e.push({type:"removeField",id:i});let r=n.fields[i];r&&t.push({type:"addField",id:i,definition:r})},modifyField:(i,r)=>{e.push({type:"modifyField",id:i,changes:r});let a=n.fields[i];a&&t.push({type:"modifyField",id:i,changes:a})},deprecateField:i=>{e.push({type:"deprecateField",id:i}),t.push({type:"modifyField",id:i,changes:{deprecated:!1}})},addIndex:i=>{e.push({type:"addIndex",definition:i}),t.push({type:"removeIndex",name:i.name})},removeIndex:i=>{e.push({type:"removeIndex",name:i});let r=n.indexes?.find(a=>a.name===i);r&&t.push({type:"addIndex",definition:r})},modifyIndex:(i,r)=>{e.push({type:"modifyIndex",name:i,changes:r});let a=n.indexes?.find(s=>s.name===i);a&&t.push({type:"modifyIndex",name:i,changes:a})},addConstraint:i=>{e.push({type:"addConstraint",constraint:i}),t.push({type:"removeConstraint",name:i.name})},removeConstraint:i=>{e.push({type:"removeConstraint",name:i});let r=n.constraints?.find(a=>"name"in a&&a.name===i);r&&t.push({type:"addConstraint",constraint:r})},modifyConstraint:(i,r)=>{e.push({type:"modifyConstraint",name:i,changes:r});let a=n.constraints?.find(s=>"name"in s&&s.name===i);a&&t.push({type:"modifyConstraint",name:i,changes:a})},addNestedSchema:(i,r)=>{e.push({type:"addNestedSchema",id:i,definition:r}),t.push({type:"removeNestedSchema",id:i})},removeNestedSchema:i=>{e.push({type:"removeNestedSchema",id:i});let r=n.nestedSchemas[i];r&&t.push({type:"addNestedSchema",id:i,definition:r})},modifyNestedSchema:(i,r)=>{e.push({type:"modifyNestedSchema",id:i,changes:r});let a=n.nestedSchemas[i];a&&t.push({type:"modifyNestedSchema",id:i,changes:a})},changes:()=>({migrate:e,rollback:t})}};import"@isomorphic-git/lightning-fs";import R from"isomorphic-git";import te from"isomorphic-git/http/web";import ct from"@isomorphic-git/lightning-fs";function je(n){let e=n.toString(),t=e.substring(e.indexOf("(")+1,e.indexOf(")")),i=e.substring(e.indexOf("{")+1,e.lastIndexOf("}")).trim();return JSON.stringify({params:t,body:i})}function Ve(n){let{params:e,body:t}=JSON.parse(n),i=Object.getPrototypeOf(function*(){}).constructor;return new i(e,t)}function he(n){let e=n.toString(),t=e.match(/\(([^)]*)\)\s*=>\s*(.+)/s),i=e.match(/function\s*\(([^)]*)\)\s*{([\s\S]*)}/),r=e.match(/([^(]*)\(([^)]*)\)\s*{([\s\S]*)}/),a,s;return t?(a=t[1],s=t[2].includes("{")?t[2].substring(1,t[2].length-1).trim():`return ${t[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:t?"arrow":i?"function":r?"method":"unknown"})}function pe(n){let{params:e,body:t,type:i}=JSON.parse(n),r=new Function(e,t);return i==="arrow"&&Object.defineProperty(r,"toString",{value:()=>`(${e}) => ${t}`,configurable:!0}),r}import{Buffer as dt}from"buffer";window.Buffer=dt;var ee=class{fs;fsp;rootDir;constructor(e="/registry"){this.fs=new ct(`${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||!B(e))throw new Error("Invalid schema");let t=`${this.rootDir}/${e.name}`;if(await this.fileExists(`${t}/schema.json`))throw new Error(`Schema ${e.name} already exists`);return await this.fsp.mkdir(t),await this.fsp.mkdir(`${t}/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 t=`${this.rootDir}/${e.name}`;if(!await this.fileExists(`${t}/schema.json`))throw new Error(`Schema ${e.name} not found`);return this.saveSchema(e,"update")}async saveSchema(e,t){let i=`${this.rootDir}/${e.name}`,r=await this.processAndStoreMigrations(i,e),a=this.serializeSchema(e);await this.writeSchemaFile(i,a);let s=await J(a);await this.updateIndex(i,e,s,r,t),await this.updateRegistryMetadata(e,t),await this.sync()}async delete({name:e}){let t=`${this.rootDir}/${e}`;if(!await this.fileExists(`${t}/schema.json`))throw new Error(`Schema ${e} not found`);await this.rmdirRecursive(t);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(t=>({name:t.name,version:t.version}))}async schema({name:e,version:t,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 t&&t!==s.version&&!s.history.some(o=>o.version===t)?null:(i&&(a.migrations=await this.migrations({name:e,version:t})),a)}async stats({schema:e}){return e?this.readSchemaIndex(e):this.readRegistryMetadata()}async sync(){let e={updated:new Date().toISOString(),hashes:[]},t=await this.listFilesRecursive(this.rootDir);for(let i of t)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 J(r)])}await this.fsp.writeFile(`${this.rootDir}/schema-lock.json`,JSON.stringify(e),"utf8")}async migrations({name:e,version:t}){let i=await this.readSchemaIndex(e),r=t||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 d=JSON.parse(String(await this.fsp.readFile(c,"utf8")));j(d.schemaVersion,r)<=0&&a.push(this.deserializeMigration(d))}}return a.sort((s,o)=>j(s.schemaVersion,o.schemaVersion))}async history({name:e}){let t=await this.readSchemaIndex(e),i=this.deserializeSchema(JSON.parse(String(await this.fsp.readFile(`${this.rootDir}/${e}/schema.json`,"utf8"))));return Promise.all(t.history.map(async r=>({...i,version:r.version,description:r.description,migrations:await this.migrations({name:e,version:r.version})})))}async processAndStoreMigrations(e,t){return Promise.all((t.migrations||[]).map(async i=>{let r={...i};if(i.transform?.forward){let o=i.transform;r.transform={forward:he(o.forward),backward:he(o.backward||(c=>c))}}let a=JSON.stringify(r),s=await J(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?je(e.mock):null})}deserializeSchema(e){return e.mock&&(e.mock=Ve(e.mock)),e}deserializeMigration(e){return e.transform?.forward&&(e.transform={forward:pe(e.transform.forward),backward:pe(e.transform.backward)}),e}async writeSchemaFile(e,t){let i=`${e}/schema.json`;return await this.fsp.writeFile(i,t,"utf8"),i}async updateIndex(e,t,i,r,a){let s=`${e}/index.json`,o=a==="create"?{schema:t.name,version:t.version,history:[],migrations:{}}:JSON.parse(String(await this.fsp.readFile(s,"utf8")));o.history.push({version:t.version,hash:i,date:new Date().toISOString(),description:t.description||(a==="create"?"Initial version":"Updated version"),migrations:r.map(c=>c.id),predicates:[],changelog:[]}),o.version=t.version,r.forEach(({id:c,hash:d,checksum:l})=>{o.migrations[c]={hash:d,checksum:l}}),await this.fsp.writeFile(s,JSON.stringify(o),"utf8")}async updateRegistryMetadata(e,t){let i=await this.readRegistryMetadata();i.schemas[e.name]={name:e.name,version:e.version,description:e.description||"",created:t==="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 t=`${this.rootDir}/${e}/index.json`;if(!await this.fileExists(t))throw new Error(`Schema ${e} not found`);return JSON.parse(String(await this.fsp.readFile(t,"utf8")))}async fileExists(e){try{return await this.fsp.stat(e),!0}catch{return!1}}async rmdirRecursive(e){let t=await this.fsp.readdir(e);for(let i of t){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 t=[],i=await this.fsp.readdir(e);for(let r of i){let a=`${e}/${r}`;(await this.fsp.stat(a)).isDirectory()?t.push(...await this.listFilesRecursive(a)):t.push(a)}return t}};var ye=class{locks=new Map;async acquire(e){let t,i=new Promise(a=>{t=a}),r=this.locks.get(e)||Promise.resolve();return this.locks.set(e,r.then(()=>i)),await r,t}async withLock(e,t){let i=await this.acquire(e);try{return await t()}finally{i()}}},ge=class{cache=new Map;ttl;constructor(e=3e4){this.ttl=e}get(e){let t=this.cache.get(e);return!t||Date.now()-t.timestamp>this.ttl?(this.cache.delete(e),null):t.schema}set(e,t){this.cache.set(e,{schema:t,timestamp:Date.now()})}invalidate(e){e?this.cache.delete(e):this.cache.clear()}};async function ne(n,e){try{return await n()}catch(t){throw console.error(`${e}:`,t),new Error(`${e}: ${t.message}`)}}async function ie(n,e,t,i,r){await i.init(),await R.init({fs:n,dir:e,defaultBranch:t}),await R.setConfig({fs:n,dir:e,path:"core.autocrlf",value:"false"}),await R.setConfig({fs:n,dir:e,path:"core.eol",value:"lf"}),await R.add({fs:n,dir:e,filepath:"."}),await R.commit({fs:n,dir:e,message:"chore: initial commit",author:r})}async function ln(n="/registry",e={}){let t=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 ee(n),d=c.fs,l=n.startsWith("/")?n:`/${n}`,x=new ye,w=new ge(e.cacheTtl);async function P(u,f){let h=o;do{let b=s[o];try{return await u(b)}catch(D){if(console.warn(`Failed with proxy ${b}: ${D.message}`),o=(o+1)%s.length,o===h)throw new Error(`${f}: All CORS proxies failed`)}}while(!0)}async function y(u,f="."){return ne(async()=>(await R.add({fs:d,dir:l,filepath:f}),(await R.statusMatrix({fs:d,dir:l})).some(([b,D,C])=>D!==C)?await R.commit({fs:d,dir:l,message:u,author:a}):null),"Failed to commit changes")}async function m(u,f,h){return ne(async()=>{if(await T(u))throw new Error(`Tag ${u} already exists`);await R.annotatedTag({fs:d,dir:l,ref:u,message:f,tagger:a,object:h})},`Failed to create tag ${u}`)}async function T(u){try{return(await R.listTags({fs:d,dir:l})).includes(u)}catch{return!1}}async function v(u){return(await R.listTags({fs:d,dir:l})).filter(b=>b.startsWith(u))}async function p(u){return ne(async()=>{let h=(await R.listTags({fs:d,dir:l})).filter(b=>b.startsWith(u));for(let b of h)await R.deleteTag({fs:d,dir:l,ref:b});return h},`Failed to delete tags with prefix ${u}`)}async function g(u){return ne(async()=>{await R.checkout({fs:d,dir:l,ref:u})},`Failed to checkout ${u}`)}async function S(u,{delete:f=!1,force:h=!1}={}){i&&await P(async b=>{await R.push({fs:d,http:te,dir:l,ref:u,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:b,delete:f,force:h})},`Failed to push ${u}`)}async function $(u,f=!0){i&&await P(async h=>{try{await R.pull({fs:d,http:te,dir:l,ref:u,author:a,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:h,fastForwardOnly:!0})}catch(b){if(!f)console.warn(`Fast-forward pull failed for ${u}, attempting regular pull`),await R.pull({fs:d,http:te,dir:l,ref:u,author:a,remote:"origin",url:i.authURL(),onAuth:()=>i.credentials(),corsProxy:h,fastForwardOnly:!1});else throw b}},`Failed to pull ${u}`)}if(i&&!await c.fileExists(l)){let u=l.slice(1);if(await i.exists({name:u}).catch(()=>!1))await P(async h=>{await R.clone({fs:d,http:te,dir:l,url:i.authURL(),ref:t,singleBranch:!0,depth:1,onAuth:()=>i.credentials(),corsProxy:h})},"Failed to clone repository");else if(r)try{i=await i.create({name:u,private:!0}),await ie(d,l,t,c,a),await R.addRemote({fs:d,dir:l,remote:"origin",url:i.url()}),await S(t)}catch(h){console.error("Failed to create and push to remote repository:",h),await ie(d,l,t,c,a)}else await ie(d,l,t,c,a)}else await ie(d,l,t,c,a);return{async init(){return x.withLock("init",()=>c.init())},async create(u){let{name:f,version:h}=u.schema;return x.withLock(`schema:${f}`,async()=>{await g(t),await c.create(u);let b=await y(`feat: create schema ${f}`);b&&await m(`${f}-${h}`,`Version ${h}`,b),w.invalidate(f)})},async update(u){let{name:f,version:h}=u.schema;return x.withLock(`schema:${f}`,async()=>{await g(t),await c.update(u);let b=await y(`fix: update schema ${f}`);b&&await m(`${f}-${h}`,`Version ${h}`,b),w.invalidate(f)})},async delete(u){let{name:f}=u;return x.withLock(`schema:${f}`,async()=>{await g(t),await R.remove({fs:d,dir:l,filepath:f}),await c.delete(u);let h=await y(`chore: delete schema ${f}`),b=await v(`${f}-`);if(i&&h){await S(t);for(let D of b)await S(D,{delete:!0,force:!0}).catch(C=>console.warn(`Failed to delete remote tag ${D}: ${C.message}`))}await p(`${f}-`),w.invalidate(f)})},async list(){return x.withLock("list",()=>c.list())},async schema(u){let{name:f,version:h}=u,b=`${f}-${h||"latest"}-${u.migrations||!1}`,D=w.get(b);return D||x.withLock(`schema:${f}`,async()=>{if(h){let A=`${f}-${h}`;if(await T(A))await g(A);else throw new Error(`Version ${h} of schema ${f} not found`)}else await g(t);let C=await c.schema(u);return w.set(b,C),C})},async stats(u){return x.withLock("stats",()=>c.stats(u))},async sync(){return x.withLock("sync",async()=>{if(await g(t),await c.sync(),await y("chore: sync local changes"),i){await $(t,!1),await S(t);let u=await R.listTags({fs:d,dir:l});for(let h of u)await S(h,{force:!0});let f=await R.listTags({fs:d,dir:l});for(let h of f)u.includes(h)||await S(h,{delete:!0})}w.invalidate()})},async migrations(u){let{name:f,version:h}=u,b=`migrations-${f}-${h||"latest"}`,D=w.get(b);return D||x.withLock(`migrations:${f}`,async()=>{if(h){let A=`${f}-${h}`;if(await T(A))await g(A);else throw new Error(`Version ${h} of schema ${f} not found`)}else await g(t);let C=await c.migrations(u);return w.set(b,C),C})},async history(u){let{name:f}=u,h=`history-${f}`,b=w.get(h);return b||x.withLock(`history:${f}`,async()=>{await g(t);let D=await c.history(u);return w.set(h,D),D})}}}function M(n){return"predicate"in n}function $n(n,e=!0,t=!0){let i="",r=t?"export ":"",a=new Map,s=new Map,o=(y,m=[])=>{if(!e||!y&&!m.length)return"";let T=y?[y]:[];return m.forEach(v=>T.push(v)),`/**
2
+ * ${T.join(`
3
3
  * `)}
4
4
  */
5
- `},o=u=>u.charAt(0).toUpperCase()+u.slice(1),c=(u,m)=>{for(let[h,g]of Object.entries(u))if(g.type==="string"&&g.constraints){let D=g.constraints.find(f=>f.predicate==="enum"||f.predicate==="oneOf");if(D&&Array.isArray(D.parameters)){let f=`${m}${Ae(g.name)}`,p=D.parameters.map(v=>String(v));r.set(f,p)}}};c(n.fields,n.name);for(let[u,m]of Object.entries(n.nestedSchemas))c(m.fields,o(m.name));for(let[u,m]of r){i+=a(`Union type for ${u.toLowerCase()} field values`);let h=m.map(g=>`"${g}"`).join(" | ");i+=`${s}type ${u} = ${h};
5
+ `},c=y=>y.charAt(0).toUpperCase()+y.slice(1),d=(y,m)=>{let T=s.get(m)||new Map;for(let[v,p]of Object.entries(y))if(p.type==="enum"&&Array.isArray(p.values)){let g=`${m}${c(p.name)}`,S=p.values.map($=>String($));a.set(g,S)}else if(p.type==="string"&&p.constraints){let g=p.constraints.find(S=>M(S)&&(S.predicate==="enum"||S.predicate==="oneOf"));if(g&&M(g)&&Array.isArray(g.parameters)){let S=`${m}${c(p.name)}`,$=g.parameters.map(u=>String(u));a.set(S,$)}}else if(p.type==="record"){let g=`${m}${c(p.name)}`;T.set(p.name,g)}T.size>0&&s.set(m,T)};d(n.fields,n.name);for(let[y,m]of Object.entries(n.nestedSchemas||{}))Array.isArray(m.fields)?m.fields.forEach(T=>d(T.fields,c(m.name))):d(m.fields,c(m.name));for(let[y,m]of a){i+=o(`Union type for ${y.toLowerCase()} field values`);let T=m.map(v=>`"${v}"`).join(" | ");i+=`${r}type ${y} = ${T};
6
6
 
7
- `}for(let[u,m]of Object.entries(n.nestedSchemas)){let h=o(m.name),g=m.constraints?.map(D=>`@constraint ${D.name}: ${D.description||D.predicate}`)||[];i+=a(m.description,g),i+=`${s}type ${h} = {
8
- `;for(let[D,f]of Object.entries(m.fields)){let p=f.constraints?.map($=>`@constraint ${$.name}: ${$.description||$.predicate}`)||[];f.unique&&p.push("@unique Ensures unique values"),f.default!==void 0&&p.push(`@default ${JSON.stringify(f.default)}`),e&&f.description?i+=a(f.description,p):p.length&&(i+=a(void 0,p)),f.deprecated&&(i+=` /** @deprecated */
9
- `);let v=Re(f,n,h),C=f.required===!1?"?":"";i+=` ${f.name}${C}: ${v};
10
- `}if(m.metadata&&(i+=` metadata: Record<string, any>;
7
+ `}for(let[y,m]of Object.entries(n.nestedSchemas||{})){let T=c(m.name),v=m.constraints?.map($=>M($)?`@constraint ${$.name}: ${$.description||$.predicate}`:`@constraint ${$.name}`)||[];m.concrete&&v.push("@concrete Indicates a concrete schema"),i+=o(m.description,v);let p=s.get(T)||new Map,g=Array.from(p.entries()).map(([$,u])=>`${u} extends Record<string, any> = Record<string, any>`).join(", "),S=p.size>0?`<${g}>`:"";if(Array.isArray(m.fields)){let $=m.fields.filter(b=>!b.when),u=m.fields.filter(b=>b.when),f="";if($.length>0){f+=`{
8
+ `;for(let b of $)for(let[D,C]of Object.entries(b.fields)){let A=C.constraints?.map(N=>M(N)?`@constraint ${N.name}: ${N.description||N.predicate}`:`@constraint ${N.name}`)||[];C.unique&&A.push("@unique Ensures unique values"),C.default!==void 0&&A.push(`@default ${JSON.stringify(C.default)}`),e&&C.description?f+=o(C.description,A):A.length&&(f+=o(void 0,A)),C.deprecated&&(f+=` /** @deprecated */
9
+ `);let I=se(C,n,T,p),V=C.required===!1?"?":"";f+=` ${C.name}${V}: ${I};
10
+ `}f+="}"}let h="";u.length>0&&(h=u.map(D=>{let C=`{
11
+ `;for(let[A,I]of Object.entries(D.fields)){let V=I.constraints?.map(H=>M(H)?`@constraint ${H.name}: ${H.description||H.predicate}`:`@constraint ${H.name}`)||[];I.unique&&V.push("@unique Ensures unique values"),I.default!==void 0&&V.push(`@default ${JSON.stringify(I.default)}`),e&&I.description?C+=o(I.description,V):V.length&&(C+=o(void 0,V)),I.deprecated&&(C+=` /** @deprecated */
12
+ `);let N=se(I,n,T,p),Ne=I.required===!1?"?":"";C+=` ${I.name}${Ne}: ${N};
13
+ `}if(D.when)for(let[A,I]of Object.entries(D.when))C+=` ${A}: "${I}";
14
+ `;return C+="}",C}).join(" | ")),f&&h?i+=`${r}type ${T}${S} = ${f} & (${h});
15
+
16
+ `:f?i+=`${r}type ${T}${S} = ${f};
17
+
18
+ `:h&&(i+=`${r}type ${T}${S} = ${h};
19
+
20
+ `)}else{i+=`${r}type ${T}${S} = {
21
+ `;for(let[$,u]of Object.entries(m.fields)){let f=u.constraints?.map(D=>M(D)?`@constraint ${D.name}: ${D.description||D.predicate}`:`@constraint ${D.name}`)||[];u.unique&&f.push("@unique Ensures unique values"),u.default!==void 0&&f.push(`@default ${JSON.stringify(u.default)}`),e&&u.description?i+=o(u.description,f):f.length&&(i+=o(void 0,f)),u.deprecated&&(i+=` /** @deprecated */
22
+ `);let h=se(u,n,T,p),b=u.required===!1?"?":"";i+=` ${u.name}${b}: ${h};
23
+ `}m.metadata&&(i+=` metadata: Record<string, any>;
11
24
  `),i+=`};
12
25
 
13
- `,m.indexes?.length){i+=a(`Available indexes for ${h}`),i+=`${s}enum ${h}IndexNames {
14
- `;for(let D of m.indexes)i+=` ${D.name} = "${D.name}",
26
+ `}if(m.indexes?.length){i+=o(`Available indexes for ${T}`),i+=`${r}enum ${T}IndexNames {
27
+ `;for(let $ of m.indexes)i+=` ${$.name} = "${$.name}",
15
28
  `;i+=`}
16
29
 
17
- `}}let d=n.constraints?.map(u=>`@constraint ${u.name}: ${u.description||u.predicate}`)||[];i+=a(n.description,d),i+=`${s}type ${n.name} = {
18
- `;for(let[u,m]of Object.entries(n.fields)){let h=m.constraints?.map(f=>`@constraint ${f.name}: ${f.description||f.predicate}`)||[];m.unique&&h.push("@unique Ensures unique values"),m.default!==void 0&&h.push(`@default ${JSON.stringify(m.default)}`),e&&m.description?i+=a(m.description,h):h.length&&(i+=a(void 0,h)),m.deprecated&&(i+=` /** @deprecated */
19
- `);let g=Re(m,n,n.name),D=m.required===!1?"?":"";i+=` ${m.name}${D}: ${g};
30
+ `}}let l=n.constraints?.map(y=>M(y)?`@constraint ${y.name}: ${y.description||y.predicate}`:`@constraint ${y.name}`)||[];i+=o(n.description,l);let x=s.get(n.name)||new Map,w=Array.from(x.entries()).map(([y,m])=>`${m} extends Record<string, any> = Record<string, any>`).join(", "),P=x.size>0?`<${w}>`:"";i+=`${r}type ${n.name}${P} = {
31
+ `;for(let[y,m]of Object.entries(n.fields)){let T=m.constraints?.map(g=>M(g)?`@constraint ${g.name}: ${g.description||g.predicate}`:`@constraint ${g.name}`)||[];m.unique&&T.push("@unique Ensures unique values"),m.default!==void 0&&T.push(`@default ${JSON.stringify(m.default)}`),e&&m.description?i+=o(m.description,T):T.length&&(i+=o(void 0,T)),m.deprecated&&(i+=` /** @deprecated */
32
+ `);let v=se(m,n,n.name,x),p=m.required===!1?"?":"";i+=` ${m.name}${p}: ${v};
20
33
  `}if(n.metadata&&(i+=` metadata: Record<string, any>;
21
34
  `),i+=`};
22
35
 
23
- `,n.indexes?.length){i+=a(`Available indexes for ${n.name}`),i+=`${s}enum ${n.name}IndexNames {
24
- `;for(let u of n.indexes)i+=` ${u.name} = "${u.name}",
36
+ `,n.indexes?.length){i+=o(`Available indexes for ${n.name}`),i+=`${r}enum ${n.name}IndexNames {
37
+ `;for(let y of n.indexes)i+=` ${y.name} = "${y.name}",
25
38
  `;i+=`}
26
- `}return i}function Re(n,e,t){switch(n.type){case"string":if(n.constraints){let i=n.constraints.find(s=>s.predicate==="enum"||s.predicate==="oneOf");if(i&&Array.isArray(i.parameters))return`${t}${Ae(n.name)}`}return"string";case"number":return"number";case"boolean":return"boolean";case"array":if(n.itemsType){if(n.itemsType==="object"&&n.nestedSchema){let i=e.nestedSchemas[n.nestedSchema.id];return`Array<${fe(i.name)}>`}return`${n.itemsType}[]`}return"any[]";case"set":if(n.itemsType){if(n.itemsType==="object"&&n.nestedSchema){let i=e.nestedSchemas[n.nestedSchema.id];return`Set<${fe(i.name)}>`}return`Set<${n.itemsType}>`}return"Set<any>";case"object":if(n.nestedSchema){let i=e.nestedSchemas[n.nestedSchema.id];return fe(i.name)}return n.reference?`${n.reference.schema}${n.required===!1?" | null":""}`:"Record<string, any>";case"dynamic":return"unknown";default:return"any"}}function Ae(n){return n.split(/[-_\s]/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function fe(n){return n.charAt(0).toUpperCase()+n.slice(1)}function mn(n,e=!0){let i=`${e?"export ":""}interface ${n.name}Validator {
27
- `;return i+=` /**
28
- * Validates a ${n.name} object against all schema constraints
29
- * @param data The data to validate
30
- * @returns Validation result with any errors
31
- */
32
- `,i+=` validate(data: ${n.name}): { valid: boolean; errors: Array<{ field: string; message: string }> };
33
-
34
- `,i+=` /**
35
- * Checks if the given object conforms to the ${n.name} type structure
36
- * @param data The object to check
37
- * @returns Whether the object matches the expected structure
38
- */
39
- `,i+=` isType(data: any): data is ${n.name};
40
- `,i+=`}
41
- `,i}function ln(n,e){let t=[],i=a=>a===void 0?"`None`":`\`${JSON.stringify(a,null,2)}\``,s=a=>{let o=`**${a.field}** ${a.operator}`;return a.value!==void 0&&(o+=` ${JSON.stringify(a.value)}`),a.conditions&&(o+=` [
42
- ${a.conditions.map(c=>` ${s(c)}`).join(`
39
+ `}return i.trim()}function se(n,e,t,i){switch(n.type){case"string":if(n.constraints){let r=n.constraints.find(a=>M(a)&&(a.predicate==="enum"||a.predicate==="oneOf"));if(r&&M(r)&&Array.isArray(r.parameters))return`${t}${L(n.name)}`}return"string";case"number":return"number";case"boolean":return"boolean";case"array":if(n.itemsType){if(n.itemsType==="object"&&n.schema&&!Array.isArray(n.schema)){let r=e.nestedSchemas[n.schema.id];return`${L(r.name)}[]`}return`${n.itemsType}[]`}return"any[]";case"set":if(n.itemsType){if(n.itemsType==="object"&&n.schema&&!Array.isArray(n.schema)){let r=e.nestedSchemas[n.schema.id];return`Set<${L(r.name)}>`}return`Set<${n.itemsType}>`}return"Set<any>";case"enum":return n.values?`${t}${L(n.name)}`:"string";case"object":if(n.schema&&!Array.isArray(n.schema)){let r=e.nestedSchemas[n.schema.id],a=L(r.name);return r.concrete?`string | ${a}`:a}if(n.nestedSchema){let r=e.nestedSchemas[n.nestedSchema.id],a=L(r.name);return r.concrete?`string | ${a}`:a}return n.reference?`${n.reference.schema}${n.required===!1?" | null":""}`:"Record<string, any>";case"record":return i.get(n.name)||"Record<string, any>";case"union":return n.schema&&Array.isArray(n.schema)?n.schema.map(a=>{let s=e.nestedSchemas[a.id];return L(s.name)}).join(" | "):"any";case"dynamic":return"unknown";default:return"any"}}function L(n){return n.charAt(0).toUpperCase()+n.slice(1)}function Sn(n,e){let t=[],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(`
43
41
  `)}
44
- ]`),o},r=(a,o=1)=>{let c="#".repeat(o+2);return Object.entries(a).map(([d,u])=>{let m=`${c} ${d} (${u.type})
42
+ ]`),o},a=(s,o=1)=>{let c="#".repeat(o+2);return Object.entries(s).map(([d,l])=>{let x=`${c} ${d} (${l.type})
45
43
 
46
- `;return m+=`**Required:** ${u.required?"Yes":"No"}
44
+ `;return x+=`**Required:** ${l.required?"Yes":"No"}
47
45
 
48
- `,u.description&&(m+=`**Description:** ${u.description}
46
+ `,l.description&&(x+=`**Description:** ${l.description}
49
47
 
50
- `),u.itemsType&&(m+=`**Item Type:** ${u.itemsType}
48
+ `),l.itemsType&&(x+=`**Item Type:** ${l.itemsType}
51
49
 
52
- `),u.nestedSchema&&(m+=r(u.nestedSchema,o+1)),m}).join(`
50
+ `),l.nestedSchema&&(x+=a(l.nestedSchema,o+1)),x}).join(`
53
51
  `)};t.push(`# ${n.name} Schema (Version ${n.version})`),n.description&&t.push(`
54
52
  ${n.description}
55
53
  `),t.push("## Metadata"),t.push(`- **Dependencies:** ${n.dependencies?.join(", ")||"None"}`),t.push(`- **Created:** ${new Date().toISOString()}
56
54
  `),t.push(`## Fields
57
- `),t.push("| Name | Type | Required | Default | Description | Deprecated | Unique | Constraints |"),t.push("|------|------|----------|---------|-------------|------------|--------|-------------|");for(let[a,o]of Object.entries(n.fields))t.push([a,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(n.fields).forEach(([a,o])=>{o.nestedSchema&&(t.push(`
58
- ### Nested Schema: ${a}
59
- `),t.push(r(o.nestedSchema)))}),t.push(`
55
+ `),t.push("| Name | Type | Required | Default | Description | Deprecated | Unique | Constraints |"),t.push("|------|------|----------|---------|-------------|------------|--------|-------------|");for(let[s,o]of Object.entries(n.fields))t.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(n.fields).forEach(([s,o])=>{o.nestedSchema&&(t.push(`
56
+ ### Nested Schema: ${s}
57
+ `),t.push(a(o.nestedSchema)))}),t.push(`
60
58
  ## Indexes
61
- `),t.push("| Name | Type | Fields | Unique | Order | Partial Condition | Description |"),t.push("|------|------|--------|--------|-------|-------------------|-------------|");for(let a of n.indexes||[])t.push([a.name,a.type,a.fields.join(", "),a.unique?"Yes":"No",a.order||"asc",a.partial?s(a.partial):"None",a.description||""].join("|"));t.push(`
59
+ `),t.push("| Name | Type | Fields | Unique | Order | Partial Condition | Description |"),t.push("|------|------|--------|--------|-------|-------------------|-------------|");for(let s of n.indexes||[])t.push([s.name,s.type,s.fields.join(", "),s.unique?"Yes":"No",s.order||"asc",s.partial?r(s.partial):"None",s.description||""].join("|"));t.push(`
62
60
  ## Constraints
63
61
  `),n.constraints&&t.push("### Schema-level Constraints"),t.push(`
64
62
  ## Migrations
65
- `),t.push("| ID | Description | Status | Changes |"),t.push("|----|-------------|--------|---------|");for(let a of n.migrations||[])t.push([a.id,a.description,a.status,a.changes.length].join("|"));if(n.mock&&e?.faker)try{let a=n.mock(e.faker).next().value;t.push("\n## Example Data\n```json\n"+JSON.stringify(a,null,2)+"\n```")}catch{t.push(`
63
+ `),t.push("| ID | Description | Status | Changes |"),t.push("|----|-------------|--------|---------|");for(let s of n.migrations||[])t.push([s.id,s.description,s.status,s.changes.length].join("|"));if(n.mock&&e?.faker)try{let s=n.mock(e.faker).next().value;t.push("\n## Example Data\n```json\n"+JSON.stringify(s,null,2)+"\n```")}catch{t.push(`
66
64
  <!-- Error generating mock data -->`)}return t.join(`
67
- `)}function yn(n){let e={},t={};n.hint?.groups&&n.hint.groups.forEach(s=>{t[s.name]={label:s.label,description:s.description}}),Me(n.fields,"",n.nestedSchemas||{},e);let i=[];for(let[s,r]of Object.entries(e)){let a=s!=="ungrouped"?t[s]:void 0;i.push({name:s!=="ungrouped"?s:"ungrouped",label:a?.label||"Ungrouped",description:a?.description,fields:r})}return i}function Me(n,e,t,i){for(let[s,r]of Object.entries(n)){let a=e?`${e}.${r.name}`:r.name,o={...r,name:a};if(!r.hint?.input?.ignore){if(r.type!=="object"){let c=r.hint?.input?.group||"ungrouped";i[c]||(i[c]=[]),i[c].push(o)}if(r.nestedSchema?.id&&t[r.nestedSchema.id]){let c=t[r.nestedSchema.id];Me(c.fields,a,t,i)}}}}export{P as JsonPatchError,ke as MigrationEngine,x as MigrationError,et as MigrationErrorCode,B as SchemaRegistry,X as applyPatch,De as calculateNextVersion,M as compareSemanticVersions,sn as createGitSchemaRegistry,at as createPatch,tt as createSchemaMigrationHelper,Ue as createStandardSchemaValidator,pe as deepMerge,ln as docgen,yn as extractInputFieldGroups,j as generateSHA256Hash,mn as generateValidationInterface,Oe as normalizePath,me as schemaChangeToPatch,fn as schemaToTypes,J as serializeParams,pt as sortSemanticVars,mt as validate,Ce as validateMigration,Te as validateSchemaChange,q as validateSchemaDefinition};
65
+ `)}function vn(n){let e={},t={};n.hint?.groups&&n.hint.groups.forEach(r=>{t[r.name]={label:r.label,description:r.description}}),$e(n.fields,"",n.nestedSchemas||{},e);let i=[];for(let[r,a]of Object.entries(e)){let s=r!=="ungrouped"?t[r]:void 0;i.push({name:r!=="ungrouped"?r:"ungrouped",label:s?.label||"Ungrouped",description:s?.description,fields:a})}return i}function $e(n,e,t,i,r){if(Array.isArray(n))n.forEach(a=>{let s=a.when?e?`${e}.${a.when?.field}`:a.when?.field:void 0;$e(a.fields,e,t,i,s?{[s]:a.when?.value}:void 0)});else for(let[a,s]of Object.entries(n)){if(s.hint?.input.ignore)continue;let o=e?`${e}.${s.name}`:s.name,c={...s,name:o};if(s.type!=="object"){let d=s.hint?.input?.group||"ungrouped";i[d]||(i[d]=[]),i[d].push(c)}if(r&&(c.when=r),s.schema&&"id"in s.schema&&t[s.schema.id]){let d=t[s.schema.id];$e(d.fields,o,t,i,r)}}}export{F as JsonPatchError,Oe as MigrationEngine,k as MigrationError,at as MigrationErrorCode,ee as SchemaRegistry,oe as applyPatch,Me as calculateNextVersion,j as compareSemanticVersions,ln as createGitSchemaRegistry,ut as createPatch,ot as createSchemaMigrationHelper,He as createStandardSchemaValidator,ve as deepMerge,Sn as docgen,vn as extractInputFieldGroups,mt as formResolver,J as generateSHA256Hash,qe as normalizePath,we as schemaChangeToPatch,$n as schemaToTypes,Z as serializeParams,vt as sortSemanticVars,wt as validate,Pe as validateMigration,Fe as validateSchemaChange,B as validateSchemaDefinition};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@asaidimu/anansi",
3
- "version": "1.5.3",
3
+ "version": "1.6.1",
4
4
  "description": "A toolkit for advanced data modelling",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -49,6 +49,7 @@
49
49
  "fake-indexeddb": "^6.0.0",
50
50
  "happy-dom": "^17.0.4",
51
51
  "playwright": "^1.50.1",
52
+ "react-hook-form": "^7.55.0",
52
53
  "tailwindcss": "^4.0.6",
53
54
  "tsup": "^8.3.6",
54
55
  "typescript": "^5.7.3",