UNPKG

jsonv-ts

Version:

JSON Schema builder and validator for TypeScript with static type inference, Hono middleware for OpenAPI generation and validation, and MCP server/client implementation. Lightweight, dependency-free, and built on Web Standards.

4 lines (2 loc) 28.3 kB
var L=(t=[],e="")=>"/"+[e,...t.map(n=>String(n).replace(/\./g,"/"))].filter(Boolean).join("/"),te=t=>t.split("/").slice(1);function Oe(t,e,n=void 0){let r=typeof e=="string"?te(e):L(e);return j(t,r,n)}function j(t,e,n=void 0){let r=typeof e=="string"?e.split(/[.\[\]\"]+/).filter(o=>o):e;if(r.length===0)return t;try{let[o,...i]=r;return!o||!(o in t)?n:j(t[o],i,n)}catch{if(typeof n<"u")return n;throw new Error(`Invalid path: ${r.join(".")}`)}}var d=(t={},e,n,r)=>({valid:!1,errors:[...t.errors??[],{keywordLocation:L([...t.keywordPath??[],e]),instanceLocation:L(t.instancePath),error:typeof n=="string"?n:`Invalid value for ${e}`,data:r}]}),a=()=>({valid:!0,errors:[]}),I=(t,e,n)=>{let r=Array.isArray(e)?e:[e],o=n?Array.isArray(n)?n:[n]:[];return{...t,keywordPath:[...t.keywordPath??[],...r],instancePath:o?[...t.instancePath??[],...o]:t.instancePath}},A=(t={})=>({...t,errors:[]});var b=class extends Error{constructor(e){super(`Expected ${e}`)}},W=class extends Error{constructor(n,r){super(`${n??"Invalid raw schema"}: ${JSON.stringify(r)}`);this.schema=r}},B=class extends Error{constructor(n,r){super(`${n}, got: 'type "${typeof r}": ${JSON.stringify(r)}'`);this.value=r}};var h=Symbol.for("jsonv-ts:schema");function xe(t){return t===null}function u(t){return!Array.isArray(t)&&typeof t=="object"&&t!==null}function ge(t){return Object.prototype.toString.call(t)==="[object Object]"}function O(t){return typeof t=="string"}function S(t){return typeof t=="number"}function be(t){return typeof t=="number"&&Number.isInteger(t)}function C(t){return typeof t=="boolean"}function x(t){return Array.isArray(t)}function dt(t){return typeof t!="boolean"}function we(t){return t!==void 0&&dt(t)&&"type"in t}function l(t){return t!==void 0&&u(t)&&h in t}function ke(t){return l(t)&&typeof t.toJSON()=="boolean"}function ne(t,e,n){if(!t)throw new B(e,n)}var Se=new WeakMap;function w(t){if(t==null||typeof t=="boolean"||typeof t=="number")return t;if(O(t))return t.normalize("NFC");if(x(t)||u(t)){let e=Se.get(t);if(e!==void 0)return e;let n;if(x(t))n=t.map(w).sort();else{let r=Object.entries(t).sort(([o],[i])=>o.localeCompare(i)).map(([o,i])=>[o,w(i)]);n=Object.fromEntries(r)}return Se.set(t,n),n}return t}function Te(t,e){return e.reduce((n,r)=>(r in t&&(n[r]=t[r]),n),{})}function F(t){try{return structuredClone(t)}catch{return t}}var R=class{constructor(e){this.root=e;this.cache=new Map}cache;hasRef(e,n){return n!==void 0&&"$ref"in e&&O(e.$ref)}resolve(e){let n=this.cache.get(e);if(!n){if(n=Oe(this.root,e),!l(n))throw new Error(`ref not found: ${e}`);if("$ref"in n&&n.$ref===e)throw new Error(`ref loop: ${e}`);this.cache.set(e,n)}return n}};function Pe(t,e,n={}){let r=e;try{r=structuredClone(e)}catch{r=JSON.parse(JSON.stringify(e))}let o={resolver:n.resolver||new R(t),depth:n.depth||0,dropUnknown:n.dropUnknown||!1};return o.resolver.hasRef(t,r)?o.resolver.resolve(t.$ref).coerce(r,{...o,depth:o.depth+1}):r}var Ie=({type:t},e,n={})=>{if(t===void 0)return a();if(e===void 0)return a();let r,o={string:O,number:S,integer:be,object:u,array:x,boolean:C,null:xe};if(Array.isArray(t)){for(let i of t){if(!(i in o))throw new b(`Unknown type: ${i}`);if(o[i](e))return a()}r=`Expected one of: ${t.join(", ")}`}else{if(!(t in o))throw new b(`Unknown type: ${t}`);o[t](e)||(r=`Expected ${t}`)}return r?d(n,"type",r,e):a()},Re=({const:t},e,n={})=>{let r=JSON.stringify(w(t)),o=JSON.stringify(w(e));return r!==o?d(n,"const",`Expected const: ${r}`,o):a()},$e=({enum:t=[]},e,n={})=>{let r=JSON.stringify(t.map(w)),o=JSON.stringify(w(e));return r.includes(o)?a():d(n,"enum",`Expected enum: ${r}`,e)};function U(t,e,n={}){return t.map(r=>r.validate(e,A(n)).valid?r:void 0).filter(Boolean)}var Ne=({anyOf:t=[]},e,n={})=>U(t,e,n).length>0?a():d(n,"anyOf","Expected at least one to match",e),je=({oneOf:t=[]},e,n={})=>U(t,e).length===1?a():d(n,"oneOf","Expected exactly one to match",e),Ce=({allOf:t=[]},e,n={})=>U(t,e,n).length===t.length?a():d(n,"allOf","Expected all to match",e),Ee=({not:t},e,n={})=>e===void 0?a():l(t)&&t.validate(e,n).valid?d(n,"not","Expected not to match",e):a(),ve=({if:t,then:e,else:n},r,o={})=>{if(t&&(e||n)){if(t.validate(r,A(o)).valid)return e?e.validate(r,A(o)):a();if(n)return n.validate(r,A(o))}return a()},Ae=({pattern:t=""},e,n={})=>{if(!O(e))return a();if(t instanceof RegExp){if(t.test(e))return a()}else if(new RegExp(t,"u").test(e))return a();return d(n,"pattern",`Expected string matching pattern ${t}`,e)},Ue=({minLength:t=0},e,n={})=>O(e)?[...w(e)].length>=t?a():d(n,"minLength",`Expected string with minimum length of ${t}`,e):a(),ze=({maxLength:t=0},e,n={})=>O(e)?[...w(e)].length<=t?a():d(n,"maxLength",`Expected string with maximum length of ${t}`,e):a(),Je=({multipleOf:t=0},e,n={})=>{if(!S(e))return a();if(!(Number.isFinite(e)&&Number.isFinite(t))||t<=0)throw new b("number");let r=e/t,o=Number.EPSILON*Math.max(1,Math.abs(r));return Math.abs(r-Math.round(r))<=o?a():d(n,"multipleOf",`Expected number being a multiple of ${t}`,e)},Ve=({maximum:t=0},e,n={})=>!S(e)||e<=t?a():d(n,"maximum",`Expected number less than or equal to ${t}`,e),Me=({exclusiveMaximum:t=0},e,n={})=>!S(e)||e<t?a():d(n,"exclusiveMaximum",`Expected number less than ${t}`,e),Ke=({minimum:t=0},e,n={})=>!S(e)||e>=t?a():d(n,"minimum",`Expected number greater than or equal to ${t}`,e),qe=({exclusiveMinimum:t=0},e,n={})=>!S(e)||e>t?a():d(n,"exclusiveMinimum",`Expected number greater than ${t}`,e),De=({properties:t={}},e,n={})=>{if(!u(e))return a();for(let[r,o]of Object.entries(e)){let i=t[r];if(!l(i))continue;let s=i.validate(o,I(n,["properties",r],r));if(!s.valid)return s}return a()},Le=({properties:t={},additionalProperties:e,patternProperties:n},r,o={})=>{if(!u(r))return a();if(!l(e))throw new b("additionalProperties must be a boolean or a managed schema");let i=Object.keys(t),s=u(n)?Object.keys(r).filter(c=>Object.keys(n).some(m=>new RegExp(m).test(c))):[],p=Object.keys(r).filter(c=>!i.includes(c)&&!s.includes(c));if(p.length>0){if(ke(e)){if(e.toJSON()===!0)return a();let c=p.reduce((m,f)=>(m[f]=r[f],m),{});return d(o,"additionalProperties","Additional properties are not allowed",c)}else if(l(e))for(let c of p){let m=e.validate(r[c],I(o,["additionalProperties"],c));if(!m.valid)return m}}return a()},We=({dependentRequired:t},e,n={})=>{if(!u(e))return a();let r=Object.keys(e).filter(o=>typeof e[o]!="function");if(u(t)){for(let[o,i]of Object.entries(t))if(r.includes(o)){for(let s of i)if(!r.includes(s))return d(n,"dependentRequired",`Expected dependent required property ${s}`,e)}}return a()},Be=({required:t=[]},e,n={})=>{if(!u(e))return a();let r=Object.keys(e).filter(o=>typeof e[o]!="function");return t.every(o=>r.includes(o))?a():d(n,"required",`Expected object with required properties ${t.join(", ")}`,e)},Fe=({dependentSchemas:t},e,n={})=>{if(!u(e))return a();let r=Object.keys(e).filter(o=>typeof e[o]!="function");if(u(t)){for(let[o,i]of Object.entries(t))if(r.includes(o)){let s=i.validate(e,n);if(!s.valid)return s}}return a()},_e=({minProperties:t=0},e,n={})=>u(e)?Object.keys(e).length>=t?a():d(n,"minProperties",`Expected object with at least ${t} properties`,e):a(),Ye=({maxProperties:t=0},e,n={})=>!u(e)||Object.keys(e).length<=t?a():d(n,"maxProperties",`Expected object with at most ${t} properties`,e),He=({patternProperties:t={}},e,n={})=>{if(!u(e))return a();if(!u(t))throw new b("patternProperties must be an object");for(let[r,o]of Object.entries(e))for(let[i,s]of Object.entries(t))if(new RegExp(i,"u").test(r)){let p=s.validate(o,I(n,["patternProperties"],r));if(!p.valid)return p}return a()},Ze=({propertyNames:t},e,n={})=>{if(!u(e)||t===void 0)return a();if(!l(t))throw new b("propertyNames must be a managed schema");for(let r of Object.keys(e)){let o=t.validate(r,I(n,["propertyNames"],r));if(!o.valid)return o}return a()},Ge=({items:t,prefixItems:e=[]},n,r={})=>{if(!x(n)||t===void 0)return a();if(!l(t))throw new b("items must be a managed schema");for(let[o,i]of n.slice(e.length).entries()){let s=t.validate(i,I(r,["items"],String(o)));if(!s.valid)return s}return a()},Qe=({minItems:t=0},e,n={})=>!x(e)||e.length>=t?a():d(n,"minItems",`Expected array with at least ${t} items`,e),Xe=({maxItems:t=0},e,n={})=>!x(e)||e.length<=t?a():d(n,"maxItems",`Expected array with at most ${t} items`,e),et=({uniqueItems:t=!1},e,n={})=>{if(!x(e)||!t)return a();let r=e.map(w);return new Set(r.map(o=>JSON.stringify(o))).size===e.length?a():d(n,"uniqueItems","Expected array with unique items",e)},tt=({contains:t,minContains:e,maxContains:n},r,o={})=>{if(!l(t))throw new Error("contains must be a managed schema");if(!x(r))return a();let i=r.filter(s=>t.validate(s).valid).length;return i<(e??1)?d(o,e?"minContains":"contains",`Expected array to contain at least ${e??1}, but found ${i}`,r):n!==void 0&&i>n?d(o,"maxContains",`Expected array to contain at most ${n}, but found ${i}`,r):a()},nt=({prefixItems:t=[]},e,n={})=>{if(!x(e))return a();for(let r=0;r<e.length;r++){let o=t[r]?.validate(e[r],I(n,String(r),String(r)));if(o&&o?.valid!==!0)return o}return a()};var _={email:t=>{if(t.length>318)return!1;if(/^[a-z0-9!#$%&'*+/=?^_`{|}~-]{1,20}(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]{1,21}){0,2}@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,60}[a-z0-9])?){0,3}$/i.test(t))return!0;if(!t.includes("@")||/(^\.|^"|\.@|\.\.)/.test(t))return!1;let[n,r,...o]=t.split("@");return!n||!r||o.length!==0||n.length>64||r.length>253||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(n)?!1:r.split(".").every(i=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(i))},hostname:t=>t.length>(t.endsWith(".")?254:253)?!1:/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*\.?$/i.test(t),date:t=>{if(t.length!==10)return!1;if(t[5]==="0"&&t[6]==="2"){if(/^\d\d\d\d-02-(?:[012][1-8]|[12]0|[01]9)$/.test(t))return!0;let e=t.match(/^(\d\d\d\d)-02-29$/);if(!e)return!1;let n=Number(e[1]);return n%16===0||n%4===0&&n%25!==0}return t.endsWith("31")?/^\d\d\d\d-(?:0[13578]|1[02])-31$/.test(t):/^\d\d\d\d-(?:0[13-9]|1[012])-(?:[012][1-9]|[123]0)$/.test(t)},time:t=>{if(t.length>27||!/^(?:2[0-3]|[0-1]\d):[0-5]\d:(?:[0-5]\d|60)(?:\.\d+)?(?:z|[+-](?:2[0-3]|[0-1]\d)(?::?[0-5]\d)?)?$/i.test(t))return!1;if(!/:60/.test(t))return!0;let n=t.match(/([0-9.]+|[^0-9.])/g);if(!n)return!1;let r=Number(n[0])*60+Number(n[2]);return n[5]==="+"?r+=24*60-Number(n[6]||0)*60-Number(n[8]||0):n[5]==="-"&&(r+=Number(n[6]||0)*60+Number(n[8]||0)),r%(24*60)===23*60+59},"date-time":t=>{if(t.length>38)return!1;let e=/^\d\d\d\d-(?:0[1-9]|1[0-2])-(?:[0-2]\d|3[01])[t\s](?:2[0-3]|[0-1]\d):[0-5]\d:(?:[0-5]\d|60)(?:\.\d+)?(?:z|[+-](?:2[0-3]|[0-1]\d)(?::?[0-5]\d)?)$/i,n=t[5]==="0"&&t[6]==="2";if(n&&t[8]==="3"||!e.test(t))return!1;if(t[17]==="6"){let r=t.slice(11).match(/([0-9.]+|[^0-9.])/g);if(!r)return!1;let o=Number(r[0])*60+Number(r[2]);if(r[5]==="+"?o+=24*60-Number(r[6]||0)*60-Number(r[8]||0):r[5]==="-"&&(o+=Number(r[6]||0)*60+Number(r[8]||0)),o%(24*60)!==23*60+59)return!1}if(n){if(/^\d\d\d\d-02-(?:[012][1-8]|[12]0|[01]9)/.test(t))return!0;let r=t.match(/^(\d\d\d\d)-02-29/);if(!r)return!1;let o=Number(r[1]??0);return o%16===0||o%4===0&&o%25!==0}return t[8]==="3"&&t[9]==="1"?/^\d\d\d\d-(?:0[13578]|1[02])-31/.test(t):/^\d\d\d\d-(?:0[13-9]|1[012])-(?:[012][1-9]|[123]0)/.test(t)},ipv4:t=>t.length<=15&&/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)$/.test(t),ipv6:t=>{if(t.length>45||t.length<2)return!1;let e=0,n=0,r=0,o=!1,i=!1,s=0,p=!0;for(let m=0;m<t.length;m++){let f=t.charCodeAt(m);if(m===1&&s===58&&f!==58)return!1;if(f>=48&&f<=57){if(++r>4)return!1}else if(f===46){if(e>6||n>=3||r===0||i)return!1;n++,r=0}else if(f===58){if(n>0||e>=7)return!1;if(s===58){if(o)return!1;o=!0}else m===0&&(p=!1);e++,r=0,i=!1}else if(f>=97&&f<=102||f>=65&&f<=70){if(n>0||++r>4)return!1;i=!0}else return!1;s=f}if(e<2||n>0&&(n!==3||r===0))return!1;if(o&&t.length===2)return!0;if(n>0&&!/(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/.test(t))return!1;let c=n>0?6:7;return o?(p||r>0)&&e<c:e===c&&p&&r>0},uri:t=>/^[a-z][a-z0-9+\-.]*:(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\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]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i.test(t),"json-pointer":t=>/^(?:|\/(?:[^~]|~0|~1)*)$/.test(t),"relative-json-pointer":t=>/^(?:0|[1-9][0-9]*)(?:|#|\/(?:[^~]|~0|~1)*)$/.test(t),uuid:t=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t),duration:t=>t.length>1&&t.length<80&&(/^P\d+([.,]\d+)?W$/.test(t)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(t)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(t)),regex:t=>{if(/[^\\]\\Z/.test(t))return!1;try{return new RegExp(t,"u"),!0}catch{return!1}},binary:()=>!0,password:()=>!0},rt=({format:t},e,n={})=>!O(e)||!t?a():_[t]?_[t](e)?a():d(n,"format",`Expected format: ${t}`,e):a();function ft(t,e){_[t]=e}function mt(){return Object.keys(_)}var re={type:Ie,const:Re,enum:$e,allOf:Ce,anyOf:Ne,oneOf:je,not:Ee,minLength:Ue,maxLength:ze,pattern:Ae,format:rt,minimum:Ke,exclusiveMinimum:qe,maximum:Ve,exclusiveMaximum:Me,multipleOf:Je,required:Be,dependentRequired:We,dependentSchemas:Fe,minProperties:_e,maxProperties:Ye,propertyNames:Ze,properties:De,patternProperties:He,additionalProperties:Le,minItems:Qe,maxItems:Xe,uniqueItems:et,contains:tt,prefixItems:nt,items:Ge,if:ve};function ot(t,e,n={}){let r={keywordPath:n.keywordPath||[],instancePath:n.instancePath||[],coerce:n.coerce||!1,errors:n.errors||[],shortCircuit:n.shortCircuit||!1,ignoreUnsupported:n.ignoreUnsupported||!1,resolver:n.resolver||t.getResolver?.()||new R(t),depth:n.depth?n.depth+1:0,skipClone:n.skipClone||!1},o;if(n?.coerce&&t.coerce){let i=t.coerce(e,{resolver:r.resolver,depth:r.depth});o=r.skipClone?i:structuredClone(i)}else o=r.skipClone?e:structuredClone(e);if(n.ignoreUnsupported!==!0){let i=["$defs"];for(let s of i)if(t[s])throw new Error(`${s} not implemented`)}if(r.resolver.hasRef(t,o)){let i=r.resolver.resolve(t.$ref).validate(o,{...r,errors:[]});i.valid||r.errors.push(...i.errors)}else{let i={keywordPath:r.keywordPath,instancePath:r.instancePath,coerce:r.coerce,errors:[],shortCircuit:r.shortCircuit,ignoreUnsupported:r.ignoreUnsupported,resolver:r.resolver,depth:r.depth};for(let s in t)if(s==="type"&&t.type!==void 0){if(o!==void 0){let p=re[s];if(p){i.errors=[];let c=p(t,o,i);if(!c.valid){if(n.shortCircuit)return c;r.errors.push(...c.errors)}}}}else if(s in re&&t[s]!==void 0){if(o===void 0)continue;let p=re[s];if(p){i.errors=[];let c=p(t,o,i);if(!c.valid){if(n.shortCircuit)return c;r.errors.push(...c.errors)}}}}return{valid:r.errors.length===0,errors:r.errors}}var y=class{"~standard";[h];_resolver;type;$id;$ref;$schema;title;description;readOnly;writeOnly;$comment;examples;constructor(e,n){let{type:r,validate:o,coerce:i,template:s,...p}=e||{};Object.assign(this,{type:r},p),this[h]={raw:e,optional:!1,overrides:n},this["~standard"]={version:1,vendor:"jsonv-ts",validate:c=>{let m=this.validate(c);return m.valid?{value:c}:{issues:m.errors.map(f=>({message:f.error,path:te(f.instanceLocation)}))}}}}template(e,n){let r=this,o=e;if(r.const!==void 0?o=r.const:o===void 0&&(r.default!==void 0&&(o=r.default),n?.withExtendedOptional&&r.enum!==void 0&&(o=r.enum[0])),n?.withOptional!==!0&&o===void 0&&this.isOptional())return o;if(this[h].raw?.template){let s=this[h].raw.template(o,n);s!==void 0&&(o=s)}let i=this[h].overrides?.template?.(o,n);return i!==void 0&&(o=i),o}validate(e,n){let r={keywordPath:n?.keywordPath||[],instancePath:n?.instancePath||[],coerce:n?.coerce||!1,errors:n?.errors||[],shortCircuit:n?.shortCircuit||!1,ignoreUnsupported:n?.ignoreUnsupported||!1,resolver:n?.resolver||this.getResolver(),depth:n?.depth?n.depth+1:0,skipClone:n?.skipClone??!0},o=this[h].raw?.validate;if(o!==void 0){let i=o(e,r);if(!i.valid)return i}return ot(this,e,r)}coerce(e,n){let r={...n,resolver:n?.resolver||this.getResolver(),depth:n?.depth?n.depth+1:0,dropUnknown:n?.dropUnknown||!1},o=this[h].raw?.coerce;if(o!==void 0)return o(e,r);let i=this[h].overrides?.coerce?.(e,r)??e;return Pe(this,i,r)}optional(){return this[h].optional=!0,this}isOptional(){return this[h].optional}getResolver(){return this._resolver||(this._resolver=new R(this)),this._resolver}children(e){return[]}*walk({instancePath:e=[],keywordPath:n=[],data:r,maxDepth:o=Number.POSITIVE_INFINITY,...i}={}){let s=e.length===0&&r?F(r):r;if(i.includeSelf!==!1&&(yield new g(this,{instancePath:e,keywordPath:n,data:s,...i})),!(e.length>=o))for(let p of this.children(i)){let c=[...e,...p.instancePath];yield*p.schema.walk({...i,data:s,maxDepth:o,instancePath:c,keywordPath:[...n,...p.keywordPath]})}}*[Symbol.iterator](e){for(let n of this.walk(e))yield n}toJSON(){let{toJSON:e,"~standard":n,_resolver:r,...o}=this;return JSON.parse(JSON.stringify(o))}},g=class{constructor(e,n={}){this.schema=e;this.instancePath=n.instancePath||[],this.keywordPath=n.keywordPath||[],this.depth=this.instancePath.length;try{if(n.data!==void 0){let r=j(n.data,this.instancePath);e.validate(r).valid&&(this.data=r)}}catch{}}instancePath;keywordPath;data;depth;appendInstancePath(e){return this.instancePath=[...this.instancePath,...e],this}appendKeywordPath(e){return this.keywordPath=[...this.keywordPath,...e],this}setData(e){return this.data=e,this}};function $(t,e,n){return new class extends y{type=t}(e,n)}var oe=class extends y{constructor(n){super();this.bool=n}toJSON(){return this.bool}validate(n,r){return this.bool?a():d(r,"","Always fails",n)}};function E(t){return new oe(t)}var z=t=>$(t?.type,t),ie=(t,e)=>$(void 0,{...e,const:t});var Y=class extends y{type="object";properties;required;constructor(e,n){let r=[];for(let[i,s]of Object.entries(e||{}))ne(l(s),"properties must be managed schemas",s),s[h].optional||r.push(i);let o=n?.additionalProperties===!1?E(!1):n?.additionalProperties;r=r.length>0?r:void 0,super({...n,additionalProperties:o,properties:e,required:r},{template:(i,s)=>{let p=structuredClone(u(i)?i:{}),c={...p};if(this.properties)for(let[m,f]of Object.entries(this.properties)){let T=j(p,m);if(f.isOptional()&&s?.withOptional!==!0&&T===void 0&&i===void 0)continue;let P=f.template(T,s);P!==void 0&&(c[m]=P)}if(!(Object.keys(c).length===0&&!s?.withExtendedOptional))return c},coerce:(i,s)=>{let p=Object.keys(this.properties),c=F(i),m=p.length>0&&Object.values(this.properties).every(f=>!f[h].optional);if(ge(c)&&(s?.dropUnknown===!0||m)&&(c=Te(c,p)),typeof c=="string"&&c.match(/^\{/)&&(c=JSON.parse(c)),!(typeof c!="object"||c===null)){if(this.properties)for(let[f,T]of Object.entries(this.properties)){let P=c[f];P!==void 0&&(c[f]=T.coerce(P,s))}return c}}}),this.properties=e,this.required=r}strict(){return this.additionalProperties=E(!1),this[h].raw.additionalProperties=!1,this}partial(){for(let[,e]of Object.entries(this.properties))e[h].optional=!0;return this.required=void 0,this}children(e){let n=[];for(let[r,o]of Object.entries(this.properties)){let i=new g(o,e);i.appendInstancePath([r]),i.appendKeywordPath(["properties",r]),n.push(i)}return n}},N=(t,e)=>new Y(t,e),se=(t,e)=>N(t,e).strict(),ae=(t,e)=>N(t,e).partial();var H=class extends y{type="object";additionalProperties;constructor(e,n){super({...n,additionalProperties:e},{template:(r,o)=>o?.withExtendedOptional&&(r===void 0||!u(r))?{}:r}),this.additionalProperties=e}children(e){let n=[],r=new g(this.additionalProperties,e);return r.appendKeywordPath(["additionalProperties"]),n.push(r),n}},ce=(t,e)=>new H(t,e);var Z=class extends y{type="string";constructor(e){super(e,{template:(n,r)=>r?.withExtendedOptional&&(n===void 0||!O(n))?"":n,coerce:n=>S(n)?String(n):n})}toJSON(){let{pattern:e,"~standard":n,_resolver:r,...o}=this;return JSON.parse(JSON.stringify({...o,pattern:e instanceof RegExp?e.source:e}))}},J=t=>new Z(t);var it=(t,e,n)=>$(t,n,{template:(r,o)=>o?.withExtendedOptional&&(r===void 0||!S(r))?n?.minimum??0:r,coerce:r=>{if(O(r)){let o=e.parseFn(r);if(!Number.isNaN(o))return o}return r}}),V=t=>it("number",{parseFn:Number},t),M=t=>it("integer",{parseFn:Number.parseInt},t);var G=class extends y{constructor(n,r={}){super({...r,items:n},{template:o=>o===void 0||!Array.isArray(o)?[]:o,coerce:(o,i)=>{try{let s=typeof o=="string"?JSON.parse(o):o;if(!Array.isArray(s))return;if(l(this.items))for(let[p,c]of s.entries())s[p]=this.items.coerce(c,i);return s}catch{}return o}});this.items=n;this.items=n}type="array";children(n){let r=[];if(this.items){let o=new g(this.items,n);o.appendKeywordPath(["items"]),r.push(o)}return r}},K=(t,e)=>new G(t,e);var q=t=>$("boolean",t,{template:(e,n)=>n?.withExtendedOptional&&(e===void 0||!C(e))?!1:e,coerce:e=>{if(O(e)&&["true","false","1","0"].includes(e))return e==="true"||e==="1";if(S(e)){if(e===1)return!0;if(e===0)return!1}return e}});var Q=Symbol.for("unionType"),X=class extends y{[Q];constructor(e,n,r){super({...r,[n]:e},{coerce:(o,i)=>{let s=r?.coerce;if(s!==void 0)return s.bind(this)(o,i);let p=U(e,o,{ignoreUnsupported:!0,resolver:i?.resolver,coerce:!0});return p.length>0?p[0].coerce(o,i):o}}),this[Q]=n}get schemas(){return this[this[Q]]}children(e){let n=[];for(let[r,o]of this.schemas.entries()){let i=new g(o,e);i.appendKeywordPath([this[Q],r]),n.push(i)}return n}},pe=(t,e)=>new X(t,"anyOf",e),de=(t,e)=>new X(t,"oneOf",e);function st(t,e){return Array.isArray(t)?t.map(e):t!==void 0?[e(t)]:[]}function at(t,e,n=r=>r){return Object.fromEntries(Object.entries(t).map(([r,o])=>[r,n(e(o),r)]))}function k(t){if(C(t))return E(t);let e=structuredClone(t);if(!u(e))throw new W("non-object schemas not implemented",e);"properties"in e&&e.properties&&(e.properties=at(e.properties,k,(i,s)=>"required"in e&&Array.isArray(e.required)&&e.required.includes(s)?i:i.optional()));let n=["patternProperties","dependentSchemas","$defs"];for(let i of n)i in e&&e[i]&&(e[i]=at(e[i],k));let r=["additionalProperties","items","prefixItems","propertyNames","contains","not","if","then","else"];for(let i of r)i in e&&typeof e[i]<"u"&&(x(e[i])?e[i]=st(e[i],k):e[i]=k(e[i]));let o=["anyOf","oneOf","allOf"];for(let i of o)if(i in e){let{[i]:s}=e;e[i]=st(s,k)}if(we(e))switch(e.type){case"string":return J(e);case"number":return V(e);case"integer":return M(e);case"boolean":return q(e);case"object":{let{properties:i,...s}=e;return N(i,s)}case"array":{let{items:i,...s}=e;return K(i,s)}}return z(e)}var me=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),fe=t=>typeof globalThis.structuredClone=="function"?globalThis.structuredClone(t):JSON.parse(JSON.stringify(t)),lt=["maximum","exclusiveMaximum","maxLength","maxItems","maxProperties"],ht=["minimum","exclusiveMinimum","minLength","minItems","minProperties"];function yt(){return{type(e){let r=e.map(o=>Array.isArray(o)?new Set(o):new Set([o])).reduce((o,i)=>o?new Set([...o].filter(s=>i.has(s))):new Set(i));if(!r.size)throw new Error('Incompatible "type" in allOf');return r.size===1?[...r][0]:[...r]},enum(e){let n=e.map(r=>new Set(r)).reduce((r,o)=>new Set([...r].filter(i=>o.has(i))));if(!n.size)throw new Error('Incompatible "enum" in allOf');return[...n]},required(e){return[...new Set(e.flat())]},properties(e,n,r){return e.reduce((o,i)=>r(o,i),{})},patternProperties(e,n,r){return e.reduce((o,i)=>r(o,i),{})},$defs(e,n,r){return e.reduce((o,i)=>r(o,i),{})},definitions(e,n,r){return e.reduce((o,i)=>r(o,i),{})},...Object.fromEntries(lt.map(e=>[e,n=>Math.min(...n)])),...Object.fromEntries(ht.map(e=>[e,n=>Math.max(...n)]))}}function Ot(t){let e={...yt(),...t.resolvers};function n(r,o){if(Array.isArray(r)&&Array.isArray(o))return[...new Set([...r,...o])];if(me(r)&&me(o)){let i={...r};for(let[s,p]of Object.entries(o))if(s in i){let c=e[s];i[s]=c?c([i[s],p],s,n):fe(p)}else i[s]=fe(p);return i}return fe(o)}return n}var St=t=>t===!0||t===!1?t:null;function ct(t,e={}){let n=e.deep!==!1,r=Ot(e);function o(i){if(Array.isArray(i))return i.map(o);if(!me(i))return i;if(Array.isArray(i.allOf)){let p=i.allOf.map(o);if(p.some(v=>v===!1))return!1;let c=p.filter(v=>v!==!0);if(!c.length)return!0;let m=c.reduce((v,pt)=>r(v,pt),{}),f=St(m);if(f!==null)return f;let T={...i};delete T.allOf;let P=r(m,n?o(T):T);return n?o(P):P}let s={};for(let[p,c]of Object.entries(i))s[p]=o(c);return s}return o(t)}var ue=(t,e)=>{let n=JSON.parse(JSON.stringify({...e,allOf:t}));return k(ct(n))};var D=class extends y{$ref;constructor(e,n){if(!n&&!l(e))throw new Error("Ref not set");if(l(e)&&!e.$id)throw new Error("Ref must have an $id");let r=n??e?.$id;super({$ref:r},{coerce:(o,i)=>{let s=i?.resolver?.resolve(this.$ref);if(!l(s))throw new Error(`Ref not found: ${this.$ref}`);return s.coerce(o,i)}}),this.$ref=r}},le=(t,e)=>new D(t,e),he=t=>new D(void 0,t),ye=t=>t(new y({$ref:"#",coerce:(e,n)=>{let r=n?.resolver?.resolve("#");if(!l(r))throw new Error("Ref not found: #");return r.coerce(e,n)}}));var ee=class extends Error{constructor(n,r,o=[]){super(`Invalid schema given for ${JSON.stringify(r,null,2)} Error: ${JSON.stringify(o[0],null,2)}`);this.schema=n;this.value=r;this.errors=o}first(){return this.errors[0]}firstToString(){let n=this.first();return`${n.error} at ${n.instanceLocation}`}},xt=t=>{let e=t.toJSON();return k(e)};function gt(t,e,n){let r=n?.clone?xt(t):t,o=n?.coerce!==!1?r.coerce(e,{dropUnknown:n?.coerceDropUnknown??!1}):e;n?.withDefaults!==!1&&(o=r.template(o,{withOptional:!0,withExtendedOptional:n?.withExtendedDefaults??!1}));let i=t.validate(o,{shortCircuit:!0,ignoreUnsupported:!0});if(!i.valid)if(n?.onError)n.onError(i.errors);else throw new ee(r,e,i.errors);return o}var Zn={boolean:q,any:z,literal:ie,object:N,strictObject:se,partialObject:ae,record:ce,string:J,number:V,integer:M,array:K,anyOf:pe,oneOf:de,allOf:ue,ref:le,refId:he,recursive:ye};export{G as ArraySchema,ee as InvalidSchemaError,Y as ObjectSchema,H as RecordSchema,D as RefType,y as Schema,Z as StringSchema,ue as allOf,z as any,pe as anyOf,K as array,q as boolean,E as booleanSchema,d as error,k as fromSchema,mt as getFormats,M as integer,ne as invariant,l as isSchema,ie as literal,I as makeOpts,V as number,N as object,de as oneOf,gt as parse,ae as partialObject,ce as record,ye as recursive,le as ref,he as refId,ft as registerFormat,Zn as s,se as strictObject,J as string,a as valid};