@mastra/schema-compat
Version:
Tool schema compatibility layer for Mastra.ai
1,413 lines • 257 kB
JavaScript
import { n as __commonJSMin, r as __toESM, t as require_json_schema_traverse } from "./json-schema-traverse-B35mHRM8.js";
//#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/ajv/8.20.0/45a7731a7f226afbb54bce5941cf72055c748f37aa24c1b293e6625f57e4ce6e/node_modules/ajv/dist/compile/codegen/code.js
var require_code$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0;
var _CodeOrName = class {};
exports._CodeOrName = _CodeOrName;
exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
var Name = class extends _CodeOrName {
constructor(s) {
super();
if (!exports.IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier");
this.str = s;
}
toString() {
return this.str;
}
emptyStr() {
return false;
}
get names() {
return { [this.str]: 1 };
}
};
exports.Name = Name;
var _Code = class extends _CodeOrName {
constructor(code) {
super();
this._items = typeof code === "string" ? [code] : code;
}
toString() {
return this.str;
}
emptyStr() {
if (this._items.length > 1) return false;
const item = this._items[0];
return item === "" || item === "\"\"";
}
get str() {
var _a;
return (_a = this._str) !== null && _a !== void 0 ? _a : this._str = this._items.reduce((s, c) => `${s}${c}`, "");
}
get names() {
var _a;
return (_a = this._names) !== null && _a !== void 0 ? _a : this._names = this._items.reduce((names, c) => {
if (c instanceof Name) names[c.str] = (names[c.str] || 0) + 1;
return names;
}, {});
}
};
exports._Code = _Code;
exports.nil = new _Code("");
function _(strs, ...args) {
const code = [strs[0]];
let i = 0;
while (i < args.length) {
addCodeArg(code, args[i]);
code.push(strs[++i]);
}
return new _Code(code);
}
exports._ = _;
const plus = new _Code("+");
function str(strs, ...args) {
const expr = [safeStringify(strs[0])];
let i = 0;
while (i < args.length) {
expr.push(plus);
addCodeArg(expr, args[i]);
expr.push(plus, safeStringify(strs[++i]));
}
optimize(expr);
return new _Code(expr);
}
exports.str = str;
function addCodeArg(code, arg) {
if (arg instanceof _Code) code.push(...arg._items);
else if (arg instanceof Name) code.push(arg);
else code.push(interpolate(arg));
}
exports.addCodeArg = addCodeArg;
function optimize(expr) {
let i = 1;
while (i < expr.length - 1) {
if (expr[i] === plus) {
const res = mergeExprItems(expr[i - 1], expr[i + 1]);
if (res !== void 0) {
expr.splice(i - 1, 3, res);
continue;
}
expr[i++] = "+";
}
i++;
}
}
function mergeExprItems(a, b) {
if (b === "\"\"") return a;
if (a === "\"\"") return b;
if (typeof a == "string") {
if (b instanceof Name || a[a.length - 1] !== "\"") return;
if (typeof b != "string") return `${a.slice(0, -1)}${b}"`;
if (b[0] === "\"") return a.slice(0, -1) + b.slice(1);
return;
}
if (typeof b == "string" && b[0] === "\"" && !(a instanceof Name)) return `"${a}${b.slice(1)}`;
}
function strConcat(c1, c2) {
return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`;
}
exports.strConcat = strConcat;
function interpolate(x) {
return typeof x == "number" || typeof x == "boolean" || x === null ? x : safeStringify(Array.isArray(x) ? x.join(",") : x);
}
function stringify(x) {
return new _Code(safeStringify(x));
}
exports.stringify = stringify;
function safeStringify(x) {
return JSON.stringify(x).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
}
exports.safeStringify = safeStringify;
function getProperty(key) {
return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`;
}
exports.getProperty = getProperty;
function getEsmExportName(key) {
if (typeof key == "string" && exports.IDENTIFIER.test(key)) return new _Code(`${key}`);
throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`);
}
exports.getEsmExportName = getEsmExportName;
function regexpCode(rx) {
return new _Code(rx.toString());
}
exports.regexpCode = regexpCode;
}));
//#endregion
//#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/ajv/8.20.0/45a7731a7f226afbb54bce5941cf72055c748f37aa24c1b293e6625f57e4ce6e/node_modules/ajv/dist/compile/codegen/scope.js
var require_scope = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0;
const code_1 = require_code$1();
var ValueError = class extends Error {
constructor(name) {
super(`CodeGen: "code" for ${name} not defined`);
this.value = name.value;
}
};
var UsedValueState;
(function(UsedValueState) {
UsedValueState[UsedValueState["Started"] = 0] = "Started";
UsedValueState[UsedValueState["Completed"] = 1] = "Completed";
})(UsedValueState || (exports.UsedValueState = UsedValueState = {}));
exports.varKinds = {
const: new code_1.Name("const"),
let: new code_1.Name("let"),
var: new code_1.Name("var")
};
var Scope = class {
constructor({ prefixes, parent } = {}) {
this._names = {};
this._prefixes = prefixes;
this._parent = parent;
}
toName(nameOrPrefix) {
return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix);
}
name(prefix) {
return new code_1.Name(this._newName(prefix));
}
_newName(prefix) {
const ng = this._names[prefix] || this._nameGroup(prefix);
return `${prefix}${ng.index++}`;
}
_nameGroup(prefix) {
var _a, _b;
if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`);
return this._names[prefix] = {
prefix,
index: 0
};
}
};
exports.Scope = Scope;
var ValueScopeName = class extends code_1.Name {
constructor(prefix, nameStr) {
super(nameStr);
this.prefix = prefix;
}
setValue(value, { property, itemIndex }) {
this.value = value;
this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`;
}
};
exports.ValueScopeName = ValueScopeName;
const line = (0, code_1._)`\n`;
var ValueScope = class extends Scope {
constructor(opts) {
super(opts);
this._values = {};
this._scope = opts.scope;
this.opts = {
...opts,
_n: opts.lines ? line : code_1.nil
};
}
get() {
return this._scope;
}
name(prefix) {
return new ValueScopeName(prefix, this._newName(prefix));
}
value(nameOrPrefix, value) {
var _a;
if (value.ref === void 0) throw new Error("CodeGen: ref must be passed in value");
const name = this.toName(nameOrPrefix);
const { prefix } = name;
const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref;
let vs = this._values[prefix];
if (vs) {
const _name = vs.get(valueKey);
if (_name) return _name;
} else vs = this._values[prefix] = /* @__PURE__ */ new Map();
vs.set(valueKey, name);
const s = this._scope[prefix] || (this._scope[prefix] = []);
const itemIndex = s.length;
s[itemIndex] = value.ref;
name.setValue(value, {
property: prefix,
itemIndex
});
return name;
}
getValue(prefix, keyOrRef) {
const vs = this._values[prefix];
if (!vs) return;
return vs.get(keyOrRef);
}
scopeRefs(scopeName, values = this._values) {
return this._reduceValues(values, (name) => {
if (name.scopePath === void 0) throw new Error(`CodeGen: name "${name}" has no value`);
return (0, code_1._)`${scopeName}${name.scopePath}`;
});
}
scopeCode(values = this._values, usedValues, getCode) {
return this._reduceValues(values, (name) => {
if (name.value === void 0) throw new Error(`CodeGen: name "${name}" has no value`);
return name.value.code;
}, usedValues, getCode);
}
_reduceValues(values, valueCode, usedValues = {}, getCode) {
let code = code_1.nil;
for (const prefix in values) {
const vs = values[prefix];
if (!vs) continue;
const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map();
vs.forEach((name) => {
if (nameSet.has(name)) return;
nameSet.set(name, UsedValueState.Started);
let c = valueCode(name);
if (c) {
const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const;
code = (0, code_1._)`${code}${def} ${name} = ${c};${this.opts._n}`;
} else if (c = getCode === null || getCode === void 0 ? void 0 : getCode(name)) code = (0, code_1._)`${code}${c}${this.opts._n}`;
else throw new ValueError(name);
nameSet.set(name, UsedValueState.Completed);
});
}
return code;
}
};
exports.ValueScope = ValueScope;
}));
//#endregion
//#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/ajv/8.20.0/45a7731a7f226afbb54bce5941cf72055c748f37aa24c1b293e6625f57e4ce6e/node_modules/ajv/dist/compile/codegen/index.js
var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0;
const code_1 = require_code$1();
const scope_1 = require_scope();
var code_2 = require_code$1();
Object.defineProperty(exports, "_", {
enumerable: true,
get: function() {
return code_2._;
}
});
Object.defineProperty(exports, "str", {
enumerable: true,
get: function() {
return code_2.str;
}
});
Object.defineProperty(exports, "strConcat", {
enumerable: true,
get: function() {
return code_2.strConcat;
}
});
Object.defineProperty(exports, "nil", {
enumerable: true,
get: function() {
return code_2.nil;
}
});
Object.defineProperty(exports, "getProperty", {
enumerable: true,
get: function() {
return code_2.getProperty;
}
});
Object.defineProperty(exports, "stringify", {
enumerable: true,
get: function() {
return code_2.stringify;
}
});
Object.defineProperty(exports, "regexpCode", {
enumerable: true,
get: function() {
return code_2.regexpCode;
}
});
Object.defineProperty(exports, "Name", {
enumerable: true,
get: function() {
return code_2.Name;
}
});
var scope_2 = require_scope();
Object.defineProperty(exports, "Scope", {
enumerable: true,
get: function() {
return scope_2.Scope;
}
});
Object.defineProperty(exports, "ValueScope", {
enumerable: true,
get: function() {
return scope_2.ValueScope;
}
});
Object.defineProperty(exports, "ValueScopeName", {
enumerable: true,
get: function() {
return scope_2.ValueScopeName;
}
});
Object.defineProperty(exports, "varKinds", {
enumerable: true,
get: function() {
return scope_2.varKinds;
}
});
exports.operators = {
GT: new code_1._Code(">"),
GTE: new code_1._Code(">="),
LT: new code_1._Code("<"),
LTE: new code_1._Code("<="),
EQ: new code_1._Code("==="),
NEQ: new code_1._Code("!=="),
NOT: new code_1._Code("!"),
OR: new code_1._Code("||"),
AND: new code_1._Code("&&"),
ADD: new code_1._Code("+")
};
var Node = class {
optimizeNodes() {
return this;
}
optimizeNames(_names, _constants) {
return this;
}
};
var Def = class extends Node {
constructor(varKind, name, rhs) {
super();
this.varKind = varKind;
this.name = name;
this.rhs = rhs;
}
render({ es5, _n }) {
const varKind = es5 ? scope_1.varKinds.var : this.varKind;
const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`;
return `${varKind} ${this.name}${rhs};` + _n;
}
optimizeNames(names, constants) {
if (!names[this.name.str]) return;
if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants);
return this;
}
get names() {
return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {};
}
};
var Assign = class extends Node {
constructor(lhs, rhs, sideEffects) {
super();
this.lhs = lhs;
this.rhs = rhs;
this.sideEffects = sideEffects;
}
render({ _n }) {
return `${this.lhs} = ${this.rhs};` + _n;
}
optimizeNames(names, constants) {
if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) return;
this.rhs = optimizeExpr(this.rhs, names, constants);
return this;
}
get names() {
return addExprNames(this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names }, this.rhs);
}
};
var AssignOp = class extends Assign {
constructor(lhs, op, rhs, sideEffects) {
super(lhs, rhs, sideEffects);
this.op = op;
}
render({ _n }) {
return `${this.lhs} ${this.op}= ${this.rhs};` + _n;
}
};
var Label = class extends Node {
constructor(label) {
super();
this.label = label;
this.names = {};
}
render({ _n }) {
return `${this.label}:` + _n;
}
};
var Break = class extends Node {
constructor(label) {
super();
this.label = label;
this.names = {};
}
render({ _n }) {
return `break${this.label ? ` ${this.label}` : ""};` + _n;
}
};
var Throw = class extends Node {
constructor(error) {
super();
this.error = error;
}
render({ _n }) {
return `throw ${this.error};` + _n;
}
get names() {
return this.error.names;
}
};
var AnyCode = class extends Node {
constructor(code) {
super();
this.code = code;
}
render({ _n }) {
return `${this.code};` + _n;
}
optimizeNodes() {
return `${this.code}` ? this : void 0;
}
optimizeNames(names, constants) {
this.code = optimizeExpr(this.code, names, constants);
return this;
}
get names() {
return this.code instanceof code_1._CodeOrName ? this.code.names : {};
}
};
var ParentNode = class extends Node {
constructor(nodes = []) {
super();
this.nodes = nodes;
}
render(opts) {
return this.nodes.reduce((code, n) => code + n.render(opts), "");
}
optimizeNodes() {
const { nodes } = this;
let i = nodes.length;
while (i--) {
const n = nodes[i].optimizeNodes();
if (Array.isArray(n)) nodes.splice(i, 1, ...n);
else if (n) nodes[i] = n;
else nodes.splice(i, 1);
}
return nodes.length > 0 ? this : void 0;
}
optimizeNames(names, constants) {
const { nodes } = this;
let i = nodes.length;
while (i--) {
const n = nodes[i];
if (n.optimizeNames(names, constants)) continue;
subtractNames(names, n.names);
nodes.splice(i, 1);
}
return nodes.length > 0 ? this : void 0;
}
get names() {
return this.nodes.reduce((names, n) => addNames(names, n.names), {});
}
};
var BlockNode = class extends ParentNode {
render(opts) {
return "{" + opts._n + super.render(opts) + "}" + opts._n;
}
};
var Root = class extends ParentNode {};
var Else = class extends BlockNode {};
Else.kind = "else";
var If = class If extends BlockNode {
constructor(condition, nodes) {
super(nodes);
this.condition = condition;
}
render(opts) {
let code = `if(${this.condition})` + super.render(opts);
if (this.else) code += "else " + this.else.render(opts);
return code;
}
optimizeNodes() {
super.optimizeNodes();
const cond = this.condition;
if (cond === true) return this.nodes;
let e = this.else;
if (e) {
const ns = e.optimizeNodes();
e = this.else = Array.isArray(ns) ? new Else(ns) : ns;
}
if (e) {
if (cond === false) return e instanceof If ? e : e.nodes;
if (this.nodes.length) return this;
return new If(not(cond), e instanceof If ? [e] : e.nodes);
}
if (cond === false || !this.nodes.length) return void 0;
return this;
}
optimizeNames(names, constants) {
var _a;
this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants);
if (!(super.optimizeNames(names, constants) || this.else)) return;
this.condition = optimizeExpr(this.condition, names, constants);
return this;
}
get names() {
const names = super.names;
addExprNames(names, this.condition);
if (this.else) addNames(names, this.else.names);
return names;
}
};
If.kind = "if";
var For = class extends BlockNode {};
For.kind = "for";
var ForLoop = class extends For {
constructor(iteration) {
super();
this.iteration = iteration;
}
render(opts) {
return `for(${this.iteration})` + super.render(opts);
}
optimizeNames(names, constants) {
if (!super.optimizeNames(names, constants)) return;
this.iteration = optimizeExpr(this.iteration, names, constants);
return this;
}
get names() {
return addNames(super.names, this.iteration.names);
}
};
var ForRange = class extends For {
constructor(varKind, name, from, to) {
super();
this.varKind = varKind;
this.name = name;
this.from = from;
this.to = to;
}
render(opts) {
const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind;
const { name, from, to } = this;
return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts);
}
get names() {
return addExprNames(addExprNames(super.names, this.from), this.to);
}
};
var ForIter = class extends For {
constructor(loop, varKind, name, iterable) {
super();
this.loop = loop;
this.varKind = varKind;
this.name = name;
this.iterable = iterable;
}
render(opts) {
return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);
}
optimizeNames(names, constants) {
if (!super.optimizeNames(names, constants)) return;
this.iterable = optimizeExpr(this.iterable, names, constants);
return this;
}
get names() {
return addNames(super.names, this.iterable.names);
}
};
var Func = class extends BlockNode {
constructor(name, args, async) {
super();
this.name = name;
this.args = args;
this.async = async;
}
render(opts) {
return `${this.async ? "async " : ""}function ${this.name}(${this.args})` + super.render(opts);
}
};
Func.kind = "func";
var Return = class extends ParentNode {
render(opts) {
return "return " + super.render(opts);
}
};
Return.kind = "return";
var Try = class extends BlockNode {
render(opts) {
let code = "try" + super.render(opts);
if (this.catch) code += this.catch.render(opts);
if (this.finally) code += this.finally.render(opts);
return code;
}
optimizeNodes() {
var _a, _b;
super.optimizeNodes();
(_a = this.catch) === null || _a === void 0 || _a.optimizeNodes();
(_b = this.finally) === null || _b === void 0 || _b.optimizeNodes();
return this;
}
optimizeNames(names, constants) {
var _a, _b;
super.optimizeNames(names, constants);
(_a = this.catch) === null || _a === void 0 || _a.optimizeNames(names, constants);
(_b = this.finally) === null || _b === void 0 || _b.optimizeNames(names, constants);
return this;
}
get names() {
const names = super.names;
if (this.catch) addNames(names, this.catch.names);
if (this.finally) addNames(names, this.finally.names);
return names;
}
};
var Catch = class extends BlockNode {
constructor(error) {
super();
this.error = error;
}
render(opts) {
return `catch(${this.error})` + super.render(opts);
}
};
Catch.kind = "catch";
var Finally = class extends BlockNode {
render(opts) {
return "finally" + super.render(opts);
}
};
Finally.kind = "finally";
var CodeGen = class {
constructor(extScope, opts = {}) {
this._values = {};
this._blockStarts = [];
this._constants = {};
this.opts = {
...opts,
_n: opts.lines ? "\n" : ""
};
this._extScope = extScope;
this._scope = new scope_1.Scope({ parent: extScope });
this._nodes = [new Root()];
}
toString() {
return this._root.render(this.opts);
}
name(prefix) {
return this._scope.name(prefix);
}
scopeName(prefix) {
return this._extScope.name(prefix);
}
scopeValue(prefixOrName, value) {
const name = this._extScope.value(prefixOrName, value);
(this._values[name.prefix] || (this._values[name.prefix] = /* @__PURE__ */ new Set())).add(name);
return name;
}
getScopeValue(prefix, keyOrRef) {
return this._extScope.getValue(prefix, keyOrRef);
}
scopeRefs(scopeName) {
return this._extScope.scopeRefs(scopeName, this._values);
}
scopeCode() {
return this._extScope.scopeCode(this._values);
}
_def(varKind, nameOrPrefix, rhs, constant) {
const name = this._scope.toName(nameOrPrefix);
if (rhs !== void 0 && constant) this._constants[name.str] = rhs;
this._leafNode(new Def(varKind, name, rhs));
return name;
}
const(nameOrPrefix, rhs, _constant) {
return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant);
}
let(nameOrPrefix, rhs, _constant) {
return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant);
}
var(nameOrPrefix, rhs, _constant) {
return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant);
}
assign(lhs, rhs, sideEffects) {
return this._leafNode(new Assign(lhs, rhs, sideEffects));
}
add(lhs, rhs) {
return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs));
}
code(c) {
if (typeof c == "function") c();
else if (c !== code_1.nil) this._leafNode(new AnyCode(c));
return this;
}
object(...keyValues) {
const code = ["{"];
for (const [key, value] of keyValues) {
if (code.length > 1) code.push(",");
code.push(key);
if (key !== value || this.opts.es5) {
code.push(":");
(0, code_1.addCodeArg)(code, value);
}
}
code.push("}");
return new code_1._Code(code);
}
if(condition, thenBody, elseBody) {
this._blockNode(new If(condition));
if (thenBody && elseBody) this.code(thenBody).else().code(elseBody).endIf();
else if (thenBody) this.code(thenBody).endIf();
else if (elseBody) throw new Error("CodeGen: \"else\" body without \"then\" body");
return this;
}
elseIf(condition) {
return this._elseNode(new If(condition));
}
else() {
return this._elseNode(new Else());
}
endIf() {
return this._endBlockNode(If, Else);
}
_for(node, forBody) {
this._blockNode(node);
if (forBody) this.code(forBody).endFor();
return this;
}
for(iteration, forBody) {
return this._for(new ForLoop(iteration), forBody);
}
forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) {
const name = this._scope.toName(nameOrPrefix);
return this._for(new ForRange(varKind, name, from, to), () => forBody(name));
}
forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) {
const name = this._scope.toName(nameOrPrefix);
if (this.opts.es5) {
const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable);
return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i) => {
this.var(name, (0, code_1._)`${arr}[${i}]`);
forBody(name);
});
}
return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name));
}
forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) {
if (this.opts.ownProperties) return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody);
const name = this._scope.toName(nameOrPrefix);
return this._for(new ForIter("in", varKind, name, obj), () => forBody(name));
}
endFor() {
return this._endBlockNode(For);
}
label(label) {
return this._leafNode(new Label(label));
}
break(label) {
return this._leafNode(new Break(label));
}
return(value) {
const node = new Return();
this._blockNode(node);
this.code(value);
if (node.nodes.length !== 1) throw new Error("CodeGen: \"return\" should have one node");
return this._endBlockNode(Return);
}
try(tryBody, catchCode, finallyCode) {
if (!catchCode && !finallyCode) throw new Error("CodeGen: \"try\" without \"catch\" and \"finally\"");
const node = new Try();
this._blockNode(node);
this.code(tryBody);
if (catchCode) {
const error = this.name("e");
this._currNode = node.catch = new Catch(error);
catchCode(error);
}
if (finallyCode) {
this._currNode = node.finally = new Finally();
this.code(finallyCode);
}
return this._endBlockNode(Catch, Finally);
}
throw(error) {
return this._leafNode(new Throw(error));
}
block(body, nodeCount) {
this._blockStarts.push(this._nodes.length);
if (body) this.code(body).endBlock(nodeCount);
return this;
}
endBlock(nodeCount) {
const len = this._blockStarts.pop();
if (len === void 0) throw new Error("CodeGen: not in self-balancing block");
const toClose = this._nodes.length - len;
if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`);
this._nodes.length = len;
return this;
}
func(name, args = code_1.nil, async, funcBody) {
this._blockNode(new Func(name, args, async));
if (funcBody) this.code(funcBody).endFunc();
return this;
}
endFunc() {
return this._endBlockNode(Func);
}
optimize(n = 1) {
while (n-- > 0) {
this._root.optimizeNodes();
this._root.optimizeNames(this._root.names, this._constants);
}
}
_leafNode(node) {
this._currNode.nodes.push(node);
return this;
}
_blockNode(node) {
this._currNode.nodes.push(node);
this._nodes.push(node);
}
_endBlockNode(N1, N2) {
const n = this._currNode;
if (n instanceof N1 || N2 && n instanceof N2) {
this._nodes.pop();
return this;
}
throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`);
}
_elseNode(node) {
const n = this._currNode;
if (!(n instanceof If)) throw new Error("CodeGen: \"else\" without \"if\"");
this._currNode = n.else = node;
return this;
}
get _root() {
return this._nodes[0];
}
get _currNode() {
const ns = this._nodes;
return ns[ns.length - 1];
}
set _currNode(node) {
const ns = this._nodes;
ns[ns.length - 1] = node;
}
};
exports.CodeGen = CodeGen;
function addNames(names, from) {
for (const n in from) names[n] = (names[n] || 0) + (from[n] || 0);
return names;
}
function addExprNames(names, from) {
return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names;
}
function optimizeExpr(expr, names, constants) {
if (expr instanceof code_1.Name) return replaceName(expr);
if (!canOptimize(expr)) return expr;
return new code_1._Code(expr._items.reduce((items, c) => {
if (c instanceof code_1.Name) c = replaceName(c);
if (c instanceof code_1._Code) items.push(...c._items);
else items.push(c);
return items;
}, []));
function replaceName(n) {
const c = constants[n.str];
if (c === void 0 || names[n.str] !== 1) return n;
delete names[n.str];
return c;
}
function canOptimize(e) {
return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== void 0);
}
}
function subtractNames(names, from) {
for (const n in from) names[n] = (names[n] || 0) - (from[n] || 0);
}
function not(x) {
return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._)`!${par(x)}`;
}
exports.not = not;
const andCode = mappend(exports.operators.AND);
function and(...args) {
return args.reduce(andCode);
}
exports.and = and;
const orCode = mappend(exports.operators.OR);
function or(...args) {
return args.reduce(orCode);
}
exports.or = or;
function mappend(op) {
return (x, y) => x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._)`${par(x)} ${op} ${par(y)}`;
}
function par(x) {
return x instanceof code_1.Name ? x : (0, code_1._)`(${x})`;
}
}));
//#endregion
//#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/ajv/8.20.0/45a7731a7f226afbb54bce5941cf72055c748f37aa24c1b293e6625f57e4ce6e/node_modules/ajv/dist/compile/util.js
var require_util = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0;
const codegen_1 = require_codegen();
const code_1 = require_code$1();
function toHash(arr) {
const hash = {};
for (const item of arr) hash[item] = true;
return hash;
}
exports.toHash = toHash;
function alwaysValidSchema(it, schema) {
if (typeof schema == "boolean") return schema;
if (Object.keys(schema).length === 0) return true;
checkUnknownRules(it, schema);
return !schemaHasRules(schema, it.self.RULES.all);
}
exports.alwaysValidSchema = alwaysValidSchema;
function checkUnknownRules(it, schema = it.schema) {
const { opts, self } = it;
if (!opts.strictSchema) return;
if (typeof schema === "boolean") return;
const rules = self.RULES.keywords;
for (const key in schema) if (!rules[key]) checkStrictMode(it, `unknown keyword: "${key}"`);
}
exports.checkUnknownRules = checkUnknownRules;
function schemaHasRules(schema, rules) {
if (typeof schema == "boolean") return !schema;
for (const key in schema) if (rules[key]) return true;
return false;
}
exports.schemaHasRules = schemaHasRules;
function schemaHasRulesButRef(schema, RULES) {
if (typeof schema == "boolean") return !schema;
for (const key in schema) if (key !== "$ref" && RULES.all[key]) return true;
return false;
}
exports.schemaHasRulesButRef = schemaHasRulesButRef;
function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) {
if (!$data) {
if (typeof schema == "number" || typeof schema == "boolean") return schema;
if (typeof schema == "string") return (0, codegen_1._)`${schema}`;
}
return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`;
}
exports.schemaRefOrVal = schemaRefOrVal;
function unescapeFragment(str) {
return unescapeJsonPointer(decodeURIComponent(str));
}
exports.unescapeFragment = unescapeFragment;
function escapeFragment(str) {
return encodeURIComponent(escapeJsonPointer(str));
}
exports.escapeFragment = escapeFragment;
function escapeJsonPointer(str) {
if (typeof str == "number") return `${str}`;
return str.replace(/~/g, "~0").replace(/\//g, "~1");
}
exports.escapeJsonPointer = escapeJsonPointer;
function unescapeJsonPointer(str) {
return str.replace(/~1/g, "/").replace(/~0/g, "~");
}
exports.unescapeJsonPointer = unescapeJsonPointer;
function eachItem(xs, f) {
if (Array.isArray(xs)) for (const x of xs) f(x);
else f(xs);
}
exports.eachItem = eachItem;
function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName }) {
return (gen, from, to, toName) => {
const res = to === void 0 ? from : to instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof codegen_1.Name ? (mergeToName(gen, to, from), from) : mergeValues(from, to);
return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res;
};
}
exports.mergeEvaluated = {
props: makeMergeEvaluated({
mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => {
gen.if((0, codegen_1._)`${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._)`${to} || {}`).code((0, codegen_1._)`Object.assign(${to}, ${from})`));
}),
mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => {
if (from === true) gen.assign(to, true);
else {
gen.assign(to, (0, codegen_1._)`${to} || {}`);
setEvaluated(gen, to, from);
}
}),
mergeValues: (from, to) => from === true ? true : {
...from,
...to
},
resultToName: evaluatedPropsToName
}),
items: makeMergeEvaluated({
mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)),
mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._)`${to} > ${from} ? ${to} : ${from}`)),
mergeValues: (from, to) => from === true ? true : Math.max(from, to),
resultToName: (gen, items) => gen.var("items", items)
})
};
function evaluatedPropsToName(gen, ps) {
if (ps === true) return gen.var("props", true);
const props = gen.var("props", (0, codegen_1._)`{}`);
if (ps !== void 0) setEvaluated(gen, props, ps);
return props;
}
exports.evaluatedPropsToName = evaluatedPropsToName;
function setEvaluated(gen, props, ps) {
Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p)}`, true));
}
exports.setEvaluated = setEvaluated;
const snippets = {};
function useFunc(gen, f) {
return gen.scopeValue("func", {
ref: f,
code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code))
});
}
exports.useFunc = useFunc;
var Type;
(function(Type) {
Type[Type["Num"] = 0] = "Num";
Type[Type["Str"] = 1] = "Str";
})(Type || (exports.Type = Type = {}));
function getErrorPath(dataProp, dataPropType, jsPropertySyntax) {
if (dataProp instanceof codegen_1.Name) {
const isNumber = dataPropType === Type.Num;
return jsPropertySyntax ? isNumber ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`;
}
return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp);
}
exports.getErrorPath = getErrorPath;
function checkStrictMode(it, msg, mode = it.opts.strictSchema) {
if (!mode) return;
msg = `strict mode: ${msg}`;
if (mode === true) throw new Error(msg);
it.self.logger.warn(msg);
}
exports.checkStrictMode = checkStrictMode;
}));
//#endregion
//#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/ajv/8.20.0/45a7731a7f226afbb54bce5941cf72055c748f37aa24c1b293e6625f57e4ce6e/node_modules/ajv/dist/compile/names.js
var require_names = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require_codegen();
exports.default = {
data: new codegen_1.Name("data"),
valCxt: new codegen_1.Name("valCxt"),
instancePath: new codegen_1.Name("instancePath"),
parentData: new codegen_1.Name("parentData"),
parentDataProperty: new codegen_1.Name("parentDataProperty"),
rootData: new codegen_1.Name("rootData"),
dynamicAnchors: new codegen_1.Name("dynamicAnchors"),
vErrors: new codegen_1.Name("vErrors"),
errors: new codegen_1.Name("errors"),
this: new codegen_1.Name("this"),
self: new codegen_1.Name("self"),
scope: new codegen_1.Name("scope"),
json: new codegen_1.Name("json"),
jsonPos: new codegen_1.Name("jsonPos"),
jsonLen: new codegen_1.Name("jsonLen"),
jsonPart: new codegen_1.Name("jsonPart")
};
}));
//#endregion
//#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/ajv/8.20.0/45a7731a7f226afbb54bce5941cf72055c748f37aa24c1b293e6625f57e4ce6e/node_modules/ajv/dist/compile/errors.js
var require_errors = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0;
const codegen_1 = require_codegen();
const util_1 = require_util();
const names_1 = require_names();
exports.keywordError = { message: ({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation` };
exports.keyword$DataError = { message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` };
function reportError(cxt, error = exports.keywordError, errorPaths, overrideAllErrors) {
const { it } = cxt;
const { gen, compositeRule, allErrors } = it;
const errObj = errorObjectCode(cxt, error, errorPaths);
if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) addError(gen, errObj);
else returnErrors(it, (0, codegen_1._)`[${errObj}]`);
}
exports.reportError = reportError;
function reportExtraError(cxt, error = exports.keywordError, errorPaths) {
const { it } = cxt;
const { gen, compositeRule, allErrors } = it;
addError(gen, errorObjectCode(cxt, error, errorPaths));
if (!(compositeRule || allErrors)) returnErrors(it, names_1.default.vErrors);
}
exports.reportExtraError = reportExtraError;
function resetErrorsCount(gen, errsCount) {
gen.assign(names_1.default.errors, errsCount);
gen.if((0, codegen_1._)`${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._)`${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null)));
}
exports.resetErrorsCount = resetErrorsCount;
function extendErrors({ gen, keyword, schemaValue, data, errsCount, it }) {
/* istanbul ignore if */
if (errsCount === void 0) throw new Error("ajv implementation error");
const err = gen.name("err");
gen.forRange("i", errsCount, names_1.default.errors, (i) => {
gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i}]`);
gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath)));
gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`);
if (it.opts.verbose) {
gen.assign((0, codegen_1._)`${err}.schema`, schemaValue);
gen.assign((0, codegen_1._)`${err}.data`, data);
}
});
}
exports.extendErrors = extendErrors;
function addError(gen, errObj) {
const err = gen.const("err", errObj);
gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err})`);
gen.code((0, codegen_1._)`${names_1.default.errors}++`);
}
function returnErrors(it, errs) {
const { gen, validateName, schemaEnv } = it;
if (schemaEnv.$async) gen.throw((0, codegen_1._)`new ${it.ValidationError}(${errs})`);
else {
gen.assign((0, codegen_1._)`${validateName}.errors`, errs);
gen.return(false);
}
}
const E = {
keyword: new codegen_1.Name("keyword"),
schemaPath: new codegen_1.Name("schemaPath"),
params: new codegen_1.Name("params"),
propertyName: new codegen_1.Name("propertyName"),
message: new codegen_1.Name("message"),
schema: new codegen_1.Name("schema"),
parentSchema: new codegen_1.Name("parentSchema")
};
function errorObjectCode(cxt, error, errorPaths) {
const { createErrors } = cxt.it;
if (createErrors === false) return (0, codegen_1._)`{}`;
return errorObject(cxt, error, errorPaths);
}
function errorObject(cxt, error, errorPaths = {}) {
const { gen, it } = cxt;
const keyValues = [errorInstancePath(it, errorPaths), errorSchemaPath(cxt, errorPaths)];
extraErrorProps(cxt, error, keyValues);
return gen.object(...keyValues);
}
function errorInstancePath({ errorPath }, { instancePath }) {
const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath;
return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)];
}
function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) {
let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword}`;
if (schemaPath) schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`;
return [E.schemaPath, schPath];
}
function extraErrorProps(cxt, { params, message }, keyValues) {
const { keyword, data, schemaValue, it } = cxt;
const { opts, propertyName, topSchemaRef, schemaPath } = it;
keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]);
if (opts.messages) keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]);
if (opts.verbose) keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]);
if (propertyName) keyValues.push([E.propertyName, propertyName]);
}
}));
//#endregion
//#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/ajv/8.20.0/45a7731a7f226afbb54bce5941cf72055c748f37aa24c1b293e6625f57e4ce6e/node_modules/ajv/dist/compile/validate/boolSchema.js
var require_boolSchema = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0;
const errors_1 = require_errors();
const codegen_1 = require_codegen();
const names_1 = require_names();
const boolError = { message: "boolean schema is false" };
function topBoolOrEmptySchema(it) {
const { gen, schema, validateName } = it;
if (schema === false) falseSchemaError(it, false);
else if (typeof schema == "object" && schema.$async === true) gen.return(names_1.default.data);
else {
gen.assign((0, codegen_1._)`${validateName}.errors`, null);
gen.return(true);
}
}
exports.topBoolOrEmptySchema = topBoolOrEmptySchema;
function boolOrEmptySchema(it, valid) {
const { gen, schema } = it;
if (schema === false) {
gen.var(valid, false);
falseSchemaError(it);
} else gen.var(valid, true);
}
exports.boolOrEmptySchema = boolOrEmptySchema;
function falseSchemaError(it, overrideAllErrors) {
const { gen, data } = it;
const cxt = {
gen,
keyword: "false schema",
data,
schema: false,
schemaCode: false,
schemaValue: false,
params: {},
it
};
(0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors);
}
}));
//#endregion
//#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/ajv/8.20.0/45a7731a7f226afbb54bce5941cf72055c748f37aa24c1b293e6625f57e4ce6e/node_modules/ajv/dist/compile/rules.js
var require_rules = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.getRules = exports.isJSONType = void 0;
const jsonTypes = /* @__PURE__ */ new Set([
"string",
"number",
"integer",
"boolean",
"null",
"object",
"array"
]);
function isJSONType(x) {
return typeof x == "string" && jsonTypes.has(x);
}
exports.isJSONType = isJSONType;
function getRules() {
const groups = {
number: {
type: "number",
rules: []
},
string: {
type: "string",
rules: []
},
array: {
type: "array",
rules: []
},
object: {
type: "object",
rules: []
}
};
return {
types: {
...groups,
integer: true,
boolean: true,
null: true
},
rules: [
{ rules: [] },
groups.number,
groups.string,
groups.array,
groups.object
],
post: { rules: [] },
all: {},
keywords: {}
};
}
exports.getRules = getRules;
}));
//#endregion
//#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/ajv/8.20.0/45a7731a7f226afbb54bce5941cf72055c748f37aa24c1b293e6625f57e4ce6e/node_modules/ajv/dist/compile/validate/applicability.js
var require_applicability = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0;
function schemaHasRulesForType({ schema, self }, type) {
const group = self.RULES.types[type];
return group && group !== true && shouldUseGroup(schema, group);
}
exports.schemaHasRulesForType = schemaHasRulesForType;
function shouldUseGroup(schema, group) {
return group.rules.some((rule) => shouldUseRule(schema, rule));
}
exports.shouldUseGroup = shouldUseGroup;
function shouldUseRule(schema, rule) {
var _a;
return schema[rule.keyword] !== void 0 || ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== void 0));
}
exports.shouldUseRule = shouldUseRule;
}));
//#endregion
//#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/ajv/8.20.0/45a7731a7f226afbb54bce5941cf72055c748f37aa24c1b293e6625f57e4ce6e/node_modules/ajv/dist/compile/validate/dataType.js
var require_dataType = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0;
const rules_1 = require_rules();
const applicability_1 = require_applicability();
const errors_1 = require_errors();
const codegen_1 = require_codegen();
const util_1 = require_util();
var DataType;
(function(DataType) {
DataType[DataType["Correct"] = 0] = "Correct";
DataType[DataType["Wrong"] = 1] = "Wrong";
})(DataType || (exports.DataType = DataType = {}));
function getSchemaTypes(schema) {
const types = getJSONTypes(schema.type);
if (types.includes("null")) {
if (schema.nullable === false) throw new Error("type: null contradicts nullable: false");
} else {
if (!types.length && schema.nullable !== void 0) throw new Error("\"nullable\" cannot be used without \"type\"");
if (schema.nullable === true) types.push("null");
}
return types;
}
exports.getSchemaTypes = getSchemaTypes;
function getJSONTypes(ts) {
const types = Array.isArray(ts) ? ts : ts ? [ts] : [];
if (types.every(rules_1.isJSONType)) return types;
throw new Error("type must be JSONType or JSONType[]: " + types.join(","));
}
exports.getJSONTypes = getJSONTypes;
function coerceAndCheckDataType(it, types) {
const { gen, data, opts } = it;
const coerceTo = coerceToTypes(types, opts.coerceTypes);
const checkTypes = types.length > 0 && !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0]));
if (checkTypes) {
const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong);
gen.if(wrongType, () => {
if (coerceTo.length) coerceData(it, types, coerceTo);
else reportTypeError(it);
});
}
return checkTypes;
}
exports.coerceAndCheckDataType = coerceAndCheckDataType;
const COERCIBLE = /* @__PURE__ */ new Set([
"string",
"number",
"integer",
"boolean",
"null"
]);
function coerceToTypes(types, coerceTypes) {
return coerceTypes ? types.filter((t) => COERCIBLE.has(t) || coerceTypes === "array" && t === "array") : [];
}
function coerceData(it, types, coerceTo) {
const { gen, data, opts } = it;
const dataType = gen.let("dataType", (0, codegen_1._)`typeof ${data}`);
const coerced = gen.let("coerced", (0, codegen_1._)`undefined`);
if (opts.coerceTypes === "array") gen.if((0, codegen_1._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1._)`${data}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data}`).if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data)));
gen.if((0, codegen_1._)`${coerced} !== undefined`);
for (const t of coerceTo) if (COERCIBLE.has(t) || t === "array" && opts.coerceTypes === "array") coerceSpecificType(t);
gen.else();
reportTypeError(it);
gen.endIf();
gen.if((0, codegen_1._)`${coerced} !== undefined`, () => {
gen.assign(data, coerced);
assignParentData(it, coerced);
});
function coerceSpecificType(t) {
switch (t) {
case "string":
gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data}`).elseIf((0, codegen_1._)`${data} === null`).assign(coerced, (0, codegen_1._)`""`);
return;
case "number":
gen.elseIf((0, codegen_1._)`${dataType} == "boolean" || ${data} === null
|| (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced, (0, codegen_1._)`+${data}`);
return;
case "integer":
gen.elseIf((0, codegen_1._)`${dataType} === "boolean" || ${data} === null
|| (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced, (0, codegen_1._)`+${data}`);
return;
case "boolean":
gen.elseIf((0, codegen_1._)`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data} === "true" || ${data} === 1`).assign(coerced, true);
return;
case "null":
gen.elseIf((0, codegen_1._)`${data} === "" || ${data} === 0 || ${data} === false`);
gen.assign(coerced, null);
return;
case "array": gen.elseIf((0, codegen_1._)`${dataType} === "string" || ${dataT