from-schema
Version:
Infer TypeScript types from JSON schemas
483 lines (454 loc) • 40.2 kB
JavaScript
(function(s,$){typeof exports=="object"&&typeof module<"u"?$(exports):typeof define=="function"&&define.amd?define(["exports"],$):(s=typeof globalThis<"u"?globalThis:s||self,$(s["From Schema"]={}))})(this,function(s){"use strict";var Te=Object.defineProperty;var Oe=(s,$,m)=>$ in s?Te(s,$,{enumerable:!0,configurable:!0,writable:!0,value:m}):s[$]=m;var O=(s,$,m)=>(Oe(s,typeof $!="symbol"?$+"":$,m),m);const $=e=>({type:"object",..."description"in e?{description:e.description}:{},properties:Object.fromEntries(Object.entries(e.properties).map(([t,r])=>[t,y(r)])),..."required"in e?{required:e.required}:{},..."minProperties"in e?{minProperties:e.minProperties}:{},..."maxProperties"in e?{maxProperties:e.maxProperties}:{},..."examples"in e?{examples:e.examples}:{}}),m=e=>{const t={type:"string",...e};return delete t.bsonType,t},T=e=>{const t={...e};return delete t.bsonType,t},B=e=>({type:"number",...T(e)}),_=e=>({type:"array",...T(e),items:y(e.items)}),F=e=>({enum:e.enum.map(t=>y(t))}),D=e=>({type:"boolean",...T(e)}),ne=e=>({type:"string",pattern:"^[0-9a-f]{24}$"}),ie=e=>({type:"string",format:"date-time"}),oe=e=>({oneOf:e.oneOf.map(t=>y(t))}),ae=e=>({allOf:e.allOf.map(t=>y(t))}),se=e=>({anyOf:e.anyOf.map(t=>y(t))}),q=e=>e instanceof Date&&!isNaN(e.getTime()),h=(e,t="",r=new Set)=>{if(e===null)return"null";if(typeof e=="object"&&e!==null){if(r.has(e))throw new Error("Circular reference detected during stringification");r.add(e)}switch(typeof e){case"string":{let n=e;return n=n.replace(/\\/g,"\\\\"),n=n.replace(/"/g,'\\"'),n.includes(`
`)&&(n=n.replace(/\n/g,"\\n")),n.includes("\r")&&(n=n.replace(/\r/g,"\\r")),n.includes(" ")&&(n=n.replace(/\t/g,"\\t")),n.includes("\f")&&(n=n.replace(/\f/g,"\\f")),n.includes("\b")&&(n=n.replace(/\b/g,"\\b")),`"${n}"`}case"undefined":return"undefined";case"number":return isNaN(e)?"NaN":isFinite(e)?e.toString():e<0?"-Infinity":"Infinity";case"boolean":return e.toString();case"symbol":case"function":return e.toString();case"bigint":return e.toString()+"n";case"object":if(Array.isArray(e)){const n=[];for(let l=0;l<e.length;l++)l in e?n.push(h(e[l],t,r)):n.push("undefined");return`[${n.join(", ")}]`}if(q(e))return`new Date("${e.toISOString()}")`;if(e instanceof Error){const n={};e.message&&(n.message=e.message),e.name&&(n.name=e.name),e.stack&&(n.stack=e.stack);for(const p of Object.keys(e))n[p]=e[p];const l=Object.entries(n).map(([p,o])=>{const a=`"${p.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`,c=h(o,t,r);return`${a}: ${c}`}).join(", ");return r.delete(e),`{${l}}`}const i=Object.entries(e).map(([n,l])=>{const p=`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`,o=h(l,t,r);return`${p}: ${o}`}).join(", ");return r.delete(e),`{${i}}`}throw new Error("Unsupported type: "+typeof e)};class d extends Error{constructor(r,i){super(`${r} at position ${i}`);O(this,"position");this.position=i}}const ue=1e4,z=1e8,U=1e8;function le(e){const t=[];let r=0;const i=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?Z/;if(i.test(e))return t.push({type:"string",value:e,position:0}),t;for(;r<e.length;){const n=e[r];if(/\s/.test(n)){r++;continue}if(n==="{"){t.push({type:"object_start",value:"{",position:r}),r++;continue}if(n==="}"){t.push({type:"object_end",value:"}",position:r}),r++;continue}if(n==="["){t.push({type:"array_start",value:"[",position:r}),r++;continue}if(n==="]"){t.push({type:"array_end",value:"]",position:r}),r++;continue}if(n===":"){t.push({type:"colon",value:":",position:r}),r++;continue}if(n===","){t.push({type:"comma",value:",",position:r}),r++;continue}if(n==='"'){let o="",a=r;for(r++;r<e.length;){const c=e[r];if(c==="\\"&&r+1<e.length){const f=e[r+1];if(f==='"'){o+='"',r+=2;continue}o+=c+f,r+=2;continue}if(c==='"'){r++;break}o+=c,r++}t.push({type:"string",value:o,position:a});continue}const p=e.substring(r).match(i);if(p&&p.index===0){const o=p[0];t.push({type:"string",value:o,position:r}),r+=o.length;continue}if(e.startsWith("true",r)){t.push({type:"true",value:"true",position:r}),r+=4;continue}if(e.startsWith("false",r)){t.push({type:"false",value:"false",position:r}),r+=5;continue}if(e.startsWith("null",r)){t.push({type:"null",value:"null",position:r}),r+=4;continue}if(e.startsWith("undefined",r)){t.push({type:"undefined",value:"undefined",position:r}),r+=9;continue}if(/[\d.-]/.test(n)){let o="",a=r,c=!1;for(;r<e.length;){const f=e[r];if(f==="n"){c=!0,r++;break}if(/[\d.e+-]/.test(f)){o+=f,r++;continue}break}c?t.push({type:"bigint",value:o,position:a}):t.push({type:"number",value:o,position:a});continue}throw new d(`Unexpected character '${n}'`,r)}return t}function x(e,t=0,r=0){var n,l,p,o,a,c,f,g,X,Q,Y,k,ee,te,re;if(r>ue)throw new d("Maximum nesting depth exceeded",((n=e[t])==null?void 0:n.position)||-1);if(t>=e.length)throw new d("Unexpected end of input",-1);const i=e[t];switch(i.type){case"string":if(i.value.length>z)throw new d(`String length exceeds maximum allowed (${z})`,i.position);return{value:i.value,nextIdx:t+1};case"number":{const u=Number(i.value);if(!Number.isFinite(u)&&!Number.isNaN(u))throw new d(`Invalid number value: ${i.value}`,i.position);return{value:u,nextIdx:t+1}}case"bigint":try{return{value:BigInt(i.value),nextIdx:t+1}}catch{throw new d(`Invalid BigInt value: ${i.value}`,i.position)}case"true":return{value:!0,nextIdx:t+1};case"false":return{value:!1,nextIdx:t+1};case"null":return{value:null,nextIdx:t+1};case"undefined":return{value:void 0,nextIdx:t+1};case"object_start":{let u=t+1;const A={};let v=0;if(u<e.length&&e[u].type==="object_end")return{value:{},nextIdx:u+1};for(;u<e.length;){if(v>1e5)throw new d("Object contains too many properties",i.position);if(((l=e[u])==null?void 0:l.type)!=="string")throw new d(`Expected string key, got ${((p=e[u])==null?void 0:p.type)||"undefined"}`,((o=e[u])==null?void 0:o.position)||-1);const V=e[u].value;if(V==="__proto__"||V==="constructor"||V==="prototype")throw new d(`Potentially unsafe property name: ${V}`,e[u].position);if(u++,u>=e.length||((a=e[u])==null?void 0:a.type)!=="colon")throw new d('Expected ":"',u<e.length&&((c=e[u])==null?void 0:c.position)||-1);u++;const{value:Ve,nextIdx:Ae}=x(e,u,r+1);if(A[V]=Ve,u=Ae,v++,u>=e.length)throw new d("Unexpected end of input",-1);if(((f=e[u])==null?void 0:f.type)==="object_end")return{value:A,nextIdx:u+1};if(((g=e[u])==null?void 0:g.type)!=="comma")throw new d(`Expected "," or "}", got ${((X=e[u])==null?void 0:X.type)||"undefined"}`,((Q=e[u])==null?void 0:Q.position)||-1);u++}throw new d("Unexpected end of input",-1)}case"array_start":{let u=t+1;const A=[];if(u<e.length&&((Y=e[u])==null?void 0:Y.type)==="array_end")return{value:[],nextIdx:u+1};for(;u<e.length;){if(A.length>1e7)throw new d("Array contains too many elements",i.position);const{value:v,nextIdx:V}=x(e,u,r+1);if(A.push(v),u=V,u>=e.length)throw new d("Unexpected end of input",-1);if(((k=e[u])==null?void 0:k.type)==="array_end")return{value:A,nextIdx:u+1};if(((ee=e[u])==null?void 0:ee.type)!=="comma")throw new d(`Expected "," or "]", got ${((te=e[u])==null?void 0:te.type)||"undefined"}`,((re=e[u])==null?void 0:re.position)||-1);u++}throw new d("Unexpected end of input",-1)}default:throw new d(`Unexpected token type: ${i.type}`,i.position)}}function ce(e){return/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?Z$/.test(e)}function S(e){if(e==null)return e;if(typeof e=="string"&&ce(e)){const t=new Date(e);if(q(t))return t}if(Array.isArray(e))return e.map(S);if(typeof e=="object"){const t={};for(const[r,i]of Object.entries(e))t[r]=S(i);return t}return e}const J=e=>{try{if(e==null)throw new Error("Input cannot be null or undefined");if(typeof e!="string")throw new Error("Input must be a string");if(e.length===0)throw new Error("Empty input");if(e.length>U)throw new Error(`Input exceeds maximum allowed length (${U})`);const t=le(e);if(t.length===0)throw new Error("No valid tokens found in input");const{value:r,nextIdx:i}=x(t,0,0);if(i<t.length)throw new d(`Unexpected token after end of BON: ${t[i].type}`,t[i].position);return S(r)}catch(t){throw t instanceof d?new Error(`BON parse error: ${t.message}`):t}},pe=e=>typeof e=="string"?J(e):null,fe=Object.freeze(Object.defineProperty({__proto__:null,bigint:{type:"bigint",description:"Any bigint"},boolean:{type:"boolean",description:"Either true or false"},date:{type:"date",description:"Any date"},natural:{type:"integer",description:"Any natural number",minimum:1},number:{type:"number",description:"Any number, should probably be constrained at some point"},string:{type:"string",description:"Some text i guess lmao"}},Symbol.toStringTag,{value:"Module"})),y=e=>{if(typeof e=="string"||typeof e=="boolean"||typeof e=="number")return e;if(typeof e=="object"){if("enum"in e)return F(e);if("oneOf"in e)return oe(e);if("allOf"in e)return ae(e);if("anyOf"in e)return se(e);if("bsonType"in e)switch(e.bsonType){case"array":return _(e);case"object":return $(e);case"string":return m(e);case"decimal":case"int":case"long":case"double":return B(e);case"bool":return D(e);case"objectId":return ne();case"date":return ie();default:throw new Error(`Unsupported bsonType: ${e.bsonType}`)}throw new Error(`Invalid BSON schema: object must have either "enum" or "bsonType" property: ${h(e)}`)}throw new Error("Invalid BSON schema: unexpected type")},de=e=>({type:"number",...T(e)});function $e(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const b=e=>{if(typeof e=="string")return`"${e}"`;if(typeof e=="boolean"||typeof e=="number")return e.toString();if(typeof e=="object"){if("enum"in e)return`${e.enum.map(t=>b(t)).join(" | ")}`;if("oneOf"in e)return`(${e.oneOf.map(t=>b(t)).join(" | ")})`;if("allOf"in e)return`(${e.allOf.map(t=>b(t)).join(" & ")})`;if("anyOf"in e)return`(${e.anyOf.map(t=>b(t)).join(" | ")})`;if("type"in e)switch(e.type){case"array":return`Array<${b(e.items)}>`;case"object":{const t=Object.entries(e.properties),r="required"in e?e.required:[];return`{ ${t.map(([i,n])=>`${i}${r.includes(i)?"":"?"}: ${b(n)}`).join("; ")} }`}case"string":return"string";case"boolean":return"boolean";case"integer":return"number";case"number":return"number";default:throw new Error(`Unknown type: ${e.type}`)}throw new Error(`Unknown json object schema: ${e}`)}throw new Error(`Unknown bson schema type ${typeof e}: ${e}`)},ge=Object.freeze(Object.defineProperty({__proto__:null,boolean:{type:"boolean",description:"Either true or false"},date:{type:"string",format:"date-time"},email:{type:"string",format:"email"},integer:{type:"integer",description:"Any integer"},natural:{type:"integer",description:"Any natural number",minimum:1},number:{type:"number",description:"Any number, should probably be constrained at some point"},string:{type:"string",description:"Some text i guess lmao"},uid:{type:"string",pattern:"^[0-9a-f]{24}$",description:"MongoDB UID (24 character hex string)"},uuidv4:{type:"string",pattern:"^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$",description:"UUID v4 (36 character hex string)"},uuidv5:{type:"string",pattern:"^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$",description:"UUID v5 (36 character hex string)"},whole:{type:"integer",description:"Any whole number",minimum:0}},Symbol.toStringTag,{value:"Module"})),me=Object.freeze(Object.defineProperty({__proto__:null,bool:{bsonType:"bool",description:"Either true or false"},date:{bsonType:"date",description:"BSON Date"},double:{bsonType:"double",description:"A double-precision floating point number"},email:{bsonType:"string",format:"email"},int:{bsonType:"int",description:"Any integer"},long:{bsonType:"long",description:"Any number, should probably be constrained at some point"},natural:{bsonType:"long",description:"Any natural number",minimum:1},objectId:{bsonType:"objectId",description:"BSON ObjectId"},string:{bsonType:"string",description:"Some text i guess lmao"},uid:{bsonType:"string",pattern:"^[0-9a-f]{24}$",description:"MongoDB UID (24 character hex string)"},uuidv4:{bsonType:"string",pattern:"^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$",description:"UUID v4 (36 character hex string)"},uuidv5:{bsonType:"string",pattern:"^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$",description:"UUID v5 (36 character hex string)"},whole:{bsonType:"long",description:"Any whole number",minimum:0}},Symbol.toStringTag,{value:"Module"})),w=e=>{if(typeof e=="string")return`"${e}"`;if(typeof e=="boolean"||typeof e=="number")return e.toString();if(typeof e=="object"){if("enum"in e)return`${e.enum.map(t=>w(t)).join(" | ")}`;if("oneOf"in e)return`(${e.oneOf.map(t=>w(t)).join(" | ")})`;if("allOf"in e)return`(${e.allOf.map(t=>w(t)).join(" & ")})`;if("anyOf"in e)return`(${e.anyOf.map(t=>w(t)).join(" | ")})`;if("bsonType"in e)switch(e.bsonType){case"array":return`Array<${w(e.items)}>`;case"object":{const t=Object.entries(e.properties),r="required"in e?e.required:[];return`{ ${t.map(([i,n])=>`${i}${r.includes(i)?"":"?"}: ${w(n)}`).join("; ")} }`}case"string":return"string";case"bool":return"boolean";case"int":return"number";case"long":return"number";case"double":return"number";case"decimal":return"number";case"date":return"Date";default:throw new Error(`Unknown bsonType: ${e.bsonType}`)}throw new Error(`Unknown bson object schema: ${e}`)}throw new Error(`Unknown bson schema type ${typeof e}: ${e}`)},I=e=>{if(!e.type)throw new Error(`erm ${h(e)}`);switch(e.type){case"enum":return e;case"array":return{...e,items:I(e.items)};case"char":case"character":case"bpchar":case"text":case"varchar":case"character varying":return{...e,type:"string"};case"bool":case"boolean":return{...e,type:"boolean"};case"int8":case"bigint":case"bigserial":case"serial8":return{...e,type:"bigint",...e.default?{default:e.default==="nextval"?-1n:e.default}:{}};case"double precision":case"float8":case"int":case"smallint":case"int2":case"int4":case"integer":case"money":case"serial":case"serial4":case"smallserial":case"serial2":case"numeric":return{...e,type:"number",...typeof e.default<"u"?{default:e.default==="nextval"?-1:e.default}:{}};case"date":case"timestamp":case"timestamptz":return{...e,type:"date"};case"jsonb":return e.schema??{type:"object",properties:{},required:[]};default:throw console.log("Invalid model",e),new Error(`Unknown type: ${e.type} on ${h(e)}`)}},be=(e,t)=>{const r=Object.entries(e.properties),i="required"in e?e.required:[],n=t?i.filter(l=>"default"in e||"generated"in e):i;return{type:"object",properties:Object.fromEntries(r.map(([l,p])=>[l,I(p)])),required:n}};class he{constructor(t="generated"){O(this,"indent","");O(this,"messages",new Set);O(this,"enums",new Set);this.packageName=t}incrementIndent(){this.indent+=" "}decrementIndent(){this.indent=this.indent.slice(2)}typeToProto(t){return t.type==="enum"||t.enum?"enum":{string:"string",text:"string",number:"double",integer:"int32",boolean:"bool",bigint:"int64",bigserial:"int64",object:"message",array:"repeated"}[t.type]||"string"}generateEnum(t,r){const i=[`enum ${t} {`];return this.incrementIndent(),r.forEach((n,l)=>{const p=n.toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^[0-9]/,"_$&");i.push(`${this.indent}${p} = ${l};`)}),this.decrementIndent(),i.push("}"),i.join(`
`)}generateMessage(t,r){if(r.type==="enum"||r.enum){const o=r.enum||[],a=this.generateEnum(t,o);return this.enums.add(a),""}const i=[`message ${t} {`];this.incrementIndent();let n=1;const l=r.properties||{};for(const[o,a]of Object.entries(l)){let c=this.typeToProto(a),f="";if(c==="enum"){const g=`${t}${o.charAt(0).toUpperCase()}${o.slice(1)}Enum`;this.enums.add(this.generateEnum(g,a.enum)),f=`${this.indent}${g} ${o} = ${n};`}else if(c==="message"){const g=`${t}${o.charAt(0).toUpperCase()}${o.slice(1)}`;this.generateMessage(g,a),f=`${this.indent}${g} ${o} = ${n};`}else if(c==="repeated"){const g=this.typeToProto(a.items);f=`${this.indent}repeated ${g} ${o} = ${n};`}else f=`${this.indent}${c} ${o} = ${n};`;i.push(f),n++}this.decrementIndent(),i.push("}");const p=i.join(`
`);return this.messages.add(p),p}generateSchema(t){this.messages.clear(),this.enums.clear();for(const[i,n]of Object.entries(t)){const l=i.charAt(0).toUpperCase()+i.slice(1);this.generateMessage(l,n)}return['syntax = "proto3";',"",`package ${this.packageName};`,"",'import "google/protobuf/timestamp.proto";',"",...Array.from(this.enums),"",...Array.from(this.messages)].join(`
`)}}const E=e=>{if(typeof e=="string")return`"${e}"`;if(typeof e=="boolean"||typeof e=="number"||typeof e=="bigint")return e.toString();if(typeof e=="object"){if("$ref"in e)return e.$ref,"any";if("enum"in e)return`${e.enum.map(t=>E(t)).join(" | ")}`;if("oneOf"in e)return`(${e.oneOf.map(t=>E(t)).join(" | ")})`;if("allOf"in e)return`(${e.allOf.map(t=>E(t)).join(" & ")})`;if("anyOf"in e)return`(${e.anyOf.map(t=>E(t)).join(" | ")})`;if("type"in e)switch(e.type){case"array":return`Array<${E(e.items)}>`;case"object":{const t=e.properties?Object.entries(e.properties):[],r="required"in e?e.required:[];return`{ ${t.map(([i,n])=>`${i}${r.includes(i)?"":"?"}: ${E(n)}`).join("; ")} }`}case"string":return"string";case"boolean":return"boolean";case"integer":case"number":return"number";case"bigint":return"bigint";case"date":return"Date";default:throw new Error(`Unknown type: ${e.type}`)}throw new Error(`Unknown tson schema: ${JSON.stringify(e,null,4)}`)}throw new Error(`Unknown tson schema type ${typeof e}: ${e}`)},N=e=>{switch(e.type){case"enum":return`${e.enum.map(t=>`'${t}'`).join(" | ")}`;case"array":return`Array<${N(e.items)}>`;case"char":case"character":case"bpchar":case"text":case"varchar":case"character varying":return"string";case"bool":case"boolean":return"boolean";case"int8":case"bigint":return"bigint";case"int":case"smallint":case"int2":case"int4":case"integer":case"double precision":case"float8":case"money":return"number";case"bigserial":case"serial8":return"Generated<bigint>";case"serial":case"serial4":case"serial2":case"smallserial":return"Generated<number>";case"date":case"timestamp":case"timestamptz":return"Date";case"jsonb":return e.schema?b(e.schema):"unknown";default:throw new Error(`Unknown type: ${e.type}`)}},ye=e=>{const t=Object.entries(e.properties),r="required"in e?e.required:[];return`{ ${t.map(([i,n])=>`${i}${r.includes(i)?"":"?"}: ${N(n)}`).join("; ")} }`};function P(e,t){const r={};let i="",n="",l="";for(const[o,a]of Object.entries(t.properties||{})){const c=`${e}["${o}"]`;r[o]=j(c,a),i+=`
if ("${o}" in ${e}) {
try {
${r[o].validateOrThrow}
} catch (error) {
throw new Error(\`Property "${o}": \${error.message}\`);
}
}
`,n+=`
if ("${o}" in ${e}) {
const propResult = (() => {
${r[o].isValid}
return true;
})();
if (propResult !== true) {
return \`Property "${o}": \${propResult}\`;
}
}
`,l+=`
if ("${o}" in ${e}) {
const propErrors = [];
{
let allErrors = propErrors;
${r[o].validate}
}
for (const error of propErrors) {
allErrors.push(\`Property "${o}": \${error}\`);
}
}
`}const p="required"in t?t.required:[];return{validateOrThrow:`
if (typeof ${e} !== 'object' || ${e} === null || Array.isArray(${e})) {
throw new Error('Value must be an object');
}
for (const prop of ${JSON.stringify(p)}) {
if (!(prop in ${e})) {
throw new Error(\`Missing required property: \${prop}\`);
}
}
${i}
`,isValid:`
if (typeof ${e} !== 'object' || ${e} === null || Array.isArray(${e})) {
return 'Value must be an object';
}
for (const prop of ${JSON.stringify(p)}) {
if (!(prop in ${e})) {
return \`Missing required property: \${prop}\`;
}
}
${n}`,validate:`
if (typeof ${e} !== 'object' || ${e} === null || Array.isArray(${e})) {
allErrors.push('Value must be an object');
} else {
for (const prop of ${JSON.stringify(p)}) {
if (!(prop in ${e})) {
allErrors.push(\`Missing required property: \${prop}\`);
}
}
${l}
}`}}const we={date:/^\d{4}-\d{2}-\d{2}$/,time:/^([0-1][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\.\d+)?(Z|[+-]\d{2}:[0-5][0-9])?$/,"date-time":/^\d{4}-\d{2}-\d{2}T([0-1][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\.\d+)?(Z|[+-]\d{2}:[0-5][0-9])?$/,email:/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,hostname:/^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,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]|\\.|\[(?:[^\]\\]|\\.)*\]|\((?:[^)\\]|\\.)*\)|\{(?:[^}\\]|\\.)*\})+|[?*+{}()[\]\\|/])$/};function M(e,t){var o;if("const"in t){const a=t.const,c=`
if (typeof ${e} !== "string") throw new Error("Value must be a string");
else if (${e} !== "${a}") throw new Error('Expected "${a}", got "' + ${e} + '"');
`,f=`
if (typeof ${e} !== "string") return "Value must be a string";
else if (${e} !== "${a}") return 'Expected "${a}", got "' + ${e} + '"';
`;return{validate:`
if (typeof ${e} !== "string") {
allErrors.push("Value must be a string");
}
else if (${e} !== "${a}") {
allErrors.push('Expected "${a}", got "' + ${e} + '"');
}
`,validateOrThrow:c,isValid:f}}const r=[],i=[];if(t.minLength!==void 0&&(r.push(`if (${e}.length < ${t.minLength}) return "String must be at least ${t.minLength} characters long";`),i.push(`if (${e}.length < ${t.minLength}) throw new Error("String must be at least ${t.minLength} characters long");`)),t.maxLength!==void 0&&(r.push(`if (${e}.length > ${t.maxLength}) return "String must be at most ${t.maxLength} characters long";`),i.push(`if (${e}.length > ${t.maxLength}) throw new Error("String must be at most ${t.maxLength} characters long");`)),t.format!==void 0){const a=we[t.format];if(a){const c=((o=a.toString().match(/\/([gimuy]*)$/))==null?void 0:o[1])||"",f=a.toString().slice(1,-1-(c.length?c.length+1:0)).replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$");r.push(`if (!new RegExp("${f}", "${c}").test(${e})) return "String must be a valid ${t.format} format";`),i.push(`if (!new RegExp("${f}", "${c}").test(${e})) throw new Error("String must be a valid ${t.format} format");`)}}t.pattern!==void 0&&(r.push(`if (!new RegExp("${t.pattern}").test(${e})) return "String must match pattern: ${t.pattern}";`),i.push(`if (!new RegExp("${t.pattern}").test(${e})) throw new Error("String must match pattern: ${t.pattern}");`));const n=`
if (typeof ${e} !== "string") throw new Error("Value must be a string");
${i.reduce((a,c)=>a+" else "+c,"")}
`,l=`
if (typeof ${e} !== "string") return "Value must be a string";
${r.reduce((a,c)=>a+" else "+c,"")}
`;return{validate:`
if (typeof ${e} !== "string") {
allErrors.push("Value must be a string");
} else {
${r.map(a=>a.replace("return","allErrors.push(").replace(/;$/,");")).join(`
`)}
}
`,validateOrThrow:n,isValid:l}}function Z(e,t){if("const"in t){const n=t.const;return{validateOrThrow:`
if (typeof ${e} !== 'boolean') throw new Error("Expected boolean, got " + typeof ${e});
if (${e} !== ${n}) throw new Error("Expected ${n}, got " + ${e});
`,isValid:`
if (typeof ${e} !== 'boolean') return "Expected boolean, got " + typeof ${e};
if (${e} !== ${n}) return "Expected ${n}, got " + ${e};
`,validate:`
if (typeof ${e} !== 'boolean') allErrors.push("Expected boolean, got " + typeof ${e});
else if (${e} !== ${n}) allErrors.push("Expected ${n}, got " + ${e});
`}}const r=t.default!==void 0,i=t.default;return{validateOrThrow:`
${r?`if (typeof ${e} === 'undefined') return ${JSON.stringify(i)};`:""}
if(typeof ${e} !== 'boolean') throw new Error("Expected boolean, got " + typeof ${e});
return ${e};
`,isValid:`
${r?`if (typeof ${e} === 'undefined') {} else`:""}
if (typeof ${e} !== 'boolean')
return "Expected boolean, got " + typeof ${e};
`,validate:`
${r?`if (typeof ${e} === 'undefined') {} else`:""}
if (typeof ${e} !== 'boolean') {
allErrors.push("Expected boolean, got " + typeof ${e});
}
`}}function C(e,t){if("const"in t){const o=t.const,a=`
let numValue = ${e};
if (typeof ${e} === "string") {
numValue = Number(${e});
if (isNaN(numValue)) {
throw new Error("Value must be a valid number");
}
} else if (typeof ${e} !== "number") {
throw new Error("Value must be a number");
}
if (numValue !== ${o}) throw new Error("Expected ${o}, got " + numValue);
`,c=`
let numValue = ${e};
if (typeof ${e} === "string") {
numValue = Number(${e});
if (isNaN(numValue)) {
return "Value must be a valid number";
}
} else if (typeof ${e} !== "number") {
return "Value must be a number";
}
if (numValue !== ${o}) return "Expected ${o}, got " + numValue;
`;return{validate:`
let numValue = ${e};
if (typeof ${e} === "string") {
numValue = Number(${e});
if (isNaN(numValue)) {
allErrors.push("Value must be a valid number");
} else if (numValue !== ${o}) {
allErrors.push("Expected ${o}, got " + numValue);
}
} else if (typeof ${e} !== "number") {
allErrors.push("Value must be a number");
} else if (numValue !== ${o}) {
allErrors.push("Expected ${o}, got " + numValue);
}
`,validateOrThrow:a,isValid:c}}const r=[];t.minimum!==void 0&&r.push(`if (numValue < ${t.minimum}) return "Value must be greater than or equal to ${t.minimum}";`),t.maximum!==void 0&&r.push(`if (numValue > ${t.maximum}) return "Value must be less than or equal to ${t.maximum}";`);const i=`
let numValue = ${e};
if (typeof ${e} === "string") {
numValue = Number(${e});
if (isNaN(numValue)) {
return "Value must be a valid number";
}
} else if (typeof ${e} !== "number") {
return "Value must be a number";
}
${t.type==="integer"?`if (!Number.isInteger(numValue)) {
return "Value must be an integer";
}`:""}
`,n=`
${i.replace(/return "(.*?)";/g,'throw new Error("$1");')}
${r.map(o=>o.replace(/return "(.*?)";/g,'throw new Error("$1");')).join(`
`)}
`,l=`
${i}
${r.join(`
`)}
`;return{validate:`
let numValue = ${e};
if (typeof ${e} === "string") {
numValue = Number(${e});
if (isNaN(numValue)) {
allErrors.push("Value must be a valid number");
} else {
${t.type==="integer"?`if (!Number.isInteger(numValue)) {
allErrors.push("Value must be an integer");
} else {`:""}
${r.map(o=>o.replace(/return "(.*?)";/,'allErrors.push("$1");')).join(" else ")}
${t.type==="integer"?"}":""}
}
} else if (typeof ${e} !== "number") {
allErrors.push("Value must be a number");
} else {
${t.type==="integer"?`if (!Number.isInteger(${e})) {
allErrors.push("Value must be an integer");
} else {`:""}
${r.map(o=>o.replace(/numValue/g,e).replace(/return "(.*?)";/,'allErrors.push("$1");')).join(" else ")}
${t.type==="integer"?"}":""}
}
`,validateOrThrow:n,isValid:l}}function R(e,t){if("const"in t){const o=t.const,a=`
let bigintValue = ${e};
if (typeof ${e} === "string") {
try {
bigintValue = BigInt(${e});
} catch {
throw new Error("Value must be a bigint");
}
} else if (typeof ${e} !== "bigint") {
throw new Error("Value must be a bigint");
}
if (bigintValue !== ${o}n) throw new Error("Expected ${o}, got " + bigintValue);
`,c=`
let bigintValue = ${e};
if (typeof ${e} === "string") {
try {
bigintValue = BigInt(${e});
} catch {
return "Value must be a bigint";
}
} else if (typeof ${e} !== "bigint") {
return "Value must be a bigint";
}
if (bigintValue !== ${o}n) return "Expected ${o}, got " + bigintValue;
`;return{validate:`
let bigintValue = ${e};
let hasError = false;
if (typeof ${e} === "string") {
try {
bigintValue = BigInt(${e});
} catch {
allErrors.push("Value must be a bigint");
hasError = true;
}
} else if (typeof ${e} !== "bigint") {
allErrors.push("Value must be a bigint");
hasError = true;
}
if (!hasError && bigintValue !== ${o}n) {
allErrors.push("Expected ${o}, got " + bigintValue);
}
`,validateOrThrow:a,isValid:c}}const r=[];if(t.minimum!==void 0){const o=t.minimum.toString();r.push(`if (bigintValue < ${o}n) return "Value must be greater than or equal to ${o}";`)}if(t.maximum!==void 0){const o=t.maximum.toString();r.push(`if (bigintValue > ${o}n) return "Value must be less than or equal to ${o}";`)}const i=`
let bigintValue = ${e};
if (typeof ${e} === "string") {
try {
bigintValue = BigInt(${e});
} catch {
return "Value must be a bigint";
}
} else if (typeof ${e} !== "bigint") {
return "Value must be a bigint";
}
`,n=`
${i.replace(/return "(.*?)";/g,'throw new Error("$1");')}
${r.map(o=>o.replace(/return "(.*?)";/g,'throw new Error("$1");')).join(`
`)}
`,l=`
${i}
${r.join(`
`)}
`;return{validate:`
let bigintValue = ${e};
let hasError = false;
if (typeof ${e} === "string") {
try {
bigintValue = BigInt(${e});
} catch {
allErrors.push("Value must be a bigint");
hasError = true;
}
} else if (typeof ${e} !== "bigint") {
allErrors.push("Value must be a bigint");
hasError = true;
}
if (!hasError) {
${r.map(o=>o.replace(/return "(.*?)";/,'allErrors.push("$1");')).join(" else ")}
}
`,validateOrThrow:n,isValid:l}}function L(e,t){const r="default"in t,i=r?JSON.stringify(t.default):void 0,n=t.enum.map(p=>JSON.stringify(p)).join(", "),l=t.enum.join(", ");return{isValid:`
if (${e} === undefined) {
${r?"return true;":'return "Expected string, got undefined";'}
} else if (typeof ${e} !== "string") {
return "Expected string, got " + typeof ${e};
} else if (![${n}].includes(${e})) {
return "Value must be one of: ${l}";
}`,validateOrThrow:`
if (${e} === undefined) {
${r?`return ${i};`:'throw new Error("Expected string, got undefined");'}
} else if (typeof ${e} !== "string") {
throw new Error("Expected string, got " + typeof ${e});
} else if (![${n}].includes(${e})) {
throw new Error("Value must be one of: ${l}");
} else {
return ${e};
}`,validate:`
if (${e} === undefined) {
${r?"":'allErrors.push("Expected string, got undefined");'}
} else if (typeof ${e} !== "string") {
allErrors.push("Expected string, got " + typeof ${e});
} else if (![${n}].includes(${e})) {
allErrors.push("Value must be one of: ${l}");
}`}}const G=e=>btoa(e).replace(/=/g,"");function K(e,t){const r=t.oneOf.map(a=>j(e,a)),i="Value must match one of the allowed schemas",n=G(e),l=`
let anyMatch_${n} = false;
${r.reduce((a,c,f)=>`
try {
${c.validateOrThrow};
anyMatch_${n} = true;
} catch {${a}}`,"")}
if (!anyMatch_${n}) {
throw new Error("${i}");
}
`,p=`
let anyMatch_${n} = false;
${r.map((a,c)=>`
if (typeof (()=>{${a.isValid}})() !== 'string') {
anyMatch_${n} = true;
}`).join(" else ")}
if(!anyMatch_${n}) return "${i}";
`;return{validate:`
let anyMatch_${n} = false;
${r.map((a,c)=>`
{
const tempErrors = [];
{
let allErrors = tempErrors;
${a.validate}
}
if (tempErrors.length === 0) {
anyMatch_${n} = true;
}
}
`).join("")}
if (!anyMatch_${n}) {
allErrors.push("${i}");
}
`,validateOrThrow:l,isValid:p}}const W=(e,t)=>{if("const"in t){const n=t.const.getTime();return{validateOrThrow:`
if (!(${e} instanceof Date)) {
throw new Error("Value must be a Date");
}
if (isNaN(${e}.getTime())) throw new Error("Value must be a valid Date");
if (${e}.getTime() !== ${n}) throw new Error('Expected ' + new Date(${n}).toISOString() + ', got ' + ${e}.toISOString());
`,isValid:`
if (!(${e} instanceof Date)) {
return "Value must be a Date";
}
if (isNaN(value.getTime())) return "Value must be a valid Date";
if (${e}.getTime() !== ${n}) return 'Expected ' + new Date(${n}).toISOString() + ', got ' + value.toISOString();
`,validate:`
if (!(${e} instanceof Date)) {
allErrors.push("Value must be a Date");
}
if (isNaN(value.getTime())) {
allErrors.push("Value must be a valid Date");
}
if (${e}.getTime() !== ${n}) allErrors.push('Expected ' + new Date(${n}).toISOString() + ', got ' + ${e}.toISOString());
`}}const r=[];if("minimum"in t&&t.minimum!==void 0){const n=t.minimum.getTime();r.push(`if (${e}.getTime() < ${n}) return 'Date must be greater than or equal to ' + new Date(${n}).toISOString();`)}if("maximum"in t&&t.maximum!==void 0){const n=t.maximum.getTime();r.push(`if (${e}.getTime() > ${n}) return 'Date must be less than or equal to ' + new Date(${n}).toISOString();`)}const i=`
if (!(${e} instanceof Date)) {
return "Value must be a Date";
}
if (isNaN(${e}.getTime())) return "Value must be a valid Date";
`;return{validateOrThrow:`
${i.replace(/return "(.*?)";/g,'throw new Error("$1");')}
${r.map(n=>n.replace(/return "(.*?)";/g,'throw new Error("$1");')).join(`
`)}
`,isValid:`
${i}
${r.join(`
`)}
`,validate:`
if (!(${e} instanceof Date)) {
allErrors.push("Value must be a Date");
}
else if (isNaN(${e}.getTime())) {
allErrors.push("Value must be a valid Date");
}
${r.map(n=>n.replace(/return "(.*?)";/,'allErrors.push("$1");')).join(`
`)}
`}};function j(e,t){switch(typeof t){case"string":case"number":case"boolean":case"bigint":{const r=t;return{validate:`
if(${e} !== ${JSON.stringify(r)})
allErrors.push('Expected ${typeof t=="string"?`"${t}"`:t}, got ' + ${e})
`,validateOrThrow:`
if (${e} !== ${JSON.stringify(r)}) {
throw new Error('Expected ${typeof t=="string"?`"${t}"`:t}, got ' + ${e});
}
`,isValid:`
if(${e} !== ${JSON.stringify(r)})
return 'Expected ${typeof t=="string"?`"${t}"`:t}, got ' + ${e}
`}}}if(Array.isArray(t)){const r=t;return{validate:`
${e} === ${JSON.stringify(r)} ? [] : allErrors.push('Expected ${t}, got ' + ${e})`,validateOrThrow:`
if (${e} !== ${JSON.stringify(r)}) {
throw new Error('Expected ${t}, got ' + ${e});
}
`,isValid:`
${e} === ${JSON.stringify(r)} ? true : 'Expected ${t}, got ' + ${e}`}}if("enum"in t)return L(e,t);if("oneOf"in t)return K(e,t);switch("type"in t&&t.type){case"array":return H(e,t);case"object":return P(e,t);case"string":return M(e,t);case"bigint":return R(e,t);case"number":case"integer":return C(e,t);case"boolean":return Z(e,t);case"date":return W(e,t);default:throw new Error(`Invalid schema: ${JSON.stringify(t,null,4)}`)}}function H(e,t){const r=G(e)+"_item",i=j(r,t.items),n=`
if (!Array.isArray(${e})) {
allErrors.push('Value must be an array');
} else {
${t.minItems!==void 0?`
if (${e}.length < ${t.minItems}) {
allErrors.push(\`Array length \${${e}.length} is less than minimum length ${t.minItems}\`);
}
`:""}
${t.maxItems!==void 0?`
if (${e}.length > ${t.maxItems}) {
allErrors.push(\`Array length \${${e}.length} exceeds maximum length ${t.maxItems}\`);
}
`:""}
for (let i = 0; i < ${e}.length; i++) {
const ${r} = ${e}[i];
const itemErrors = [];
{
let allErrors = itemErrors;
${i.validate}
}
for (const error of itemErrors) {
allErrors.push(\`Invalid item at index \${i}: \${error}\`);
}
}
}
`,l=`
if (!Array.isArray(${e})) {
throw new Error('Value must be an array');
}
${t.minItems!==void 0?`
if (${e}.length < ${t.minItems}) {
throw new Error(\`Array length \${${e}.length} is less than minimum length ${t.minItems}\`);
}
`:""}
${t.maxItems!==void 0?`
if (${e}.length > ${t.maxItems}) {
throw new Error(\`Array length \${${e}.length} exceeds maximum length ${t.maxItems}\`);
}
`:""}
for (let i = 0; i < ${e}.length; i++) {
const ${r} = ${e}[i];
try {
${i.validateOrThrow}
} catch (error) {
throw new Error(\`Invalid item at index \${i}: \${error.message}\`);
}
}
`,p=`
if (!Array.isArray(${e})) {
return 'Value must be an array';
}
${t.minItems!==void 0?`
if (${e}.length < ${t.minItems}) {
return \`Array length \${${e}.length} is less than minimum length ${t.minItems}\`;
}
`:""}
${t.maxItems!==void 0?`
if (${e}.length > ${t.maxItems}) {
return \`Array length \${${e}.length} exceeds maximum length ${t.maxItems}\`;
}
`:""}
for (let i = 0; i < ${e}.length; i++) {
const ${r} = ${e}[i];
const itemResult = (() => {
${i.isValid}
return true;
})();
if (itemResult !== true) {
return \`Invalid item at index \${i}: \${itemResult}\`;
}
}
`;return{validate:n,validateOrThrow:l,isValid:p}}class Ee extends Error{constructor(t){super(t),this.name="ValidationError"}}s.ProtoGenerator=he,s.ValidationError=Ee,s.arrayBsonToJson=_,s.booleanBsonToJson=D,s.bsonPrimitives=me,s.bsonToJson=y,s.bsonToType=w,s.buildArrayValidator=H,s.buildBigintValidator=R,s.buildBooleanValidator=Z,s.buildDateValidator=W,s.buildEnumValidator=L,s.buildNumberValidator=C,s.buildObjectValidator=P,s.buildOneOfValidator=K,s.buildStringValidator=M,s.buildValidator=j,s.enumBsonToJson=F,s.isObject=$e,s.jsonPrimitives=ge,s.jsonToType=b,s.numberBsonToJson=B,s.objectBsonToJson=$,s.parseBON=J,s.parsePossibleBON=pe,s.postgresColumnToKysely=N,s.postgresColumnToTson=I,s.postgresRecordToKysely=ye,s.postgresRecordToTson=be,s.stringBsonToJson=m,s.stringifyBON=h,s.stripBsonType=T,s.tsonPrimitives=fe,s.tsonToType=E,s.wholeBsonToJson=de,Object.defineProperty(s,Symbol.toStringTag,{value:"Module"})});