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