UNPKG

sury

Version:

🧬 The fastest schema with next-gen DX

1,944 lines (1,793 loc) • 164 kB
'use strict'; // 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 }; } } let Arrayable = { classify: classify }; /* No side effect */ 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; } let 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) { let _x = xs; let _acc = 0; while (true) { let acc = _acc; let x = _x; if (x === 0) { return acc; } _acc = acc + 1 | 0; _x = x.tl; continue; }} function fillAux(arr, _i, _x) { while (true) { let x = _x; let i = _i; if (x === 0) { return; } arr[i] = x.hd; _x = x.tl; _i = i + 1 | 0; continue; }} function fromArray$1(a) { let _i = a.length - 1 | 0; let _res = /* [] */0; while (true) { let res = _res; let i = _i; if (i < 0) { return res; } _res = { hd: a[i], tl: res }; _i = i - 1 | 0; continue; }} function toArray$1(x) { let len = length$1(x); let arr = new Array(len); fillAux(arr, 0, x); return arr; } /* No side effect */ function getOr$1(opt, $$default) { if (opt !== undefined) { return valFromOption(opt); } else { return $$default; } } /* No side effect */ let idMap = {}; function create(str) { let v = idMap[str]; if (v !== undefined) { let id = v + 1 | 0; idMap[str] = id; return str + ("/" + id); } idMap[str] = 1; return str; } /* No side effect */ // Generated by ReScript, PLEASE EDIT WITH CARE let immutableEmpty = {}; let immutableEmpty$1 = []; let copy = ((d) => ({...d})); function fromString(string) { let _idx = 0; while (true) { let idx = _idx; let 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) { let len = array.length; if (len !== 1) { if (len !== 0) { return array.map(fromLocation).join(""); } else { return ""; } } else { return `[` + fromString(array[0]) + `]`; } } function concat(path, concatedPath) { return path + concatedPath; } let vendor = "sury"; let s = Symbol(vendor); let itemSymbol = Symbol(vendor + ":item"); let stringTag = "string"; let numberTag = "number"; let bigintTag = "bigint"; let booleanTag = "boolean"; let symbolTag = "symbol"; let nullTag = "null"; let undefinedTag = "undefined"; let nanTag = "nan"; let functionTag = "function"; let instanceTag = "instance"; let arrayTag = "array"; let objectTag = "object"; let unionTag = "union"; let neverTag = "never"; let unknownTag = "unknown"; let refTag = "ref"; let Exn = /* @__PURE__ */create("Sury.Exn"); let constField = "const"; function isOptional(schema) { if (schema.type === undefinedTag) { return true; } else if (schema.type === unionTag) { return undefinedTag in schema.has; } else { return false; } } function has(acc, flag) { return (acc & flag) !== 0; } let flags = { [unknownTag]: 1, [stringTag]: 2, [numberTag]: 4, [booleanTag]: 8, [undefinedTag]: 16, [nullTag]: 32, [objectTag]: 64, [arrayTag]: 128, [unionTag]: 256, [refTag]: 512, [bigintTag]: 1024, [nanTag]: 2048, ["function"]: 4096, [instanceTag]: 8192, [neverTag]: 32768, [symbolTag]: 16384, }; function stringify(unknown) { let tagFlag = flags[typeof unknown]; if (tagFlag & 16) { return undefinedTag; } if (!(tagFlag & 64)) { if (tagFlag & 2) { return `"` + unknown + `"`; } else if (tagFlag & 1024) { return unknown + `n`; } else if (tagFlag & 4096) { return `Function`; } else { return unknown.toString(); } } if (unknown === null) { return nullTag; } if (Array.isArray(unknown)) { let string = "["; for (let 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); } let keys = Object.keys(unknown); let string$1 = "{ "; for (let i$1 = 0, i_finish$1 = keys.length; i$1 < i_finish$1; ++i$1) { let key = keys[i$1]; let value = unknown[key]; string$1 = string$1 + key + `: ` + stringify(value) + `; `; } return string$1 + "}"; } function toExpression(schema) { let tag = schema.type; let to = schema.to; let $$const = schema.const; let name = schema.name; if (name !== undefined) { return name; } if ($$const !== undefined) { return stringify($$const); } let format = schema.format; let anyOf = schema.anyOf; if (anyOf !== undefined) { return anyOf.map(toExpression).join(" | "); } if (format !== undefined) { if (format !== "compactColumns") { return format; } let additionalItems = schema.additionalItems; if (to === undefined) { if (additionalItems !== undefined && additionalItems !== "strip" && additionalItems !== "strict") { return toExpression(additionalItems) + `[]`; } else { return "unknown[][]"; } } let props = to.properties; if (props === undefined) { return "unknown[][]"; } let keys = Object.keys(props); return `[` + keys.map(key => { let propSchema = props[key]; return toExpression(propSchema) + `[]`; }).join(", ") + `]`; } switch (tag) { case "nan" : return "NaN"; case "object" : let additionalItems$1 = schema.additionalItems; let properties = schema.properties; let locations = Object.keys(properties); if (locations.length === 0) { if (typeof additionalItems$1 === objectTag) { return `{ [key: string]: ` + toExpression(additionalItems$1) + `; }`; } else { return `{}`; } } else { return `{ ` + locations.map(location => location + `: ` + toExpression(properties[location]) + `;`).join(" ") + ` }`; } default: if (schema.b) { return tag; } switch (tag) { case "instance" : return schema.class.name; case "array" : let additionalItems$2 = schema.additionalItems; let items = schema.items; if (typeof additionalItems$2 !== objectTag) { return `[` + items.map(toExpression).join(", ") + `]`; } let itemName = toExpression(additionalItems$2); return ( additionalItems$2.type === unionTag ? `(` + itemName + `)` : itemName ) + "[]"; default: return tag; } } } class SuryError extends Error { constructor(params) { super(); for (let key in params) { this[key] = params[key]; } } } var d = Object.defineProperty, p = SuryError.prototype; d(p, 'message', { get() { return message(this); }, }); d(p, 'name', {value: 'SuryError'}); d(p, 's', {value: s}); d(p, '_1', { get() { return this }, }); d(p, 'RE_EXN_ID', { value: Exn, }); var seq = 1; var Schema = function() {}, 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; } function message(error) { let nonEmptyPath = error.path; let tmp = nonEmptyPath === "" ? "" : `Failed at ` + nonEmptyPath + `: `; return tmp + error.reason; } let globalConfig = { m: message, d: undefined, a: "strip", f: 0 }; let valueOptions = {}; let configurableValueOptions = {configurable: true}; let valKey = "value"; let reversedKey = "r"; function base(tag, selfReverse) { let s = new Schema(); s.type = tag; s.seq = (seq++); if (selfReverse) { valueOptions[valKey] = s; d(s, reversedKey, valueOptions); } return s; } function noopDecoder(input) { return input; } let factoryCache = {}; function cached(key, tag, init) { if (factoryCache[key]) { return factoryCache[key]; } let s = base(tag, true); init(s); factoryCache[key] = s; return s; } let unknown = base(unknownTag, true); unknown.decoder = noopDecoder; let copySchema = ((schema) => { let c = new Schema(); for (let k in schema) { c[k] = schema[k]; } c.seq = seq++; return c }); function updateOutput(schema, fn) { let root = copySchema(schema); let mut = root; while (mut.to) { let next = copySchema(mut.to); mut.to = next; mut = next; } fn(mut); return root; } let $$class = SuryError; function make(prim) { return new SuryError(prim); } let $$Error = { $$class: $$class, make: make }; function embed(b, value) { let e = b.g.e; let l = e.length; e[l] = value; return `e[` + l + `]`; } function inlineConst(b, schema) { let tagFlag = flags[schema.type]; let $$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 & 28672) { return embed(b, schema.const); } else { return $$const; } } function inlineLocation(global, location) { let key = `"` + location + `"`; let i = global[key]; if (i !== undefined) { return i; } let inlinedLocation = fromString(location); global[key] = inlinedLocation; return inlinedLocation; } function _var() { return this.i; } function _bondVar() { let val = this; let bond = val.b; return bond.v(); } function _prevVar() { let val = this; let prev = val.prev; return prev.v(); } function varWithoutAllocation(global) { let newCounter = global.v + 1; global.v = newCounter; return `v` + newCounter; } function hoistDecl(owner, decl) { owner.hd = owner.hd === "" ? decl : owner.hd + "," + decl; } function _notVarBeforeValidation() { let val = this; let v = varWithoutAllocation(val.g); val.cp = `let ` + v + `=` + val.i + `;`; val.i = v; val.v = _var; return v; } function _notVarAtParent() { let val = this; let parent = val.p; if (parent.fz) { val.v = _var; return val.i; } let v = varWithoutAllocation(val.g); hoistDecl(parent, v + `=` + val.i); val.v = _var; val.i = v; return v; } function _notVar() { let val = this; if (val.fz) { val.v = _var; val.i = `(` + val.i + `)`; return val.i; } let v = varWithoutAllocation(val.g); let match = val.prev; if (match !== undefined) { let i = val.i; if (i === "") { val.cp = `let ` + v + `;` + val.cp; } else { val.cp = val.cp + (`let ` + v + `=` + i + `;`); } } else { let i$1 = val.i; if (i$1 === "") { hoistDecl(val, v); } else { hoistDecl(val, v + `=` + i$1); } } val.v = _var; val.i = v; return v; } function operationArg(schema, expected, flag, defs) { return { v: _var, i: "i", s: schema, e: expected, f: 0, cp: "", hd: "", path: "", g: { v: -1, o: flag, e: [], d: defs } }; } function unsupportedDecode(b, from, target) { let errorDetails_0 = b.path; let errorDetails_1 = `Can't decode ` + toExpression(from) + ` to ` + toExpression(target) + `. Use S.to to define a custom decoder`; let errorDetails = { code: "unsupported_decode", path: errorDetails_0, reason: errorDetails_1, from: from, to: target }; throw new SuryError(errorDetails); } function failWithArg(b, fn, arg) { return embed(b, arg => { let errorDetails = fn(arg); throw new SuryError(errorDetails); }) + `(` + arg + `)`; } function makeInvalidConversionDetails(input, to, cause) { if ((cause&&cause.s===s)) { if (!cause["p"]) { cause.path = input.path + cause.path; } return cause; } let tmp; if ((cause instanceof Error)) { let text = ("" + cause); tmp = text.startsWith("Error: ") ? text.slice(7) : text; } else { tmp = stringify(cause); } return { code: "invalid_conversion", path: input.path, reason: tmp, from: input.s, to: to, cause: cause }; } function makeInvalidInputDetails(expected, received, path, input, includeInput, unionErrors, reasonOverride) { let reasonRef = reasonOverride !== undefined ? reasonOverride : `Expected ` + toExpression(expected) + `, received ` + ( includeInput ? stringify(input) : toExpression(received) ); if (unionErrors !== undefined) { let reasonsDict = {}; for (let idx = 0, idx_finish = unionErrors.length; idx < idx_finish; ++idx) { let caseError = unionErrors[idx]; let caseReason = caseError.reason.split("\n").join("\n "); let nonEmptyPath = caseError.path; let location = nonEmptyPath === "" ? "" : `At ` + nonEmptyPath + `: `; let line = `\n- ` + location + caseReason; if (!reasonsDict[line]) { reasonsDict[line] = 1; reasonRef = reasonRef + line; } } } let details = { code: "invalid_input", path: path, reason: reasonRef, expected: expected, received: received, unionErrors: unionErrors }; if (includeInput) { details.input = input; } return details; } function invalidInputBuilder(expected, $staropt$star, reasonOverride, $staropt$star$1) { return input => { let extraPath = $staropt$star !== undefined ? $staropt$star : ""; let includeInput = $staropt$star$1 !== undefined ? $staropt$star$1 : true; let expected$1 = expected !== undefined ? expected : input.e; let p = input.prev; let received = p !== undefined ? p.s : input.s; let path = extraPath === "" ? input.path : input.path + extraPath; return value => makeInvalidInputDetails(expected$1, received, path, value, includeInput, undefined, reasonOverride); }; } function failInvalidType(input) { let em = input.e.errorMessage; let override; if (em !== undefined) { let m = em["type"]; override = m !== undefined ? m : em["_"]; } else { override = undefined; } return invalidInputBuilder(undefined, undefined, override, undefined)(input); } function failWithErrorMessage(key, defaultMessage) { return input => { let em = input.e.errorMessage; let override; if (em !== undefined) { let m = em[key]; override = m !== undefined ? m : em["_"]; } else { override = undefined; } let m$1; if (override !== undefined) { m$1 = override; } else { if (defaultMessage === undefined) { return failInvalidType(input); } m$1 = defaultMessage; } return invalidInputBuilder(undefined, undefined, m$1, undefined)(input); }; } function embedInvalidInput(input, expectedOpt) { let expected = expectedOpt !== undefined ? expectedOpt : input.e; return failWithArg(input, invalidInputBuilder(expected, undefined, undefined, undefined)(input), input.v()); } function emitChecks(val, inputVar) { let checks = val.vc; let len = checks.length; if (len === 1) { let check = checks[0]; return check.c(inputVar) + `||` + failWithArg(val, check.f(val), inputVar) + `;`; } let out = ""; let i = 0; while (i < len) { let head = checks[i]; let fail = head.f; let cond = head.c(inputVar); i = i + 1 | 0; while (i < len && checks[i].f === fail) { cond = cond + "&&" + checks[i].c(inputVar); i = i + 1 | 0; } out = out + (cond + `||` + failWithArg(val, fail(val), inputVar) + `;`); } return out; } function isHoistable(val) { if (val.t === true) { if (val.prev.t !== true) { return val.cp === ""; } else { return false; } } else { return true; } } function merge(val, hoistCond) { let current = val; let code = ""; while (current !== undefined) { let val$1 = current; current = val$1.prev; let currentCode = ""; if (val$1.vc) { if (hoistCond !== undefined && isHoistable(val$1)) { let prev = current; let inputVar = prev.v(); let allChecks = val$1.vc; let localHoist = ""; for (let i = 0, i_finish = allChecks.length; i < i_finish; ++i) { let check = allChecks[i]; let condCode = check.c(inputVar); if (check.f === failInvalidType) { localHoist = localHoist ? localHoist + `&&` + condCode : condCode; } else if (val$1.e.noValidation !== true) { currentCode = currentCode + (condCode + `||` + failWithArg(val$1, check.f(val$1), inputVar) + `;`); } } if (localHoist) { if (hoistCond.contents) { hoistCond.contents = localHoist + `&&` + hoistCond.contents; } else { hoistCond.contents = localHoist; } } } else if (val$1.e.noValidation !== true) { let prev$1 = current; currentCode = emitChecks(val$1, prev$1.v()); } } if (val$1.hd !== "") { currentCode = currentCode + (`let ` + val$1.hd + `;`); } val$1.fz = true; currentCode = val$1.cp + currentCode; code = currentCode + code; } return code; } function next(prev, initial, schema, expectedOpt) { let expected = expectedOpt !== undefined ? expectedOpt : prev.e; return { v: _notVar, i: initial, s: schema, e: expected, prev: prev, f: 0, d: prev.d, cp: "", hd: "", t: true, path: prev.path, g: prev.g }; } function refine(val, schemaOpt, checks, expectedOpt) { let schema = schemaOpt !== undefined ? schemaOpt : val.s; let expected = expectedOpt !== undefined ? expectedOpt : val.e; let shouldLink = val.v !== _var; let nextVal = { v: shouldLink ? _prevVar : _var, i: val.i, s: schema, e: expected, prev: val, f: val.f, d: val.d, cp: "", hd: "", vc: checks, t: val.t, path: val.path, g: val.g }; if (shouldLink) { let valVar = (val.v.bind(val)); val.v = () => { let v = valVar(); nextVal.i = v; nextVal.v = _var; return v; }; } return nextVal; } function pushCheck(val, check) { let arr = val.vc; if (arr !== undefined) { arr.push(check); } else { val.vc = [check]; } } function markOutput(val, valInput) { let fn = valInput.e.inputRefiner; let deferredInputChecks; if (fn !== undefined) { let checks = fn(valInput); if (checks.length !== 0) { let match = valInput.prev; if (match !== undefined) { for (let i = 0, i_finish = checks.length; i < i_finish; ++i) { pushCheck(valInput, checks[i]); } deferredInputChecks = undefined; } else { deferredInputChecks = checks; } } else { deferredInputChecks = undefined; } } else { deferredInputChecks = undefined; } let fn$1 = val.e.refiner; let outputChecks; if (fn$1 !== undefined) { let checks$1 = fn$1(val); outputChecks = checks$1.length !== 0 ? checks$1 : undefined; } else { outputChecks = undefined; } let val$1 = deferredInputChecks !== undefined ? ( outputChecks !== undefined ? refine(val, undefined, deferredInputChecks.concat(outputChecks), undefined) : refine(val, undefined, deferredInputChecks, undefined) ) : ( outputChecks !== undefined ? refine(val, undefined, outputChecks, undefined) : val ); val$1.io = true; return val$1; } function hoistChildChecks(parent, child, key) { if (!child.vc) { return; } let inlinedLocation = inlineLocation(parent.g, key); let pathAppend = `[` + inlinedLocation + `]`; child.vc.forEach(check => pushCheck(parent, { c: inputVar => check.c(inputVar + pathAppend), f: check.f })); child.vc = undefined; } function dynamicScope(from, locationVar) { let match = from.s.additionalItems; let tmp; tmp = match !== undefined && match !== "strip" && match !== "strict" ? match : unknown; let match$1 = from.e.additionalItems; let tmp$1; tmp$1 = match$1 !== undefined && match$1 !== "strip" && match$1 !== "strict" ? match$1 : unknown; return { p: from, v: _notVarBeforeValidation, i: from.v() + `[` + locationVar + `]`, s: tmp, e: tmp$1, f: from.f, cp: "", hd: "", path: "", g: from.g }; } function nextConst(from, schema, expected) { return next(from, inlineConst(from, schema), schema, expected); } function asyncVal(from, initial) { let v = next(from, initial, from.s, undefined); v.f = 1; return v; } function add(objectVal, location, val) { if (objectVal.s.type === arrayTag) { objectVal.s.items.push(val.s); } else { if (!val.o) { objectVal.s.required.push(location); } objectVal.s.properties[location] = val.s; } if (val.f & 1) { val.v(); } objectVal.cp = objectVal.cp + merge(val, undefined); objectVal.d[location] = val; } function addKey(objVal, key, value) { return objVal.v() + `[` + key + `]=` + value.i; } function scope(val) { let shouldLink = val.v !== _var; let nextVal = { b: val, v: shouldLink ? _bondVar : _var, i: val.i, s: val.s, io: val.io, e: val.e, f: 0, d: val.d, cp: "", hd: "", u: false, t: false, path: val.path, g: val.g }; if (shouldLink) { let valVar = (val.v.bind(val)); val.v = () => { let v = valVar(); nextVal.i = v; nextVal.v = _var; return v; }; } return nextVal; } function embedTransformation(input, fn, isAsync) { let outputVar = varWithoutAllocation(input.g); let output = next(input, outputVar, unknown, input.e.to); output.v = _var; if (isAsync) { if (!(input.g.o & 1)) { throw new SuryError({ code: "invalid_operation", path: "", reason: "Encountered unexpected async transform or refine. Use parseAsyncOrThrow operation instead" }); } output.f = output.f | 1; } let embededFn = embed(input, fn); let failure = failWithArg(output, e => makeInvalidConversionDetails(input, unknown, e), `x`); output.cp = `let ` + outputVar + `;try{` + outputVar + `=` + embededFn + `(` + ( input.vc ? input.v() : input.i ) + `)` + ( isAsync ? `.catch(x=>` + failure + `)` : "" ) + `}catch(x){` + failure + `}`; return output; } function effectCtx(input) { return { fail: (message, pathOpt) => { let path = pathOpt !== undefined ? pathOpt : ""; let error = new SuryError(invalidInputBuilder(undefined, path, message, false)(input)((void 0))); error["p"] = 1; throw error; } }; } function invalidOperation(val, description) { throw new SuryError({ code: "invalid_operation", path: val.path, reason: description }); } function mergeWithPathPrepend(val, parent, locationVar, appendSafe) { if (val.path === "" && locationVar === undefined) { return merge(val, undefined); } else { let $$catch = errorVar => { let path = parent.path; let tmp = path === "" ? "" : fromString(path) + `+`; return errorVar + `.path=` + tmp + ( locationVar !== undefined ? `'["'+` + locationVar + `+'"]'+` : "" ) + errorVar + `.path`; }; let valCode = merge(val, undefined); if (valCode === "" && !(val.f & 1)) { return valCode + ( appendSafe !== undefined ? appendSafe() : "" ); } let errorVar = varWithoutAllocation(val.g); let catchCode = $$catch(errorVar) + `;throw ` + errorVar; if (val.f & 1) { val.i = val.i + `.catch(` + errorVar + `=>{` + catchCode + `})`; } return `try{` + valCode + ( appendSafe !== undefined ? appendSafe() : "" ) + `}catch(` + errorVar + `){` + catchCode + `}`; } } function noopOperation(i) { return i; } noopOperation.embedded = immutableEmpty$1; function int32FormatValidation(inputVar) { return inputVar + `<=2147483647&&` + inputVar + `>=-2147483648&&` + inputVar + `%1===0`; } function typeofCond(tag) { return inputVar => `typeof ` + inputVar + `==="` + tag + `"`; } function nanCond(inputVar) { return `Number.isNaN(` + inputVar + `)`; } function isArrayCond(inputVar) { return `Array.isArray(` + inputVar + `)`; } function objectTagCond(inputVar) { return typeofCond(objectTag)(inputVar) + `&&` + inputVar; } function instanceofCond(b, $$class) { return inputVar => inputVar + ` instanceof ` + embed(b, $$class); } function numberDecoder(input) { let inputTagFlag = flags[input.s.type]; if (inputTagFlag & 1) { let checks = [{ c: typeofCond(numberTag), f: failInvalidType }]; let match = input.e.format; let exit = 0; if (match === "int32") { checks.push({ c: int32FormatValidation, f: failInvalidType }); } else { exit = 1; } if (exit === 1) { if (!(input.g.o & 2)) { checks.push({ c: inputVar => `!` + nanCond(inputVar), f: failInvalidType }); } } return refine(input, input.e, checks, undefined); } if (!(inputTagFlag & 2)) { if (inputTagFlag & 4) { if (input.s.format !== input.e.format && input.e.format === "int32") { return refine(input, input.e, [{ c: int32FormatValidation, f: failInvalidType }], undefined); } else { return input; } } else { return unsupportedDecode(input, input.s, input.e); } } let outputVar = varWithoutAllocation(input.g); let output = next(input, outputVar, input.e, undefined); output.v = _var; output.cp = `let ` + outputVar + `=+` + input.v() + `;`; output.vc = [{ c: param => { let match = input.e.format; if (match !== undefined) { if (match === "int32") { return int32FormatValidation(outputVar); } else { return `!` + nanCond(outputVar); } } else { return `!` + nanCond(outputVar); } }, f: failInvalidType }]; return output; } function float() { return cached(numberTag, numberTag, s => { s.decoder = numberDecoder; }); } function int() { return cached("i", numberTag, s => { s.format = "int32"; s.decoder = numberDecoder; }); } function inputToString(input) { return next(input, `""+` + input.i, string(), undefined); } function stringDecoderFn(input) { let inputTagFlag = flags[input.s.type]; if (inputTagFlag & 1) { return refine(input, input.e, [{ c: typeofCond(stringTag), f: failInvalidType }], undefined); } if (!(inputTagFlag & 3132 && constField in input.s)) { if (inputTagFlag & 1036) { return inputToString(input); } else if (inputTagFlag & 2) { return input; } else { return unsupportedDecode(input, input.s, input.e); } } let $$const = (""+input.s.const); let schema = base(stringTag, false); schema.const = $$const; return next(input, `"` + $$const + `"`, schema, undefined); } function string() { return cached(stringTag, stringTag, s => { s.decoder = stringDecoderFn; }); } function booleanDecoder(input) { let inputTagFlag = flags[input.s.type]; if (inputTagFlag & 1) { return refine(input, input.e, [{ c: typeofCond(booleanTag), f: failInvalidType }], undefined); } if (!(inputTagFlag & 2)) { if (inputTagFlag & 8) { return input; } else { return unsupportedDecode(input, input.s, input.e); } } let outputVar = varWithoutAllocation(input.g); let output = next(input, outputVar, input.e, undefined); output.v = _var; let inputVar = input.v(); output.cp = `let ` + outputVar + `;(` + output.i + `=` + inputVar + `==="true")||` + inputVar + `==="false"||` + embedInvalidInput(input, undefined) + `;`; return output; } function bool() { return cached(booleanTag, booleanTag, s => { s.decoder = booleanDecoder; }); } function bigintDecoder(input) { let inputTagFlag = flags[input.s.type]; if (inputTagFlag & 1) { return refine(input, input.e, [{ c: typeofCond(bigintTag), f: failInvalidType }], undefined); } if (!(inputTagFlag & 2)) { if (inputTagFlag & 4) { return next(input, `BigInt(` + input.i + `)`, input.e, undefined); } else if (inputTagFlag & 1024) { return input; } else { return unsupportedDecode(input, input.s, input.e); } } let outputVar = varWithoutAllocation(input.g); let output = next(input, outputVar, input.e, undefined); output.v = _var; output.cp = `let ` + outputVar + `;try{` + outputVar + `=BigInt(` + input.v() + `)}catch(_){` + embedInvalidInput(input, undefined) + `}`; return output; } function bigint() { return cached(bigintTag, bigintTag, s => { s.decoder = bigintDecoder; }); } function symbolDecoder(input) { let inputTagFlag = flags[input.s.type]; if (inputTagFlag & 1) { return refine(input, input.e, [{ c: typeofCond(symbolTag), f: failInvalidType }], undefined); } else if (inputTagFlag & 16384) { return input; } else { return unsupportedDecode(input, input.s, input.e); } } function symbol() { return cached(symbolTag, symbolTag, s => { s.decoder = symbolDecoder; }); } function setHas(has, tag) { has[flags[tag] & 768 ? unknownTag : tag] = true; } let jsonName = `JSON`; function literalDecoder(input) { let expectedSchema = input.e; if (expectedSchema.noValidation && !input.u) { return nextConst(input, expectedSchema, undefined); } if (constField in input.s) { if (input.s.const === expectedSchema.const) { return input; } else { return nextConst(input, expectedSchema, undefined); } } let schemaTagFlag = flags[expectedSchema.type]; if (!(flags[input.s.type] & 2 && schemaTagFlag & 3132)) { if (schemaTagFlag & 2048) { return refine(input, expectedSchema, [{ c: nanCond, f: failInvalidType }], undefined); } else { return refine(input, expectedSchema, [{ c: inputVar => inputVar + `===` + inlineConst(input, expectedSchema), f: failInvalidType }], undefined); } } let stringConstSchema = base(stringTag, false); stringConstSchema.const = ("" + expectedSchema.const); let stringConstVal = nextConst(input, stringConstSchema, stringConstSchema); stringConstVal.vc = [{ c: inputVar => inputVar + `==="` + stringConstSchema.const + `"`, f: failInvalidType }]; return nextConst(stringConstVal, expectedSchema, expectedSchema); } function unit() { return cached(undefinedTag, undefinedTag, s => { s.const = (void 0); s.decoder = literalDecoder; }); } function nullLiteral() { return cached(nullTag, nullTag, s => { s.const = null; s.decoder = literalDecoder; }); } function nan() { return cached(nanTag, nanTag, s => { s.const = NaN; s.decoder = literalDecoder; }); } function parse(value) { if (value === null) { return nullLiteral(); } let tag = typeof value; if (tag === undefinedTag) { return unit(); } if (tag === numberTag && Number.isNaN(value)) { return nan(); } if (tag === objectTag) { let s = base(instanceTag, true); s.class = value.constructor; s.const = value; s.decoder = literalDecoder; return s; } let s$1 = base(tag, true); s$1.const = value; s$1.decoder = literalDecoder; return s$1; } function parse$1(input) { let valRef = input; let appliedEncoderRef; let loopCount = 0; while (!valRef.io || valRef.e.to) { let appliedEncoder = appliedEncoderRef; appliedEncoderRef = undefined; let loopInput = valRef; loopCount = loopCount + 1 | 0; if (loopCount > 50) { throw (new Error("Loop count exceeded 100")); } if (loopInput.e.$defs) { if (loopInput.g.d) { Object.assign(loopInput.g.d, loopInput.e.$defs); } else { loopInput.g.d = loopInput.e.$defs; } } if (loopInput.f & 1) { let operationInputVar = loopInput.v(); let operationInput = scope(loopInput); let operationOutput = parse$1(operationInput); let operationCode = merge(operationOutput, undefined); valRef = operationInput.i !== operationOutput.i || operationCode !== "" ? next(loopInput, operationInputVar + `.then(` + operationInputVar + `=>{` + operationCode + `return ` + operationOutput.i + `})`, operationOutput.s, operationOutput.e) : refine(loopInput, operationOutput.s, undefined, operationOutput.e); valRef.f = valRef.f | 1; valRef.io = true; } else if (loopInput.io) { let to = loopInput.e.to; let match = loopInput.e; let parser = match.parser; valRef = parser !== undefined ? parser(loopInput) : refine(valRef, undefined, undefined, to); } else { let maybeEncoder = loopInput.s.encoder; if (maybeEncoder && maybeEncoder !== appliedEncoder && loopInput.s !== loopInput.e && loopInput.e.type !== unknownTag) { valRef = maybeEncoder(loopInput, loopInput.e); } if (loopInput !== valRef) { appliedEncoderRef = maybeEncoder; } else { valRef = loopInput.e.decoder(loopInput); if (!valRef.io) { valRef = markOutput(valRef, valRef); } } } } return valRef; } function getOutputSchema(_schema) { while (true) { let schema = _schema; let to = schema.to; if (to === undefined) { return schema; } _schema = to; continue; }} function reverse(schema) { if (reversedKey in schema) { return schema[reversedKey]; } let reversedHead; let current = schema; while (current) { let mut = copySchema(current); let next = mut.to; let to = reversedHead; if (to !== undefined) { mut.to = to; } else { ((delete mut.to)); } let parser = mut.parser; let serializer = mut.serializer; if (serializer !== undefined) { mut.parser = serializer; } else { ((delete mut.parser)); } if (parser !== undefined) { mut.serializer = parser; } else { ((delete mut.serializer)); } let refiner = mut.refiner; let inputRefiner = mut.inputRefiner; if (inputRefiner !== undefined) { mut.refiner = inputRefiner; } else { ((delete mut.refiner)); } if (refiner !== undefined) { mut.inputRefiner = refiner; } else { ((delete mut.inputRefiner)); } let fromDefault = mut.fromDefault; let $$default = mut.default; if ($$default !== undefined) { mut.fromDefault = $$default; } else { ((delete mut.fromDefault)); } if (fromDefault !== undefined) { mut.default = fromDefault; } else { ((delete mut.default)); } let items = mut.items; if (items !== undefined) { mut.items = items.map(reverse); } let properties = mut.properties; if (properties !== undefined) { let newProperties = {}; let keys = Object.keys(properties); for (let idx = 0, idx_finish = keys.length; idx < idx_finish; ++idx) { let key = keys[idx]; newProperties[key] = reverse(properties[key]); } mut.properties = newProperties; } if (typeof mut.additionalItems === objectTag) { mut.additionalItems = reverse(mut.additionalItems); } let anyOf = mut.anyOf; if (anyOf !== undefined) { let has = {}; let newAnyOf = []; for (let idx$1 = 0, idx_finish$1 = anyOf.length; idx$1 < idx_finish$1; ++idx$1) { let s = anyOf[idx$1]; let reversed = reverse(s); newAnyOf.push(reversed); setHas(has, reversed.type); } mut.has = has; mut.anyOf = newAnyOf; } let defs = mut.$defs; if (defs !== undefined) { let reversedDefs = {}; for (let idx$2 = 0, idx_finish$2 = Object.keys(defs).length; idx$2 < idx_finish$2; ++idx$2) { let key$1 = Object.keys(defs)[idx$2]; reversedDefs[key$1] = reverse(defs[key$1]); } mut.$defs = reversedDefs; } reversedHead = mut; current = next; } let r = reversedHead; valueOptions[valKey] = r; d(schema, reversedKey, valueOptions); valueOptions[valKey] = schema; d(r, reversedKey, valueOptions); return r; } function parseDynamic(input) { try { return parse$1(input); } catch (exn) { let error = getOrRethrow(exn); let p = input.p; error.path = ( p !== undefined ? p.path : "" ) + (input.path + "[]" + error.path); throw error; } } function compileDecoder(schema, expected, flag, defs) { let input = operationArg(constField in schema ? unknown : schema, expected, flag, defs); let output = parse$1(input); let code = merge(output, undefined); let isAsync = has(output.f, 1); expected.isAsync = isAsync; let hasTransform = output.t === true; expected.hasTransform = hasTransform; if (code === "" && (output === input || output.i === input.i) && !(flag & 1)) { return noopOperation; } let inlinedOutput = output.i; if (flag & 1 && !isAsync && !defs) { inlinedOutput = `Promise.resolve(` + inlinedOutput + `)`; } let inlinedFunction = "i" + `=>{` + code + `return ` + inlinedOutput + `}`; let ctxVarValue1 = input.g.e; let fn = new Function("e", "s", `return ` + inlinedFunction)(ctxVarValue1, s); fn.embedded = input.g.e; return fn; } function getDecoder(param, param$1) { let args = arguments; let idx = 0; let flag; let keyRef = ""; let maxSeq = 0; let cacheTarget; while (flag === undefined) { let arg = args[idx]; if (arg) { if (typeof arg === numberTag) { let f = arg | globalConfig.f; flag = f; keyRef = keyRef + "-" + f; } else { let seq = arg.seq; if (seq > maxSeq) { maxSeq = seq; cacheTarget = arg; } keyRef = keyRef + seq + "-"; idx = idx + 1 | 0; } } else { let f$1 = globalConfig.f; flag = f$1; keyRef = keyRef + "-" + f$1; } } let cacheTarget$1 = cacheTarget; if (cacheTarget$1 !== undefined) { let key = keyRef; if (key in cacheTarget$1) { return cacheTarget$1[key]; } let schema = args[idx - 1 | 0]; for (let i = idx - 2 | 0; i >= 0; --i) { let to = schema; schema = updateOutput(args[i], mut => { mut.to = to; }); } let f$2 = compileDecoder(schema, schema, flag, 0); valueOptions[valKey] = f$2; d(cacheTarget$1, key, valueOptions); return f$2; } throw new Error(`[Sury] ` + "No schema provided for decoder."); } let nestedLoc = "BS_PRIVATE_NESTED_SOME_NONE"; function neverBuilderFn(input) { let output = refine(input, undefined, undefined, never_()); output.cp = embedInvalidInput(input, undefined) + ";"; return output; } function never_() { return cached(neverTag, neverTag, s => { s.decoder = neverBuilderFn; }); } function nestedOptionParser(input) { let nextSchema = input.e.to; return next(input, `{` + nestedLoc + `:` + getOutputSchema(input.e).properties[nestedLoc].const + `}`, nextSchema, nextSchema); } function instanceDecoder(input) { let inputTagFlag = flags[input.s.type]; if (inputTagFlag & 1) { return refine(input, input.e, [{ c: instanceofCond(input, input.e.class), f: failInvalidType }], undefined); } else if (inputTagFlag & 8192 && input.s.class === input.e.class) { return input; } else { return unsupportedDecode(input, input.s, input.e); } } function instance(class_) { let mut = base(instanceTag, true); mut.class = class_; mut.decoder = instanceDecoder; return mut; } function makeObjectVal(prev, schema) { return { v: _notVar, i: "", s: schema.type === arrayTag ? ({ type: arrayTag, decoder: arrayDecoder, additionalItems: "strict", items: [] }) : ({ type: objectTag, decoder: objectDecoder, additionalItems: "strict", required: [], properties: {} }), e: prev.e, prev: prev, f: 0, d: {}, cp: "", hd: "", t: true, path: prev.path, g: prev.g }; } function option(item) { return optionFactory(item, unit()); } function objectDecoder(unknownInput) { let isUnion = unknownInput.u; let expectedSchema = unknownInput.e; let unknownInputTagFlag = flags[unknownInput.s.type]; let input; if (unknownInputTagFlag & 65) { let isObjectInput = unknownInputTagFlag & 64; let schema; if (isObjectInput) { schema = unknownInput.s; } else { let mut = base(objectTag, false); mut.properties = immutableEmpty; mut.additionalItems = unknown; schema = mut; } let checks = []; if (!isObjectInput) { checks.push({ c: objectTagCond, f: failInvalidType }); if (expectedSchema.additionalItems !== "strip") { checks.push({ c: inputVar => `!` + isArrayCond(inputVar), f: failInvalidType }); } } input = checks.length !== 0 ? refine(unknownInput, schema, checks, undefined) : refine(unknownInput, schema, undefined, undefined); } else { input = unsupportedDecode(unknownInput, unknownInput.s, expectedSchema); } let s = expectedSchema.additionalItems; let dictItem; dictItem = s === "strip" || s === "strict" ? undefined : s; let match = input.s.additionalItems; let sourceIsDict; sourceIsDict = match !== "strip" && match !== "strict"; let output; if (dictItem !== undefined) { if (dictItem === unknown) { output = input; } else if (sourceIsDict) { let inputVar = input.v(); let keyVar = varWithoutAllocation(input.g); let itemInput = dynamicScope(input, keyVar); let itemOutput = parseDynamic(itemInput); let hasTransform = itemOutput.t; let output$1 = hasTransform ? next(input, "{}", expectedSchema, undefined) : refine(input, expectedSchema, undefined, undefined); let itemCode = mergeWithPathPrepend(itemOutput, input, keyVar, hasTransform ? () => addKey(output$1, keyVar, itemOutput) : undefined); if (hasTransform || itemCode !== "") { output$1.cp = output$1.cp + (`for(let ` + keyVar + ` in ` + inputVar + `){` + itemCode + `}`); } if (itemOutput.f & 1) { let resolveVar = varWithoutAllocation(output$1.g); let rejectVar = varWithoutAllocation(output$1.g); let asyncParseResultVar = varWithoutAllocation(output$1.g); let counterVar = varWithoutAllocation(output$1.g); let outputVar = output$1.v(); output = asyncVal(output$1, `new Promise((` + resolveVar + `,` + rejectVar + `)=>{let ` + counterVar + `=Object.keys(` + outputVar + `).length;for(let ` + keyVar + ` in ` + outputVar + `){` + outputVar + `[` + keyVar + `].then(` + asyncParseResultVar + `=>{` + outputVar + `[` + keyVar + `]=` + asyncParseResultVar + `;if(` + counterVar + `--===1){` + resolveVar + `(` + outputVar + `)}},` + rejectVar + `)}})`); } else { output = output$1; } } else { let objectVal = makeObjectVal(input, expectedSchema); let keys = Object.keys(input.s.properties); for (let idx = 0, idx_finish = keys.length; idx < idx_finish; ++idx) { let key = keys[idx]; let itemInput$1 = valGet(input, key); itemInput$1.e = dictItem; itemInput$1.io = false; itemInput$1.u = isUnion; add(objectVal, key, parse$1(itemInput$1)); } output = completeObjectVal(objectVal); } } else { let properties = expectedSchema.properties; let keys$1 = Object.keys(properties); let keysCount = keys$1.length; let objectVal$1 = makeObjectVal(input, expectedSchema); let match$1 = expectedSchema.additionalItems; let shouldRecreateInput; shouldRecreateInput = match$1 === "strip" || match$1 === "strict" ? ( match$1 === "strip" ? sourceIsDict || Object.keys(input.s.properties).length !== keysCount : false ) : true; let s$1 = input.s.additionalItems; let isJsonParent; isJsonParent = s$1 === "strip" || s$1 === "strict" ? false : s$1.name === jsonName; for (let idx$1 = 0; idx$1 < keysCount; ++idx$1) { let key$1 = keys$1[idx$1]; let schema$1 = properties[key$1]; let itemInput$2 = valGet(input, key$1); itemInput$2.e = schema$1; itemInput$2.io = false; itemInput$2.u = isUnion; if (isJsonParent && schema$1.type === unionTag && schema$1.has[undefinedTag]) { itemInput$2.i = `(` + itemInput$2.i + `??null)`; } let itemOutput$1 = parse$1(itemInput$2); if (isUnion && constField in schema$1) { hoistChildChecks(input, itemOutput$1, key$1); } add(objectVal$1, key$1, itemOutput$1); if (!shouldRecreateInput) { shouldRecreateInput = itemOutput$1.t; } } let tmp = false; if (expectedSchema.additionalItems === "strict") { let match$2 = input.s.additionalItems; let tmp$1; tmp$1 = match$2 !== "strip" && match$2 !== "strict"; tmp = tmp$1; } if (tmp) { let keyVar$1 = varWithoutAllocation(objectVal$1.g); hoistDecl(input, keyVar$1); objectVal$1.cp = objectVal$1.cp + (`for(` + keyVar$1 + ` in ` + input.v() + `){if(`); if (keys$1.length !== 0) { for (let idx$2 = 0, idx_finish$1 = keys$1.length; idx$2 < idx_finish$1; ++idx$2) { let key$2 = keys$1[idx$2]; if (idx$2 !== 0) { objectVal$1.cp = objectVal$1.cp + "&&"; } objectVal$1.cp = objectVal$1.cp + (keyVar$1 + `!==` + inlineLocation(input.g, key$2)); } } else { objectVal$1.cp = objectVal$1.cp + "true"; } objectVal$1.cp = objectVal$1.cp + (`){` + failWithArg(input, exccessFieldName => ({ code: "unrecognized_keys", path: objectVal$1.path, reason: `Unrecognized key "` + exccessFieldName + `"`, keys: [exccessFieldName] }), keyVar$1) + `}}`); } if (shouldRecreateInput) { output = completeObjectVal(objectVal$1); } else { let o = refine(input, undefined, undefined, undefined); o.cp = objectVal$1.cp; o.d = objectVal$1.d; output = o; } } return markOutput(output, input); } function nestedNone() { let itemSchema = parse(0); let properties = {}; properties[nestedLoc] = itemSchema; return { type: objectTag, serializer: input => { let nextSchema = input.e.to; return nextConst(input, nextSchema, nextSchema); }, decoder: objectDecoder, additionalItems: "strip", required: [nestedLoc], properties: properties }; } function arrayDecoder(unknownInput) { let isUnion = unknownInput.u; let expectedSchema = unknownInput.e; let unknownInputTagFlag = flags[unknownInput.s.type]; let expectedItems = expectedSchema.items; let expectedLength = expectedItems.length; let input; if (unknownInputTagFlag & 129) { let isArrayInput = unknownInputTagFlag & 128; let schema = isArrayInput ? unknownInput.s : array(unknown); let checks = []; if (!isArrayInput) { checks.push({ c: isArrayCond, f: failInvalidType }); } let match = schema.additionalItems; let isExactSize; isExactSize = match === "strip" || match === "strict" ? ( match === "strip" ? schema.items.length === expectedLength : schema.items.length === expectedLength ) : false; if (!isExactSize) { let match$1 = expectedSchema.additionalItems; if (match$1 === "strip" || match$1 === "strict") { if (match$1 === "strip") { checks.push({ c: inputVar => inputVar + `.length>=` + expectedLength, f: failInvalidType }); } else { checks.push({ c: inputVar => inputVar + `.length===` + expectedLength, f: failInvalidType }); } } } input = checks.length !== 0 ? refine(unknownInput, schema, checks, undefined) : refine(unknownInput, schema, undefined, undefined); } else { input = unsupportedDecode(unknownInput, unknownInput.s, expectedSchema); } let itemSchema = expectedSchema.additionalItems; let output; let exit = 0; if (itemSchema === "strip" || itemSchema === "strict") { exit = 1; } else if (itemSchema === unknown) { output = input; } else { let inputVar = input.v(); let iteratorVar = varWithoutAllocation(input.g); let itemInput = dynamicScope(input, iteratorVar); let itemOutput = parseDynamic(itemInput); let hasTransform = itemOutput.t; let output$1 = hasTransform ? next(input, `new Array(` + inputVar + `.length)`, expectedSchema, undefined) : refine(input, expectedSchema, undefined, undefined); let itemCode = mergeWithPathPrepend(itemOutput, input, iteratorVar, hasTransform ? () => addKey(output$1, iteratorVar, itemOutput) : unde