@shopify/cli
Version:
A CLI tool to build for the Shopify platform
1,186 lines (1,176 loc) • 646 kB
JavaScript
import {
AbortController,
AbortError,
BugError,
captureOutput,
envPaths,
exec,
fileExists,
findPathUp,
glob,
inferPackageManagerForGlobalCLI,
isUnitTest,
mimicFunction,
outputContent,
outputDebug,
outputToken,
readFile,
require_get_stream,
runWithTimer,
writeFile
} from "./chunk-4NC2NVYY.js";
import {
dirname,
joinPath
} from "./chunk-EG6MBBEN.js";
import {
require_semver
} from "./chunk-HMDWNGIV.js";
import {
__commonJS,
__export,
__require,
__toESM,
init_cjs_shims
} from "./chunk-PKR7KJ6P.js";
// ../../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/compile/codegen/code.js
var require_code = __commonJS({
"../../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/compile/codegen/code.js"(exports) {
"use strict";
init_cjs_shims();
Object.defineProperty(exports, "__esModule", { value: !0 });
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) {
if (super(), !exports.IDENTIFIER.test(s))
throw new Error("CodeGen: name must be a valid identifier");
this.str = s;
}
toString() {
return this.str;
}
emptyStr() {
return !1;
}
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 !1;
let 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) => (c instanceof Name && (names[c.str] = (names[c.str] || 0) + 1), names), {});
}
};
exports._Code = _Code;
exports.nil = new _Code("");
function _(strs, ...args) {
let code = [strs[0]], i = 0;
for (; i < args.length; )
addCodeArg(code, args[i]), code.push(strs[++i]);
return new _Code(code);
}
exports._ = _;
var plus = new _Code("+");
function str(strs, ...args) {
let expr = [safeStringify(strs[0])], i = 0;
for (; i < args.length; )
expr.push(plus), addCodeArg(expr, args[i]), expr.push(plus, safeStringify(strs[++i]));
return optimize(expr), new _Code(expr);
}
exports.str = str;
function addCodeArg(code, arg) {
arg instanceof _Code ? code.push(...arg._items) : arg instanceof Name ? code.push(arg) : code.push(interpolate(arg));
}
exports.addCodeArg = addCodeArg;
function optimize(expr) {
let i = 1;
for (; i < expr.length - 1; ) {
if (expr[i] === plus) {
let 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")
return b instanceof Name || a[a.length - 1] !== '"' ? void 0 : typeof b != "string" ? `${a.slice(0, -1)}${b}"` : b[0] === '"' ? a.slice(0, -1) + b.slice(1) : void 0;
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 getProperty3(key) {
return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`;
}
exports.getProperty = getProperty3;
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;
}
});
// ../../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/compile/codegen/scope.js
var require_scope = __commonJS({
"../../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/compile/codegen/scope.js"(exports) {
"use strict";
init_cjs_shims();
Object.defineProperty(exports, "__esModule", { value: !0 });
exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0;
var code_1 = require_code(), ValueError = class extends Error {
constructor(name) {
super(`CodeGen: "code" for ${name} not defined`), this.value = name.value;
}
}, UsedValueState;
(function(UsedValueState2) {
UsedValueState2[UsedValueState2.Started = 0] = "Started", UsedValueState2[UsedValueState2.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) {
let 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) && _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;
var line = (0, code_1._)`\n`, 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");
let name = this.toName(nameOrPrefix), { prefix } = name, valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref, vs = this._values[prefix];
if (vs) {
let _name = vs.get(valueKey);
if (_name)
return _name;
} else
vs = this._values[prefix] = /* @__PURE__ */ new Map();
vs.set(valueKey, name);
let s = this._scope[prefix] || (this._scope[prefix] = []), itemIndex = s.length;
return s[itemIndex] = value.ref, name.setValue(value, { property: prefix, itemIndex }), name;
}
getValue(prefix, keyOrRef) {
let vs = this._values[prefix];
if (vs)
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 (let prefix in values) {
let vs = values[prefix];
if (!vs)
continue;
let 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) {
let 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?.(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;
}
});
// ../../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/compile/codegen/index.js
var require_codegen = __commonJS({
"../../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/compile/codegen/index.js"(exports) {
"use strict";
init_cjs_shims();
Object.defineProperty(exports, "__esModule", { value: !0 });
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;
var code_1 = require_code(), scope_1 = require_scope(), code_2 = require_code();
Object.defineProperty(exports, "_", { enumerable: !0, get: function() {
return code_2._;
} });
Object.defineProperty(exports, "str", { enumerable: !0, get: function() {
return code_2.str;
} });
Object.defineProperty(exports, "strConcat", { enumerable: !0, get: function() {
return code_2.strConcat;
} });
Object.defineProperty(exports, "nil", { enumerable: !0, get: function() {
return code_2.nil;
} });
Object.defineProperty(exports, "getProperty", { enumerable: !0, get: function() {
return code_2.getProperty;
} });
Object.defineProperty(exports, "stringify", { enumerable: !0, get: function() {
return code_2.stringify;
} });
Object.defineProperty(exports, "regexpCode", { enumerable: !0, get: function() {
return code_2.regexpCode;
} });
Object.defineProperty(exports, "Name", { enumerable: !0, get: function() {
return code_2.Name;
} });
var scope_2 = require_scope();
Object.defineProperty(exports, "Scope", { enumerable: !0, get: function() {
return scope_2.Scope;
} });
Object.defineProperty(exports, "ValueScope", { enumerable: !0, get: function() {
return scope_2.ValueScope;
} });
Object.defineProperty(exports, "ValueScopeName", { enumerable: !0, get: function() {
return scope_2.ValueScopeName;
} });
Object.defineProperty(exports, "varKinds", { enumerable: !0, 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;
}
}, Def = class extends Node {
constructor(varKind, name, rhs) {
super(), this.varKind = varKind, this.name = name, this.rhs = rhs;
}
render({ es5, _n }) {
let varKind = es5 ? scope_1.varKinds.var : this.varKind, rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`;
return `${varKind} ${this.name}${rhs};` + _n;
}
optimizeNames(names, constants) {
if (names[this.name.str])
return this.rhs && (this.rhs = optimizeExpr(this.rhs, names, constants)), this;
}
get names() {
return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {};
}
}, 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), this;
}
get names() {
let names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names };
return addExprNames(names, this.rhs);
}
}, 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;
}
}, Label = class extends Node {
constructor(label) {
super(), this.label = label, this.names = {};
}
render({ _n }) {
return `${this.label}:` + _n;
}
}, Break = class extends Node {
constructor(label) {
super(), this.label = label, this.names = {};
}
render({ _n }) {
return `break${this.label ? ` ${this.label}` : ""};` + _n;
}
}, Throw = class extends Node {
constructor(error) {
super(), this.error = error;
}
render({ _n }) {
return `throw ${this.error};` + _n;
}
get names() {
return this.error.names;
}
}, 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) {
return this.code = optimizeExpr(this.code, names, constants), this;
}
get names() {
return this.code instanceof code_1._CodeOrName ? this.code.names : {};
}
}, ParentNode = class extends Node {
constructor(nodes = []) {
super(), this.nodes = nodes;
}
render(opts) {
return this.nodes.reduce((code, n) => code + n.render(opts), "");
}
optimizeNodes() {
let { nodes } = this, i = nodes.length;
for (; i--; ) {
let n = nodes[i].optimizeNodes();
Array.isArray(n) ? nodes.splice(i, 1, ...n) : n ? nodes[i] = n : nodes.splice(i, 1);
}
return nodes.length > 0 ? this : void 0;
}
optimizeNames(names, constants) {
let { nodes } = this, i = nodes.length;
for (; i--; ) {
let n = nodes[i];
n.optimizeNames(names, constants) || (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), {});
}
}, BlockNode = class extends ParentNode {
render(opts) {
return "{" + opts._n + super.render(opts) + "}" + opts._n;
}
}, Root = class extends ParentNode {
}, 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);
return this.else && (code += "else " + this.else.render(opts)), code;
}
optimizeNodes() {
super.optimizeNodes();
let cond = this.condition;
if (cond === !0)
return this.nodes;
let e = this.else;
if (e) {
let ns = e.optimizeNodes();
e = this.else = Array.isArray(ns) ? new Else(ns) : ns;
}
if (e)
return cond === !1 ? e instanceof _If ? e : e.nodes : this.nodes.length ? this : new _If(not(cond), e instanceof _If ? [e] : e.nodes);
if (!(cond === !1 || !this.nodes.length))
return this;
}
optimizeNames(names, constants) {
var _a;
if (this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants), !!(super.optimizeNames(names, constants) || this.else))
return this.condition = optimizeExpr(this.condition, names, constants), this;
}
get names() {
let names = super.names;
return addExprNames(names, this.condition), this.else && addNames(names, this.else.names), 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), this;
}
get names() {
return addNames(super.names, this.iteration.names);
}
}, ForRange = class extends For {
constructor(varKind, name, from, to) {
super(), this.varKind = varKind, this.name = name, this.from = from, this.to = to;
}
render(opts) {
let varKind = opts.es5 ? scope_1.varKinds.var : this.varKind, { name, from, to } = this;
return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts);
}
get names() {
let names = addExprNames(super.names, this.from);
return addExprNames(names, this.to);
}
}, 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), this;
}
get names() {
return addNames(super.names, this.iterable.names);
}
}, 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);
return this.catch && (code += this.catch.render(opts)), this.finally && (code += this.finally.render(opts)), code;
}
optimizeNodes() {
var _a, _b;
return super.optimizeNodes(), (_a = this.catch) === null || _a === void 0 || _a.optimizeNodes(), (_b = this.finally) === null || _b === void 0 || _b.optimizeNodes(), this;
}
optimizeNames(names, constants) {
var _a, _b;
return 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), this;
}
get names() {
let names = super.names;
return this.catch && addNames(names, this.catch.names), this.finally && addNames(names, this.finally.names), names;
}
}, 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 ? `
` : "" }, this._extScope = extScope, this._scope = new scope_1.Scope({ parent: extScope }), this._nodes = [new Root()];
}
toString() {
return this._root.render(this.opts);
}
// returns unique name in the internal scope
name(prefix) {
return this._scope.name(prefix);
}
// reserves unique name in the external scope
scopeName(prefix) {
return this._extScope.name(prefix);
}
// reserves unique name in the external scope and assigns value to it
scopeValue(prefixOrName, value) {
let name = this._extScope.value(prefixOrName, value);
return (this._values[name.prefix] || (this._values[name.prefix] = /* @__PURE__ */ new Set())).add(name), name;
}
getScopeValue(prefix, keyOrRef) {
return this._extScope.getValue(prefix, keyOrRef);
}
// return code that assigns values in the external scope to the names that are used internally
// (same names that were returned by gen.scopeName or gen.scopeValue)
scopeRefs(scopeName) {
return this._extScope.scopeRefs(scopeName, this._values);
}
scopeCode() {
return this._extScope.scopeCode(this._values);
}
_def(varKind, nameOrPrefix, rhs, constant) {
let name = this._scope.toName(nameOrPrefix);
return rhs !== void 0 && constant && (this._constants[name.str] = rhs), this._leafNode(new Def(varKind, name, rhs)), name;
}
// `const` declaration (`var` in es5 mode)
const(nameOrPrefix, rhs, _constant) {
return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant);
}
// `let` declaration with optional assignment (`var` in es5 mode)
let(nameOrPrefix, rhs, _constant) {
return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant);
}
// `var` declaration with optional assignment
var(nameOrPrefix, rhs, _constant) {
return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant);
}
// assignment code
assign(lhs, rhs, sideEffects) {
return this._leafNode(new Assign(lhs, rhs, sideEffects));
}
// `+=` code
add(lhs, rhs) {
return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs));
}
// appends passed SafeExpr to code or executes Block
code(c) {
return typeof c == "function" ? c() : c !== code_1.nil && this._leafNode(new AnyCode(c)), this;
}
// returns code for object literal for the passed argument list of key-value pairs
object(...keyValues) {
let code = ["{"];
for (let [key, value] of keyValues)
code.length > 1 && code.push(","), code.push(key), (key !== value || this.opts.es5) && (code.push(":"), (0, code_1.addCodeArg)(code, value));
return code.push("}"), new code_1._Code(code);
}
// `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed)
if(condition, thenBody, elseBody) {
if (this._blockNode(new If(condition)), 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;
}
// `else if` clause - invalid without `if` or after `else` clauses
elseIf(condition) {
return this._elseNode(new If(condition));
}
// `else` clause - only valid after `if` or `else if` clauses
else() {
return this._elseNode(new Else());
}
// end `if` statement (needed if gen.if was used only with condition)
endIf() {
return this._endBlockNode(If, Else);
}
_for(node, forBody) {
return this._blockNode(node), forBody && this.code(forBody).endFor(), this;
}
// a generic `for` clause (or statement if `forBody` is passed)
for(iteration, forBody) {
return this._for(new ForLoop(iteration), forBody);
}
// `for` statement for a range of values
forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) {
let name = this._scope.toName(nameOrPrefix);
return this._for(new ForRange(varKind, name, from, to), () => forBody(name));
}
// `for-of` statement (in es5 mode replace with a normal for loop)
forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) {
let name = this._scope.toName(nameOrPrefix);
if (this.opts.es5) {
let 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));
}
// `for-in` statement.
// With option `ownProperties` replaced with a `for-of` loop for object keys
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);
let name = this._scope.toName(nameOrPrefix);
return this._for(new ForIter("in", varKind, name, obj), () => forBody(name));
}
// end `for` loop
endFor() {
return this._endBlockNode(For);
}
// `label` statement
label(label) {
return this._leafNode(new Label(label));
}
// `break` statement
break(label) {
return this._leafNode(new Break(label));
}
// `return` statement
return(value) {
let node = new Return();
if (this._blockNode(node), this.code(value), node.nodes.length !== 1)
throw new Error('CodeGen: "return" should have one node');
return this._endBlockNode(Return);
}
// `try` statement
try(tryBody, catchCode, finallyCode) {
if (!catchCode && !finallyCode)
throw new Error('CodeGen: "try" without "catch" and "finally"');
let node = new Try();
if (this._blockNode(node), this.code(tryBody), catchCode) {
let error = this.name("e");
this._currNode = node.catch = new Catch(error), catchCode(error);
}
return finallyCode && (this._currNode = node.finally = new Finally(), this.code(finallyCode)), this._endBlockNode(Catch, Finally);
}
// `throw` statement
throw(error) {
return this._leafNode(new Throw(error));
}
// start self-balancing block
block(body, nodeCount) {
return this._blockStarts.push(this._nodes.length), body && this.code(body).endBlock(nodeCount), this;
}
// end the current self-balancing block
endBlock(nodeCount) {
let len = this._blockStarts.pop();
if (len === void 0)
throw new Error("CodeGen: not in self-balancing block");
let 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`);
return this._nodes.length = len, this;
}
// `function` heading (or definition if funcBody is passed)
func(name, args = code_1.nil, async, funcBody) {
return this._blockNode(new Func(name, args, async)), funcBody && this.code(funcBody).endFunc(), this;
}
// end function definition
endFunc() {
return this._endBlockNode(Func);
}
optimize(n = 1) {
for (; n-- > 0; )
this._root.optimizeNodes(), this._root.optimizeNames(this._root.names, this._constants);
}
_leafNode(node) {
return this._currNode.nodes.push(node), this;
}
_blockNode(node) {
this._currNode.nodes.push(node), this._nodes.push(node);
}
_endBlockNode(N1, N2) {
let n = this._currNode;
if (n instanceof N1 || N2 && n instanceof N2)
return this._nodes.pop(), this;
throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`);
}
_elseNode(node) {
let n = this._currNode;
if (!(n instanceof If))
throw new Error('CodeGen: "else" without "if"');
return this._currNode = n.else = node, this;
}
get _root() {
return this._nodes[0];
}
get _currNode() {
let ns = this._nodes;
return ns[ns.length - 1];
}
set _currNode(node) {
let ns = this._nodes;
ns[ns.length - 1] = node;
}
};
exports.CodeGen = CodeGen;
function addNames(names, from) {
for (let 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) => (c instanceof code_1.Name && (c = replaceName(c)), c instanceof code_1._Code ? items.push(...c._items) : items.push(c), items), []));
function replaceName(n) {
let c = constants[n.str];
return c === void 0 || names[n.str] !== 1 ? n : (delete names[n.str], 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 (let 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;
var andCode = mappend(exports.operators.AND);
function and(...args) {
return args.reduce(andCode);
}
exports.and = and;
var 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})`;
}
}
});
// ../../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/compile/util.js
var require_util = __commonJS({
"../../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/compile/util.js"(exports) {
"use strict";
init_cjs_shims();
Object.defineProperty(exports, "__esModule", { value: !0 });
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;
var codegen_1 = require_codegen(), code_1 = require_code();
function toHash(arr) {
let hash = {};
for (let item of arr)
hash[item] = !0;
return hash;
}
exports.toHash = toHash;
function alwaysValidSchema(it, schema) {
return typeof schema == "boolean" ? schema : Object.keys(schema).length === 0 ? !0 : (checkUnknownRules(it, schema), !schemaHasRules(schema, it.self.RULES.all));
}
exports.alwaysValidSchema = alwaysValidSchema;
function checkUnknownRules(it, schema = it.schema) {
let { opts, self } = it;
if (!opts.strictSchema || typeof schema == "boolean")
return;
let rules = self.RULES.keywords;
for (let key in schema)
rules[key] || checkStrictMode(it, `unknown keyword: "${key}"`);
}
exports.checkUnknownRules = checkUnknownRules;
function schemaHasRules(schema, rules) {
if (typeof schema == "boolean")
return !schema;
for (let key in schema)
if (rules[key])
return !0;
return !1;
}
exports.schemaHasRules = schemaHasRules;
function schemaHasRulesButRef(schema, RULES) {
if (typeof schema == "boolean")
return !schema;
for (let key in schema)
if (key !== "$ref" && RULES.all[key])
return !0;
return !1;
}
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) {
return typeof str == "number" ? `${str}` : 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 (let x of xs)
f(x);
else
f(xs);
}
exports.eachItem = eachItem;
function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName }) {
return (gen, from, to, toName) => {
let 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, !0), () => 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`, () => {
from === !0 ? gen.assign(to, !0) : (gen.assign(to, (0, codegen_1._)`${to} || {}`), setEvaluated(gen, to, from));
}),
mergeValues: (from, to) => from === !0 ? !0 : { ...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 === !0 ? !0 : (0, codegen_1._)`${to} > ${from} ? ${to} : ${from}`)),
mergeValues: (from, to) => from === !0 ? !0 : Math.max(from, to),
resultToName: (gen, items) => gen.var("items", items)
})
};
function evaluatedPropsToName(gen, ps) {
if (ps === !0)
return gen.var("props", !0);
let props = gen.var("props", (0, codegen_1._)`{}`);
return ps !== void 0 && setEvaluated(gen, props, ps), 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)}`, !0));
}
exports.setEvaluated = setEvaluated;
var 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(Type2) {
Type2[Type2.Num = 0] = "Num", Type2[Type2.Str = 1] = "Str";
})(Type || (exports.Type = Type = {}));
function getErrorPath(dataProp, dataPropType, jsPropertySyntax) {
if (dataProp instanceof codegen_1.Name) {
let 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) {
if (msg = `strict mode: ${msg}`, mode === !0)
throw new Error(msg);
it.self.logger.warn(msg);
}
}
exports.checkStrictMode = checkStrictMode;
}
});
// ../../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/compile/names.js
var require_names = __commonJS({
"../../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/compile/names.js"(exports) {
"use strict";
init_cjs_shims();
Object.defineProperty(exports, "__esModule", { value: !0 });
var codegen_1 = require_codegen(), names = {
// validation function arguments
data: new codegen_1.Name("data"),
// data passed to validation function
// args passed from referencing schema
valCxt: new codegen_1.Name("valCxt"),
// validation/data context - should not be used directly, it is destructured to the names below
instancePath: new codegen_1.Name("instancePath"),
parentData: new codegen_1.Name("parentData"),
parentDataProperty: new codegen_1.Name("parentDataProperty"),
rootData: new codegen_1.Name("rootData"),
// root data - same as the data passed to the first/top validation function
dynamicAnchors: new codegen_1.Name("dynamicAnchors"),
// used to support recursiveRef and dynamicRef
// function scoped variables
vErrors: new codegen_1.Name("vErrors"),
// null or array of validation errors
errors: new codegen_1.Name("errors"),
// counter of validation errors
this: new codegen_1.Name("this"),
// "globals"
self: new codegen_1.Name("self"),
scope: new codegen_1.Name("scope"),
// JTD serialize/parse name for JSON string and position
json: new codegen_1.Name("json"),
jsonPos: new codegen_1.Name("jsonPos"),
jsonLen: new codegen_1.Name("jsonLen"),
jsonPart: new codegen_1.Name("jsonPart")
};
exports.default = names;
}
});
// ../../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/compile/errors.js
var require_errors = __commonJS({
"../../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/compile/errors.js"(exports) {
"use strict";
init_cjs_shims();
Object.defineProperty(exports, "__esModule", { value: !0 });
exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0;
var codegen_1 = require_codegen(), util_1 = require_util(), 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) {
let { it } = cxt, { gen, compositeRule, allErrors } = it, errObj = errorObjectCode(cxt, error, errorPaths);
overrideAllErrors ?? (compositeRule || allErrors) ? addError(gen, errObj) : returnErrors(it, (0, codegen_1._)`[${errObj}]`);
}
exports.reportError = reportError;
function reportExtraError(cxt, error = exports.keywordError, errorPaths) {
let { it } = cxt, { gen, compositeRule, allErrors } = it, errObj = errorObjectCode(cxt, error, errorPaths);
addError(gen, errObj), 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 }) {
if (errsCount === void 0)
throw new Error("ajv implementation error");
let 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}`), 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) {
let 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) {
let { gen, validateName, schemaEnv } = it;
schemaEnv.$async ? gen.throw((0, codegen_1._)`new ${it.ValidationError}(${errs})`) : (gen.assign((0, codegen_1._)`${validateName}.errors`, errs), gen.return(!1));
}
var E = {
keyword: new codegen_1.Name("keyword"),
schemaPath: new codegen_1.Name("schemaPath"),
// also used in JTD errors
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) {
let { createErrors } = cxt.it;
return createErrors === !1 ? (0, codegen_1._)`{}` : errorObject(cxt, error, errorPaths);
}
function errorObject(cxt, error, errorPaths = {}) {
let { gen, it } = cxt, keyValues = [
errorInstancePath(it, errorPaths),
errorSchemaPath(cxt, errorPaths)
];
return extraErrorProps(cxt, error, keyValues), gen.object(...keyValues);
}
function errorInstancePath({ errorPath }, { instancePath }) {
let 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}`;
return schemaPath && (schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`), [E.schemaPath, schPath];
}
function extraErrorProps(cxt, { params, message }, keyValues) {
let { keyword, data, schemaValue, it } = cxt, { opts, propertyName, topSchemaRef, schemaPath } = it;
keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]), opts.messages && keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]), opts.verbose && keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]), propertyName && keyValues.push([E.propertyName, propertyName]);
}
}
});
// ../../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/compile/validate/boolSchema.js
var require_boolSchema = __commonJS({
"../../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/compile/validate/boolSchema.js"(exports) {
"use strict";
init_cjs_shims();
Object.defineProperty(exports, "__esModule", { value: !0 });
exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0;
var errors_1 = require_errors(), codegen_1 = require_codegen(), names_1 = require_names(), boolError = {
message: "boolean schema is false"
};
function topBoolOrEmptySchema(it) {
let { gen, schema, validateName } = it;
schema === !1 ? falseSchemaError(it, !1) : typeof schema == "object" && schema.$async === !0 ? gen.return(names_1.default.data) : (gen.assign((0, codegen_1._)`${validateName}.errors`, null), gen.return(!0));
}
exports.topBoolOrEmptySchema = topBoolOrEmptySchema;
function boolOrEmptySchema(it, valid) {
let { gen, schema } = it;
schema === !1 ? (gen.var(valid, !1), falseSchemaError(it)) : gen.var(valid, !0);
}
exports.boolOrEmptySchema = boolOrEmptySchema;
function falseSchemaError(it, overrideAllErrors) {
let { gen, data } = it, cxt = {
gen,
keyword: "false schema",
data,
schema: !1,
schemaCode: !1,
schemaValue: !1,
params: {},
it
};
(0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors);
}
}
});
// ../../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/compile/rules.js
var require_rules = __commonJS({
"../../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/compile/rules.js"(exports) {
"use strict";
init_cjs_shims();
Object.defineProperty(exports, "__esModule", { value: !0 });
exports.getRules = exports.isJSONType = void 0;
var _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"], jsonTypes = new Set(_jsonTypes);
function isJSONType(x) {
return typeof x == "string" && jsonTypes.has(x);
}
exports.isJSONType = isJSONType;
function getRules() {
let groups = {
number: { type: "number", rules: [] },
string: { type: "string", rules: [] },
array: { type: "array", rules: [] },
object: { type: "object", rules: [] }
};
return {
types: { ...groups, integer: !0, boolean: !0, null: !0 },
rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object],
post: { rules: [] },
all: {},
keywords: {}
};
}
exports.getRules = getRules;
}
});
// ../../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/compile/validate/applicability.js
var require_applicability = __commonJS({
"../../node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/compile/validate/applicability.js"(exports) {
"use strict";
init_cjs_shims();
Object.defineProperty(exports, "__esModule", { value: !0 });