UNPKG

sury

Version:

🧬 The fastest schema with next-gen DX

1,936 lines (1,773 loc) • 141 kB
'use strict'; function some(x) { if (x === undefined) { return { BS_PRIVATE_NESTED_SOME_NONE: 0 }; } else if (x !== null && x.BS_PRIVATE_NESTED_SOME_NONE !== undefined) { return { BS_PRIVATE_NESTED_SOME_NONE: x.BS_PRIVATE_NESTED_SOME_NONE + 1 | 0 }; } else { return x; } } function valFromOption(x) { if (!(x !== null && x.BS_PRIVATE_NESTED_SOME_NONE !== undefined)) { return x; } var depth = x.BS_PRIVATE_NESTED_SOME_NONE; if (depth === 0) { return ; } else { return { BS_PRIVATE_NESTED_SOME_NONE: depth - 1 | 0 }; } } /* No side effect */ function length$1(xs) { var _x = xs; var _acc = 0; while(true) { var acc = _acc; var x = _x; if (!x) { return acc; } _acc = acc + 1 | 0; _x = x.tl; continue ; }} function fillAux(arr, _i, _x) { while(true) { var x = _x; var i = _i; if (!x) { return ; } arr[i] = x.hd; _x = x.tl; _i = i + 1 | 0; continue ; }} function fromArray$1(a) { var _i = a.length - 1 | 0; var _res = /* [] */0; while(true) { var res = _res; var i = _i; if (i < 0) { return res; } _res = { hd: a[i], tl: res }; _i = i - 1 | 0; continue ; }} function toArray$1(x) { var len = length$1(x); var arr = new Array(len); fillAux(arr, 0, x); return arr; } /* No side effect */ // Generated by ReScript, PLEASE EDIT WITH CARE function classify(arrayable) { if (Array.isArray(arrayable)) { return { TAG: "Array", _0: arrayable }; } else { return { TAG: "Single", _0: arrayable }; } } var Arrayable = { classify: classify }; /* No side effect */ var idMap = new Map(); function create(str) { var v = idMap.get(str); var id; if (v !== undefined) { var id$1 = v + 1 | 0; idMap.set(str, id$1); id = id$1; } else { idMap.set(str, 1); id = 1; } return str + ("/" + id); } /* idMap Not a pure module */ // Generated by ReScript, PLEASE EDIT WITH CARE var immutableEmpty = {}; var immutableEmpty$1 = []; function capitalize(string) { return string.slice(0, 1).toUpperCase() + string.slice(1); } var copy = ((d) => ({...d})); function fromString(string) { var _idx = 0; while(true) { var idx = _idx; var match = string[idx]; if (match === undefined) { return "\"" + string + "\""; } switch (match) { case "\"" : case "\n" : return JSON.stringify(string); default: _idx = idx + 1 | 0; continue ; } }} function toArray(path) { if (path === "") { return []; } else { return JSON.parse(path.split("\"][\"").join("\",\"")); } } function fromLocation($$location) { return "[" + fromString($$location) + "]"; } function fromArray(array) { var len = array.length; if (len !== 1) { if (len !== 0) { return "[" + array.map(fromString).join("][") + "]"; } else { return ""; } } var $$location = array[0]; return "[" + fromString($$location) + "]"; } function concat(path, concatedPath) { return path + concatedPath; } var vendor = "sury"; var s = Symbol(vendor); var itemSymbol = Symbol(vendor + ":item"); var $$Error = /* @__PURE__ */create("Sury.Error"); var isLiteral = (s => "const" in s); function isOptional(schema) { var match = schema.type; switch (match) { case "undefined" : return true; case "union" : return schema.has["undefined"]; default: return false; } } var globalConfig = { d: undefined, a: "strip", n: false }; class SuryError extends Error { constructor(code, flag, path) { super(); this.flag = flag; this.code = code; this.path = path; } } var d = Object.defineProperty, p = SuryError.prototype; d(p, 'message', { get() { return message(this); }, }); d(p, 'reason', { get() { return reason(this); } }); d(p, 'name', {value: 'SuryError'}); d(p, 's', {value: s}); d(p, '_1', { get() { return this }, }); d(p, 'RE_EXN_ID', { value: $$Error, }); var Schema = function(type) {this.type=type;}, sp = Object.create(null); d(sp, 'with', { get() { return (fn, ...args) => fn(this, ...args) }, }); // Also has ~standard below Schema.prototype = sp; function getOrRethrow(exn) { if ((exn&&exn.s===s)) { return exn; } throw exn; } var shakenRef = "as"; var shakenTraps = { get: (function (target, prop) { var l = target[shakenRef]; if (l === undefined) { return target[prop]; } if (prop === shakenRef) { return target[prop]; } var l$1 = valFromOption(l); var message = "Schema S." + l$1 + " is not enabled. To start using it, add S.enable" + capitalize(l$1) + "() at the project root."; throw new Error("[Sury] " + message); }) }; function shaken(apiName) { var mut = new Schema("never"); mut[shakenRef] = apiName; return new Proxy(mut, shakenTraps); } var unknown = new Schema("unknown"); var bool = new Schema("boolean"); var symbol = new Schema("symbol"); var string = new Schema("string"); var $$int = new Schema("number"); $$int.format = "int32"; var $$float = new Schema("number"); var bigint = new Schema("bigint"); function has(acc, flag) { return (acc & flag) !== 0; } var flags = { unknown: 1, string: 2, number: 4, boolean: 8, undefined: 16, null: 32, object: 64, array: 128, union: 256, ref: 512, bigint: 1024, nan: 2048, "function": 4096, instance: 8192, never: 16384, symbol: 32768, }; var copyWithoutCache = ((schema) => { let c = new Schema(schema.type); for (let k in schema) { if (k > "a" || k === "$ref" || k === "$defs") { c[k] = schema[k]; } } return c }); function updateOutput(schema, fn) { var root = copyWithoutCache(schema); var mut = root; while(mut.to) { var next = copyWithoutCache(mut.to); mut.to = next; mut = next; } fn(mut); return root; } var resetCacheInPlace = ((schema) => { for (let k in schema) { if (Number(k[0])) { delete schema[k]; } } }); function stringify(unknown) { var tagFlag = flags[typeof unknown]; if (tagFlag & 16) { return "undefined"; } if (!(tagFlag & 64)) { if (tagFlag & 2) { return "\"" + unknown + "\""; } else if (tagFlag & 1024) { return unknown + "n"; } else { return unknown.toString(); } } if (unknown === null) { return "null"; } if (Array.isArray(unknown)) { var string = "["; for(var i = 0 ,i_finish = unknown.length; i < i_finish; ++i){ if (i !== 0) { string = string + ", "; } string = string + stringify(unknown[i]); } return string + "]"; } if (unknown.constructor !== Object) { return Object.prototype.toString.call(unknown); } var keys = Object.keys(unknown); var string$1 = "{ "; for(var i$1 = 0 ,i_finish$1 = keys.length; i$1 < i_finish$1; ++i$1){ var key = keys[i$1]; var value = unknown[key]; string$1 = string$1 + key + ": " + stringify(value) + "; "; } return string$1 + "}"; } function toExpression(schema) { var tag = schema.type; var $$const = schema.const; var name = schema.name; if (name !== undefined) { return name; } if ($$const !== undefined) { return stringify($$const); } var format = schema.format; var anyOf = schema.anyOf; if (anyOf !== undefined) { return anyOf.map(toExpression).join(" | "); } if (format !== undefined) { return format; } switch (tag) { case "nan" : return "NaN"; case "object" : var additionalItems = schema.additionalItems; var properties = schema.properties; var locations = Object.keys(properties); if (locations.length === 0) { if (typeof additionalItems === "object") { return "{ [key: string]: " + toExpression(additionalItems) + "; }"; } else { return "{}"; } } else { return "{ " + locations.map(function ($$location) { return $$location + ": " + toExpression(properties[$$location]) + ";"; }).join(" ") + " }"; } default: if (schema.b) { return tag; } switch (tag) { case "instance" : return schema.class.name; case "array" : var additionalItems$1 = schema.additionalItems; var items = schema.items; if (typeof additionalItems$1 !== "object") { return "[" + items.map(function (item) { return toExpression(item.schema); }).join(", ") + "]"; } var itemName = toExpression(additionalItems$1); return ( additionalItems$1.type === "union" ? "(" + itemName + ")" : itemName ) + "[]"; default: return tag; } } } var value = SuryError; function constructor(prim0, prim1, prim2) { return new SuryError(prim0, prim1, prim2); } function reason(error, nestedLevelOpt) { var nestedLevel = nestedLevelOpt !== undefined ? nestedLevelOpt : 0; var reason$1 = error.code; if (typeof reason$1 !== "object") { return "Encountered unexpected async transform or refine. Use parseAsyncOrThrow operation instead"; } switch (reason$1.TAG) { case "OperationFailed" : return reason$1._0; case "InvalidOperation" : return reason$1.description; case "InvalidType" : var unionErrors = reason$1.unionErrors; var m = "Expected " + toExpression(reason$1.expected) + ", received " + stringify(reason$1.received); if (unionErrors !== undefined) { var lineBreak = "\n" + " ".repeat((nestedLevel << 1)); var reasonsDict = {}; for(var idx = 0 ,idx_finish = unionErrors.length; idx < idx_finish; ++idx){ var error$1 = unionErrors[idx]; var reason$2 = reason(error$1, nestedLevel + 1); var nonEmptyPath = error$1.path; var $$location = nonEmptyPath === "" ? "" : "At " + nonEmptyPath + ": "; var line = "- " + $$location + reason$2; if (!reasonsDict[line]) { reasonsDict[line] = 1; m = m + lineBreak + line; } } } return m; case "UnsupportedTransformation" : return "Unsupported transformation from " + toExpression(reason$1.from) + " to " + toExpression(reason$1.to); case "ExcessField" : return "Unrecognized key \"" + reason$1._0 + "\""; case "InvalidJsonSchema" : return toExpression(reason$1._0) + " is not valid JSON"; } } function reason$1(error) { return reason(error, undefined); } function message(error) { var op = error.flag; var text = "Failed "; if (op & 2) { text = text + "async "; } text = text + ( op & 1 ? ( op & 4 ? "asserting" : "parsing" ) : "converting" ); if (op & 8) { text = text + " to JSON" + ( op & 16 ? " string" : "" ); } var nonEmptyPath = error.path; var tmp = nonEmptyPath === "" ? "" : " at " + nonEmptyPath; return text + tmp + ": " + reason(error, undefined); } var ErrorClass = { value: value, constructor: constructor, reason: reason$1, message: message }; function embed(b, value) { var e = b.g.e; var l = e.length; e[l] = value; return "e[" + l + "]"; } function inlineConst(b, schema) { var tagFlag = flags[schema.type]; var $$const = schema.const; if (tagFlag & 16) { return "void 0"; } else if (tagFlag & 2) { return fromString($$const); } else if (tagFlag & 1024) { return $$const + "n"; } else if (tagFlag & 45056) { return embed(b, schema.const); } else { return $$const; } } function inlineLocation(b, $$location) { var key = "\"" + $$location + "\""; var i = b.g[key]; if (i !== undefined) { return i; } var inlinedLocation = fromString($$location); b.g[key] = inlinedLocation; return inlinedLocation; } function secondAllocate(v) { var b = this; b.l = b.l + "," + v; } function initialAllocate(v) { var b = this; b.l = v; b.a = secondAllocate; } function rootScope(flag, defs) { var $$global = { c: "", l: "", a: initialAllocate, v: -1, o: flag, f: "", e: [], d: defs }; $$global.g = $$global; return $$global; } function allocateScope(b) { ((delete b.a)); var varsAllocation = b.l; if (varsAllocation === "") { return b.f + b.c; } else { return b.f + "let " + varsAllocation + ";" + b.c; } } function varWithoutAllocation($$global) { var newCounter = $$global.v + 1; $$global.v = newCounter; return "v" + newCounter; } function _var(_b) { return this.i; } function _notVar(b) { var val = this; var v = varWithoutAllocation(b.g); var i = val.i; if (i === "") { val.b.a(v); } else if (b.a !== (void 0)) { b.a(v + "=" + i); } else { b.c = b.c + (v + "=" + i + ";"); b.g.a(v); } val.v = _var; val.i = v; return v; } function allocateVal(b, schema) { var v = varWithoutAllocation(b.g); b.a(v); return { b: b, v: _var, i: v, f: 0, type: schema.type }; } function val(b, initial, schema) { return { b: b, v: _notVar, i: initial, f: 0, type: schema.type }; } function constVal(b, schema) { return { b: b, v: _notVar, i: inlineConst(b, schema), f: 0, type: schema.type, const: schema.const }; } function asyncVal(b, initial) { return { b: b, v: _notVar, i: initial, f: 2, type: "unknown" }; } function objectJoin(inlinedLocation, value) { return inlinedLocation + ":" + value + ","; } function arrayJoin(_inlinedLocation, value) { return value + ","; } function make(b, isArray) { return { b: b, v: _notVar, i: "", f: 0, type: isArray ? "array" : "object", properties: {}, additionalItems: "strict", j: isArray ? arrayJoin : objectJoin, c: 0, r: "" }; } function add(objectVal, $$location, val) { var inlinedLocation = inlineLocation(objectVal.b, $$location); objectVal.properties[$$location] = val; if (val.f & 2) { objectVal.r = objectVal.r + val.i + ","; objectVal.i = objectVal.i + objectVal.j(inlinedLocation, "a[" + (objectVal.c++) + "]"); } else { objectVal.i = objectVal.i + objectVal.j(inlinedLocation, val.i); } } function merge(target, subObjectVal) { var locations = Object.keys(subObjectVal.properties); for(var idx = 0 ,idx_finish = locations.length; idx < idx_finish; ++idx){ var $$location = locations[idx]; add(target, $$location, subObjectVal.properties[$$location]); } } function complete(objectVal, isArray) { objectVal.i = isArray ? "[" + objectVal.i + "]" : "{" + objectVal.i + "}"; if (objectVal.c) { objectVal.f = objectVal.f | 2; objectVal.i = "Promise.all([" + objectVal.r + "]).then(a=>(" + objectVal.i + "))"; } objectVal.additionalItems = "strict"; return objectVal; } function addKey(b, input, key, val) { return input.v(b) + "[" + key + "]=" + val.i; } function set(b, input, val) { if (input === val) { return ""; } var inputVar = input.v(b); var match = input.f & 2; var match$1 = val.f & 2; if (match) { if (!match$1) { return inputVar + "=Promise.resolve(" + val.i + ")"; } } else if (match$1) { input.f = input.f | 2; return inputVar + "=" + val.i; } return inputVar + "=" + val.i; } function get(b, targetVal, $$location) { var properties = targetVal.properties; var val = properties[$$location]; if (val !== undefined) { return val; } var schema = targetVal.additionalItems; var schema$1; if (schema === "strip" || schema === "strict") { if (schema === "strip") { throw new Error("[Sury] The schema doesn't have additional items"); } throw new Error("[Sury] The schema doesn't have additional items"); } else { schema$1 = schema; } var val$1 = { b: b, v: _notVar, i: targetVal.v(b) + ("[" + fromString($$location) + "]"), f: 0, type: schema$1.type }; properties[$$location] = val$1; return val$1; } function setInlined(b, input, inlined) { return input.v(b) + "=" + inlined; } function map(inlinedFn, input) { return { b: input.b, v: _notVar, i: inlinedFn + "(" + input.i + ")", f: 0, type: "unknown" }; } function transform(b, input, operation) { if (!(input.f & 2)) { return operation(b, input); } var bb = { c: "", l: "", a: initialAllocate, f: "", g: b.g }; var operationInput = { b: b, v: _var, i: varWithoutAllocation(bb.g), f: 0, type: "unknown" }; var operationOutputVal = operation(bb, operationInput); var operationCode = allocateScope(bb); return asyncVal(input.b, input.i + ".then(" + operationInput.v(b) + "=>{" + operationCode + "return " + operationOutputVal.i + "})"); } function raise(b, code, path) { throw new SuryError(code, b.g.o, path); } function embedSyncOperation(b, input, fn) { if (input.f & 2) { return asyncVal(input.b, input.i + ".then(" + embed(b, fn) + ")"); } else { return map(embed(b, fn), input); } } function failWithArg(b, path, fn, arg) { return embed(b, (function (arg) { return raise(b, fn(arg), path); })) + "(" + arg + ")"; } function fail(b, message, path) { return embed(b, (function () { return raise(b, { TAG: "OperationFailed", _0: message }, path); })) + "()"; } function effectCtx(b, selfSchema, path) { return { schema: selfSchema, fail: (function (message, customPathOpt) { var customPath = customPathOpt !== undefined ? customPathOpt : ""; return raise(b, { TAG: "OperationFailed", _0: message }, path + customPath); }) }; } function invalidOperation(b, path, description) { return raise(b, { TAG: "InvalidOperation", description: description }, path); } function withPathPrepend(b, input, path, maybeDynamicLocationVar, appendSafe, fn) { if (path === "" && maybeDynamicLocationVar === undefined) { return fn(b, input, path); } try { var $$catch = function (b, errorVar) { b.c = errorVar + ".path=" + fromString(path) + "+" + ( maybeDynamicLocationVar !== undefined ? "'[\"'+" + maybeDynamicLocationVar + "+'\"]'+" : "" ) + errorVar + ".path"; }; var fn$1 = function (b) { return fn(b, input, ""); }; var prevCode = b.c; b.c = ""; var errorVar = varWithoutAllocation(b.g); var maybeResolveVal = $$catch(b, errorVar); var catchCode = "if(" + (errorVar + "&&" + errorVar + ".s===s") + "){" + b.c; b.c = ""; var bb = { c: "", l: "", a: initialAllocate, f: "", g: b.g }; var fnOutput = fn$1(bb); b.c = b.c + allocateScope(bb); var isNoop = fnOutput.i === input.i && b.c === ""; if (appendSafe !== undefined) { appendSafe(b, fnOutput); } if (isNoop) { return fnOutput; } var isAsync = fnOutput.f & 2; var output = input === fnOutput ? input : ( appendSafe !== undefined ? fnOutput : ({ b: b, v: _notVar, i: "", f: isAsync ? 2 : 0, type: "unknown" }) ); var catchCode$1 = maybeResolveVal !== undefined ? (function (catchLocation) { return catchCode + ( catchLocation === 1 ? "return " + maybeResolveVal.i : set(b, output, maybeResolveVal) ) + ("}else{throw " + errorVar + "}"); }) : (function (param) { return catchCode + "}throw " + errorVar; }); b.c = prevCode + ("try{" + b.c + ( isAsync ? setInlined(b, output, fnOutput.i + ".catch(" + errorVar + "=>{" + catchCode$1(1) + "})") : set(b, output, fnOutput) ) + "}catch(" + errorVar + "){" + catchCode$1(0) + "}"); return output; } catch (exn){ var error = getOrRethrow(exn); throw new SuryError(error.code, error.flag, path + "[]" + error.path); } } function validation(b, inputVar, schema, negative) { var eq = negative ? "!==" : "==="; var and_ = negative ? "||" : "&&"; var exp = negative ? "!" : ""; var tag = schema.type; var tagFlag = flags[tag]; if (tagFlag & 2048) { return exp + ("Number.isNaN(" + inputVar + ")"); } if (isLiteral(schema)) { return inputVar + eq + inlineConst(b, schema); } if (tagFlag & 4) { return "typeof " + inputVar + eq + "\"" + tag + "\""; } if (tagFlag & 64) { return "typeof " + inputVar + eq + "\"" + tag + "\"" + and_ + exp + inputVar; } if (tagFlag & 128) { return exp + "Array.isArray(" + inputVar + ")"; } if (!(tagFlag & 8192)) { return "typeof " + inputVar + eq + "\"" + tag + "\""; } var c = inputVar + " instanceof " + embed(b, schema.class); if (negative) { return "!(" + c + ")"; } else { return c; } } function refinement(b, inputVar, schema, negative) { var eq = negative ? "!==" : "==="; var and_ = negative ? "||" : "&&"; var not_ = negative ? "" : "!"; var lt = negative ? ">" : "<"; var gt = negative ? "<" : ">"; var match = schema.type; var tag; var exit = 0; var match$1 = schema.const; if (match$1 !== undefined) { return ""; } var match$2 = schema.format; if (match$2 !== undefined) { switch (match$2) { case "int32" : return and_ + inputVar + lt + "2147483647" + and_ + inputVar + gt + "-2147483648" + and_ + inputVar + "%1" + eq + "0"; case "port" : case "json" : exit = 2; break; } } else { exit = 2; } if (exit === 2) { switch (match) { case "number" : if (globalConfig.n) { return ""; } else { return and_ + not_ + "Number.isNaN(" + inputVar + ")"; } case "array" : case "object" : tag = match; break; default: return ""; } } var additionalItems = schema.additionalItems; var items = schema.items; var length = items.length; var code = tag === "array" ? ( additionalItems === "strip" || additionalItems === "strict" ? ( additionalItems === "strip" ? and_ + inputVar + ".length" + gt + length : and_ + inputVar + ".length" + eq + length ) : "" ) : ( additionalItems === "strip" ? "" : and_ + not_ + "Array.isArray(" + inputVar + ")" ); for(var idx = 0 ,idx_finish = items.length; idx < idx_finish; ++idx){ var match$3 = items[idx]; var $$location = match$3.location; var item = match$3.schema; var itemCode; if (isLiteral(item) || schema.unnest) { var inlinedLocation = inlineLocation(b, $$location); itemCode = validation(b, inputVar + ("[" + inlinedLocation + "]"), item, negative); } else if (item.items) { var inlinedLocation$1 = inlineLocation(b, $$location); var inputVar$1 = inputVar + ("[" + inlinedLocation$1 + "]"); itemCode = validation(b, inputVar$1, item, negative) + refinement(b, inputVar$1, item, negative); } else { itemCode = ""; } if (itemCode !== "") { code = code + and_ + itemCode; } } return code; } function makeRefinedOf(b, input, schema) { var mut = { b: b, v: input.v, i: input.i, f: input.f, type: schema.type }; var loop = function (mut, schema) { if (isLiteral(schema)) { mut.const = schema.const; } var items = schema.items; if (items === undefined) { return ; } var properties = {}; items.forEach(function (item) { var schema = item.schema; var isConst = isLiteral(schema); if (!(isConst || schema.items)) { return ; } var tmp; if (isConst) { tmp = inlineConst(b, schema); } else { var inlinedLocation = inlineLocation(b, item.location); tmp = mut.v(b) + ("[" + inlinedLocation + "]"); } var mut$1 = { b: mut.b, v: _notVar, i: tmp, f: 0, type: schema.type }; loop(mut$1, schema); properties[item.location] = mut$1; }); mut.properties = properties; mut.additionalItems = unknown; }; loop(mut, schema); return mut; } function typeFilterCode(b, schema, input, path) { if (schema.noValidation || flags[schema.type] & 17153) { return ""; } var inputVar = input.v(b); return "if(" + validation(b, inputVar, schema, true) + refinement(b, inputVar, schema, true) + "){" + failWithArg(b, path, (function (input) { return { TAG: "InvalidType", expected: schema, received: input }; }), inputVar) + "}"; } function unsupportedTransform(b, from, target, path) { return raise(b, { TAG: "UnsupportedTransformation", from: from, to: target }, path); } function noopOperation(i) { return i; } function setHas(has, tag) { has[tag === "union" || tag === "ref" ? "unknown" : tag] = true; } var jsonName = "JSON"; function inputToString(b, input) { return val(b, "\"\"+" + input.i, string); } function parse(prevB, schema, inputArg, path) { var b = { c: "", l: "", a: initialAllocate, f: "", g: prevB.g }; if (schema.$defs) { b.g.d = schema.$defs; } var input = inputArg; var isFromLiteral = isLiteral(input); var isSchemaLiteral = isLiteral(schema); var isSameTag = input.type === schema.type; var schemaTagFlag = flags[schema.type]; var inputTagFlag = flags[input.type]; var isUnsupported = false; if (!(schemaTagFlag & 257 || schema.format === "json")) { if (schema.name === jsonName && !(inputTagFlag & 1)) { if (!(inputTagFlag & 14)) { if (inputTagFlag & 1024) { input = inputToString(b, input); } else { isUnsupported = true; } } } else if (isSchemaLiteral) { if (isFromLiteral) { if (input.const !== schema.const) { input = constVal(b, schema); } } else if (inputTagFlag & 2 && schemaTagFlag & 3132) { var inputVar = input.v(b); b.c = b.c + (input.i + "===\"" + schema.const + "\"||" + failWithArg(b, path, (function (input) { return { TAG: "InvalidType", expected: schema, received: input }; }), inputVar) + ";"); input = constVal(b, schema); } else { b.f = typeFilterCode(prevB, schema, input, path); input.type = schema.type; input.const = schema.const; } } else if (isFromLiteral && !isSchemaLiteral) { if (!isSameTag) { if (schemaTagFlag & 2 && inputTagFlag & 3132) { var $$const = (""+input.const); input = { b: b, v: _notVar, i: "\"" + $$const + "\"", f: 0, type: "string", const: $$const }; } else { isUnsupported = true; } } } else if (inputTagFlag & 1) { var ref = schema.$ref; if (ref !== undefined) { var defs = b.g.d; var identifier = ref.slice(8); var def = defs[identifier]; var flag = schema.noValidation ? (b.g.o | 1) ^ 1 : b.g.o; var fn = def[flag]; var recOperation; if (fn !== undefined) { var fn$1 = valFromOption(fn); recOperation = fn$1 === 0 ? embed(b, def) + ("[" + flag + "]") : embed(b, fn$1); } else { def[flag] = 0; var fn$2 = internalCompile(def, flag, b.g.d); def[flag] = fn$2; recOperation = embed(b, fn$2); } input = withPathPrepend(b, input, path, undefined, undefined, (function (param, input, param$1) { var output = map(recOperation, input); if (def.isAsync === undefined) { var defsMut = copy(defs); defsMut[identifier] = unknown; isAsyncInternal(def, defsMut); } if (def.isAsync) { output.f = output.f | 2; } return output; })); input.v(b); } else { if (b.g.o & 1) { b.f = typeFilterCode(prevB, schema, input, path); } var refined = makeRefinedOf(b, input, schema); input.type = refined.type; input.i = refined.i; input.v = refined.v; input.additionalItems = refined.additionalItems; input.properties = refined.properties; if (isLiteral(refined)) { input.const = refined.const; } } } else if (schemaTagFlag & 2 && inputTagFlag & 1036) { input = inputToString(b, input); } else if (!isSameTag) { if (inputTagFlag & 2) { var inputVar$1 = input.v(b); if (schemaTagFlag & 8) { var output = allocateVal(b, schema); b.c = b.c + ("(" + output.i + "=" + inputVar$1 + "===\"true\")||" + inputVar$1 + "===\"false\"||" + failWithArg(b, path, (function (input) { return { TAG: "InvalidType", expected: schema, received: input }; }), inputVar$1) + ";"); input = output; } else if (schemaTagFlag & 4) { var output$1 = val(b, "+" + inputVar$1, schema); var outputVar = output$1.v(b); var match = schema.format; b.c = b.c + ( match !== undefined ? "(" + refinement(b, outputVar, schema, true).slice(2) + ")" : "Number.isNaN(" + outputVar + ")" ) + ("&&" + failWithArg(b, path, (function (input) { return { TAG: "InvalidType", expected: schema, received: input }; }), inputVar$1) + ";"); input = output$1; } else if (schemaTagFlag & 1024) { var output$2 = allocateVal(b, schema); b.c = b.c + ("try{" + output$2.i + "=BigInt(" + inputVar$1 + ")}catch(_){" + failWithArg(b, path, (function (input) { return { TAG: "InvalidType", expected: schema, received: input }; }), inputVar$1) + "}"); input = output$2; } else { isUnsupported = true; } } else if (inputTagFlag & 4 && schemaTagFlag & 1024) { input = val(b, "BigInt(" + input.i + ")", schema); } else { isUnsupported = true; } } } if (isUnsupported) { unsupportedTransform(b, input, schema, path); } var refiner = schema.refiner; if (refiner !== undefined) { input = refiner(b, input, schema, path); } var to = schema.to; if (to !== undefined) { var parser = schema.parser; if (parser !== undefined) { input = parser(b, input, schema, path); } if (input.t !== true) { input = parse(b, to, input, path); } } prevB.c = prevB.c + allocateScope(b); return input; } function jsonableValidation(output, parent, path, flag) { var tagFlag = flags[output.type]; if (tagFlag & 48129 || tagFlag & 16 && parent.type !== "object") { throw new SuryError({ TAG: "InvalidJsonSchema", _0: parent }, flag, path); } if (tagFlag & 256) { output.anyOf.forEach(function (s) { jsonableValidation(s, parent, path, flag); }); return ; } if (!(tagFlag & 192)) { return ; } var additionalItems = output.additionalItems; if (additionalItems === "strip" || additionalItems === "strict") ; else { jsonableValidation(additionalItems, parent, path, flag); } var p = output.properties; if (p !== undefined) { var keys = Object.keys(p); for(var idx = 0 ,idx_finish = keys.length; idx < idx_finish; ++idx){ var key = keys[idx]; jsonableValidation(p[key], parent, path, flag); } return ; } output.items.forEach(function (item) { jsonableValidation(item.schema, output, path + ("[" + fromString(item.location) + "]"), flag); }); } function reverse(schema) { var reversedHead; var current = schema; while(current) { var mut = copyWithoutCache(current); var next = mut.to; var to = reversedHead; if (to !== undefined) { mut.to = to; } else { ((delete mut.to)); } var parser = mut.parser; var serializer = mut.serializer; if (serializer !== undefined) { mut.parser = serializer; } else { ((delete mut.parser)); } if (parser !== undefined) { mut.serializer = parser; } else { ((delete mut.serializer)); } var fromDefault = mut.fromDefault; var $$default = mut.default; if ($$default !== undefined) { mut.fromDefault = $$default; } else { ((delete mut.fromDefault)); } if (fromDefault !== undefined) { mut.default = fromDefault; } else { ((delete mut.default)); } var items = mut.items; if (items !== undefined) { var properties = {}; var newItems = new Array(items.length); for(var idx = 0 ,idx_finish = items.length; idx < idx_finish; ++idx){ var item = items[idx]; var reversed_schema = reverse(item.schema); var reversed_location = item.location; var reversed = { schema: reversed_schema, location: reversed_location }; if (item.r) { reversed.r = item.r; } properties[item.location] = reversed_schema; newItems[idx] = reversed; } mut.items = newItems; var match = mut.properties; if (match !== undefined) { mut.properties = properties; } } if (typeof mut.additionalItems === "object") { mut.additionalItems = reverse(mut.additionalItems); } var anyOf = mut.anyOf; if (anyOf !== undefined) { var has = {}; var newAnyOf = []; for(var idx$1 = 0 ,idx_finish$1 = anyOf.length; idx$1 < idx_finish$1; ++idx$1){ var s = anyOf[idx$1]; var reversed$1 = reverse(s); newAnyOf.push(reversed$1); setHas(has, reversed$1.type); } mut.has = has; mut.anyOf = newAnyOf; } var defs = mut.$defs; if (defs !== undefined) { var reversedDefs = {}; for(var idx$2 = 0 ,idx_finish$2 = Object.keys(defs).length; idx$2 < idx_finish$2; ++idx$2){ var key = Object.keys(defs)[idx$2]; reversedDefs[key] = reverse(defs[key]); } mut.$defs = reversedDefs; } reversedHead = mut; current = next; } return reversedHead; } function getOutputSchema(_schema) { while(true) { var schema = _schema; var to = schema.to; if (to === undefined) { return schema; } _schema = to; continue ; }} function internalCompile(schema, flag, defs) { var b = rootScope(flag, defs); if (flag & 8) { var output = reverse(schema); jsonableValidation(output, output, "", flag); } var input = { b: b, v: _var, i: "i", f: 0, type: "unknown" }; var output$1 = parse(b, schema, input, ""); var code = allocateScope(b); var isAsync = has(output$1.f, 2); schema.isAsync = isAsync; if (code === "" && output$1 === input && !(flag & 22)) { return noopOperation; } var inlinedOutput = flag & 4 ? "void 0" : output$1.i; if (flag & 16) { inlinedOutput = "JSON.stringify(" + inlinedOutput + ")"; } if (flag & 2 && !isAsync && !defs) { inlinedOutput = "Promise.resolve(" + inlinedOutput + ")"; } var inlinedFunction = "i=>{" + code + "return " + inlinedOutput + "}"; return new Function("e", "s", "return " + inlinedFunction)(b.g.e, s); } function isAsyncInternal(schema, defs) { try { var b = rootScope(2, defs); var input = { b: b, v: _var, i: "i", f: 0, type: "unknown" }; var output = parse(b, schema, input, ""); var isAsync = has(output.f, 2); schema.isAsync = isAsync; return isAsync; } catch (exn){ getOrRethrow(exn); return false; } } function operationFn(s, o) { if ((o in s)) { return (s[o]); } var f = internalCompile(o & 32 ? reverse(s) : s, o, 0); ((s[o] = f)); return f; } d(sp, "~standard", { get: (function () { var schema = this; return { version: 1, vendor: vendor, validate: (function (input) { try { return { value: operationFn(schema, 1)(input) }; } catch (exn){ var error = getOrRethrow(exn); return { issues: [{ message: message(error), path: error.path === "" ? undefined : toArray(error.path) }] }; } }) }; }) }); function compile(schema, input, output, mode, typeValidationOpt) { var typeValidation = typeValidationOpt !== undefined ? typeValidationOpt : true; var flag = 0; var exit = 0; switch (output) { case "Output" : case "Input" : exit = 1; break; case "Assert" : flag = flag | 4; break; case "Json" : flag = flag | 8; break; case "JsonString" : flag = flag | 24; break; } if (exit === 1 && output === input) { throw new Error("[Sury] Can't compile operation to converting value to self"); } if (mode !== "Sync") { flag = flag | 2; } if (typeValidation) { flag = flag | 1; } if (input === "Output") { flag = flag | 32; } var fn = operationFn(schema, flag); if (input !== "JsonString") { return fn; } var flag$1 = flag; return function (jsonString) { try { return fn(JSON.parse(jsonString)); } catch (exn){ throw new SuryError({ TAG: "OperationFailed", _0: exn.message }, flag$1, ""); } }; } function parseOrThrow(any, schema) { return operationFn(schema, 1)(any); } function parseJsonStringOrThrow(jsonString, schema) { var tmp; try { tmp = JSON.parse(jsonString); } catch (exn){ throw new SuryError({ TAG: "OperationFailed", _0: exn.message }, 1, ""); } return parseOrThrow(tmp, schema); } function parseAsyncOrThrow(any, schema) { return operationFn(schema, 3)(any); } function convertOrThrow(input, schema) { return operationFn(schema, 0)(input); } function convertToJsonOrThrow(any, schema) { return operationFn(schema, 8)(any); } function convertToJsonStringOrThrow(input, schema) { return operationFn(schema, 24)(input); } function convertAsyncOrThrow(any, schema) { return operationFn(schema, 2)(any); } function reverseConvertOrThrow(value, schema) { return operationFn(schema, 32)(value); } function reverseConvertToJsonOrThrow(value, schema) { return operationFn(schema, 40)(value); } function reverseConvertToJsonStringOrThrow(value, schema, spaceOpt) { var space = spaceOpt !== undefined ? spaceOpt : 0; return JSON.stringify(reverseConvertToJsonOrThrow(value, schema), null, space); } function assertOrThrow(any, schema) { return operationFn(schema, 5)(any); } var $$undefined = new Schema("undefined"); $$undefined.const = (void 0); var $$null = new Schema("null"); $$null.const = null; function parse$1(value) { if (value === null) { return $$null; } var $$typeof = typeof value; var schema; if ($$typeof === "object") { var i = new Schema("instance"); i.class = value.constructor; schema = i; } else { schema = $$typeof === "undefined" ? $$undefined : ( $$typeof === "number" ? ( Number.isNaN(value) ? new Schema("nan") : new Schema($$typeof) ) : new Schema($$typeof) ); } schema.const = value; return schema; } function isAsync(schema) { var v = schema.isAsync; if (v !== undefined) { return v; } else { return isAsyncInternal(schema, 0); } } function wrapExnToFailure(exn) { if ((exn&&exn.s===s)) { return { success: false, error: exn }; } throw exn; } function js_safe(fn) { try { return { success: true, value: fn() }; } catch (exn){ return wrapExnToFailure(exn); } } function js_safeAsync(fn) { try { return fn().then((function (value) { return { success: true, value: value }; }), wrapExnToFailure); } catch (exn){ return Promise.resolve(wrapExnToFailure(exn)); } } function make$1(namespace, name) { return "m:" + namespace + ":" + name; } function internal(name) { return "m:" + name; } var Id = { make: make$1, internal: internal }; function get$1(schema, id) { return schema[id]; } function set$1(schema, id, metadata) { var mut = copyWithoutCache(schema); mut[id] = metadata; return mut; } var defsPath = "#/$defs/"; function recursive(name, fn) { var ref = defsPath + name; var refSchema = new Schema("ref"); refSchema.$ref = ref; refSchema.name = name; var isNestedRec = globalConfig.d; if (!isNestedRec) { globalConfig.d = {}; } var def = fn(refSchema); if (def.name) { refSchema.name = def.name; } else { def.name = name; } globalConfig.d[name] = def; if (isNestedRec) { return refSchema; } var schema = new Schema("ref"); schema.name = def.name; schema.$ref = ref; schema.$defs = globalConfig.d; globalConfig.d = undefined; return schema; } function noValidation(schema, value) { var mut = copyWithoutCache(schema); mut.noValidation = value; return mut; } function internalRefine(schema, refiner) { return updateOutput(schema, (function (mut) { var prevRefiner = mut.refiner; mut.refiner = (function (b, input, selfSchema, path) { return transform(b, prevRefiner !== undefined ? prevRefiner(b, input, selfSchema, path) : input, (function (b, input) { var rCode = refiner(b, input.v(b), selfSchema, path); b.c = b.c + rCode; return input; })); }); })); } function refine(schema, refiner) { return internalRefine(schema, (function (b, inputVar, selfSchema, path) { return embed(b, refiner(effectCtx(b, selfSchema, path))) + "(" + inputVar + ");"; })); } function addRefinement(schema, metadataId, refinement, refiner) { var refinements = schema[metadataId]; return internalRefine(set$1(schema, metadataId, refinements !== undefined ? refinements.concat(refinement) : [refinement]), refiner); } function transform$1(schema, transformer) { return updateOutput(schema, (function (mut) { mut.parser = (function (b, input, selfSchema, path) { var match = transformer(effectCtx(b, selfSchema, path)); var parser = match.p; if (parser !== undefined) { if (match.a !== undefined) { return invalidOperation(b, path, "The S.transform doesn't allow parser and asyncParser at the same time. Remove parser in favor of asyncParser"); } else { return embedSyncOperation(b, input, parser); } } var asyncParser = match.a; if (asyncParser !== undefined) { if (!(b.g.o & 2)) { raise(b, "UnexpectedAsync", ""); } var val = embedSyncOperation(b, input, asyncParser); val.f = val.f | 2; return val; } else if (match.s !== undefined) { return invalidOperation(b, path, "The S.transform parser is missing"); } else { return input; } }); var to = new Schema("unknown"); mut.to = (to.serializer = (function (b, input, selfSchema, path) { var match = transformer(effectCtx(b, selfSchema, path)); var serializer = match.s; if (serializer !== undefined) { return embedSyncOperation(b, input, serializer); } else if (match.a !== undefined || match.p !== undefined) { return invalidOperation(b, path, "The S.transform serializer is missing"); } else { return input; } }), to); ((delete mut.isAsync)); })); } var nullAsUnit = new Schema("null"); nullAsUnit.const = null; nullAsUnit.to = $$undefined; function neverBuilder(b, input, selfSchema, path) { b.c = b.c + failWithArg(b, path, (function (input) { return { TAG: "InvalidType", expected: selfSchema, received: input }; }), input.i) + ";"; return input; } var never = new Schema("never"); never.refiner = neverBuilder; function getItemCode(b, schema, input, output, deopt, path) { try { var globalFlag = b.g.o; if (deopt) { b.g.o = globalFlag | 1; } var bb = { c: "", l: "", a: initialAllocate, f: "", g: b.g }; var input$1 = deopt ? copy(input) : makeRefinedOf(bb, input, schema); var itemOutput = parse(bb, schema, input$1, path); if (itemOutput !== input$1) { itemOutput.b = bb; if (itemOutput.f & 2) { output.f = output.f | 2; } bb.c = bb.c + (output.v(b) + "=" + itemOutput.i); } b.g.o = globalFlag; return allocateScope(bb); } catch (exn){ return "throw " + embed(b, getOrRethrow(exn)); } } function isPriority(tagFlag, byKey) { if (tagFlag & 8320 && byKey["object"]) { return true; } else if (tagFlag & 2048) { return byKey["number"]; } else { return false; } } function isWiderUnionSchema(schemaAnyOf, inputAnyOf) { return inputAnyOf.every(function (inputSchema, idx) { var schema = schemaAnyOf[idx]; if (schema !== undefined && !(flags[inputSchema.type] & 9152) && inputSchema.type === schema.type) { return inputSchema.const === schema.const; } else { return false; } }); } function refiner(b, input, selfSchema, path) { var schemas = selfSchema.anyOf; var inputAnyOf = input.anyOf; if (inputAnyOf !== undefined) { if (isWiderUnionSchema(schemas, inputAnyOf)) { return input; } else { return unsupportedTransform(b, input, selfSchema, path); } } var fail = function (caught) { return embed(b, (function (param) { var args = arguments; return raise(b, { TAG: "InvalidType", expected: selfSchema, received: args[0], unionErrors: args.length > 1 ? Array.from(args).slice(1) : undefined }, path); })) + "(" + input.v(b) + caught + ")"; }; var typeValidation = b.g.o & 1; var initialInline = input.i; var deoptIdx = -1; var lastIdx = schemas.length - 1 | 0; var byKey = {}; var keys = []; for(var idx = 0; idx <= lastIdx; ++idx){ var target = selfSchema.to; var schema = target !== undefined && !selfSchema.parser && target.type !== "union" ? updateOutput(schemas[idx], (function(target){ return function (mut) { mut.to = target; } }(target))) : schemas[idx]; var tag = schema.type; var tagFlag = flags[tag]; if (!(tagFlag & 16 && selfSchema["fromDefault"])) { if (tagFlag & 17153 || !(flags[input.type] & 1) && input.type !== tag) { deoptIdx = idx; byKey = {}; keys = []; } else { var key = tagFlag & 8192 ? schema.class.name : tag; var arr = byKey[key]; if (arr !== undefined) { if (!