39076 lines
1.3 MiB
Plaintext
39076 lines
1.3 MiB
Plaintext
var __create = Object.create;
|
|
var __defProp = Object.defineProperty;
|
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
var __getProtoOf = Object.getPrototypeOf;
|
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
var __export = (target, all) => {
|
|
for (var name in all)
|
|
__defProp(target, name, { get: all[name], enumerable: true });
|
|
};
|
|
var __copyProps = (to, from, except, desc) => {
|
|
if (from && typeof from === "object" || typeof from === "function") {
|
|
for (let key of __getOwnPropNames(from))
|
|
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
}
|
|
return to;
|
|
};
|
|
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
// If the importer is in node compatibility mode or this is not an ESM
|
|
// file that has been converted to a CommonJS file using a Babel-
|
|
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
mod
|
|
));
|
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
|
|
// src/main.ts
|
|
var main_exports = {};
|
|
__export(main_exports, {
|
|
default: () => ClaudianPlugin
|
|
});
|
|
module.exports = __toCommonJS(main_exports);
|
|
var import_obsidian27 = require("obsidian");
|
|
|
|
// node_modules/@anthropic-ai/claude-agent-sdk/sdk.mjs
|
|
var import_path = require("path");
|
|
var import_url = require("url");
|
|
var import_events = require("events");
|
|
var import_child_process = require("child_process");
|
|
var import_readline = require("readline");
|
|
var fs = __toESM(require("fs"), 1);
|
|
var import_promises = require("fs/promises");
|
|
var import_path2 = require("path");
|
|
var import_os = require("os");
|
|
var import_path3 = require("path");
|
|
var import_process = require("process");
|
|
var import_fs = require("fs");
|
|
var import_crypto = require("crypto");
|
|
var import_crypto2 = require("crypto");
|
|
var import_fs2 = require("fs");
|
|
var import_path4 = require("path");
|
|
var import_crypto3 = require("crypto");
|
|
var import_path5 = require("path");
|
|
var import_url2 = require("url");
|
|
var import_meta = {};
|
|
var __create2 = Object.create;
|
|
var __getProtoOf2 = Object.getPrototypeOf;
|
|
var __defProp2 = Object.defineProperty;
|
|
var __getOwnPropNames2 = Object.getOwnPropertyNames;
|
|
var __hasOwnProp2 = Object.prototype.hasOwnProperty;
|
|
var __toESM2 = (mod, isNodeMode, target) => {
|
|
target = mod != null ? __create2(__getProtoOf2(mod)) : {};
|
|
const to = isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target;
|
|
for (let key of __getOwnPropNames2(mod))
|
|
if (!__hasOwnProp2.call(to, key))
|
|
__defProp2(to, key, {
|
|
get: () => mod[key],
|
|
enumerable: true
|
|
});
|
|
return to;
|
|
};
|
|
var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
|
|
var __export2 = (target, all) => {
|
|
for (var name in all)
|
|
__defProp2(target, name, {
|
|
get: all[name],
|
|
enumerable: true,
|
|
configurable: true,
|
|
set: (newValue) => all[name] = () => newValue
|
|
});
|
|
};
|
|
var require_code = __commonJS((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;
|
|
class _CodeOrName {
|
|
}
|
|
exports._CodeOrName = _CodeOrName;
|
|
exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
|
|
class Name 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;
|
|
class _Code 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._ = _;
|
|
var 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)}`;
|
|
return;
|
|
}
|
|
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;
|
|
});
|
|
var require_scope = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0;
|
|
var code_1 = require_code();
|
|
class ValueError extends Error {
|
|
constructor(name) {
|
|
super(`CodeGen: "code" for ${name} not defined`);
|
|
this.value = name.value;
|
|
}
|
|
}
|
|
var 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")
|
|
};
|
|
class Scope {
|
|
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;
|
|
class ValueScopeName 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`;
|
|
class ValueScope 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;
|
|
});
|
|
var require_codegen = __commonJS((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;
|
|
var code_1 = require_code();
|
|
var scope_1 = require_scope();
|
|
var code_2 = require_code();
|
|
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("+")
|
|
};
|
|
class Node {
|
|
optimizeNodes() {
|
|
return this;
|
|
}
|
|
optimizeNames(_names, _constants) {
|
|
return this;
|
|
}
|
|
}
|
|
class Def 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 : {};
|
|
}
|
|
}
|
|
class Assign 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() {
|
|
const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names };
|
|
return addExprNames(names, this.rhs);
|
|
}
|
|
}
|
|
class AssignOp extends Assign {
|
|
constructor(lhs, op, rhs, sideEffects) {
|
|
super(lhs, rhs, sideEffects);
|
|
this.op = op;
|
|
}
|
|
render({ _n }) {
|
|
return `${this.lhs} ${this.op}= ${this.rhs};` + _n;
|
|
}
|
|
}
|
|
class Label extends Node {
|
|
constructor(label) {
|
|
super();
|
|
this.label = label;
|
|
this.names = {};
|
|
}
|
|
render({ _n }) {
|
|
return `${this.label}:` + _n;
|
|
}
|
|
}
|
|
class Break extends Node {
|
|
constructor(label) {
|
|
super();
|
|
this.label = label;
|
|
this.names = {};
|
|
}
|
|
render({ _n }) {
|
|
const label = this.label ? ` ${this.label}` : "";
|
|
return `break${label};` + _n;
|
|
}
|
|
}
|
|
class Throw extends Node {
|
|
constructor(error2) {
|
|
super();
|
|
this.error = error2;
|
|
}
|
|
render({ _n }) {
|
|
return `throw ${this.error};` + _n;
|
|
}
|
|
get names() {
|
|
return this.error.names;
|
|
}
|
|
}
|
|
class AnyCode 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 : {};
|
|
}
|
|
}
|
|
class ParentNode 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), {});
|
|
}
|
|
}
|
|
class BlockNode extends ParentNode {
|
|
render(opts) {
|
|
return "{" + opts._n + super.render(opts) + "}" + opts._n;
|
|
}
|
|
}
|
|
class Root extends ParentNode {
|
|
}
|
|
class Else extends BlockNode {
|
|
}
|
|
Else.kind = "else";
|
|
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;
|
|
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";
|
|
class For extends BlockNode {
|
|
}
|
|
For.kind = "for";
|
|
class ForLoop 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);
|
|
}
|
|
}
|
|
class ForRange 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() {
|
|
const names = addExprNames(super.names, this.from);
|
|
return addExprNames(names, this.to);
|
|
}
|
|
}
|
|
class ForIter 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);
|
|
}
|
|
}
|
|
class Func extends BlockNode {
|
|
constructor(name, args, async) {
|
|
super();
|
|
this.name = name;
|
|
this.args = args;
|
|
this.async = async;
|
|
}
|
|
render(opts) {
|
|
const _async = this.async ? "async " : "";
|
|
return `${_async}function ${this.name}(${this.args})` + super.render(opts);
|
|
}
|
|
}
|
|
Func.kind = "func";
|
|
class Return extends ParentNode {
|
|
render(opts) {
|
|
return "return " + super.render(opts);
|
|
}
|
|
}
|
|
Return.kind = "return";
|
|
class Try 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;
|
|
}
|
|
}
|
|
class Catch extends BlockNode {
|
|
constructor(error2) {
|
|
super();
|
|
this.error = error2;
|
|
}
|
|
render(opts) {
|
|
return `catch(${this.error})` + super.render(opts);
|
|
}
|
|
}
|
|
Catch.kind = "catch";
|
|
class Finally extends BlockNode {
|
|
render(opts) {
|
|
return "finally" + super.render(opts);
|
|
}
|
|
}
|
|
Finally.kind = "finally";
|
|
class CodeGen {
|
|
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);
|
|
}
|
|
name(prefix) {
|
|
return this._scope.name(prefix);
|
|
}
|
|
scopeName(prefix) {
|
|
return this._extScope.name(prefix);
|
|
}
|
|
scopeValue(prefixOrName, value) {
|
|
const name = this._extScope.value(prefixOrName, value);
|
|
const vs = this._values[name.prefix] || (this._values[name.prefix] = /* @__PURE__ */ new Set());
|
|
vs.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 error2 = this.name("e");
|
|
this._currNode = node.catch = new Catch(error2);
|
|
catchCode(error2);
|
|
}
|
|
if (finallyCode) {
|
|
this._currNode = node.finally = new Finally();
|
|
this.code(finallyCode);
|
|
}
|
|
return this._endBlockNode(Catch, Finally);
|
|
}
|
|
throw(error2) {
|
|
return this._leafNode(new Throw(error2));
|
|
}
|
|
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;
|
|
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})`;
|
|
}
|
|
});
|
|
var require_util = __commonJS((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;
|
|
var codegen_1 = require_codegen();
|
|
var code_1 = require_code();
|
|
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: self2 } = it;
|
|
if (!opts.strictSchema)
|
|
return;
|
|
if (typeof schema === "boolean")
|
|
return;
|
|
const rules = self2.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: mergeValues3, 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) : mergeValues3(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;
|
|
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) {
|
|
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;
|
|
});
|
|
var require_names = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var codegen_1 = require_codegen();
|
|
var names = {
|
|
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")
|
|
};
|
|
exports.default = names;
|
|
});
|
|
var require_errors = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0;
|
|
var codegen_1 = require_codegen();
|
|
var util_1 = require_util();
|
|
var 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, error2 = exports.keywordError, errorPaths, overrideAllErrors) {
|
|
const { it } = cxt;
|
|
const { gen, compositeRule, allErrors } = it;
|
|
const errObj = errorObjectCode(cxt, error2, 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, error2 = exports.keywordError, errorPaths) {
|
|
const { it } = cxt;
|
|
const { gen, compositeRule, allErrors } = it;
|
|
const errObj = errorObjectCode(cxt, error2, errorPaths);
|
|
addError(gen, errObj);
|
|
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 }) {
|
|
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);
|
|
}
|
|
}
|
|
var 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, error2, errorPaths) {
|
|
const { createErrors } = cxt.it;
|
|
if (createErrors === false)
|
|
return (0, codegen_1._)`{}`;
|
|
return errorObject(cxt, error2, errorPaths);
|
|
}
|
|
function errorObject(cxt, error2, errorPaths = {}) {
|
|
const { gen, it } = cxt;
|
|
const keyValues = [
|
|
errorInstancePath(it, errorPaths),
|
|
errorSchemaPath(cxt, errorPaths)
|
|
];
|
|
extraErrorProps(cxt, error2, 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]);
|
|
}
|
|
});
|
|
var require_boolSchema = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0;
|
|
var errors_1 = require_errors();
|
|
var codegen_1 = require_codegen();
|
|
var names_1 = require_names();
|
|
var 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);
|
|
}
|
|
});
|
|
var require_rules = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.getRules = exports.isJSONType = void 0;
|
|
var _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"];
|
|
var jsonTypes = new Set(_jsonTypes);
|
|
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;
|
|
});
|
|
var require_applicability = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0;
|
|
function schemaHasRulesForType({ schema, self: self2 }, type) {
|
|
const group = self2.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;
|
|
});
|
|
var require_dataType = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0;
|
|
var rules_1 = require_rules();
|
|
var applicability_1 = require_applicability();
|
|
var errors_1 = require_errors();
|
|
var codegen_1 = require_codegen();
|
|
var util_1 = require_util();
|
|
var DataType;
|
|
(function(DataType2) {
|
|
DataType2[DataType2["Correct"] = 0] = "Correct";
|
|
DataType2[DataType2["Wrong"] = 1] = "Wrong";
|
|
})(DataType || (exports.DataType = DataType = {}));
|
|
function getSchemaTypes(schema) {
|
|
const types = getJSONTypes(schema.type);
|
|
const hasNull = types.includes("null");
|
|
if (hasNull) {
|
|
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;
|
|
var 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" || ${dataType} === "number"
|
|
|| ${dataType} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`);
|
|
}
|
|
}
|
|
}
|
|
function assignParentData({ gen, parentData, parentDataProperty }, expr) {
|
|
gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr));
|
|
}
|
|
function checkDataType(dataType, data, strictNums, correct = DataType.Correct) {
|
|
const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ;
|
|
let cond;
|
|
switch (dataType) {
|
|
case "null":
|
|
return (0, codegen_1._)`${data} ${EQ} null`;
|
|
case "array":
|
|
cond = (0, codegen_1._)`Array.isArray(${data})`;
|
|
break;
|
|
case "object":
|
|
cond = (0, codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`;
|
|
break;
|
|
case "integer":
|
|
cond = numCond((0, codegen_1._)`!(${data} % 1) && !isNaN(${data})`);
|
|
break;
|
|
case "number":
|
|
cond = numCond();
|
|
break;
|
|
default:
|
|
return (0, codegen_1._)`typeof ${data} ${EQ} ${dataType}`;
|
|
}
|
|
return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond);
|
|
function numCond(_cond = codegen_1.nil) {
|
|
return (0, codegen_1.and)((0, codegen_1._)`typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data})` : codegen_1.nil);
|
|
}
|
|
}
|
|
exports.checkDataType = checkDataType;
|
|
function checkDataTypes(dataTypes, data, strictNums, correct) {
|
|
if (dataTypes.length === 1) {
|
|
return checkDataType(dataTypes[0], data, strictNums, correct);
|
|
}
|
|
let cond;
|
|
const types = (0, util_1.toHash)(dataTypes);
|
|
if (types.array && types.object) {
|
|
const notObj = (0, codegen_1._)`typeof ${data} != "object"`;
|
|
cond = types.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`;
|
|
delete types.null;
|
|
delete types.array;
|
|
delete types.object;
|
|
} else {
|
|
cond = codegen_1.nil;
|
|
}
|
|
if (types.number)
|
|
delete types.integer;
|
|
for (const t in types)
|
|
cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct));
|
|
return cond;
|
|
}
|
|
exports.checkDataTypes = checkDataTypes;
|
|
var typeError = {
|
|
message: ({ schema }) => `must be ${schema}`,
|
|
params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (0, codegen_1._)`{type: ${schemaValue}}`
|
|
};
|
|
function reportTypeError(it) {
|
|
const cxt = getTypeErrorContext(it);
|
|
(0, errors_1.reportError)(cxt, typeError);
|
|
}
|
|
exports.reportTypeError = reportTypeError;
|
|
function getTypeErrorContext(it) {
|
|
const { gen, data, schema } = it;
|
|
const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type");
|
|
return {
|
|
gen,
|
|
keyword: "type",
|
|
data,
|
|
schema: schema.type,
|
|
schemaCode,
|
|
schemaValue: schemaCode,
|
|
parentSchema: schema,
|
|
params: {},
|
|
it
|
|
};
|
|
}
|
|
});
|
|
var require_defaults = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.assignDefaults = void 0;
|
|
var codegen_1 = require_codegen();
|
|
var util_1 = require_util();
|
|
function assignDefaults(it, ty) {
|
|
const { properties, items } = it.schema;
|
|
if (ty === "object" && properties) {
|
|
for (const key in properties) {
|
|
assignDefault(it, key, properties[key].default);
|
|
}
|
|
} else if (ty === "array" && Array.isArray(items)) {
|
|
items.forEach((sch, i) => assignDefault(it, i, sch.default));
|
|
}
|
|
}
|
|
exports.assignDefaults = assignDefaults;
|
|
function assignDefault(it, prop, defaultValue) {
|
|
const { gen, compositeRule, data, opts } = it;
|
|
if (defaultValue === void 0)
|
|
return;
|
|
const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`;
|
|
if (compositeRule) {
|
|
(0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`);
|
|
return;
|
|
}
|
|
let condition = (0, codegen_1._)`${childData} === undefined`;
|
|
if (opts.useDefaults === "empty") {
|
|
condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`;
|
|
}
|
|
gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`);
|
|
}
|
|
});
|
|
var require_code2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0;
|
|
var codegen_1 = require_codegen();
|
|
var util_1 = require_util();
|
|
var names_1 = require_names();
|
|
var util_2 = require_util();
|
|
function checkReportMissingProp(cxt, prop) {
|
|
const { gen, data, it } = cxt;
|
|
gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => {
|
|
cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true);
|
|
cxt.error();
|
|
});
|
|
}
|
|
exports.checkReportMissingProp = checkReportMissingProp;
|
|
function checkMissingProp({ gen, data, it: { opts } }, properties, missing) {
|
|
return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`)));
|
|
}
|
|
exports.checkMissingProp = checkMissingProp;
|
|
function reportMissingProp(cxt, missing) {
|
|
cxt.setParams({ missingProperty: missing }, true);
|
|
cxt.error();
|
|
}
|
|
exports.reportMissingProp = reportMissingProp;
|
|
function hasPropFunc(gen) {
|
|
return gen.scopeValue("func", {
|
|
ref: Object.prototype.hasOwnProperty,
|
|
code: (0, codegen_1._)`Object.prototype.hasOwnProperty`
|
|
});
|
|
}
|
|
exports.hasPropFunc = hasPropFunc;
|
|
function isOwnProperty(gen, data, property) {
|
|
return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`;
|
|
}
|
|
exports.isOwnProperty = isOwnProperty;
|
|
function propertyInData(gen, data, property, ownProperties) {
|
|
const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} !== undefined`;
|
|
return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data, property)}` : cond;
|
|
}
|
|
exports.propertyInData = propertyInData;
|
|
function noPropertyInData(gen, data, property, ownProperties) {
|
|
const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} === undefined`;
|
|
return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond;
|
|
}
|
|
exports.noPropertyInData = noPropertyInData;
|
|
function allSchemaProperties(schemaMap) {
|
|
return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : [];
|
|
}
|
|
exports.allSchemaProperties = allSchemaProperties;
|
|
function schemaProperties(it, schemaMap) {
|
|
return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p]));
|
|
}
|
|
exports.schemaProperties = schemaProperties;
|
|
function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) {
|
|
const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data;
|
|
const valCxt = [
|
|
[names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)],
|
|
[names_1.default.parentData, it.parentData],
|
|
[names_1.default.parentDataProperty, it.parentDataProperty],
|
|
[names_1.default.rootData, names_1.default.rootData]
|
|
];
|
|
if (it.opts.dynamicRef)
|
|
valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]);
|
|
const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`;
|
|
return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`;
|
|
}
|
|
exports.callValidateCode = callValidateCode;
|
|
var newRegExp = (0, codegen_1._)`new RegExp`;
|
|
function usePattern({ gen, it: { opts } }, pattern) {
|
|
const u = opts.unicodeRegExp ? "u" : "";
|
|
const { regExp } = opts.code;
|
|
const rx = regExp(pattern, u);
|
|
return gen.scopeValue("pattern", {
|
|
key: rx.toString(),
|
|
ref: rx,
|
|
code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})`
|
|
});
|
|
}
|
|
exports.usePattern = usePattern;
|
|
function validateArray(cxt) {
|
|
const { gen, data, keyword, it } = cxt;
|
|
const valid = gen.name("valid");
|
|
if (it.allErrors) {
|
|
const validArr = gen.let("valid", true);
|
|
validateItems(() => gen.assign(validArr, false));
|
|
return validArr;
|
|
}
|
|
gen.var(valid, true);
|
|
validateItems(() => gen.break());
|
|
return valid;
|
|
function validateItems(notValid) {
|
|
const len = gen.const("len", (0, codegen_1._)`${data}.length`);
|
|
gen.forRange("i", 0, len, (i) => {
|
|
cxt.subschema({
|
|
keyword,
|
|
dataProp: i,
|
|
dataPropType: util_1.Type.Num
|
|
}, valid);
|
|
gen.if((0, codegen_1.not)(valid), notValid);
|
|
});
|
|
}
|
|
}
|
|
exports.validateArray = validateArray;
|
|
function validateUnion(cxt) {
|
|
const { gen, schema, keyword, it } = cxt;
|
|
if (!Array.isArray(schema))
|
|
throw new Error("ajv implementation error");
|
|
const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch));
|
|
if (alwaysValid && !it.opts.unevaluated)
|
|
return;
|
|
const valid = gen.let("valid", false);
|
|
const schValid = gen.name("_valid");
|
|
gen.block(() => schema.forEach((_sch, i) => {
|
|
const schCxt = cxt.subschema({
|
|
keyword,
|
|
schemaProp: i,
|
|
compositeRule: true
|
|
}, schValid);
|
|
gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`);
|
|
const merged = cxt.mergeValidEvaluated(schCxt, schValid);
|
|
if (!merged)
|
|
gen.if((0, codegen_1.not)(valid));
|
|
}));
|
|
cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
|
|
}
|
|
exports.validateUnion = validateUnion;
|
|
});
|
|
var require_keyword = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0;
|
|
var codegen_1 = require_codegen();
|
|
var names_1 = require_names();
|
|
var code_1 = require_code2();
|
|
var errors_1 = require_errors();
|
|
function macroKeywordCode(cxt, def) {
|
|
const { gen, keyword, schema, parentSchema, it } = cxt;
|
|
const macroSchema = def.macro.call(it.self, schema, parentSchema, it);
|
|
const schemaRef = useKeyword(gen, keyword, macroSchema);
|
|
if (it.opts.validateSchema !== false)
|
|
it.self.validateSchema(macroSchema, true);
|
|
const valid = gen.name("valid");
|
|
cxt.subschema({
|
|
schema: macroSchema,
|
|
schemaPath: codegen_1.nil,
|
|
errSchemaPath: `${it.errSchemaPath}/${keyword}`,
|
|
topSchemaRef: schemaRef,
|
|
compositeRule: true
|
|
}, valid);
|
|
cxt.pass(valid, () => cxt.error(true));
|
|
}
|
|
exports.macroKeywordCode = macroKeywordCode;
|
|
function funcKeywordCode(cxt, def) {
|
|
var _a;
|
|
const { gen, keyword, schema, parentSchema, $data, it } = cxt;
|
|
checkAsyncKeyword(it, def);
|
|
const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate;
|
|
const validateRef = useKeyword(gen, keyword, validate);
|
|
const valid = gen.let("valid");
|
|
cxt.block$data(valid, validateKeyword);
|
|
cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid);
|
|
function validateKeyword() {
|
|
if (def.errors === false) {
|
|
assignValid();
|
|
if (def.modifying)
|
|
modifyData(cxt);
|
|
reportErrs(() => cxt.error());
|
|
} else {
|
|
const ruleErrs = def.async ? validateAsync() : validateSync();
|
|
if (def.modifying)
|
|
modifyData(cxt);
|
|
reportErrs(() => addErrs(cxt, ruleErrs));
|
|
}
|
|
}
|
|
function validateAsync() {
|
|
const ruleErrs = gen.let("ruleErrs", null);
|
|
gen.try(() => assignValid((0, codegen_1._)`await `), (e) => gen.assign(valid, false).if((0, codegen_1._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e)));
|
|
return ruleErrs;
|
|
}
|
|
function validateSync() {
|
|
const validateErrs = (0, codegen_1._)`${validateRef}.errors`;
|
|
gen.assign(validateErrs, null);
|
|
assignValid(codegen_1.nil);
|
|
return validateErrs;
|
|
}
|
|
function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) {
|
|
const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self;
|
|
const passSchema = !("compile" in def && !$data || def.schema === false);
|
|
gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying);
|
|
}
|
|
function reportErrs(errors3) {
|
|
var _a2;
|
|
gen.if((0, codegen_1.not)((_a2 = def.valid) !== null && _a2 !== void 0 ? _a2 : valid), errors3);
|
|
}
|
|
}
|
|
exports.funcKeywordCode = funcKeywordCode;
|
|
function modifyData(cxt) {
|
|
const { gen, data, it } = cxt;
|
|
gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`));
|
|
}
|
|
function addErrs(cxt, errs) {
|
|
const { gen } = cxt;
|
|
gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => {
|
|
gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`);
|
|
(0, errors_1.extendErrors)(cxt);
|
|
}, () => cxt.error());
|
|
}
|
|
function checkAsyncKeyword({ schemaEnv }, def) {
|
|
if (def.async && !schemaEnv.$async)
|
|
throw new Error("async keyword in sync schema");
|
|
}
|
|
function useKeyword(gen, keyword, result) {
|
|
if (result === void 0)
|
|
throw new Error(`keyword "${keyword}" failed to compile`);
|
|
return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) });
|
|
}
|
|
function validSchemaType(schema, schemaType, allowUndefined = false) {
|
|
return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined");
|
|
}
|
|
exports.validSchemaType = validSchemaType;
|
|
function validateKeywordUsage({ schema, opts, self: self2, errSchemaPath }, def, keyword) {
|
|
if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) {
|
|
throw new Error("ajv implementation error");
|
|
}
|
|
const deps = def.dependencies;
|
|
if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) {
|
|
throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`);
|
|
}
|
|
if (def.validateSchema) {
|
|
const valid = def.validateSchema(schema[keyword]);
|
|
if (!valid) {
|
|
const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self2.errorsText(def.validateSchema.errors);
|
|
if (opts.validateSchema === "log")
|
|
self2.logger.error(msg);
|
|
else
|
|
throw new Error(msg);
|
|
}
|
|
}
|
|
}
|
|
exports.validateKeywordUsage = validateKeywordUsage;
|
|
});
|
|
var require_subschema = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0;
|
|
var codegen_1 = require_codegen();
|
|
var util_1 = require_util();
|
|
function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) {
|
|
if (keyword !== void 0 && schema !== void 0) {
|
|
throw new Error('both "keyword" and "schema" passed, only one allowed');
|
|
}
|
|
if (keyword !== void 0) {
|
|
const sch = it.schema[keyword];
|
|
return schemaProp === void 0 ? {
|
|
schema: sch,
|
|
schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`,
|
|
errSchemaPath: `${it.errSchemaPath}/${keyword}`
|
|
} : {
|
|
schema: sch[schemaProp],
|
|
schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`,
|
|
errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}`
|
|
};
|
|
}
|
|
if (schema !== void 0) {
|
|
if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) {
|
|
throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');
|
|
}
|
|
return {
|
|
schema,
|
|
schemaPath,
|
|
topSchemaRef,
|
|
errSchemaPath
|
|
};
|
|
}
|
|
throw new Error('either "keyword" or "schema" must be passed');
|
|
}
|
|
exports.getSubschema = getSubschema;
|
|
function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) {
|
|
if (data !== void 0 && dataProp !== void 0) {
|
|
throw new Error('both "data" and "dataProp" passed, only one allowed');
|
|
}
|
|
const { gen } = it;
|
|
if (dataProp !== void 0) {
|
|
const { errorPath, dataPathArr, opts } = it;
|
|
const nextData = gen.let("data", (0, codegen_1._)`${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true);
|
|
dataContextProps(nextData);
|
|
subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`;
|
|
subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`;
|
|
subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty];
|
|
}
|
|
if (data !== void 0) {
|
|
const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true);
|
|
dataContextProps(nextData);
|
|
if (propertyName !== void 0)
|
|
subschema.propertyName = propertyName;
|
|
}
|
|
if (dataTypes)
|
|
subschema.dataTypes = dataTypes;
|
|
function dataContextProps(_nextData) {
|
|
subschema.data = _nextData;
|
|
subschema.dataLevel = it.dataLevel + 1;
|
|
subschema.dataTypes = [];
|
|
it.definedProperties = /* @__PURE__ */ new Set();
|
|
subschema.parentData = it.data;
|
|
subschema.dataNames = [...it.dataNames, _nextData];
|
|
}
|
|
}
|
|
exports.extendSubschemaData = extendSubschemaData;
|
|
function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) {
|
|
if (compositeRule !== void 0)
|
|
subschema.compositeRule = compositeRule;
|
|
if (createErrors !== void 0)
|
|
subschema.createErrors = createErrors;
|
|
if (allErrors !== void 0)
|
|
subschema.allErrors = allErrors;
|
|
subschema.jtdDiscriminator = jtdDiscriminator;
|
|
subschema.jtdMetadata = jtdMetadata;
|
|
}
|
|
exports.extendSubschemaMode = extendSubschemaMode;
|
|
});
|
|
var require_fast_deep_equal = __commonJS((exports, module2) => {
|
|
module2.exports = function equal(a, b) {
|
|
if (a === b)
|
|
return true;
|
|
if (a && b && typeof a == "object" && typeof b == "object") {
|
|
if (a.constructor !== b.constructor)
|
|
return false;
|
|
var length, i, keys;
|
|
if (Array.isArray(a)) {
|
|
length = a.length;
|
|
if (length != b.length)
|
|
return false;
|
|
for (i = length; i-- !== 0; )
|
|
if (!equal(a[i], b[i]))
|
|
return false;
|
|
return true;
|
|
}
|
|
if (a.constructor === RegExp)
|
|
return a.source === b.source && a.flags === b.flags;
|
|
if (a.valueOf !== Object.prototype.valueOf)
|
|
return a.valueOf() === b.valueOf();
|
|
if (a.toString !== Object.prototype.toString)
|
|
return a.toString() === b.toString();
|
|
keys = Object.keys(a);
|
|
length = keys.length;
|
|
if (length !== Object.keys(b).length)
|
|
return false;
|
|
for (i = length; i-- !== 0; )
|
|
if (!Object.prototype.hasOwnProperty.call(b, keys[i]))
|
|
return false;
|
|
for (i = length; i-- !== 0; ) {
|
|
var key = keys[i];
|
|
if (!equal(a[key], b[key]))
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
return a !== a && b !== b;
|
|
};
|
|
});
|
|
var require_json_schema_traverse = __commonJS((exports, module2) => {
|
|
var traverse = module2.exports = function(schema, opts, cb) {
|
|
if (typeof opts == "function") {
|
|
cb = opts;
|
|
opts = {};
|
|
}
|
|
cb = opts.cb || cb;
|
|
var pre = typeof cb == "function" ? cb : cb.pre || function() {
|
|
};
|
|
var post = cb.post || function() {
|
|
};
|
|
_traverse(opts, pre, post, schema, "", schema);
|
|
};
|
|
traverse.keywords = {
|
|
additionalItems: true,
|
|
items: true,
|
|
contains: true,
|
|
additionalProperties: true,
|
|
propertyNames: true,
|
|
not: true,
|
|
if: true,
|
|
then: true,
|
|
else: true
|
|
};
|
|
traverse.arrayKeywords = {
|
|
items: true,
|
|
allOf: true,
|
|
anyOf: true,
|
|
oneOf: true
|
|
};
|
|
traverse.propsKeywords = {
|
|
$defs: true,
|
|
definitions: true,
|
|
properties: true,
|
|
patternProperties: true,
|
|
dependencies: true
|
|
};
|
|
traverse.skipKeywords = {
|
|
default: true,
|
|
enum: true,
|
|
const: true,
|
|
required: true,
|
|
maximum: true,
|
|
minimum: true,
|
|
exclusiveMaximum: true,
|
|
exclusiveMinimum: true,
|
|
multipleOf: true,
|
|
maxLength: true,
|
|
minLength: true,
|
|
pattern: true,
|
|
format: true,
|
|
maxItems: true,
|
|
minItems: true,
|
|
uniqueItems: true,
|
|
maxProperties: true,
|
|
minProperties: true
|
|
};
|
|
function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
|
|
if (schema && typeof schema == "object" && !Array.isArray(schema)) {
|
|
pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
|
|
for (var key in schema) {
|
|
var sch = schema[key];
|
|
if (Array.isArray(sch)) {
|
|
if (key in traverse.arrayKeywords) {
|
|
for (var i = 0; i < sch.length; i++)
|
|
_traverse(opts, pre, post, sch[i], jsonPtr + "/" + key + "/" + i, rootSchema, jsonPtr, key, schema, i);
|
|
}
|
|
} else if (key in traverse.propsKeywords) {
|
|
if (sch && typeof sch == "object") {
|
|
for (var prop in sch)
|
|
_traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);
|
|
}
|
|
} else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) {
|
|
_traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema);
|
|
}
|
|
}
|
|
post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
|
|
}
|
|
}
|
|
function escapeJsonPtr(str) {
|
|
return str.replace(/~/g, "~0").replace(/\//g, "~1");
|
|
}
|
|
});
|
|
var require_resolve = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0;
|
|
var util_1 = require_util();
|
|
var equal = require_fast_deep_equal();
|
|
var traverse = require_json_schema_traverse();
|
|
var SIMPLE_INLINED = /* @__PURE__ */ new Set([
|
|
"type",
|
|
"format",
|
|
"pattern",
|
|
"maxLength",
|
|
"minLength",
|
|
"maxProperties",
|
|
"minProperties",
|
|
"maxItems",
|
|
"minItems",
|
|
"maximum",
|
|
"minimum",
|
|
"uniqueItems",
|
|
"multipleOf",
|
|
"required",
|
|
"enum",
|
|
"const"
|
|
]);
|
|
function inlineRef(schema, limit = true) {
|
|
if (typeof schema == "boolean")
|
|
return true;
|
|
if (limit === true)
|
|
return !hasRef(schema);
|
|
if (!limit)
|
|
return false;
|
|
return countKeys(schema) <= limit;
|
|
}
|
|
exports.inlineRef = inlineRef;
|
|
var REF_KEYWORDS = /* @__PURE__ */ new Set([
|
|
"$ref",
|
|
"$recursiveRef",
|
|
"$recursiveAnchor",
|
|
"$dynamicRef",
|
|
"$dynamicAnchor"
|
|
]);
|
|
function hasRef(schema) {
|
|
for (const key in schema) {
|
|
if (REF_KEYWORDS.has(key))
|
|
return true;
|
|
const sch = schema[key];
|
|
if (Array.isArray(sch) && sch.some(hasRef))
|
|
return true;
|
|
if (typeof sch == "object" && hasRef(sch))
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
function countKeys(schema) {
|
|
let count = 0;
|
|
for (const key in schema) {
|
|
if (key === "$ref")
|
|
return Infinity;
|
|
count++;
|
|
if (SIMPLE_INLINED.has(key))
|
|
continue;
|
|
if (typeof schema[key] == "object") {
|
|
(0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch));
|
|
}
|
|
if (count === Infinity)
|
|
return Infinity;
|
|
}
|
|
return count;
|
|
}
|
|
function getFullPath(resolver, id = "", normalize2) {
|
|
if (normalize2 !== false)
|
|
id = normalizeId(id);
|
|
const p = resolver.parse(id);
|
|
return _getFullPath(resolver, p);
|
|
}
|
|
exports.getFullPath = getFullPath;
|
|
function _getFullPath(resolver, p) {
|
|
const serialized = resolver.serialize(p);
|
|
return serialized.split("#")[0] + "#";
|
|
}
|
|
exports._getFullPath = _getFullPath;
|
|
var TRAILING_SLASH_HASH = /#\/?$/;
|
|
function normalizeId(id) {
|
|
return id ? id.replace(TRAILING_SLASH_HASH, "") : "";
|
|
}
|
|
exports.normalizeId = normalizeId;
|
|
function resolveUrl(resolver, baseId, id) {
|
|
id = normalizeId(id);
|
|
return resolver.resolve(baseId, id);
|
|
}
|
|
exports.resolveUrl = resolveUrl;
|
|
var ANCHOR = /^[a-z_][-a-z0-9._]*$/i;
|
|
function getSchemaRefs(schema, baseId) {
|
|
if (typeof schema == "boolean")
|
|
return {};
|
|
const { schemaId, uriResolver } = this.opts;
|
|
const schId = normalizeId(schema[schemaId] || baseId);
|
|
const baseIds = { "": schId };
|
|
const pathPrefix = getFullPath(uriResolver, schId, false);
|
|
const localRefs = {};
|
|
const schemaRefs = /* @__PURE__ */ new Set();
|
|
traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => {
|
|
if (parentJsonPtr === void 0)
|
|
return;
|
|
const fullPath = pathPrefix + jsonPtr;
|
|
let innerBaseId = baseIds[parentJsonPtr];
|
|
if (typeof sch[schemaId] == "string")
|
|
innerBaseId = addRef.call(this, sch[schemaId]);
|
|
addAnchor.call(this, sch.$anchor);
|
|
addAnchor.call(this, sch.$dynamicAnchor);
|
|
baseIds[jsonPtr] = innerBaseId;
|
|
function addRef(ref) {
|
|
const _resolve = this.opts.uriResolver.resolve;
|
|
ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref);
|
|
if (schemaRefs.has(ref))
|
|
throw ambiguos(ref);
|
|
schemaRefs.add(ref);
|
|
let schOrRef = this.refs[ref];
|
|
if (typeof schOrRef == "string")
|
|
schOrRef = this.refs[schOrRef];
|
|
if (typeof schOrRef == "object") {
|
|
checkAmbiguosRef(sch, schOrRef.schema, ref);
|
|
} else if (ref !== normalizeId(fullPath)) {
|
|
if (ref[0] === "#") {
|
|
checkAmbiguosRef(sch, localRefs[ref], ref);
|
|
localRefs[ref] = sch;
|
|
} else {
|
|
this.refs[ref] = fullPath;
|
|
}
|
|
}
|
|
return ref;
|
|
}
|
|
function addAnchor(anchor) {
|
|
if (typeof anchor == "string") {
|
|
if (!ANCHOR.test(anchor))
|
|
throw new Error(`invalid anchor "${anchor}"`);
|
|
addRef.call(this, `#${anchor}`);
|
|
}
|
|
}
|
|
});
|
|
return localRefs;
|
|
function checkAmbiguosRef(sch1, sch2, ref) {
|
|
if (sch2 !== void 0 && !equal(sch1, sch2))
|
|
throw ambiguos(ref);
|
|
}
|
|
function ambiguos(ref) {
|
|
return new Error(`reference "${ref}" resolves to more than one schema`);
|
|
}
|
|
}
|
|
exports.getSchemaRefs = getSchemaRefs;
|
|
});
|
|
var require_validate = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0;
|
|
var boolSchema_1 = require_boolSchema();
|
|
var dataType_1 = require_dataType();
|
|
var applicability_1 = require_applicability();
|
|
var dataType_2 = require_dataType();
|
|
var defaults_1 = require_defaults();
|
|
var keyword_1 = require_keyword();
|
|
var subschema_1 = require_subschema();
|
|
var codegen_1 = require_codegen();
|
|
var names_1 = require_names();
|
|
var resolve_1 = require_resolve();
|
|
var util_1 = require_util();
|
|
var errors_1 = require_errors();
|
|
function validateFunctionCode(it) {
|
|
if (isSchemaObj(it)) {
|
|
checkKeywords(it);
|
|
if (schemaCxtHasRules(it)) {
|
|
topSchemaObjCode(it);
|
|
return;
|
|
}
|
|
}
|
|
validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it));
|
|
}
|
|
exports.validateFunctionCode = validateFunctionCode;
|
|
function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) {
|
|
if (opts.code.es5) {
|
|
gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => {
|
|
gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`);
|
|
destructureValCxtES5(gen, opts);
|
|
gen.code(body);
|
|
});
|
|
} else {
|
|
gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body));
|
|
}
|
|
}
|
|
function destructureValCxt(opts) {
|
|
return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`;
|
|
}
|
|
function destructureValCxtES5(gen, opts) {
|
|
gen.if(names_1.default.valCxt, () => {
|
|
gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`);
|
|
gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`);
|
|
gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`);
|
|
gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`);
|
|
if (opts.dynamicRef)
|
|
gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`);
|
|
}, () => {
|
|
gen.var(names_1.default.instancePath, (0, codegen_1._)`""`);
|
|
gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`);
|
|
gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`);
|
|
gen.var(names_1.default.rootData, names_1.default.data);
|
|
if (opts.dynamicRef)
|
|
gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`);
|
|
});
|
|
}
|
|
function topSchemaObjCode(it) {
|
|
const { schema, opts, gen } = it;
|
|
validateFunction(it, () => {
|
|
if (opts.$comment && schema.$comment)
|
|
commentKeyword(it);
|
|
checkNoDefault(it);
|
|
gen.let(names_1.default.vErrors, null);
|
|
gen.let(names_1.default.errors, 0);
|
|
if (opts.unevaluated)
|
|
resetEvaluated(it);
|
|
typeAndKeywords(it);
|
|
returnResults(it);
|
|
});
|
|
return;
|
|
}
|
|
function resetEvaluated(it) {
|
|
const { gen, validateName } = it;
|
|
it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`);
|
|
gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`));
|
|
gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`));
|
|
}
|
|
function funcSourceUrl(schema, opts) {
|
|
const schId = typeof schema == "object" && schema[opts.schemaId];
|
|
return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil;
|
|
}
|
|
function subschemaCode(it, valid) {
|
|
if (isSchemaObj(it)) {
|
|
checkKeywords(it);
|
|
if (schemaCxtHasRules(it)) {
|
|
subSchemaObjCode(it, valid);
|
|
return;
|
|
}
|
|
}
|
|
(0, boolSchema_1.boolOrEmptySchema)(it, valid);
|
|
}
|
|
function schemaCxtHasRules({ schema, self: self2 }) {
|
|
if (typeof schema == "boolean")
|
|
return !schema;
|
|
for (const key in schema)
|
|
if (self2.RULES.all[key])
|
|
return true;
|
|
return false;
|
|
}
|
|
function isSchemaObj(it) {
|
|
return typeof it.schema != "boolean";
|
|
}
|
|
function subSchemaObjCode(it, valid) {
|
|
const { schema, gen, opts } = it;
|
|
if (opts.$comment && schema.$comment)
|
|
commentKeyword(it);
|
|
updateContext(it);
|
|
checkAsyncSchema(it);
|
|
const errsCount = gen.const("_errs", names_1.default.errors);
|
|
typeAndKeywords(it, errsCount);
|
|
gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`);
|
|
}
|
|
function checkKeywords(it) {
|
|
(0, util_1.checkUnknownRules)(it);
|
|
checkRefsAndKeywords(it);
|
|
}
|
|
function typeAndKeywords(it, errsCount) {
|
|
if (it.opts.jtd)
|
|
return schemaKeywords(it, [], false, errsCount);
|
|
const types = (0, dataType_1.getSchemaTypes)(it.schema);
|
|
const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types);
|
|
schemaKeywords(it, types, !checkedTypes, errsCount);
|
|
}
|
|
function checkRefsAndKeywords(it) {
|
|
const { schema, errSchemaPath, opts, self: self2 } = it;
|
|
if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self2.RULES)) {
|
|
self2.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`);
|
|
}
|
|
}
|
|
function checkNoDefault(it) {
|
|
const { schema, opts } = it;
|
|
if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) {
|
|
(0, util_1.checkStrictMode)(it, "default is ignored in the schema root");
|
|
}
|
|
}
|
|
function updateContext(it) {
|
|
const schId = it.schema[it.opts.schemaId];
|
|
if (schId)
|
|
it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId);
|
|
}
|
|
function checkAsyncSchema(it) {
|
|
if (it.schema.$async && !it.schemaEnv.$async)
|
|
throw new Error("async schema in sync schema");
|
|
}
|
|
function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) {
|
|
const msg = schema.$comment;
|
|
if (opts.$comment === true) {
|
|
gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`);
|
|
} else if (typeof opts.$comment == "function") {
|
|
const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`;
|
|
const rootName = gen.scopeValue("root", { ref: schemaEnv.root });
|
|
gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`);
|
|
}
|
|
}
|
|
function returnResults(it) {
|
|
const { gen, schemaEnv, validateName, ValidationError, opts } = it;
|
|
if (schemaEnv.$async) {
|
|
gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`));
|
|
} else {
|
|
gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors);
|
|
if (opts.unevaluated)
|
|
assignEvaluated(it);
|
|
gen.return((0, codegen_1._)`${names_1.default.errors} === 0`);
|
|
}
|
|
}
|
|
function assignEvaluated({ gen, evaluated, props, items }) {
|
|
if (props instanceof codegen_1.Name)
|
|
gen.assign((0, codegen_1._)`${evaluated}.props`, props);
|
|
if (items instanceof codegen_1.Name)
|
|
gen.assign((0, codegen_1._)`${evaluated}.items`, items);
|
|
}
|
|
function schemaKeywords(it, types, typeErrors, errsCount) {
|
|
const { gen, schema, data, allErrors, opts, self: self2 } = it;
|
|
const { RULES } = self2;
|
|
if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) {
|
|
gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition));
|
|
return;
|
|
}
|
|
if (!opts.jtd)
|
|
checkStrictTypes(it, types);
|
|
gen.block(() => {
|
|
for (const group of RULES.rules)
|
|
groupKeywords(group);
|
|
groupKeywords(RULES.post);
|
|
});
|
|
function groupKeywords(group) {
|
|
if (!(0, applicability_1.shouldUseGroup)(schema, group))
|
|
return;
|
|
if (group.type) {
|
|
gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers));
|
|
iterateKeywords(it, group);
|
|
if (types.length === 1 && types[0] === group.type && typeErrors) {
|
|
gen.else();
|
|
(0, dataType_2.reportTypeError)(it);
|
|
}
|
|
gen.endIf();
|
|
} else {
|
|
iterateKeywords(it, group);
|
|
}
|
|
if (!allErrors)
|
|
gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`);
|
|
}
|
|
}
|
|
function iterateKeywords(it, group) {
|
|
const { gen, schema, opts: { useDefaults } } = it;
|
|
if (useDefaults)
|
|
(0, defaults_1.assignDefaults)(it, group.type);
|
|
gen.block(() => {
|
|
for (const rule of group.rules) {
|
|
if ((0, applicability_1.shouldUseRule)(schema, rule)) {
|
|
keywordCode(it, rule.keyword, rule.definition, group.type);
|
|
}
|
|
}
|
|
});
|
|
}
|
|
function checkStrictTypes(it, types) {
|
|
if (it.schemaEnv.meta || !it.opts.strictTypes)
|
|
return;
|
|
checkContextTypes(it, types);
|
|
if (!it.opts.allowUnionTypes)
|
|
checkMultipleTypes(it, types);
|
|
checkKeywordTypes(it, it.dataTypes);
|
|
}
|
|
function checkContextTypes(it, types) {
|
|
if (!types.length)
|
|
return;
|
|
if (!it.dataTypes.length) {
|
|
it.dataTypes = types;
|
|
return;
|
|
}
|
|
types.forEach((t) => {
|
|
if (!includesType(it.dataTypes, t)) {
|
|
strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`);
|
|
}
|
|
});
|
|
narrowSchemaTypes(it, types);
|
|
}
|
|
function checkMultipleTypes(it, ts) {
|
|
if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) {
|
|
strictTypesError(it, "use allowUnionTypes to allow union type keyword");
|
|
}
|
|
}
|
|
function checkKeywordTypes(it, ts) {
|
|
const rules = it.self.RULES.all;
|
|
for (const keyword in rules) {
|
|
const rule = rules[keyword];
|
|
if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) {
|
|
const { type } = rule.definition;
|
|
if (type.length && !type.some((t) => hasApplicableType(ts, t))) {
|
|
strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
function hasApplicableType(schTs, kwdT) {
|
|
return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer");
|
|
}
|
|
function includesType(ts, t) {
|
|
return ts.includes(t) || t === "integer" && ts.includes("number");
|
|
}
|
|
function narrowSchemaTypes(it, withTypes) {
|
|
const ts = [];
|
|
for (const t of it.dataTypes) {
|
|
if (includesType(withTypes, t))
|
|
ts.push(t);
|
|
else if (withTypes.includes("integer") && t === "number")
|
|
ts.push("integer");
|
|
}
|
|
it.dataTypes = ts;
|
|
}
|
|
function strictTypesError(it, msg) {
|
|
const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;
|
|
msg += ` at "${schemaPath}" (strictTypes)`;
|
|
(0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes);
|
|
}
|
|
class KeywordCxt {
|
|
constructor(it, def, keyword) {
|
|
(0, keyword_1.validateKeywordUsage)(it, def, keyword);
|
|
this.gen = it.gen;
|
|
this.allErrors = it.allErrors;
|
|
this.keyword = keyword;
|
|
this.data = it.data;
|
|
this.schema = it.schema[keyword];
|
|
this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data;
|
|
this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data);
|
|
this.schemaType = def.schemaType;
|
|
this.parentSchema = it.schema;
|
|
this.params = {};
|
|
this.it = it;
|
|
this.def = def;
|
|
if (this.$data) {
|
|
this.schemaCode = it.gen.const("vSchema", getData(this.$data, it));
|
|
} else {
|
|
this.schemaCode = this.schemaValue;
|
|
if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) {
|
|
throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`);
|
|
}
|
|
}
|
|
if ("code" in def ? def.trackErrors : def.errors !== false) {
|
|
this.errsCount = it.gen.const("_errs", names_1.default.errors);
|
|
}
|
|
}
|
|
result(condition, successAction, failAction) {
|
|
this.failResult((0, codegen_1.not)(condition), successAction, failAction);
|
|
}
|
|
failResult(condition, successAction, failAction) {
|
|
this.gen.if(condition);
|
|
if (failAction)
|
|
failAction();
|
|
else
|
|
this.error();
|
|
if (successAction) {
|
|
this.gen.else();
|
|
successAction();
|
|
if (this.allErrors)
|
|
this.gen.endIf();
|
|
} else {
|
|
if (this.allErrors)
|
|
this.gen.endIf();
|
|
else
|
|
this.gen.else();
|
|
}
|
|
}
|
|
pass(condition, failAction) {
|
|
this.failResult((0, codegen_1.not)(condition), void 0, failAction);
|
|
}
|
|
fail(condition) {
|
|
if (condition === void 0) {
|
|
this.error();
|
|
if (!this.allErrors)
|
|
this.gen.if(false);
|
|
return;
|
|
}
|
|
this.gen.if(condition);
|
|
this.error();
|
|
if (this.allErrors)
|
|
this.gen.endIf();
|
|
else
|
|
this.gen.else();
|
|
}
|
|
fail$data(condition) {
|
|
if (!this.$data)
|
|
return this.fail(condition);
|
|
const { schemaCode } = this;
|
|
this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`);
|
|
}
|
|
error(append, errorParams, errorPaths) {
|
|
if (errorParams) {
|
|
this.setParams(errorParams);
|
|
this._error(append, errorPaths);
|
|
this.setParams({});
|
|
return;
|
|
}
|
|
this._error(append, errorPaths);
|
|
}
|
|
_error(append, errorPaths) {
|
|
(append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths);
|
|
}
|
|
$dataError() {
|
|
(0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError);
|
|
}
|
|
reset() {
|
|
if (this.errsCount === void 0)
|
|
throw new Error('add "trackErrors" to keyword definition');
|
|
(0, errors_1.resetErrorsCount)(this.gen, this.errsCount);
|
|
}
|
|
ok(cond) {
|
|
if (!this.allErrors)
|
|
this.gen.if(cond);
|
|
}
|
|
setParams(obj, assign) {
|
|
if (assign)
|
|
Object.assign(this.params, obj);
|
|
else
|
|
this.params = obj;
|
|
}
|
|
block$data(valid, codeBlock, $dataValid = codegen_1.nil) {
|
|
this.gen.block(() => {
|
|
this.check$data(valid, $dataValid);
|
|
codeBlock();
|
|
});
|
|
}
|
|
check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) {
|
|
if (!this.$data)
|
|
return;
|
|
const { gen, schemaCode, schemaType, def } = this;
|
|
gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid));
|
|
if (valid !== codegen_1.nil)
|
|
gen.assign(valid, true);
|
|
if (schemaType.length || def.validateSchema) {
|
|
gen.elseIf(this.invalid$data());
|
|
this.$dataError();
|
|
if (valid !== codegen_1.nil)
|
|
gen.assign(valid, false);
|
|
}
|
|
gen.else();
|
|
}
|
|
invalid$data() {
|
|
const { gen, schemaCode, schemaType, def, it } = this;
|
|
return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema());
|
|
function wrong$DataType() {
|
|
if (schemaType.length) {
|
|
if (!(schemaCode instanceof codegen_1.Name))
|
|
throw new Error("ajv implementation error");
|
|
const st = Array.isArray(schemaType) ? schemaType : [schemaType];
|
|
return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`;
|
|
}
|
|
return codegen_1.nil;
|
|
}
|
|
function invalid$DataSchema() {
|
|
if (def.validateSchema) {
|
|
const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema });
|
|
return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`;
|
|
}
|
|
return codegen_1.nil;
|
|
}
|
|
}
|
|
subschema(appl, valid) {
|
|
const subschema = (0, subschema_1.getSubschema)(this.it, appl);
|
|
(0, subschema_1.extendSubschemaData)(subschema, this.it, appl);
|
|
(0, subschema_1.extendSubschemaMode)(subschema, appl);
|
|
const nextContext = { ...this.it, ...subschema, items: void 0, props: void 0 };
|
|
subschemaCode(nextContext, valid);
|
|
return nextContext;
|
|
}
|
|
mergeEvaluated(schemaCxt, toName) {
|
|
const { it, gen } = this;
|
|
if (!it.opts.unevaluated)
|
|
return;
|
|
if (it.props !== true && schemaCxt.props !== void 0) {
|
|
it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName);
|
|
}
|
|
if (it.items !== true && schemaCxt.items !== void 0) {
|
|
it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName);
|
|
}
|
|
}
|
|
mergeValidEvaluated(schemaCxt, valid) {
|
|
const { it, gen } = this;
|
|
if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {
|
|
gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name));
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
exports.KeywordCxt = KeywordCxt;
|
|
function keywordCode(it, keyword, def, ruleType) {
|
|
const cxt = new KeywordCxt(it, def, keyword);
|
|
if ("code" in def) {
|
|
def.code(cxt, ruleType);
|
|
} else if (cxt.$data && def.validate) {
|
|
(0, keyword_1.funcKeywordCode)(cxt, def);
|
|
} else if ("macro" in def) {
|
|
(0, keyword_1.macroKeywordCode)(cxt, def);
|
|
} else if (def.compile || def.validate) {
|
|
(0, keyword_1.funcKeywordCode)(cxt, def);
|
|
}
|
|
}
|
|
var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
|
|
var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
|
|
function getData($data, { dataLevel, dataNames, dataPathArr }) {
|
|
let jsonPointer;
|
|
let data;
|
|
if ($data === "")
|
|
return names_1.default.rootData;
|
|
if ($data[0] === "/") {
|
|
if (!JSON_POINTER.test($data))
|
|
throw new Error(`Invalid JSON-pointer: ${$data}`);
|
|
jsonPointer = $data;
|
|
data = names_1.default.rootData;
|
|
} else {
|
|
const matches = RELATIVE_JSON_POINTER.exec($data);
|
|
if (!matches)
|
|
throw new Error(`Invalid JSON-pointer: ${$data}`);
|
|
const up = +matches[1];
|
|
jsonPointer = matches[2];
|
|
if (jsonPointer === "#") {
|
|
if (up >= dataLevel)
|
|
throw new Error(errorMsg("property/index", up));
|
|
return dataPathArr[dataLevel - up];
|
|
}
|
|
if (up > dataLevel)
|
|
throw new Error(errorMsg("data", up));
|
|
data = dataNames[dataLevel - up];
|
|
if (!jsonPointer)
|
|
return data;
|
|
}
|
|
let expr = data;
|
|
const segments = jsonPointer.split("/");
|
|
for (const segment of segments) {
|
|
if (segment) {
|
|
data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`;
|
|
expr = (0, codegen_1._)`${expr} && ${data}`;
|
|
}
|
|
}
|
|
return expr;
|
|
function errorMsg(pointerType, up) {
|
|
return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`;
|
|
}
|
|
}
|
|
exports.getData = getData;
|
|
});
|
|
var require_validation_error = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
class ValidationError extends Error {
|
|
constructor(errors3) {
|
|
super("validation failed");
|
|
this.errors = errors3;
|
|
this.ajv = this.validation = true;
|
|
}
|
|
}
|
|
exports.default = ValidationError;
|
|
});
|
|
var require_ref_error = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var resolve_1 = require_resolve();
|
|
class MissingRefError extends Error {
|
|
constructor(resolver, baseId, ref, msg) {
|
|
super(msg || `can't resolve reference ${ref} from id ${baseId}`);
|
|
this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref);
|
|
this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef));
|
|
}
|
|
}
|
|
exports.default = MissingRefError;
|
|
});
|
|
var require_compile = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0;
|
|
var codegen_1 = require_codegen();
|
|
var validation_error_1 = require_validation_error();
|
|
var names_1 = require_names();
|
|
var resolve_1 = require_resolve();
|
|
var util_1 = require_util();
|
|
var validate_1 = require_validate();
|
|
class SchemaEnv {
|
|
constructor(env) {
|
|
var _a;
|
|
this.refs = {};
|
|
this.dynamicAnchors = {};
|
|
let schema;
|
|
if (typeof env.schema == "object")
|
|
schema = env.schema;
|
|
this.schema = env.schema;
|
|
this.schemaId = env.schemaId;
|
|
this.root = env.root || this;
|
|
this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]);
|
|
this.schemaPath = env.schemaPath;
|
|
this.localRefs = env.localRefs;
|
|
this.meta = env.meta;
|
|
this.$async = schema === null || schema === void 0 ? void 0 : schema.$async;
|
|
this.refs = {};
|
|
}
|
|
}
|
|
exports.SchemaEnv = SchemaEnv;
|
|
function compileSchema(sch) {
|
|
const _sch = getCompilingSchema.call(this, sch);
|
|
if (_sch)
|
|
return _sch;
|
|
const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId);
|
|
const { es5, lines } = this.opts.code;
|
|
const { ownProperties } = this.opts;
|
|
const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties });
|
|
let _ValidationError;
|
|
if (sch.$async) {
|
|
_ValidationError = gen.scopeValue("Error", {
|
|
ref: validation_error_1.default,
|
|
code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default`
|
|
});
|
|
}
|
|
const validateName = gen.scopeName("validate");
|
|
sch.validateName = validateName;
|
|
const schemaCxt = {
|
|
gen,
|
|
allErrors: this.opts.allErrors,
|
|
data: names_1.default.data,
|
|
parentData: names_1.default.parentData,
|
|
parentDataProperty: names_1.default.parentDataProperty,
|
|
dataNames: [names_1.default.data],
|
|
dataPathArr: [codegen_1.nil],
|
|
dataLevel: 0,
|
|
dataTypes: [],
|
|
definedProperties: /* @__PURE__ */ new Set(),
|
|
topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) } : { ref: sch.schema }),
|
|
validateName,
|
|
ValidationError: _ValidationError,
|
|
schema: sch.schema,
|
|
schemaEnv: sch,
|
|
rootId,
|
|
baseId: sch.baseId || rootId,
|
|
schemaPath: codegen_1.nil,
|
|
errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"),
|
|
errorPath: (0, codegen_1._)`""`,
|
|
opts: this.opts,
|
|
self: this
|
|
};
|
|
let sourceCode;
|
|
try {
|
|
this._compilations.add(sch);
|
|
(0, validate_1.validateFunctionCode)(schemaCxt);
|
|
gen.optimize(this.opts.code.optimize);
|
|
const validateCode = gen.toString();
|
|
sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`;
|
|
if (this.opts.code.process)
|
|
sourceCode = this.opts.code.process(sourceCode, sch);
|
|
const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode);
|
|
const validate = makeValidate(this, this.scope.get());
|
|
this.scope.value(validateName, { ref: validate });
|
|
validate.errors = null;
|
|
validate.schema = sch.schema;
|
|
validate.schemaEnv = sch;
|
|
if (sch.$async)
|
|
validate.$async = true;
|
|
if (this.opts.code.source === true) {
|
|
validate.source = { validateName, validateCode, scopeValues: gen._values };
|
|
}
|
|
if (this.opts.unevaluated) {
|
|
const { props, items } = schemaCxt;
|
|
validate.evaluated = {
|
|
props: props instanceof codegen_1.Name ? void 0 : props,
|
|
items: items instanceof codegen_1.Name ? void 0 : items,
|
|
dynamicProps: props instanceof codegen_1.Name,
|
|
dynamicItems: items instanceof codegen_1.Name
|
|
};
|
|
if (validate.source)
|
|
validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated);
|
|
}
|
|
sch.validate = validate;
|
|
return sch;
|
|
} catch (e) {
|
|
delete sch.validate;
|
|
delete sch.validateName;
|
|
if (sourceCode)
|
|
this.logger.error("Error compiling schema, function code:", sourceCode);
|
|
throw e;
|
|
} finally {
|
|
this._compilations.delete(sch);
|
|
}
|
|
}
|
|
exports.compileSchema = compileSchema;
|
|
function resolveRef(root2, baseId, ref) {
|
|
var _a;
|
|
ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref);
|
|
const schOrFunc = root2.refs[ref];
|
|
if (schOrFunc)
|
|
return schOrFunc;
|
|
let _sch = resolve7.call(this, root2, ref);
|
|
if (_sch === void 0) {
|
|
const schema = (_a = root2.localRefs) === null || _a === void 0 ? void 0 : _a[ref];
|
|
const { schemaId } = this.opts;
|
|
if (schema)
|
|
_sch = new SchemaEnv({ schema, schemaId, root: root2, baseId });
|
|
}
|
|
if (_sch === void 0)
|
|
return;
|
|
return root2.refs[ref] = inlineOrCompile.call(this, _sch);
|
|
}
|
|
exports.resolveRef = resolveRef;
|
|
function inlineOrCompile(sch) {
|
|
if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs))
|
|
return sch.schema;
|
|
return sch.validate ? sch : compileSchema.call(this, sch);
|
|
}
|
|
function getCompilingSchema(schEnv) {
|
|
for (const sch of this._compilations) {
|
|
if (sameSchemaEnv(sch, schEnv))
|
|
return sch;
|
|
}
|
|
}
|
|
exports.getCompilingSchema = getCompilingSchema;
|
|
function sameSchemaEnv(s1, s2) {
|
|
return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
|
|
}
|
|
function resolve7(root2, ref) {
|
|
let sch;
|
|
while (typeof (sch = this.refs[ref]) == "string")
|
|
ref = sch;
|
|
return sch || this.schemas[ref] || resolveSchema.call(this, root2, ref);
|
|
}
|
|
function resolveSchema(root2, ref) {
|
|
const p = this.opts.uriResolver.parse(ref);
|
|
const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p);
|
|
let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root2.baseId, void 0);
|
|
if (Object.keys(root2.schema).length > 0 && refPath === baseId) {
|
|
return getJsonPointer.call(this, p, root2);
|
|
}
|
|
const id = (0, resolve_1.normalizeId)(refPath);
|
|
const schOrRef = this.refs[id] || this.schemas[id];
|
|
if (typeof schOrRef == "string") {
|
|
const sch = resolveSchema.call(this, root2, schOrRef);
|
|
if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object")
|
|
return;
|
|
return getJsonPointer.call(this, p, sch);
|
|
}
|
|
if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object")
|
|
return;
|
|
if (!schOrRef.validate)
|
|
compileSchema.call(this, schOrRef);
|
|
if (id === (0, resolve_1.normalizeId)(ref)) {
|
|
const { schema } = schOrRef;
|
|
const { schemaId } = this.opts;
|
|
const schId = schema[schemaId];
|
|
if (schId)
|
|
baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);
|
|
return new SchemaEnv({ schema, schemaId, root: root2, baseId });
|
|
}
|
|
return getJsonPointer.call(this, p, schOrRef);
|
|
}
|
|
exports.resolveSchema = resolveSchema;
|
|
var PREVENT_SCOPE_CHANGE = /* @__PURE__ */ new Set([
|
|
"properties",
|
|
"patternProperties",
|
|
"enum",
|
|
"dependencies",
|
|
"definitions"
|
|
]);
|
|
function getJsonPointer(parsedRef, { baseId, schema, root: root2 }) {
|
|
var _a;
|
|
if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/")
|
|
return;
|
|
for (const part of parsedRef.fragment.slice(1).split("/")) {
|
|
if (typeof schema === "boolean")
|
|
return;
|
|
const partSchema = schema[(0, util_1.unescapeFragment)(part)];
|
|
if (partSchema === void 0)
|
|
return;
|
|
schema = partSchema;
|
|
const schId = typeof schema === "object" && schema[this.opts.schemaId];
|
|
if (!PREVENT_SCOPE_CHANGE.has(part) && schId) {
|
|
baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);
|
|
}
|
|
}
|
|
let env;
|
|
if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) {
|
|
const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref);
|
|
env = resolveSchema.call(this, root2, $ref);
|
|
}
|
|
const { schemaId } = this.opts;
|
|
env = env || new SchemaEnv({ schema, schemaId, root: root2, baseId });
|
|
if (env.schema !== env.root.schema)
|
|
return env;
|
|
return;
|
|
}
|
|
});
|
|
var require_data = __commonJS((exports, module2) => {
|
|
module2.exports = {
|
|
$id: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
|
|
description: "Meta-schema for $data reference (JSON AnySchema extension proposal)",
|
|
type: "object",
|
|
required: ["$data"],
|
|
properties: {
|
|
$data: {
|
|
type: "string",
|
|
anyOf: [{ format: "relative-json-pointer" }, { format: "json-pointer" }]
|
|
}
|
|
},
|
|
additionalProperties: false
|
|
};
|
|
});
|
|
var require_scopedChars = __commonJS((exports, module2) => {
|
|
var HEX = {
|
|
0: 0,
|
|
1: 1,
|
|
2: 2,
|
|
3: 3,
|
|
4: 4,
|
|
5: 5,
|
|
6: 6,
|
|
7: 7,
|
|
8: 8,
|
|
9: 9,
|
|
a: 10,
|
|
A: 10,
|
|
b: 11,
|
|
B: 11,
|
|
c: 12,
|
|
C: 12,
|
|
d: 13,
|
|
D: 13,
|
|
e: 14,
|
|
E: 14,
|
|
f: 15,
|
|
F: 15
|
|
};
|
|
module2.exports = {
|
|
HEX
|
|
};
|
|
});
|
|
var require_utils = __commonJS((exports, module2) => {
|
|
var { HEX } = require_scopedChars();
|
|
var IPV4_REG = /^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u;
|
|
function normalizeIPv4(host) {
|
|
if (findToken(host, ".") < 3) {
|
|
return { host, isIPV4: false };
|
|
}
|
|
const matches = host.match(IPV4_REG) || [];
|
|
const [address] = matches;
|
|
if (address) {
|
|
return { host: stripLeadingZeros(address, "."), isIPV4: true };
|
|
} else {
|
|
return { host, isIPV4: false };
|
|
}
|
|
}
|
|
function stringArrayToHexStripped(input, keepZero = false) {
|
|
let acc = "";
|
|
let strip = true;
|
|
for (const c of input) {
|
|
if (HEX[c] === void 0)
|
|
return;
|
|
if (c !== "0" && strip === true)
|
|
strip = false;
|
|
if (!strip)
|
|
acc += c;
|
|
}
|
|
if (keepZero && acc.length === 0)
|
|
acc = "0";
|
|
return acc;
|
|
}
|
|
function getIPV6(input) {
|
|
let tokenCount = 0;
|
|
const output = { error: false, address: "", zone: "" };
|
|
const address = [];
|
|
const buffer = [];
|
|
let isZone = false;
|
|
let endipv6Encountered = false;
|
|
let endIpv6 = false;
|
|
function consume() {
|
|
if (buffer.length) {
|
|
if (isZone === false) {
|
|
const hex = stringArrayToHexStripped(buffer);
|
|
if (hex !== void 0) {
|
|
address.push(hex);
|
|
} else {
|
|
output.error = true;
|
|
return false;
|
|
}
|
|
}
|
|
buffer.length = 0;
|
|
}
|
|
return true;
|
|
}
|
|
for (let i = 0; i < input.length; i++) {
|
|
const cursor = input[i];
|
|
if (cursor === "[" || cursor === "]") {
|
|
continue;
|
|
}
|
|
if (cursor === ":") {
|
|
if (endipv6Encountered === true) {
|
|
endIpv6 = true;
|
|
}
|
|
if (!consume()) {
|
|
break;
|
|
}
|
|
tokenCount++;
|
|
address.push(":");
|
|
if (tokenCount > 7) {
|
|
output.error = true;
|
|
break;
|
|
}
|
|
if (i - 1 >= 0 && input[i - 1] === ":") {
|
|
endipv6Encountered = true;
|
|
}
|
|
continue;
|
|
} else if (cursor === "%") {
|
|
if (!consume()) {
|
|
break;
|
|
}
|
|
isZone = true;
|
|
} else {
|
|
buffer.push(cursor);
|
|
continue;
|
|
}
|
|
}
|
|
if (buffer.length) {
|
|
if (isZone) {
|
|
output.zone = buffer.join("");
|
|
} else if (endIpv6) {
|
|
address.push(buffer.join(""));
|
|
} else {
|
|
address.push(stringArrayToHexStripped(buffer));
|
|
}
|
|
}
|
|
output.address = address.join("");
|
|
return output;
|
|
}
|
|
function normalizeIPv6(host) {
|
|
if (findToken(host, ":") < 2) {
|
|
return { host, isIPV6: false };
|
|
}
|
|
const ipv62 = getIPV6(host);
|
|
if (!ipv62.error) {
|
|
let newHost = ipv62.address;
|
|
let escapedHost = ipv62.address;
|
|
if (ipv62.zone) {
|
|
newHost += "%" + ipv62.zone;
|
|
escapedHost += "%25" + ipv62.zone;
|
|
}
|
|
return { host: newHost, escapedHost, isIPV6: true };
|
|
} else {
|
|
return { host, isIPV6: false };
|
|
}
|
|
}
|
|
function stripLeadingZeros(str, token) {
|
|
let out = "";
|
|
let skip = true;
|
|
const l = str.length;
|
|
for (let i = 0; i < l; i++) {
|
|
const c = str[i];
|
|
if (c === "0" && skip) {
|
|
if (i + 1 <= l && str[i + 1] === token || i + 1 === l) {
|
|
out += c;
|
|
skip = false;
|
|
}
|
|
} else {
|
|
if (c === token) {
|
|
skip = true;
|
|
} else {
|
|
skip = false;
|
|
}
|
|
out += c;
|
|
}
|
|
}
|
|
return out;
|
|
}
|
|
function findToken(str, token) {
|
|
let ind = 0;
|
|
for (let i = 0; i < str.length; i++) {
|
|
if (str[i] === token)
|
|
ind++;
|
|
}
|
|
return ind;
|
|
}
|
|
var RDS1 = /^\.\.?\//u;
|
|
var RDS2 = /^\/\.(?:\/|$)/u;
|
|
var RDS3 = /^\/\.\.(?:\/|$)/u;
|
|
var RDS5 = /^\/?(?:.|\n)*?(?=\/|$)/u;
|
|
function removeDotSegments(input) {
|
|
const output = [];
|
|
while (input.length) {
|
|
if (input.match(RDS1)) {
|
|
input = input.replace(RDS1, "");
|
|
} else if (input.match(RDS2)) {
|
|
input = input.replace(RDS2, "/");
|
|
} else if (input.match(RDS3)) {
|
|
input = input.replace(RDS3, "/");
|
|
output.pop();
|
|
} else if (input === "." || input === "..") {
|
|
input = "";
|
|
} else {
|
|
const im = input.match(RDS5);
|
|
if (im) {
|
|
const s = im[0];
|
|
input = input.slice(s.length);
|
|
output.push(s);
|
|
} else {
|
|
throw new Error("Unexpected dot segment condition");
|
|
}
|
|
}
|
|
}
|
|
return output.join("");
|
|
}
|
|
function normalizeComponentEncoding(components, esc2) {
|
|
const func = esc2 !== true ? escape : unescape;
|
|
if (components.scheme !== void 0) {
|
|
components.scheme = func(components.scheme);
|
|
}
|
|
if (components.userinfo !== void 0) {
|
|
components.userinfo = func(components.userinfo);
|
|
}
|
|
if (components.host !== void 0) {
|
|
components.host = func(components.host);
|
|
}
|
|
if (components.path !== void 0) {
|
|
components.path = func(components.path);
|
|
}
|
|
if (components.query !== void 0) {
|
|
components.query = func(components.query);
|
|
}
|
|
if (components.fragment !== void 0) {
|
|
components.fragment = func(components.fragment);
|
|
}
|
|
return components;
|
|
}
|
|
function recomposeAuthority(components) {
|
|
const uriTokens = [];
|
|
if (components.userinfo !== void 0) {
|
|
uriTokens.push(components.userinfo);
|
|
uriTokens.push("@");
|
|
}
|
|
if (components.host !== void 0) {
|
|
let host = unescape(components.host);
|
|
const ipV4res = normalizeIPv4(host);
|
|
if (ipV4res.isIPV4) {
|
|
host = ipV4res.host;
|
|
} else {
|
|
const ipV6res = normalizeIPv6(ipV4res.host);
|
|
if (ipV6res.isIPV6 === true) {
|
|
host = `[${ipV6res.escapedHost}]`;
|
|
} else {
|
|
host = components.host;
|
|
}
|
|
}
|
|
uriTokens.push(host);
|
|
}
|
|
if (typeof components.port === "number" || typeof components.port === "string") {
|
|
uriTokens.push(":");
|
|
uriTokens.push(String(components.port));
|
|
}
|
|
return uriTokens.length ? uriTokens.join("") : void 0;
|
|
}
|
|
module2.exports = {
|
|
recomposeAuthority,
|
|
normalizeComponentEncoding,
|
|
removeDotSegments,
|
|
normalizeIPv4,
|
|
normalizeIPv6,
|
|
stringArrayToHexStripped
|
|
};
|
|
});
|
|
var require_schemes = __commonJS((exports, module2) => {
|
|
var UUID_REG = /^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu;
|
|
var URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;
|
|
function isSecure(wsComponents) {
|
|
return typeof wsComponents.secure === "boolean" ? wsComponents.secure : String(wsComponents.scheme).toLowerCase() === "wss";
|
|
}
|
|
function httpParse(components) {
|
|
if (!components.host) {
|
|
components.error = components.error || "HTTP URIs must have a host.";
|
|
}
|
|
return components;
|
|
}
|
|
function httpSerialize(components) {
|
|
const secure = String(components.scheme).toLowerCase() === "https";
|
|
if (components.port === (secure ? 443 : 80) || components.port === "") {
|
|
components.port = void 0;
|
|
}
|
|
if (!components.path) {
|
|
components.path = "/";
|
|
}
|
|
return components;
|
|
}
|
|
function wsParse(wsComponents) {
|
|
wsComponents.secure = isSecure(wsComponents);
|
|
wsComponents.resourceName = (wsComponents.path || "/") + (wsComponents.query ? "?" + wsComponents.query : "");
|
|
wsComponents.path = void 0;
|
|
wsComponents.query = void 0;
|
|
return wsComponents;
|
|
}
|
|
function wsSerialize(wsComponents) {
|
|
if (wsComponents.port === (isSecure(wsComponents) ? 443 : 80) || wsComponents.port === "") {
|
|
wsComponents.port = void 0;
|
|
}
|
|
if (typeof wsComponents.secure === "boolean") {
|
|
wsComponents.scheme = wsComponents.secure ? "wss" : "ws";
|
|
wsComponents.secure = void 0;
|
|
}
|
|
if (wsComponents.resourceName) {
|
|
const [path12, query2] = wsComponents.resourceName.split("?");
|
|
wsComponents.path = path12 && path12 !== "/" ? path12 : void 0;
|
|
wsComponents.query = query2;
|
|
wsComponents.resourceName = void 0;
|
|
}
|
|
wsComponents.fragment = void 0;
|
|
return wsComponents;
|
|
}
|
|
function urnParse(urnComponents, options) {
|
|
if (!urnComponents.path) {
|
|
urnComponents.error = "URN can not be parsed";
|
|
return urnComponents;
|
|
}
|
|
const matches = urnComponents.path.match(URN_REG);
|
|
if (matches) {
|
|
const scheme = options.scheme || urnComponents.scheme || "urn";
|
|
urnComponents.nid = matches[1].toLowerCase();
|
|
urnComponents.nss = matches[2];
|
|
const urnScheme = `${scheme}:${options.nid || urnComponents.nid}`;
|
|
const schemeHandler = SCHEMES[urnScheme];
|
|
urnComponents.path = void 0;
|
|
if (schemeHandler) {
|
|
urnComponents = schemeHandler.parse(urnComponents, options);
|
|
}
|
|
} else {
|
|
urnComponents.error = urnComponents.error || "URN can not be parsed.";
|
|
}
|
|
return urnComponents;
|
|
}
|
|
function urnSerialize(urnComponents, options) {
|
|
const scheme = options.scheme || urnComponents.scheme || "urn";
|
|
const nid = urnComponents.nid.toLowerCase();
|
|
const urnScheme = `${scheme}:${options.nid || nid}`;
|
|
const schemeHandler = SCHEMES[urnScheme];
|
|
if (schemeHandler) {
|
|
urnComponents = schemeHandler.serialize(urnComponents, options);
|
|
}
|
|
const uriComponents = urnComponents;
|
|
const nss = urnComponents.nss;
|
|
uriComponents.path = `${nid || options.nid}:${nss}`;
|
|
options.skipEscape = true;
|
|
return uriComponents;
|
|
}
|
|
function urnuuidParse(urnComponents, options) {
|
|
const uuidComponents = urnComponents;
|
|
uuidComponents.uuid = uuidComponents.nss;
|
|
uuidComponents.nss = void 0;
|
|
if (!options.tolerant && (!uuidComponents.uuid || !UUID_REG.test(uuidComponents.uuid))) {
|
|
uuidComponents.error = uuidComponents.error || "UUID is not valid.";
|
|
}
|
|
return uuidComponents;
|
|
}
|
|
function urnuuidSerialize(uuidComponents) {
|
|
const urnComponents = uuidComponents;
|
|
urnComponents.nss = (uuidComponents.uuid || "").toLowerCase();
|
|
return urnComponents;
|
|
}
|
|
var http2 = {
|
|
scheme: "http",
|
|
domainHost: true,
|
|
parse: httpParse,
|
|
serialize: httpSerialize
|
|
};
|
|
var https2 = {
|
|
scheme: "https",
|
|
domainHost: http2.domainHost,
|
|
parse: httpParse,
|
|
serialize: httpSerialize
|
|
};
|
|
var ws = {
|
|
scheme: "ws",
|
|
domainHost: true,
|
|
parse: wsParse,
|
|
serialize: wsSerialize
|
|
};
|
|
var wss = {
|
|
scheme: "wss",
|
|
domainHost: ws.domainHost,
|
|
parse: ws.parse,
|
|
serialize: ws.serialize
|
|
};
|
|
var urn = {
|
|
scheme: "urn",
|
|
parse: urnParse,
|
|
serialize: urnSerialize,
|
|
skipNormalize: true
|
|
};
|
|
var urnuuid = {
|
|
scheme: "urn:uuid",
|
|
parse: urnuuidParse,
|
|
serialize: urnuuidSerialize,
|
|
skipNormalize: true
|
|
};
|
|
var SCHEMES = {
|
|
http: http2,
|
|
https: https2,
|
|
ws,
|
|
wss,
|
|
urn,
|
|
"urn:uuid": urnuuid
|
|
};
|
|
module2.exports = SCHEMES;
|
|
});
|
|
var require_fast_uri = __commonJS((exports, module2) => {
|
|
var { normalizeIPv6, normalizeIPv4, removeDotSegments, recomposeAuthority, normalizeComponentEncoding } = require_utils();
|
|
var SCHEMES = require_schemes();
|
|
function normalize2(uri, options) {
|
|
if (typeof uri === "string") {
|
|
uri = serialize(parse6(uri, options), options);
|
|
} else if (typeof uri === "object") {
|
|
uri = parse6(serialize(uri, options), options);
|
|
}
|
|
return uri;
|
|
}
|
|
function resolve7(baseURI, relativeURI, options) {
|
|
const schemelessOptions = Object.assign({ scheme: "null" }, options);
|
|
const resolved = resolveComponents(parse6(baseURI, schemelessOptions), parse6(relativeURI, schemelessOptions), schemelessOptions, true);
|
|
return serialize(resolved, { ...schemelessOptions, skipEscape: true });
|
|
}
|
|
function resolveComponents(base, relative5, options, skipNormalization) {
|
|
const target = {};
|
|
if (!skipNormalization) {
|
|
base = parse6(serialize(base, options), options);
|
|
relative5 = parse6(serialize(relative5, options), options);
|
|
}
|
|
options = options || {};
|
|
if (!options.tolerant && relative5.scheme) {
|
|
target.scheme = relative5.scheme;
|
|
target.userinfo = relative5.userinfo;
|
|
target.host = relative5.host;
|
|
target.port = relative5.port;
|
|
target.path = removeDotSegments(relative5.path || "");
|
|
target.query = relative5.query;
|
|
} else {
|
|
if (relative5.userinfo !== void 0 || relative5.host !== void 0 || relative5.port !== void 0) {
|
|
target.userinfo = relative5.userinfo;
|
|
target.host = relative5.host;
|
|
target.port = relative5.port;
|
|
target.path = removeDotSegments(relative5.path || "");
|
|
target.query = relative5.query;
|
|
} else {
|
|
if (!relative5.path) {
|
|
target.path = base.path;
|
|
if (relative5.query !== void 0) {
|
|
target.query = relative5.query;
|
|
} else {
|
|
target.query = base.query;
|
|
}
|
|
} else {
|
|
if (relative5.path.charAt(0) === "/") {
|
|
target.path = removeDotSegments(relative5.path);
|
|
} else {
|
|
if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) {
|
|
target.path = "/" + relative5.path;
|
|
} else if (!base.path) {
|
|
target.path = relative5.path;
|
|
} else {
|
|
target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative5.path;
|
|
}
|
|
target.path = removeDotSegments(target.path);
|
|
}
|
|
target.query = relative5.query;
|
|
}
|
|
target.userinfo = base.userinfo;
|
|
target.host = base.host;
|
|
target.port = base.port;
|
|
}
|
|
target.scheme = base.scheme;
|
|
}
|
|
target.fragment = relative5.fragment;
|
|
return target;
|
|
}
|
|
function equal(uriA, uriB, options) {
|
|
if (typeof uriA === "string") {
|
|
uriA = unescape(uriA);
|
|
uriA = serialize(normalizeComponentEncoding(parse6(uriA, options), true), { ...options, skipEscape: true });
|
|
} else if (typeof uriA === "object") {
|
|
uriA = serialize(normalizeComponentEncoding(uriA, true), { ...options, skipEscape: true });
|
|
}
|
|
if (typeof uriB === "string") {
|
|
uriB = unescape(uriB);
|
|
uriB = serialize(normalizeComponentEncoding(parse6(uriB, options), true), { ...options, skipEscape: true });
|
|
} else if (typeof uriB === "object") {
|
|
uriB = serialize(normalizeComponentEncoding(uriB, true), { ...options, skipEscape: true });
|
|
}
|
|
return uriA.toLowerCase() === uriB.toLowerCase();
|
|
}
|
|
function serialize(cmpts, opts) {
|
|
const components = {
|
|
host: cmpts.host,
|
|
scheme: cmpts.scheme,
|
|
userinfo: cmpts.userinfo,
|
|
port: cmpts.port,
|
|
path: cmpts.path,
|
|
query: cmpts.query,
|
|
nid: cmpts.nid,
|
|
nss: cmpts.nss,
|
|
uuid: cmpts.uuid,
|
|
fragment: cmpts.fragment,
|
|
reference: cmpts.reference,
|
|
resourceName: cmpts.resourceName,
|
|
secure: cmpts.secure,
|
|
error: ""
|
|
};
|
|
const options = Object.assign({}, opts);
|
|
const uriTokens = [];
|
|
const schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()];
|
|
if (schemeHandler && schemeHandler.serialize)
|
|
schemeHandler.serialize(components, options);
|
|
if (components.path !== void 0) {
|
|
if (!options.skipEscape) {
|
|
components.path = escape(components.path);
|
|
if (components.scheme !== void 0) {
|
|
components.path = components.path.split("%3A").join(":");
|
|
}
|
|
} else {
|
|
components.path = unescape(components.path);
|
|
}
|
|
}
|
|
if (options.reference !== "suffix" && components.scheme) {
|
|
uriTokens.push(components.scheme, ":");
|
|
}
|
|
const authority = recomposeAuthority(components);
|
|
if (authority !== void 0) {
|
|
if (options.reference !== "suffix") {
|
|
uriTokens.push("//");
|
|
}
|
|
uriTokens.push(authority);
|
|
if (components.path && components.path.charAt(0) !== "/") {
|
|
uriTokens.push("/");
|
|
}
|
|
}
|
|
if (components.path !== void 0) {
|
|
let s = components.path;
|
|
if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {
|
|
s = removeDotSegments(s);
|
|
}
|
|
if (authority === void 0) {
|
|
s = s.replace(/^\/\//u, "/%2F");
|
|
}
|
|
uriTokens.push(s);
|
|
}
|
|
if (components.query !== void 0) {
|
|
uriTokens.push("?", components.query);
|
|
}
|
|
if (components.fragment !== void 0) {
|
|
uriTokens.push("#", components.fragment);
|
|
}
|
|
return uriTokens.join("");
|
|
}
|
|
var hexLookUp = Array.from({ length: 127 }, (_v, k) => /[^!"$&'()*+,\-.;=_`a-z{}~]/u.test(String.fromCharCode(k)));
|
|
function nonSimpleDomain(value) {
|
|
let code = 0;
|
|
for (let i = 0, len = value.length; i < len; ++i) {
|
|
code = value.charCodeAt(i);
|
|
if (code > 126 || hexLookUp[code]) {
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
var URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;
|
|
function parse6(uri, opts) {
|
|
const options = Object.assign({}, opts);
|
|
const parsed = {
|
|
scheme: void 0,
|
|
userinfo: void 0,
|
|
host: "",
|
|
port: void 0,
|
|
path: "",
|
|
query: void 0,
|
|
fragment: void 0
|
|
};
|
|
const gotEncoding = uri.indexOf("%") !== -1;
|
|
let isIP = false;
|
|
if (options.reference === "suffix")
|
|
uri = (options.scheme ? options.scheme + ":" : "") + "//" + uri;
|
|
const matches = uri.match(URI_PARSE);
|
|
if (matches) {
|
|
parsed.scheme = matches[1];
|
|
parsed.userinfo = matches[3];
|
|
parsed.host = matches[4];
|
|
parsed.port = parseInt(matches[5], 10);
|
|
parsed.path = matches[6] || "";
|
|
parsed.query = matches[7];
|
|
parsed.fragment = matches[8];
|
|
if (isNaN(parsed.port)) {
|
|
parsed.port = matches[5];
|
|
}
|
|
if (parsed.host) {
|
|
const ipv4result = normalizeIPv4(parsed.host);
|
|
if (ipv4result.isIPV4 === false) {
|
|
const ipv6result = normalizeIPv6(ipv4result.host);
|
|
parsed.host = ipv6result.host.toLowerCase();
|
|
isIP = ipv6result.isIPV6;
|
|
} else {
|
|
parsed.host = ipv4result.host;
|
|
isIP = true;
|
|
}
|
|
}
|
|
if (parsed.scheme === void 0 && parsed.userinfo === void 0 && parsed.host === void 0 && parsed.port === void 0 && parsed.query === void 0 && !parsed.path) {
|
|
parsed.reference = "same-document";
|
|
} else if (parsed.scheme === void 0) {
|
|
parsed.reference = "relative";
|
|
} else if (parsed.fragment === void 0) {
|
|
parsed.reference = "absolute";
|
|
} else {
|
|
parsed.reference = "uri";
|
|
}
|
|
if (options.reference && options.reference !== "suffix" && options.reference !== parsed.reference) {
|
|
parsed.error = parsed.error || "URI is not a " + options.reference + " reference.";
|
|
}
|
|
const schemeHandler = SCHEMES[(options.scheme || parsed.scheme || "").toLowerCase()];
|
|
if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {
|
|
if (parsed.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) {
|
|
try {
|
|
parsed.host = URL.domainToASCII(parsed.host.toLowerCase());
|
|
} catch (e) {
|
|
parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e;
|
|
}
|
|
}
|
|
}
|
|
if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) {
|
|
if (gotEncoding && parsed.scheme !== void 0) {
|
|
parsed.scheme = unescape(parsed.scheme);
|
|
}
|
|
if (gotEncoding && parsed.host !== void 0) {
|
|
parsed.host = unescape(parsed.host);
|
|
}
|
|
if (parsed.path) {
|
|
parsed.path = escape(unescape(parsed.path));
|
|
}
|
|
if (parsed.fragment) {
|
|
parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment));
|
|
}
|
|
}
|
|
if (schemeHandler && schemeHandler.parse) {
|
|
schemeHandler.parse(parsed, options);
|
|
}
|
|
} else {
|
|
parsed.error = parsed.error || "URI can not be parsed.";
|
|
}
|
|
return parsed;
|
|
}
|
|
var fastUri = {
|
|
SCHEMES,
|
|
normalize: normalize2,
|
|
resolve: resolve7,
|
|
resolveComponents,
|
|
equal,
|
|
serialize,
|
|
parse: parse6
|
|
};
|
|
module2.exports = fastUri;
|
|
module2.exports.default = fastUri;
|
|
module2.exports.fastUri = fastUri;
|
|
});
|
|
var require_uri = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var uri = require_fast_uri();
|
|
uri.code = 'require("ajv/dist/runtime/uri").default';
|
|
exports.default = uri;
|
|
});
|
|
var require_core = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0;
|
|
var validate_1 = require_validate();
|
|
Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() {
|
|
return validate_1.KeywordCxt;
|
|
} });
|
|
var codegen_1 = require_codegen();
|
|
Object.defineProperty(exports, "_", { enumerable: true, get: function() {
|
|
return codegen_1._;
|
|
} });
|
|
Object.defineProperty(exports, "str", { enumerable: true, get: function() {
|
|
return codegen_1.str;
|
|
} });
|
|
Object.defineProperty(exports, "stringify", { enumerable: true, get: function() {
|
|
return codegen_1.stringify;
|
|
} });
|
|
Object.defineProperty(exports, "nil", { enumerable: true, get: function() {
|
|
return codegen_1.nil;
|
|
} });
|
|
Object.defineProperty(exports, "Name", { enumerable: true, get: function() {
|
|
return codegen_1.Name;
|
|
} });
|
|
Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() {
|
|
return codegen_1.CodeGen;
|
|
} });
|
|
var validation_error_1 = require_validation_error();
|
|
var ref_error_1 = require_ref_error();
|
|
var rules_1 = require_rules();
|
|
var compile_1 = require_compile();
|
|
var codegen_2 = require_codegen();
|
|
var resolve_1 = require_resolve();
|
|
var dataType_1 = require_dataType();
|
|
var util_1 = require_util();
|
|
var $dataRefSchema = require_data();
|
|
var uri_1 = require_uri();
|
|
var defaultRegExp = (str, flags) => new RegExp(str, flags);
|
|
defaultRegExp.code = "new RegExp";
|
|
var META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"];
|
|
var EXT_SCOPE_NAMES = /* @__PURE__ */ new Set([
|
|
"validate",
|
|
"serialize",
|
|
"parse",
|
|
"wrapper",
|
|
"root",
|
|
"schema",
|
|
"keyword",
|
|
"pattern",
|
|
"formats",
|
|
"validate$data",
|
|
"func",
|
|
"obj",
|
|
"Error"
|
|
]);
|
|
var removedOptions = {
|
|
errorDataPath: "",
|
|
format: "`validateFormats: false` can be used instead.",
|
|
nullable: '"nullable" keyword is supported by default.',
|
|
jsonPointers: "Deprecated jsPropertySyntax can be used instead.",
|
|
extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.",
|
|
missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.",
|
|
processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`",
|
|
sourceCode: "Use option `code: {source: true}`",
|
|
strictDefaults: "It is default now, see option `strict`.",
|
|
strictKeywords: "It is default now, see option `strict`.",
|
|
uniqueItems: '"uniqueItems" keyword is always validated.',
|
|
unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",
|
|
cache: "Map is used as cache, schema object as key.",
|
|
serialize: "Map is used as cache, schema object as key.",
|
|
ajvErrors: "It is default now."
|
|
};
|
|
var deprecatedOptions = {
|
|
ignoreKeywordsWithRef: "",
|
|
jsPropertySyntax: "",
|
|
unicode: '"minLength"/"maxLength" account for unicode characters by default.'
|
|
};
|
|
var MAX_EXPRESSION = 200;
|
|
function requiredOptions(o) {
|
|
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0;
|
|
const s = o.strict;
|
|
const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize;
|
|
const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0;
|
|
const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp;
|
|
const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default;
|
|
return {
|
|
strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true,
|
|
strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true,
|
|
strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log",
|
|
strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log",
|
|
strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false,
|
|
code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp },
|
|
loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION,
|
|
loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION,
|
|
meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true,
|
|
messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true,
|
|
inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true,
|
|
schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id",
|
|
addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true,
|
|
validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true,
|
|
validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true,
|
|
unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true,
|
|
int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true,
|
|
uriResolver
|
|
};
|
|
}
|
|
class Ajv {
|
|
constructor(opts = {}) {
|
|
this.schemas = {};
|
|
this.refs = {};
|
|
this.formats = {};
|
|
this._compilations = /* @__PURE__ */ new Set();
|
|
this._loading = {};
|
|
this._cache = /* @__PURE__ */ new Map();
|
|
opts = this.opts = { ...opts, ...requiredOptions(opts) };
|
|
const { es5, lines } = this.opts.code;
|
|
this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines });
|
|
this.logger = getLogger(opts.logger);
|
|
const formatOpt = opts.validateFormats;
|
|
opts.validateFormats = false;
|
|
this.RULES = (0, rules_1.getRules)();
|
|
checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED");
|
|
checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn");
|
|
this._metaOpts = getMetaSchemaOptions.call(this);
|
|
if (opts.formats)
|
|
addInitialFormats.call(this);
|
|
this._addVocabularies();
|
|
this._addDefaultMetaSchema();
|
|
if (opts.keywords)
|
|
addInitialKeywords.call(this, opts.keywords);
|
|
if (typeof opts.meta == "object")
|
|
this.addMetaSchema(opts.meta);
|
|
addInitialSchemas.call(this);
|
|
opts.validateFormats = formatOpt;
|
|
}
|
|
_addVocabularies() {
|
|
this.addKeyword("$async");
|
|
}
|
|
_addDefaultMetaSchema() {
|
|
const { $data, meta, schemaId } = this.opts;
|
|
let _dataRefSchema = $dataRefSchema;
|
|
if (schemaId === "id") {
|
|
_dataRefSchema = { ...$dataRefSchema };
|
|
_dataRefSchema.id = _dataRefSchema.$id;
|
|
delete _dataRefSchema.$id;
|
|
}
|
|
if (meta && $data)
|
|
this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false);
|
|
}
|
|
defaultMeta() {
|
|
const { meta, schemaId } = this.opts;
|
|
return this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : void 0;
|
|
}
|
|
validate(schemaKeyRef, data) {
|
|
let v;
|
|
if (typeof schemaKeyRef == "string") {
|
|
v = this.getSchema(schemaKeyRef);
|
|
if (!v)
|
|
throw new Error(`no schema with key or ref "${schemaKeyRef}"`);
|
|
} else {
|
|
v = this.compile(schemaKeyRef);
|
|
}
|
|
const valid = v(data);
|
|
if (!("$async" in v))
|
|
this.errors = v.errors;
|
|
return valid;
|
|
}
|
|
compile(schema, _meta) {
|
|
const sch = this._addSchema(schema, _meta);
|
|
return sch.validate || this._compileSchemaEnv(sch);
|
|
}
|
|
compileAsync(schema, meta) {
|
|
if (typeof this.opts.loadSchema != "function") {
|
|
throw new Error("options.loadSchema should be a function");
|
|
}
|
|
const { loadSchema } = this.opts;
|
|
return runCompileAsync.call(this, schema, meta);
|
|
async function runCompileAsync(_schema, _meta) {
|
|
await loadMetaSchema.call(this, _schema.$schema);
|
|
const sch = this._addSchema(_schema, _meta);
|
|
return sch.validate || _compileAsync.call(this, sch);
|
|
}
|
|
async function loadMetaSchema($ref) {
|
|
if ($ref && !this.getSchema($ref)) {
|
|
await runCompileAsync.call(this, { $ref }, true);
|
|
}
|
|
}
|
|
async function _compileAsync(sch) {
|
|
try {
|
|
return this._compileSchemaEnv(sch);
|
|
} catch (e) {
|
|
if (!(e instanceof ref_error_1.default))
|
|
throw e;
|
|
checkLoaded.call(this, e);
|
|
await loadMissingSchema.call(this, e.missingSchema);
|
|
return _compileAsync.call(this, sch);
|
|
}
|
|
}
|
|
function checkLoaded({ missingSchema: ref, missingRef }) {
|
|
if (this.refs[ref]) {
|
|
throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`);
|
|
}
|
|
}
|
|
async function loadMissingSchema(ref) {
|
|
const _schema = await _loadSchema.call(this, ref);
|
|
if (!this.refs[ref])
|
|
await loadMetaSchema.call(this, _schema.$schema);
|
|
if (!this.refs[ref])
|
|
this.addSchema(_schema, ref, meta);
|
|
}
|
|
async function _loadSchema(ref) {
|
|
const p = this._loading[ref];
|
|
if (p)
|
|
return p;
|
|
try {
|
|
return await (this._loading[ref] = loadSchema(ref));
|
|
} finally {
|
|
delete this._loading[ref];
|
|
}
|
|
}
|
|
}
|
|
addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) {
|
|
if (Array.isArray(schema)) {
|
|
for (const sch of schema)
|
|
this.addSchema(sch, void 0, _meta, _validateSchema);
|
|
return this;
|
|
}
|
|
let id;
|
|
if (typeof schema === "object") {
|
|
const { schemaId } = this.opts;
|
|
id = schema[schemaId];
|
|
if (id !== void 0 && typeof id != "string") {
|
|
throw new Error(`schema ${schemaId} must be string`);
|
|
}
|
|
}
|
|
key = (0, resolve_1.normalizeId)(key || id);
|
|
this._checkUnique(key);
|
|
this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true);
|
|
return this;
|
|
}
|
|
addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) {
|
|
this.addSchema(schema, key, true, _validateSchema);
|
|
return this;
|
|
}
|
|
validateSchema(schema, throwOrLogError) {
|
|
if (typeof schema == "boolean")
|
|
return true;
|
|
let $schema;
|
|
$schema = schema.$schema;
|
|
if ($schema !== void 0 && typeof $schema != "string") {
|
|
throw new Error("$schema must be a string");
|
|
}
|
|
$schema = $schema || this.opts.defaultMeta || this.defaultMeta();
|
|
if (!$schema) {
|
|
this.logger.warn("meta-schema not available");
|
|
this.errors = null;
|
|
return true;
|
|
}
|
|
const valid = this.validate($schema, schema);
|
|
if (!valid && throwOrLogError) {
|
|
const message = "schema is invalid: " + this.errorsText();
|
|
if (this.opts.validateSchema === "log")
|
|
this.logger.error(message);
|
|
else
|
|
throw new Error(message);
|
|
}
|
|
return valid;
|
|
}
|
|
getSchema(keyRef) {
|
|
let sch;
|
|
while (typeof (sch = getSchEnv.call(this, keyRef)) == "string")
|
|
keyRef = sch;
|
|
if (sch === void 0) {
|
|
const { schemaId } = this.opts;
|
|
const root2 = new compile_1.SchemaEnv({ schema: {}, schemaId });
|
|
sch = compile_1.resolveSchema.call(this, root2, keyRef);
|
|
if (!sch)
|
|
return;
|
|
this.refs[keyRef] = sch;
|
|
}
|
|
return sch.validate || this._compileSchemaEnv(sch);
|
|
}
|
|
removeSchema(schemaKeyRef) {
|
|
if (schemaKeyRef instanceof RegExp) {
|
|
this._removeAllSchemas(this.schemas, schemaKeyRef);
|
|
this._removeAllSchemas(this.refs, schemaKeyRef);
|
|
return this;
|
|
}
|
|
switch (typeof schemaKeyRef) {
|
|
case "undefined":
|
|
this._removeAllSchemas(this.schemas);
|
|
this._removeAllSchemas(this.refs);
|
|
this._cache.clear();
|
|
return this;
|
|
case "string": {
|
|
const sch = getSchEnv.call(this, schemaKeyRef);
|
|
if (typeof sch == "object")
|
|
this._cache.delete(sch.schema);
|
|
delete this.schemas[schemaKeyRef];
|
|
delete this.refs[schemaKeyRef];
|
|
return this;
|
|
}
|
|
case "object": {
|
|
const cacheKey = schemaKeyRef;
|
|
this._cache.delete(cacheKey);
|
|
let id = schemaKeyRef[this.opts.schemaId];
|
|
if (id) {
|
|
id = (0, resolve_1.normalizeId)(id);
|
|
delete this.schemas[id];
|
|
delete this.refs[id];
|
|
}
|
|
return this;
|
|
}
|
|
default:
|
|
throw new Error("ajv.removeSchema: invalid parameter");
|
|
}
|
|
}
|
|
addVocabulary(definitions) {
|
|
for (const def of definitions)
|
|
this.addKeyword(def);
|
|
return this;
|
|
}
|
|
addKeyword(kwdOrDef, def) {
|
|
let keyword;
|
|
if (typeof kwdOrDef == "string") {
|
|
keyword = kwdOrDef;
|
|
if (typeof def == "object") {
|
|
this.logger.warn("these parameters are deprecated, see docs for addKeyword");
|
|
def.keyword = keyword;
|
|
}
|
|
} else if (typeof kwdOrDef == "object" && def === void 0) {
|
|
def = kwdOrDef;
|
|
keyword = def.keyword;
|
|
if (Array.isArray(keyword) && !keyword.length) {
|
|
throw new Error("addKeywords: keyword must be string or non-empty array");
|
|
}
|
|
} else {
|
|
throw new Error("invalid addKeywords parameters");
|
|
}
|
|
checkKeyword.call(this, keyword, def);
|
|
if (!def) {
|
|
(0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd));
|
|
return this;
|
|
}
|
|
keywordMetaschema.call(this, def);
|
|
const definition = {
|
|
...def,
|
|
type: (0, dataType_1.getJSONTypes)(def.type),
|
|
schemaType: (0, dataType_1.getJSONTypes)(def.schemaType)
|
|
};
|
|
(0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t)));
|
|
return this;
|
|
}
|
|
getKeyword(keyword) {
|
|
const rule = this.RULES.all[keyword];
|
|
return typeof rule == "object" ? rule.definition : !!rule;
|
|
}
|
|
removeKeyword(keyword) {
|
|
const { RULES } = this;
|
|
delete RULES.keywords[keyword];
|
|
delete RULES.all[keyword];
|
|
for (const group of RULES.rules) {
|
|
const i = group.rules.findIndex((rule) => rule.keyword === keyword);
|
|
if (i >= 0)
|
|
group.rules.splice(i, 1);
|
|
}
|
|
return this;
|
|
}
|
|
addFormat(name, format) {
|
|
if (typeof format == "string")
|
|
format = new RegExp(format);
|
|
this.formats[name] = format;
|
|
return this;
|
|
}
|
|
errorsText(errors3 = this.errors, { separator = ", ", dataVar = "data" } = {}) {
|
|
if (!errors3 || errors3.length === 0)
|
|
return "No errors";
|
|
return errors3.map((e) => `${dataVar}${e.instancePath} ${e.message}`).reduce((text, msg) => text + separator + msg);
|
|
}
|
|
$dataMetaSchema(metaSchema, keywordsJsonPointers) {
|
|
const rules = this.RULES.all;
|
|
metaSchema = JSON.parse(JSON.stringify(metaSchema));
|
|
for (const jsonPointer of keywordsJsonPointers) {
|
|
const segments = jsonPointer.split("/").slice(1);
|
|
let keywords = metaSchema;
|
|
for (const seg of segments)
|
|
keywords = keywords[seg];
|
|
for (const key in rules) {
|
|
const rule = rules[key];
|
|
if (typeof rule != "object")
|
|
continue;
|
|
const { $data } = rule.definition;
|
|
const schema = keywords[key];
|
|
if ($data && schema)
|
|
keywords[key] = schemaOrData(schema);
|
|
}
|
|
}
|
|
return metaSchema;
|
|
}
|
|
_removeAllSchemas(schemas4, regex) {
|
|
for (const keyRef in schemas4) {
|
|
const sch = schemas4[keyRef];
|
|
if (!regex || regex.test(keyRef)) {
|
|
if (typeof sch == "string") {
|
|
delete schemas4[keyRef];
|
|
} else if (sch && !sch.meta) {
|
|
this._cache.delete(sch.schema);
|
|
delete schemas4[keyRef];
|
|
}
|
|
}
|
|
}
|
|
}
|
|
_addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) {
|
|
let id;
|
|
const { schemaId } = this.opts;
|
|
if (typeof schema == "object") {
|
|
id = schema[schemaId];
|
|
} else {
|
|
if (this.opts.jtd)
|
|
throw new Error("schema must be object");
|
|
else if (typeof schema != "boolean")
|
|
throw new Error("schema must be object or boolean");
|
|
}
|
|
let sch = this._cache.get(schema);
|
|
if (sch !== void 0)
|
|
return sch;
|
|
baseId = (0, resolve_1.normalizeId)(id || baseId);
|
|
const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId);
|
|
sch = new compile_1.SchemaEnv({ schema, schemaId, meta, baseId, localRefs });
|
|
this._cache.set(sch.schema, sch);
|
|
if (addSchema && !baseId.startsWith("#")) {
|
|
if (baseId)
|
|
this._checkUnique(baseId);
|
|
this.refs[baseId] = sch;
|
|
}
|
|
if (validateSchema)
|
|
this.validateSchema(schema, true);
|
|
return sch;
|
|
}
|
|
_checkUnique(id) {
|
|
if (this.schemas[id] || this.refs[id]) {
|
|
throw new Error(`schema with key or id "${id}" already exists`);
|
|
}
|
|
}
|
|
_compileSchemaEnv(sch) {
|
|
if (sch.meta)
|
|
this._compileMetaSchema(sch);
|
|
else
|
|
compile_1.compileSchema.call(this, sch);
|
|
if (!sch.validate)
|
|
throw new Error("ajv implementation error");
|
|
return sch.validate;
|
|
}
|
|
_compileMetaSchema(sch) {
|
|
const currentOpts = this.opts;
|
|
this.opts = this._metaOpts;
|
|
try {
|
|
compile_1.compileSchema.call(this, sch);
|
|
} finally {
|
|
this.opts = currentOpts;
|
|
}
|
|
}
|
|
}
|
|
Ajv.ValidationError = validation_error_1.default;
|
|
Ajv.MissingRefError = ref_error_1.default;
|
|
exports.default = Ajv;
|
|
function checkOptions(checkOpts, options, msg, log = "error") {
|
|
for (const key in checkOpts) {
|
|
const opt = key;
|
|
if (opt in options)
|
|
this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`);
|
|
}
|
|
}
|
|
function getSchEnv(keyRef) {
|
|
keyRef = (0, resolve_1.normalizeId)(keyRef);
|
|
return this.schemas[keyRef] || this.refs[keyRef];
|
|
}
|
|
function addInitialSchemas() {
|
|
const optsSchemas = this.opts.schemas;
|
|
if (!optsSchemas)
|
|
return;
|
|
if (Array.isArray(optsSchemas))
|
|
this.addSchema(optsSchemas);
|
|
else
|
|
for (const key in optsSchemas)
|
|
this.addSchema(optsSchemas[key], key);
|
|
}
|
|
function addInitialFormats() {
|
|
for (const name in this.opts.formats) {
|
|
const format = this.opts.formats[name];
|
|
if (format)
|
|
this.addFormat(name, format);
|
|
}
|
|
}
|
|
function addInitialKeywords(defs) {
|
|
if (Array.isArray(defs)) {
|
|
this.addVocabulary(defs);
|
|
return;
|
|
}
|
|
this.logger.warn("keywords option as map is deprecated, pass array");
|
|
for (const keyword in defs) {
|
|
const def = defs[keyword];
|
|
if (!def.keyword)
|
|
def.keyword = keyword;
|
|
this.addKeyword(def);
|
|
}
|
|
}
|
|
function getMetaSchemaOptions() {
|
|
const metaOpts = { ...this.opts };
|
|
for (const opt of META_IGNORE_OPTIONS)
|
|
delete metaOpts[opt];
|
|
return metaOpts;
|
|
}
|
|
var noLogs = { log() {
|
|
}, warn() {
|
|
}, error() {
|
|
} };
|
|
function getLogger(logger) {
|
|
if (logger === false)
|
|
return noLogs;
|
|
if (logger === void 0)
|
|
return console;
|
|
if (logger.log && logger.warn && logger.error)
|
|
return logger;
|
|
throw new Error("logger must implement log, warn and error methods");
|
|
}
|
|
var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i;
|
|
function checkKeyword(keyword, def) {
|
|
const { RULES } = this;
|
|
(0, util_1.eachItem)(keyword, (kwd) => {
|
|
if (RULES.keywords[kwd])
|
|
throw new Error(`Keyword ${kwd} is already defined`);
|
|
if (!KEYWORD_NAME.test(kwd))
|
|
throw new Error(`Keyword ${kwd} has invalid name`);
|
|
});
|
|
if (!def)
|
|
return;
|
|
if (def.$data && !("code" in def || "validate" in def)) {
|
|
throw new Error('$data keyword must have "code" or "validate" function');
|
|
}
|
|
}
|
|
function addRule(keyword, definition, dataType) {
|
|
var _a;
|
|
const post = definition === null || definition === void 0 ? void 0 : definition.post;
|
|
if (dataType && post)
|
|
throw new Error('keyword with "post" flag cannot have "type"');
|
|
const { RULES } = this;
|
|
let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType);
|
|
if (!ruleGroup) {
|
|
ruleGroup = { type: dataType, rules: [] };
|
|
RULES.rules.push(ruleGroup);
|
|
}
|
|
RULES.keywords[keyword] = true;
|
|
if (!definition)
|
|
return;
|
|
const rule = {
|
|
keyword,
|
|
definition: {
|
|
...definition,
|
|
type: (0, dataType_1.getJSONTypes)(definition.type),
|
|
schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType)
|
|
}
|
|
};
|
|
if (definition.before)
|
|
addBeforeRule.call(this, ruleGroup, rule, definition.before);
|
|
else
|
|
ruleGroup.rules.push(rule);
|
|
RULES.all[keyword] = rule;
|
|
(_a = definition.implements) === null || _a === void 0 || _a.forEach((kwd) => this.addKeyword(kwd));
|
|
}
|
|
function addBeforeRule(ruleGroup, rule, before) {
|
|
const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);
|
|
if (i >= 0) {
|
|
ruleGroup.rules.splice(i, 0, rule);
|
|
} else {
|
|
ruleGroup.rules.push(rule);
|
|
this.logger.warn(`rule ${before} is not defined`);
|
|
}
|
|
}
|
|
function keywordMetaschema(def) {
|
|
let { metaSchema } = def;
|
|
if (metaSchema === void 0)
|
|
return;
|
|
if (def.$data && this.opts.$data)
|
|
metaSchema = schemaOrData(metaSchema);
|
|
def.validateSchema = this.compile(metaSchema, true);
|
|
}
|
|
var $dataRef = {
|
|
$ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"
|
|
};
|
|
function schemaOrData(schema) {
|
|
return { anyOf: [schema, $dataRef] };
|
|
}
|
|
});
|
|
var require_id = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var def = {
|
|
keyword: "id",
|
|
code() {
|
|
throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID');
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_ref = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.callRef = exports.getValidate = void 0;
|
|
var ref_error_1 = require_ref_error();
|
|
var code_1 = require_code2();
|
|
var codegen_1 = require_codegen();
|
|
var names_1 = require_names();
|
|
var compile_1 = require_compile();
|
|
var util_1 = require_util();
|
|
var def = {
|
|
keyword: "$ref",
|
|
schemaType: "string",
|
|
code(cxt) {
|
|
const { gen, schema: $ref, it } = cxt;
|
|
const { baseId, schemaEnv: env, validateName, opts, self: self2 } = it;
|
|
const { root: root2 } = env;
|
|
if (($ref === "#" || $ref === "#/") && baseId === root2.baseId)
|
|
return callRootRef();
|
|
const schOrEnv = compile_1.resolveRef.call(self2, root2, baseId, $ref);
|
|
if (schOrEnv === void 0)
|
|
throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref);
|
|
if (schOrEnv instanceof compile_1.SchemaEnv)
|
|
return callValidate(schOrEnv);
|
|
return inlineRefSchema(schOrEnv);
|
|
function callRootRef() {
|
|
if (env === root2)
|
|
return callRef(cxt, validateName, env, env.$async);
|
|
const rootName = gen.scopeValue("root", { ref: root2 });
|
|
return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root2, root2.$async);
|
|
}
|
|
function callValidate(sch) {
|
|
const v = getValidate(cxt, sch);
|
|
callRef(cxt, v, sch, sch.$async);
|
|
}
|
|
function inlineRefSchema(sch) {
|
|
const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch });
|
|
const valid = gen.name("valid");
|
|
const schCxt = cxt.subschema({
|
|
schema: sch,
|
|
dataTypes: [],
|
|
schemaPath: codegen_1.nil,
|
|
topSchemaRef: schName,
|
|
errSchemaPath: $ref
|
|
}, valid);
|
|
cxt.mergeEvaluated(schCxt);
|
|
cxt.ok(valid);
|
|
}
|
|
}
|
|
};
|
|
function getValidate(cxt, sch) {
|
|
const { gen } = cxt;
|
|
return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`;
|
|
}
|
|
exports.getValidate = getValidate;
|
|
function callRef(cxt, v, sch, $async) {
|
|
const { gen, it } = cxt;
|
|
const { allErrors, schemaEnv: env, opts } = it;
|
|
const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil;
|
|
if ($async)
|
|
callAsyncRef();
|
|
else
|
|
callSyncRef();
|
|
function callAsyncRef() {
|
|
if (!env.$async)
|
|
throw new Error("async schema referenced by sync schema");
|
|
const valid = gen.let("valid");
|
|
gen.try(() => {
|
|
gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`);
|
|
addEvaluatedFrom(v);
|
|
if (!allErrors)
|
|
gen.assign(valid, true);
|
|
}, (e) => {
|
|
gen.if((0, codegen_1._)`!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e));
|
|
addErrorsFrom(e);
|
|
if (!allErrors)
|
|
gen.assign(valid, false);
|
|
});
|
|
cxt.ok(valid);
|
|
}
|
|
function callSyncRef() {
|
|
cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v));
|
|
}
|
|
function addErrorsFrom(source) {
|
|
const errs = (0, codegen_1._)`${source}.errors`;
|
|
gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`);
|
|
gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`);
|
|
}
|
|
function addEvaluatedFrom(source) {
|
|
var _a;
|
|
if (!it.opts.unevaluated)
|
|
return;
|
|
const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated;
|
|
if (it.props !== true) {
|
|
if (schEvaluated && !schEvaluated.dynamicProps) {
|
|
if (schEvaluated.props !== void 0) {
|
|
it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props);
|
|
}
|
|
} else {
|
|
const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`);
|
|
it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name);
|
|
}
|
|
}
|
|
if (it.items !== true) {
|
|
if (schEvaluated && !schEvaluated.dynamicItems) {
|
|
if (schEvaluated.items !== void 0) {
|
|
it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items);
|
|
}
|
|
} else {
|
|
const items = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`);
|
|
it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
exports.callRef = callRef;
|
|
exports.default = def;
|
|
});
|
|
var require_core2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var id_1 = require_id();
|
|
var ref_1 = require_ref();
|
|
var core2 = [
|
|
"$schema",
|
|
"$id",
|
|
"$defs",
|
|
"$vocabulary",
|
|
{ keyword: "$comment" },
|
|
"definitions",
|
|
id_1.default,
|
|
ref_1.default
|
|
];
|
|
exports.default = core2;
|
|
});
|
|
var require_limitNumber = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var codegen_1 = require_codegen();
|
|
var ops = codegen_1.operators;
|
|
var KWDs = {
|
|
maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT },
|
|
minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT },
|
|
exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE },
|
|
exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE }
|
|
};
|
|
var error2 = {
|
|
message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`,
|
|
params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`
|
|
};
|
|
var def = {
|
|
keyword: Object.keys(KWDs),
|
|
type: "number",
|
|
schemaType: "number",
|
|
$data: true,
|
|
error: error2,
|
|
code(cxt) {
|
|
const { keyword, data, schemaCode } = cxt;
|
|
cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`);
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_multipleOf = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var codegen_1 = require_codegen();
|
|
var error2 = {
|
|
message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`,
|
|
params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}`
|
|
};
|
|
var def = {
|
|
keyword: "multipleOf",
|
|
type: "number",
|
|
schemaType: "number",
|
|
$data: true,
|
|
error: error2,
|
|
code(cxt) {
|
|
const { gen, data, schemaCode, it } = cxt;
|
|
const prec = it.opts.multipleOfPrecision;
|
|
const res = gen.let("res");
|
|
const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`;
|
|
cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`);
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_ucs2length = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
function ucs2length(str) {
|
|
const len = str.length;
|
|
let length = 0;
|
|
let pos = 0;
|
|
let value;
|
|
while (pos < len) {
|
|
length++;
|
|
value = str.charCodeAt(pos++);
|
|
if (value >= 55296 && value <= 56319 && pos < len) {
|
|
value = str.charCodeAt(pos);
|
|
if ((value & 64512) === 56320)
|
|
pos++;
|
|
}
|
|
}
|
|
return length;
|
|
}
|
|
exports.default = ucs2length;
|
|
ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default';
|
|
});
|
|
var require_limitLength = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var codegen_1 = require_codegen();
|
|
var util_1 = require_util();
|
|
var ucs2length_1 = require_ucs2length();
|
|
var error2 = {
|
|
message({ keyword, schemaCode }) {
|
|
const comp = keyword === "maxLength" ? "more" : "fewer";
|
|
return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`;
|
|
},
|
|
params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}`
|
|
};
|
|
var def = {
|
|
keyword: ["maxLength", "minLength"],
|
|
type: "string",
|
|
schemaType: "number",
|
|
$data: true,
|
|
error: error2,
|
|
code(cxt) {
|
|
const { keyword, data, schemaCode, it } = cxt;
|
|
const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT;
|
|
const len = it.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`;
|
|
cxt.fail$data((0, codegen_1._)`${len} ${op} ${schemaCode}`);
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_pattern = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var code_1 = require_code2();
|
|
var codegen_1 = require_codegen();
|
|
var error2 = {
|
|
message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`,
|
|
params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}`
|
|
};
|
|
var def = {
|
|
keyword: "pattern",
|
|
type: "string",
|
|
schemaType: "string",
|
|
$data: true,
|
|
error: error2,
|
|
code(cxt) {
|
|
const { data, $data, schema, schemaCode, it } = cxt;
|
|
const u = it.opts.unicodeRegExp ? "u" : "";
|
|
const regExp = $data ? (0, codegen_1._)`(new RegExp(${schemaCode}, ${u}))` : (0, code_1.usePattern)(cxt, schema);
|
|
cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`);
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_limitProperties = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var codegen_1 = require_codegen();
|
|
var error2 = {
|
|
message({ keyword, schemaCode }) {
|
|
const comp = keyword === "maxProperties" ? "more" : "fewer";
|
|
return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`;
|
|
},
|
|
params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}`
|
|
};
|
|
var def = {
|
|
keyword: ["maxProperties", "minProperties"],
|
|
type: "object",
|
|
schemaType: "number",
|
|
$data: true,
|
|
error: error2,
|
|
code(cxt) {
|
|
const { keyword, data, schemaCode } = cxt;
|
|
const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT;
|
|
cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`);
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_required = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var code_1 = require_code2();
|
|
var codegen_1 = require_codegen();
|
|
var util_1 = require_util();
|
|
var error2 = {
|
|
message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`,
|
|
params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}`
|
|
};
|
|
var def = {
|
|
keyword: "required",
|
|
type: "object",
|
|
schemaType: "array",
|
|
$data: true,
|
|
error: error2,
|
|
code(cxt) {
|
|
const { gen, schema, schemaCode, data, $data, it } = cxt;
|
|
const { opts } = it;
|
|
if (!$data && schema.length === 0)
|
|
return;
|
|
const useLoop = schema.length >= opts.loopRequired;
|
|
if (it.allErrors)
|
|
allErrorsMode();
|
|
else
|
|
exitOnErrorMode();
|
|
if (opts.strictRequired) {
|
|
const props = cxt.parentSchema.properties;
|
|
const { definedProperties } = cxt.it;
|
|
for (const requiredKey of schema) {
|
|
if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) {
|
|
const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;
|
|
const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`;
|
|
(0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired);
|
|
}
|
|
}
|
|
}
|
|
function allErrorsMode() {
|
|
if (useLoop || $data) {
|
|
cxt.block$data(codegen_1.nil, loopAllRequired);
|
|
} else {
|
|
for (const prop of schema) {
|
|
(0, code_1.checkReportMissingProp)(cxt, prop);
|
|
}
|
|
}
|
|
}
|
|
function exitOnErrorMode() {
|
|
const missing = gen.let("missing");
|
|
if (useLoop || $data) {
|
|
const valid = gen.let("valid", true);
|
|
cxt.block$data(valid, () => loopUntilMissing(missing, valid));
|
|
cxt.ok(valid);
|
|
} else {
|
|
gen.if((0, code_1.checkMissingProp)(cxt, schema, missing));
|
|
(0, code_1.reportMissingProp)(cxt, missing);
|
|
gen.else();
|
|
}
|
|
}
|
|
function loopAllRequired() {
|
|
gen.forOf("prop", schemaCode, (prop) => {
|
|
cxt.setParams({ missingProperty: prop });
|
|
gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error());
|
|
});
|
|
}
|
|
function loopUntilMissing(missing, valid) {
|
|
cxt.setParams({ missingProperty: missing });
|
|
gen.forOf(missing, schemaCode, () => {
|
|
gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties));
|
|
gen.if((0, codegen_1.not)(valid), () => {
|
|
cxt.error();
|
|
gen.break();
|
|
});
|
|
}, codegen_1.nil);
|
|
}
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_limitItems = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var codegen_1 = require_codegen();
|
|
var error2 = {
|
|
message({ keyword, schemaCode }) {
|
|
const comp = keyword === "maxItems" ? "more" : "fewer";
|
|
return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`;
|
|
},
|
|
params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}`
|
|
};
|
|
var def = {
|
|
keyword: ["maxItems", "minItems"],
|
|
type: "array",
|
|
schemaType: "number",
|
|
$data: true,
|
|
error: error2,
|
|
code(cxt) {
|
|
const { keyword, data, schemaCode } = cxt;
|
|
const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT;
|
|
cxt.fail$data((0, codegen_1._)`${data}.length ${op} ${schemaCode}`);
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_equal = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var equal = require_fast_deep_equal();
|
|
equal.code = 'require("ajv/dist/runtime/equal").default';
|
|
exports.default = equal;
|
|
});
|
|
var require_uniqueItems = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var dataType_1 = require_dataType();
|
|
var codegen_1 = require_codegen();
|
|
var util_1 = require_util();
|
|
var equal_1 = require_equal();
|
|
var error2 = {
|
|
message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`,
|
|
params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}`
|
|
};
|
|
var def = {
|
|
keyword: "uniqueItems",
|
|
type: "array",
|
|
schemaType: "boolean",
|
|
$data: true,
|
|
error: error2,
|
|
code(cxt) {
|
|
const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt;
|
|
if (!$data && !schema)
|
|
return;
|
|
const valid = gen.let("valid");
|
|
const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : [];
|
|
cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`);
|
|
cxt.ok(valid);
|
|
function validateUniqueItems() {
|
|
const i = gen.let("i", (0, codegen_1._)`${data}.length`);
|
|
const j = gen.let("j");
|
|
cxt.setParams({ i, j });
|
|
gen.assign(valid, true);
|
|
gen.if((0, codegen_1._)`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j));
|
|
}
|
|
function canOptimize() {
|
|
return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array");
|
|
}
|
|
function loopN(i, j) {
|
|
const item = gen.name("item");
|
|
const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong);
|
|
const indices = gen.const("indices", (0, codegen_1._)`{}`);
|
|
gen.for((0, codegen_1._)`;${i}--;`, () => {
|
|
gen.let(item, (0, codegen_1._)`${data}[${i}]`);
|
|
gen.if(wrongType, (0, codegen_1._)`continue`);
|
|
if (itemTypes.length > 1)
|
|
gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`);
|
|
gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => {
|
|
gen.assign(j, (0, codegen_1._)`${indices}[${item}]`);
|
|
cxt.error();
|
|
gen.assign(valid, false).break();
|
|
}).code((0, codegen_1._)`${indices}[${item}] = ${i}`);
|
|
});
|
|
}
|
|
function loopN2(i, j) {
|
|
const eql = (0, util_1.useFunc)(gen, equal_1.default);
|
|
const outer = gen.name("outer");
|
|
gen.label(outer).for((0, codegen_1._)`;${i}--;`, () => gen.for((0, codegen_1._)`${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i}], ${data}[${j}])`, () => {
|
|
cxt.error();
|
|
gen.assign(valid, false).break(outer);
|
|
})));
|
|
}
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_const = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var codegen_1 = require_codegen();
|
|
var util_1 = require_util();
|
|
var equal_1 = require_equal();
|
|
var error2 = {
|
|
message: "must be equal to constant",
|
|
params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}`
|
|
};
|
|
var def = {
|
|
keyword: "const",
|
|
$data: true,
|
|
error: error2,
|
|
code(cxt) {
|
|
const { gen, data, $data, schemaCode, schema } = cxt;
|
|
if ($data || schema && typeof schema == "object") {
|
|
cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`);
|
|
} else {
|
|
cxt.fail((0, codegen_1._)`${schema} !== ${data}`);
|
|
}
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_enum = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var codegen_1 = require_codegen();
|
|
var util_1 = require_util();
|
|
var equal_1 = require_equal();
|
|
var error2 = {
|
|
message: "must be equal to one of the allowed values",
|
|
params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}`
|
|
};
|
|
var def = {
|
|
keyword: "enum",
|
|
schemaType: "array",
|
|
$data: true,
|
|
error: error2,
|
|
code(cxt) {
|
|
const { gen, data, $data, schema, schemaCode, it } = cxt;
|
|
if (!$data && schema.length === 0)
|
|
throw new Error("enum must have non-empty array");
|
|
const useLoop = schema.length >= it.opts.loopEnum;
|
|
let eql;
|
|
const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default);
|
|
let valid;
|
|
if (useLoop || $data) {
|
|
valid = gen.let("valid");
|
|
cxt.block$data(valid, loopEnum);
|
|
} else {
|
|
if (!Array.isArray(schema))
|
|
throw new Error("ajv implementation error");
|
|
const vSchema = gen.const("vSchema", schemaCode);
|
|
valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i)));
|
|
}
|
|
cxt.pass(valid);
|
|
function loopEnum() {
|
|
gen.assign(valid, false);
|
|
gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break()));
|
|
}
|
|
function equalCode(vSchema, i) {
|
|
const sch = schema[i];
|
|
return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i}])` : (0, codegen_1._)`${data} === ${sch}`;
|
|
}
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_validation = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var limitNumber_1 = require_limitNumber();
|
|
var multipleOf_1 = require_multipleOf();
|
|
var limitLength_1 = require_limitLength();
|
|
var pattern_1 = require_pattern();
|
|
var limitProperties_1 = require_limitProperties();
|
|
var required_1 = require_required();
|
|
var limitItems_1 = require_limitItems();
|
|
var uniqueItems_1 = require_uniqueItems();
|
|
var const_1 = require_const();
|
|
var enum_1 = require_enum();
|
|
var validation = [
|
|
limitNumber_1.default,
|
|
multipleOf_1.default,
|
|
limitLength_1.default,
|
|
pattern_1.default,
|
|
limitProperties_1.default,
|
|
required_1.default,
|
|
limitItems_1.default,
|
|
uniqueItems_1.default,
|
|
{ keyword: "type", schemaType: ["string", "array"] },
|
|
{ keyword: "nullable", schemaType: "boolean" },
|
|
const_1.default,
|
|
enum_1.default
|
|
];
|
|
exports.default = validation;
|
|
});
|
|
var require_additionalItems = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.validateAdditionalItems = void 0;
|
|
var codegen_1 = require_codegen();
|
|
var util_1 = require_util();
|
|
var error2 = {
|
|
message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`,
|
|
params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}`
|
|
};
|
|
var def = {
|
|
keyword: "additionalItems",
|
|
type: "array",
|
|
schemaType: ["boolean", "object"],
|
|
before: "uniqueItems",
|
|
error: error2,
|
|
code(cxt) {
|
|
const { parentSchema, it } = cxt;
|
|
const { items } = parentSchema;
|
|
if (!Array.isArray(items)) {
|
|
(0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas');
|
|
return;
|
|
}
|
|
validateAdditionalItems(cxt, items);
|
|
}
|
|
};
|
|
function validateAdditionalItems(cxt, items) {
|
|
const { gen, schema, data, keyword, it } = cxt;
|
|
it.items = true;
|
|
const len = gen.const("len", (0, codegen_1._)`${data}.length`);
|
|
if (schema === false) {
|
|
cxt.setParams({ len: items.length });
|
|
cxt.pass((0, codegen_1._)`${len} <= ${items.length}`);
|
|
} else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
|
|
const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`);
|
|
gen.if((0, codegen_1.not)(valid), () => validateItems(valid));
|
|
cxt.ok(valid);
|
|
}
|
|
function validateItems(valid) {
|
|
gen.forRange("i", items.length, len, (i) => {
|
|
cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid);
|
|
if (!it.allErrors)
|
|
gen.if((0, codegen_1.not)(valid), () => gen.break());
|
|
});
|
|
}
|
|
}
|
|
exports.validateAdditionalItems = validateAdditionalItems;
|
|
exports.default = def;
|
|
});
|
|
var require_items = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.validateTuple = void 0;
|
|
var codegen_1 = require_codegen();
|
|
var util_1 = require_util();
|
|
var code_1 = require_code2();
|
|
var def = {
|
|
keyword: "items",
|
|
type: "array",
|
|
schemaType: ["object", "array", "boolean"],
|
|
before: "uniqueItems",
|
|
code(cxt) {
|
|
const { schema, it } = cxt;
|
|
if (Array.isArray(schema))
|
|
return validateTuple(cxt, "additionalItems", schema);
|
|
it.items = true;
|
|
if ((0, util_1.alwaysValidSchema)(it, schema))
|
|
return;
|
|
cxt.ok((0, code_1.validateArray)(cxt));
|
|
}
|
|
};
|
|
function validateTuple(cxt, extraItems, schArr = cxt.schema) {
|
|
const { gen, parentSchema, data, keyword, it } = cxt;
|
|
checkStrictTuple(parentSchema);
|
|
if (it.opts.unevaluated && schArr.length && it.items !== true) {
|
|
it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items);
|
|
}
|
|
const valid = gen.name("valid");
|
|
const len = gen.const("len", (0, codegen_1._)`${data}.length`);
|
|
schArr.forEach((sch, i) => {
|
|
if ((0, util_1.alwaysValidSchema)(it, sch))
|
|
return;
|
|
gen.if((0, codegen_1._)`${len} > ${i}`, () => cxt.subschema({
|
|
keyword,
|
|
schemaProp: i,
|
|
dataProp: i
|
|
}, valid));
|
|
cxt.ok(valid);
|
|
});
|
|
function checkStrictTuple(sch) {
|
|
const { opts, errSchemaPath } = it;
|
|
const l = schArr.length;
|
|
const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false);
|
|
if (opts.strictTuples && !fullTuple) {
|
|
const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`;
|
|
(0, util_1.checkStrictMode)(it, msg, opts.strictTuples);
|
|
}
|
|
}
|
|
}
|
|
exports.validateTuple = validateTuple;
|
|
exports.default = def;
|
|
});
|
|
var require_prefixItems = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var items_1 = require_items();
|
|
var def = {
|
|
keyword: "prefixItems",
|
|
type: "array",
|
|
schemaType: ["array"],
|
|
before: "uniqueItems",
|
|
code: (cxt) => (0, items_1.validateTuple)(cxt, "items")
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_items2020 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var codegen_1 = require_codegen();
|
|
var util_1 = require_util();
|
|
var code_1 = require_code2();
|
|
var additionalItems_1 = require_additionalItems();
|
|
var error2 = {
|
|
message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`,
|
|
params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}`
|
|
};
|
|
var def = {
|
|
keyword: "items",
|
|
type: "array",
|
|
schemaType: ["object", "boolean"],
|
|
before: "uniqueItems",
|
|
error: error2,
|
|
code(cxt) {
|
|
const { schema, parentSchema, it } = cxt;
|
|
const { prefixItems } = parentSchema;
|
|
it.items = true;
|
|
if ((0, util_1.alwaysValidSchema)(it, schema))
|
|
return;
|
|
if (prefixItems)
|
|
(0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems);
|
|
else
|
|
cxt.ok((0, code_1.validateArray)(cxt));
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_contains = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var codegen_1 = require_codegen();
|
|
var util_1 = require_util();
|
|
var error2 = {
|
|
message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`,
|
|
params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}`
|
|
};
|
|
var def = {
|
|
keyword: "contains",
|
|
type: "array",
|
|
schemaType: ["object", "boolean"],
|
|
before: "uniqueItems",
|
|
trackErrors: true,
|
|
error: error2,
|
|
code(cxt) {
|
|
const { gen, schema, parentSchema, data, it } = cxt;
|
|
let min;
|
|
let max;
|
|
const { minContains, maxContains } = parentSchema;
|
|
if (it.opts.next) {
|
|
min = minContains === void 0 ? 1 : minContains;
|
|
max = maxContains;
|
|
} else {
|
|
min = 1;
|
|
}
|
|
const len = gen.const("len", (0, codegen_1._)`${data}.length`);
|
|
cxt.setParams({ min, max });
|
|
if (max === void 0 && min === 0) {
|
|
(0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`);
|
|
return;
|
|
}
|
|
if (max !== void 0 && min > max) {
|
|
(0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`);
|
|
cxt.fail();
|
|
return;
|
|
}
|
|
if ((0, util_1.alwaysValidSchema)(it, schema)) {
|
|
let cond = (0, codegen_1._)`${len} >= ${min}`;
|
|
if (max !== void 0)
|
|
cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`;
|
|
cxt.pass(cond);
|
|
return;
|
|
}
|
|
it.items = true;
|
|
const valid = gen.name("valid");
|
|
if (max === void 0 && min === 1) {
|
|
validateItems(valid, () => gen.if(valid, () => gen.break()));
|
|
} else if (min === 0) {
|
|
gen.let(valid, true);
|
|
if (max !== void 0)
|
|
gen.if((0, codegen_1._)`${data}.length > 0`, validateItemsWithCount);
|
|
} else {
|
|
gen.let(valid, false);
|
|
validateItemsWithCount();
|
|
}
|
|
cxt.result(valid, () => cxt.reset());
|
|
function validateItemsWithCount() {
|
|
const schValid = gen.name("_valid");
|
|
const count = gen.let("count", 0);
|
|
validateItems(schValid, () => gen.if(schValid, () => checkLimits(count)));
|
|
}
|
|
function validateItems(_valid, block) {
|
|
gen.forRange("i", 0, len, (i) => {
|
|
cxt.subschema({
|
|
keyword: "contains",
|
|
dataProp: i,
|
|
dataPropType: util_1.Type.Num,
|
|
compositeRule: true
|
|
}, _valid);
|
|
block();
|
|
});
|
|
}
|
|
function checkLimits(count) {
|
|
gen.code((0, codegen_1._)`${count}++`);
|
|
if (max === void 0) {
|
|
gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break());
|
|
} else {
|
|
gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break());
|
|
if (min === 1)
|
|
gen.assign(valid, true);
|
|
else
|
|
gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true));
|
|
}
|
|
}
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_dependencies = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0;
|
|
var codegen_1 = require_codegen();
|
|
var util_1 = require_util();
|
|
var code_1 = require_code2();
|
|
exports.error = {
|
|
message: ({ params: { property, depsCount, deps } }) => {
|
|
const property_ies = depsCount === 1 ? "property" : "properties";
|
|
return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`;
|
|
},
|
|
params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property},
|
|
missingProperty: ${missingProperty},
|
|
depsCount: ${depsCount},
|
|
deps: ${deps}}`
|
|
};
|
|
var def = {
|
|
keyword: "dependencies",
|
|
type: "object",
|
|
schemaType: "object",
|
|
error: exports.error,
|
|
code(cxt) {
|
|
const [propDeps, schDeps] = splitDependencies(cxt);
|
|
validatePropertyDeps(cxt, propDeps);
|
|
validateSchemaDeps(cxt, schDeps);
|
|
}
|
|
};
|
|
function splitDependencies({ schema }) {
|
|
const propertyDeps = {};
|
|
const schemaDeps = {};
|
|
for (const key in schema) {
|
|
if (key === "__proto__")
|
|
continue;
|
|
const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps;
|
|
deps[key] = schema[key];
|
|
}
|
|
return [propertyDeps, schemaDeps];
|
|
}
|
|
function validatePropertyDeps(cxt, propertyDeps = cxt.schema) {
|
|
const { gen, data, it } = cxt;
|
|
if (Object.keys(propertyDeps).length === 0)
|
|
return;
|
|
const missing = gen.let("missing");
|
|
for (const prop in propertyDeps) {
|
|
const deps = propertyDeps[prop];
|
|
if (deps.length === 0)
|
|
continue;
|
|
const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties);
|
|
cxt.setParams({
|
|
property: prop,
|
|
depsCount: deps.length,
|
|
deps: deps.join(", ")
|
|
});
|
|
if (it.allErrors) {
|
|
gen.if(hasProperty, () => {
|
|
for (const depProp of deps) {
|
|
(0, code_1.checkReportMissingProp)(cxt, depProp);
|
|
}
|
|
});
|
|
} else {
|
|
gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`);
|
|
(0, code_1.reportMissingProp)(cxt, missing);
|
|
gen.else();
|
|
}
|
|
}
|
|
}
|
|
exports.validatePropertyDeps = validatePropertyDeps;
|
|
function validateSchemaDeps(cxt, schemaDeps = cxt.schema) {
|
|
const { gen, data, keyword, it } = cxt;
|
|
const valid = gen.name("valid");
|
|
for (const prop in schemaDeps) {
|
|
if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop]))
|
|
continue;
|
|
gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => {
|
|
const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid);
|
|
cxt.mergeValidEvaluated(schCxt, valid);
|
|
}, () => gen.var(valid, true));
|
|
cxt.ok(valid);
|
|
}
|
|
}
|
|
exports.validateSchemaDeps = validateSchemaDeps;
|
|
exports.default = def;
|
|
});
|
|
var require_propertyNames = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var codegen_1 = require_codegen();
|
|
var util_1 = require_util();
|
|
var error2 = {
|
|
message: "property name must be valid",
|
|
params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}`
|
|
};
|
|
var def = {
|
|
keyword: "propertyNames",
|
|
type: "object",
|
|
schemaType: ["object", "boolean"],
|
|
error: error2,
|
|
code(cxt) {
|
|
const { gen, schema, data, it } = cxt;
|
|
if ((0, util_1.alwaysValidSchema)(it, schema))
|
|
return;
|
|
const valid = gen.name("valid");
|
|
gen.forIn("key", data, (key) => {
|
|
cxt.setParams({ propertyName: key });
|
|
cxt.subschema({
|
|
keyword: "propertyNames",
|
|
data: key,
|
|
dataTypes: ["string"],
|
|
propertyName: key,
|
|
compositeRule: true
|
|
}, valid);
|
|
gen.if((0, codegen_1.not)(valid), () => {
|
|
cxt.error(true);
|
|
if (!it.allErrors)
|
|
gen.break();
|
|
});
|
|
});
|
|
cxt.ok(valid);
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_additionalProperties = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var code_1 = require_code2();
|
|
var codegen_1 = require_codegen();
|
|
var names_1 = require_names();
|
|
var util_1 = require_util();
|
|
var error2 = {
|
|
message: "must NOT have additional properties",
|
|
params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}`
|
|
};
|
|
var def = {
|
|
keyword: "additionalProperties",
|
|
type: ["object"],
|
|
schemaType: ["boolean", "object"],
|
|
allowUndefined: true,
|
|
trackErrors: true,
|
|
error: error2,
|
|
code(cxt) {
|
|
const { gen, schema, parentSchema, data, errsCount, it } = cxt;
|
|
if (!errsCount)
|
|
throw new Error("ajv implementation error");
|
|
const { allErrors, opts } = it;
|
|
it.props = true;
|
|
if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema))
|
|
return;
|
|
const props = (0, code_1.allSchemaProperties)(parentSchema.properties);
|
|
const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties);
|
|
checkAdditionalProperties();
|
|
cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`);
|
|
function checkAdditionalProperties() {
|
|
gen.forIn("key", data, (key) => {
|
|
if (!props.length && !patProps.length)
|
|
additionalPropertyCode(key);
|
|
else
|
|
gen.if(isAdditional(key), () => additionalPropertyCode(key));
|
|
});
|
|
}
|
|
function isAdditional(key) {
|
|
let definedProp;
|
|
if (props.length > 8) {
|
|
const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties");
|
|
definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key);
|
|
} else if (props.length) {
|
|
definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._)`${key} === ${p}`));
|
|
} else {
|
|
definedProp = codegen_1.nil;
|
|
}
|
|
if (patProps.length) {
|
|
definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p)}.test(${key})`));
|
|
}
|
|
return (0, codegen_1.not)(definedProp);
|
|
}
|
|
function deleteAdditional(key) {
|
|
gen.code((0, codegen_1._)`delete ${data}[${key}]`);
|
|
}
|
|
function additionalPropertyCode(key) {
|
|
if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) {
|
|
deleteAdditional(key);
|
|
return;
|
|
}
|
|
if (schema === false) {
|
|
cxt.setParams({ additionalProperty: key });
|
|
cxt.error();
|
|
if (!allErrors)
|
|
gen.break();
|
|
return;
|
|
}
|
|
if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
|
|
const valid = gen.name("valid");
|
|
if (opts.removeAdditional === "failing") {
|
|
applyAdditionalSchema(key, valid, false);
|
|
gen.if((0, codegen_1.not)(valid), () => {
|
|
cxt.reset();
|
|
deleteAdditional(key);
|
|
});
|
|
} else {
|
|
applyAdditionalSchema(key, valid);
|
|
if (!allErrors)
|
|
gen.if((0, codegen_1.not)(valid), () => gen.break());
|
|
}
|
|
}
|
|
}
|
|
function applyAdditionalSchema(key, valid, errors3) {
|
|
const subschema = {
|
|
keyword: "additionalProperties",
|
|
dataProp: key,
|
|
dataPropType: util_1.Type.Str
|
|
};
|
|
if (errors3 === false) {
|
|
Object.assign(subschema, {
|
|
compositeRule: true,
|
|
createErrors: false,
|
|
allErrors: false
|
|
});
|
|
}
|
|
cxt.subschema(subschema, valid);
|
|
}
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_properties = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var validate_1 = require_validate();
|
|
var code_1 = require_code2();
|
|
var util_1 = require_util();
|
|
var additionalProperties_1 = require_additionalProperties();
|
|
var def = {
|
|
keyword: "properties",
|
|
type: "object",
|
|
schemaType: "object",
|
|
code(cxt) {
|
|
const { gen, schema, parentSchema, data, it } = cxt;
|
|
if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) {
|
|
additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties"));
|
|
}
|
|
const allProps = (0, code_1.allSchemaProperties)(schema);
|
|
for (const prop of allProps) {
|
|
it.definedProperties.add(prop);
|
|
}
|
|
if (it.opts.unevaluated && allProps.length && it.props !== true) {
|
|
it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props);
|
|
}
|
|
const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p]));
|
|
if (properties.length === 0)
|
|
return;
|
|
const valid = gen.name("valid");
|
|
for (const prop of properties) {
|
|
if (hasDefault(prop)) {
|
|
applyPropertySchema(prop);
|
|
} else {
|
|
gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties));
|
|
applyPropertySchema(prop);
|
|
if (!it.allErrors)
|
|
gen.else().var(valid, true);
|
|
gen.endIf();
|
|
}
|
|
cxt.it.definedProperties.add(prop);
|
|
cxt.ok(valid);
|
|
}
|
|
function hasDefault(prop) {
|
|
return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== void 0;
|
|
}
|
|
function applyPropertySchema(prop) {
|
|
cxt.subschema({
|
|
keyword: "properties",
|
|
schemaProp: prop,
|
|
dataProp: prop
|
|
}, valid);
|
|
}
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_patternProperties = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var code_1 = require_code2();
|
|
var codegen_1 = require_codegen();
|
|
var util_1 = require_util();
|
|
var util_2 = require_util();
|
|
var def = {
|
|
keyword: "patternProperties",
|
|
type: "object",
|
|
schemaType: "object",
|
|
code(cxt) {
|
|
const { gen, schema, data, parentSchema, it } = cxt;
|
|
const { opts } = it;
|
|
const patterns = (0, code_1.allSchemaProperties)(schema);
|
|
const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p]));
|
|
if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) {
|
|
return;
|
|
}
|
|
const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties;
|
|
const valid = gen.name("valid");
|
|
if (it.props !== true && !(it.props instanceof codegen_1.Name)) {
|
|
it.props = (0, util_2.evaluatedPropsToName)(gen, it.props);
|
|
}
|
|
const { props } = it;
|
|
validatePatternProperties();
|
|
function validatePatternProperties() {
|
|
for (const pat of patterns) {
|
|
if (checkProperties)
|
|
checkMatchingProperties(pat);
|
|
if (it.allErrors) {
|
|
validateProperties(pat);
|
|
} else {
|
|
gen.var(valid, true);
|
|
validateProperties(pat);
|
|
gen.if(valid);
|
|
}
|
|
}
|
|
}
|
|
function checkMatchingProperties(pat) {
|
|
for (const prop in checkProperties) {
|
|
if (new RegExp(pat).test(prop)) {
|
|
(0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`);
|
|
}
|
|
}
|
|
}
|
|
function validateProperties(pat) {
|
|
gen.forIn("key", data, (key) => {
|
|
gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => {
|
|
const alwaysValid = alwaysValidPatterns.includes(pat);
|
|
if (!alwaysValid) {
|
|
cxt.subschema({
|
|
keyword: "patternProperties",
|
|
schemaProp: pat,
|
|
dataProp: key,
|
|
dataPropType: util_2.Type.Str
|
|
}, valid);
|
|
}
|
|
if (it.opts.unevaluated && props !== true) {
|
|
gen.assign((0, codegen_1._)`${props}[${key}]`, true);
|
|
} else if (!alwaysValid && !it.allErrors) {
|
|
gen.if((0, codegen_1.not)(valid), () => gen.break());
|
|
}
|
|
});
|
|
});
|
|
}
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_not = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var util_1 = require_util();
|
|
var def = {
|
|
keyword: "not",
|
|
schemaType: ["object", "boolean"],
|
|
trackErrors: true,
|
|
code(cxt) {
|
|
const { gen, schema, it } = cxt;
|
|
if ((0, util_1.alwaysValidSchema)(it, schema)) {
|
|
cxt.fail();
|
|
return;
|
|
}
|
|
const valid = gen.name("valid");
|
|
cxt.subschema({
|
|
keyword: "not",
|
|
compositeRule: true,
|
|
createErrors: false,
|
|
allErrors: false
|
|
}, valid);
|
|
cxt.failResult(valid, () => cxt.reset(), () => cxt.error());
|
|
},
|
|
error: { message: "must NOT be valid" }
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_anyOf = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var code_1 = require_code2();
|
|
var def = {
|
|
keyword: "anyOf",
|
|
schemaType: "array",
|
|
trackErrors: true,
|
|
code: code_1.validateUnion,
|
|
error: { message: "must match a schema in anyOf" }
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_oneOf = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var codegen_1 = require_codegen();
|
|
var util_1 = require_util();
|
|
var error2 = {
|
|
message: "must match exactly one schema in oneOf",
|
|
params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}`
|
|
};
|
|
var def = {
|
|
keyword: "oneOf",
|
|
schemaType: "array",
|
|
trackErrors: true,
|
|
error: error2,
|
|
code(cxt) {
|
|
const { gen, schema, parentSchema, it } = cxt;
|
|
if (!Array.isArray(schema))
|
|
throw new Error("ajv implementation error");
|
|
if (it.opts.discriminator && parentSchema.discriminator)
|
|
return;
|
|
const schArr = schema;
|
|
const valid = gen.let("valid", false);
|
|
const passing = gen.let("passing", null);
|
|
const schValid = gen.name("_valid");
|
|
cxt.setParams({ passing });
|
|
gen.block(validateOneOf);
|
|
cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
|
|
function validateOneOf() {
|
|
schArr.forEach((sch, i) => {
|
|
let schCxt;
|
|
if ((0, util_1.alwaysValidSchema)(it, sch)) {
|
|
gen.var(schValid, true);
|
|
} else {
|
|
schCxt = cxt.subschema({
|
|
keyword: "oneOf",
|
|
schemaProp: i,
|
|
compositeRule: true
|
|
}, schValid);
|
|
}
|
|
if (i > 0) {
|
|
gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i}]`).else();
|
|
}
|
|
gen.if(schValid, () => {
|
|
gen.assign(valid, true);
|
|
gen.assign(passing, i);
|
|
if (schCxt)
|
|
cxt.mergeEvaluated(schCxt, codegen_1.Name);
|
|
});
|
|
});
|
|
}
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_allOf = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var util_1 = require_util();
|
|
var def = {
|
|
keyword: "allOf",
|
|
schemaType: "array",
|
|
code(cxt) {
|
|
const { gen, schema, it } = cxt;
|
|
if (!Array.isArray(schema))
|
|
throw new Error("ajv implementation error");
|
|
const valid = gen.name("valid");
|
|
schema.forEach((sch, i) => {
|
|
if ((0, util_1.alwaysValidSchema)(it, sch))
|
|
return;
|
|
const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i }, valid);
|
|
cxt.ok(valid);
|
|
cxt.mergeEvaluated(schCxt);
|
|
});
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_if = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var codegen_1 = require_codegen();
|
|
var util_1 = require_util();
|
|
var error2 = {
|
|
message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`,
|
|
params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}`
|
|
};
|
|
var def = {
|
|
keyword: "if",
|
|
schemaType: ["object", "boolean"],
|
|
trackErrors: true,
|
|
error: error2,
|
|
code(cxt) {
|
|
const { gen, parentSchema, it } = cxt;
|
|
if (parentSchema.then === void 0 && parentSchema.else === void 0) {
|
|
(0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored');
|
|
}
|
|
const hasThen = hasSchema(it, "then");
|
|
const hasElse = hasSchema(it, "else");
|
|
if (!hasThen && !hasElse)
|
|
return;
|
|
const valid = gen.let("valid", true);
|
|
const schValid = gen.name("_valid");
|
|
validateIf();
|
|
cxt.reset();
|
|
if (hasThen && hasElse) {
|
|
const ifClause = gen.let("ifClause");
|
|
cxt.setParams({ ifClause });
|
|
gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause));
|
|
} else if (hasThen) {
|
|
gen.if(schValid, validateClause("then"));
|
|
} else {
|
|
gen.if((0, codegen_1.not)(schValid), validateClause("else"));
|
|
}
|
|
cxt.pass(valid, () => cxt.error(true));
|
|
function validateIf() {
|
|
const schCxt = cxt.subschema({
|
|
keyword: "if",
|
|
compositeRule: true,
|
|
createErrors: false,
|
|
allErrors: false
|
|
}, schValid);
|
|
cxt.mergeEvaluated(schCxt);
|
|
}
|
|
function validateClause(keyword, ifClause) {
|
|
return () => {
|
|
const schCxt = cxt.subschema({ keyword }, schValid);
|
|
gen.assign(valid, schValid);
|
|
cxt.mergeValidEvaluated(schCxt, valid);
|
|
if (ifClause)
|
|
gen.assign(ifClause, (0, codegen_1._)`${keyword}`);
|
|
else
|
|
cxt.setParams({ ifClause: keyword });
|
|
};
|
|
}
|
|
}
|
|
};
|
|
function hasSchema(it, keyword) {
|
|
const schema = it.schema[keyword];
|
|
return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema);
|
|
}
|
|
exports.default = def;
|
|
});
|
|
var require_thenElse = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var util_1 = require_util();
|
|
var def = {
|
|
keyword: ["then", "else"],
|
|
schemaType: ["object", "boolean"],
|
|
code({ keyword, parentSchema, it }) {
|
|
if (parentSchema.if === void 0)
|
|
(0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`);
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_applicator = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var additionalItems_1 = require_additionalItems();
|
|
var prefixItems_1 = require_prefixItems();
|
|
var items_1 = require_items();
|
|
var items2020_1 = require_items2020();
|
|
var contains_1 = require_contains();
|
|
var dependencies_1 = require_dependencies();
|
|
var propertyNames_1 = require_propertyNames();
|
|
var additionalProperties_1 = require_additionalProperties();
|
|
var properties_1 = require_properties();
|
|
var patternProperties_1 = require_patternProperties();
|
|
var not_1 = require_not();
|
|
var anyOf_1 = require_anyOf();
|
|
var oneOf_1 = require_oneOf();
|
|
var allOf_1 = require_allOf();
|
|
var if_1 = require_if();
|
|
var thenElse_1 = require_thenElse();
|
|
function getApplicator(draft2020 = false) {
|
|
const applicator = [
|
|
not_1.default,
|
|
anyOf_1.default,
|
|
oneOf_1.default,
|
|
allOf_1.default,
|
|
if_1.default,
|
|
thenElse_1.default,
|
|
propertyNames_1.default,
|
|
additionalProperties_1.default,
|
|
dependencies_1.default,
|
|
properties_1.default,
|
|
patternProperties_1.default
|
|
];
|
|
if (draft2020)
|
|
applicator.push(prefixItems_1.default, items2020_1.default);
|
|
else
|
|
applicator.push(additionalItems_1.default, items_1.default);
|
|
applicator.push(contains_1.default);
|
|
return applicator;
|
|
}
|
|
exports.default = getApplicator;
|
|
});
|
|
var require_format = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var codegen_1 = require_codegen();
|
|
var error2 = {
|
|
message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`,
|
|
params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}`
|
|
};
|
|
var def = {
|
|
keyword: "format",
|
|
type: ["number", "string"],
|
|
schemaType: "string",
|
|
$data: true,
|
|
error: error2,
|
|
code(cxt, ruleType) {
|
|
const { gen, data, $data, schema, schemaCode, it } = cxt;
|
|
const { opts, errSchemaPath, schemaEnv, self: self2 } = it;
|
|
if (!opts.validateFormats)
|
|
return;
|
|
if ($data)
|
|
validate$DataFormat();
|
|
else
|
|
validateFormat();
|
|
function validate$DataFormat() {
|
|
const fmts = gen.scopeValue("formats", {
|
|
ref: self2.formats,
|
|
code: opts.code.formats
|
|
});
|
|
const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`);
|
|
const fType = gen.let("fType");
|
|
const format = gen.let("format");
|
|
gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format, fDef));
|
|
cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt()));
|
|
function unknownFmt() {
|
|
if (opts.strictSchema === false)
|
|
return codegen_1.nil;
|
|
return (0, codegen_1._)`${schemaCode} && !${format}`;
|
|
}
|
|
function invalidFmt() {
|
|
const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` : (0, codegen_1._)`${format}(${data})`;
|
|
const validData = (0, codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`;
|
|
return (0, codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`;
|
|
}
|
|
}
|
|
function validateFormat() {
|
|
const formatDef = self2.formats[schema];
|
|
if (!formatDef) {
|
|
unknownFormat();
|
|
return;
|
|
}
|
|
if (formatDef === true)
|
|
return;
|
|
const [fmtType, format, fmtRef] = getFormat(formatDef);
|
|
if (fmtType === ruleType)
|
|
cxt.pass(validCondition());
|
|
function unknownFormat() {
|
|
if (opts.strictSchema === false) {
|
|
self2.logger.warn(unknownMsg());
|
|
return;
|
|
}
|
|
throw new Error(unknownMsg());
|
|
function unknownMsg() {
|
|
return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`;
|
|
}
|
|
}
|
|
function getFormat(fmtDef) {
|
|
const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : void 0;
|
|
const fmt = gen.scopeValue("formats", { key: schema, ref: fmtDef, code });
|
|
if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) {
|
|
return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._)`${fmt}.validate`];
|
|
}
|
|
return ["string", fmtDef, fmt];
|
|
}
|
|
function validCondition() {
|
|
if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) {
|
|
if (!schemaEnv.$async)
|
|
throw new Error("async format in sync schema");
|
|
return (0, codegen_1._)`await ${fmtRef}(${data})`;
|
|
}
|
|
return typeof format == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`;
|
|
}
|
|
}
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_format2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var format_1 = require_format();
|
|
var format = [format_1.default];
|
|
exports.default = format;
|
|
});
|
|
var require_metadata = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.contentVocabulary = exports.metadataVocabulary = void 0;
|
|
exports.metadataVocabulary = [
|
|
"title",
|
|
"description",
|
|
"default",
|
|
"deprecated",
|
|
"readOnly",
|
|
"writeOnly",
|
|
"examples"
|
|
];
|
|
exports.contentVocabulary = [
|
|
"contentMediaType",
|
|
"contentEncoding",
|
|
"contentSchema"
|
|
];
|
|
});
|
|
var require_draft7 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var core_1 = require_core2();
|
|
var validation_1 = require_validation();
|
|
var applicator_1 = require_applicator();
|
|
var format_1 = require_format2();
|
|
var metadata_1 = require_metadata();
|
|
var draft7Vocabularies = [
|
|
core_1.default,
|
|
validation_1.default,
|
|
(0, applicator_1.default)(),
|
|
format_1.default,
|
|
metadata_1.metadataVocabulary,
|
|
metadata_1.contentVocabulary
|
|
];
|
|
exports.default = draft7Vocabularies;
|
|
});
|
|
var require_types = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.DiscrError = void 0;
|
|
var DiscrError;
|
|
(function(DiscrError2) {
|
|
DiscrError2["Tag"] = "tag";
|
|
DiscrError2["Mapping"] = "mapping";
|
|
})(DiscrError || (exports.DiscrError = DiscrError = {}));
|
|
});
|
|
var require_discriminator = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var codegen_1 = require_codegen();
|
|
var types_1 = require_types();
|
|
var compile_1 = require_compile();
|
|
var ref_error_1 = require_ref_error();
|
|
var util_1 = require_util();
|
|
var error2 = {
|
|
message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`,
|
|
params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`
|
|
};
|
|
var def = {
|
|
keyword: "discriminator",
|
|
type: "object",
|
|
schemaType: "object",
|
|
error: error2,
|
|
code(cxt) {
|
|
const { gen, data, schema, parentSchema, it } = cxt;
|
|
const { oneOf } = parentSchema;
|
|
if (!it.opts.discriminator) {
|
|
throw new Error("discriminator: requires discriminator option");
|
|
}
|
|
const tagName = schema.propertyName;
|
|
if (typeof tagName != "string")
|
|
throw new Error("discriminator: requires propertyName");
|
|
if (schema.mapping)
|
|
throw new Error("discriminator: mapping is not supported");
|
|
if (!oneOf)
|
|
throw new Error("discriminator: requires oneOf keyword");
|
|
const valid = gen.let("valid", false);
|
|
const tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`);
|
|
gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName }));
|
|
cxt.ok(valid);
|
|
function validateMapping() {
|
|
const mapping = getMapping();
|
|
gen.if(false);
|
|
for (const tagValue in mapping) {
|
|
gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`);
|
|
gen.assign(valid, applyTagSchema(mapping[tagValue]));
|
|
}
|
|
gen.else();
|
|
cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName });
|
|
gen.endIf();
|
|
}
|
|
function applyTagSchema(schemaProp) {
|
|
const _valid = gen.name("valid");
|
|
const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid);
|
|
cxt.mergeEvaluated(schCxt, codegen_1.Name);
|
|
return _valid;
|
|
}
|
|
function getMapping() {
|
|
var _a;
|
|
const oneOfMapping = {};
|
|
const topRequired = hasRequired(parentSchema);
|
|
let tagRequired = true;
|
|
for (let i = 0; i < oneOf.length; i++) {
|
|
let sch = oneOf[i];
|
|
if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) {
|
|
const ref = sch.$ref;
|
|
sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref);
|
|
if (sch instanceof compile_1.SchemaEnv)
|
|
sch = sch.schema;
|
|
if (sch === void 0)
|
|
throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref);
|
|
}
|
|
const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName];
|
|
if (typeof propSch != "object") {
|
|
throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`);
|
|
}
|
|
tagRequired = tagRequired && (topRequired || hasRequired(sch));
|
|
addMappings(propSch, i);
|
|
}
|
|
if (!tagRequired)
|
|
throw new Error(`discriminator: "${tagName}" must be required`);
|
|
return oneOfMapping;
|
|
function hasRequired({ required: required2 }) {
|
|
return Array.isArray(required2) && required2.includes(tagName);
|
|
}
|
|
function addMappings(sch, i) {
|
|
if (sch.const) {
|
|
addMapping(sch.const, i);
|
|
} else if (sch.enum) {
|
|
for (const tagValue of sch.enum) {
|
|
addMapping(tagValue, i);
|
|
}
|
|
} else {
|
|
throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`);
|
|
}
|
|
}
|
|
function addMapping(tagValue, i) {
|
|
if (typeof tagValue != "string" || tagValue in oneOfMapping) {
|
|
throw new Error(`discriminator: "${tagName}" values must be unique strings`);
|
|
}
|
|
oneOfMapping[tagValue] = i;
|
|
}
|
|
}
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_json_schema_draft_07 = __commonJS((exports, module2) => {
|
|
module2.exports = {
|
|
$schema: "http://json-schema.org/draft-07/schema#",
|
|
$id: "http://json-schema.org/draft-07/schema#",
|
|
title: "Core schema meta-schema",
|
|
definitions: {
|
|
schemaArray: {
|
|
type: "array",
|
|
minItems: 1,
|
|
items: { $ref: "#" }
|
|
},
|
|
nonNegativeInteger: {
|
|
type: "integer",
|
|
minimum: 0
|
|
},
|
|
nonNegativeIntegerDefault0: {
|
|
allOf: [{ $ref: "#/definitions/nonNegativeInteger" }, { default: 0 }]
|
|
},
|
|
simpleTypes: {
|
|
enum: ["array", "boolean", "integer", "null", "number", "object", "string"]
|
|
},
|
|
stringArray: {
|
|
type: "array",
|
|
items: { type: "string" },
|
|
uniqueItems: true,
|
|
default: []
|
|
}
|
|
},
|
|
type: ["object", "boolean"],
|
|
properties: {
|
|
$id: {
|
|
type: "string",
|
|
format: "uri-reference"
|
|
},
|
|
$schema: {
|
|
type: "string",
|
|
format: "uri"
|
|
},
|
|
$ref: {
|
|
type: "string",
|
|
format: "uri-reference"
|
|
},
|
|
$comment: {
|
|
type: "string"
|
|
},
|
|
title: {
|
|
type: "string"
|
|
},
|
|
description: {
|
|
type: "string"
|
|
},
|
|
default: true,
|
|
readOnly: {
|
|
type: "boolean",
|
|
default: false
|
|
},
|
|
examples: {
|
|
type: "array",
|
|
items: true
|
|
},
|
|
multipleOf: {
|
|
type: "number",
|
|
exclusiveMinimum: 0
|
|
},
|
|
maximum: {
|
|
type: "number"
|
|
},
|
|
exclusiveMaximum: {
|
|
type: "number"
|
|
},
|
|
minimum: {
|
|
type: "number"
|
|
},
|
|
exclusiveMinimum: {
|
|
type: "number"
|
|
},
|
|
maxLength: { $ref: "#/definitions/nonNegativeInteger" },
|
|
minLength: { $ref: "#/definitions/nonNegativeIntegerDefault0" },
|
|
pattern: {
|
|
type: "string",
|
|
format: "regex"
|
|
},
|
|
additionalItems: { $ref: "#" },
|
|
items: {
|
|
anyOf: [{ $ref: "#" }, { $ref: "#/definitions/schemaArray" }],
|
|
default: true
|
|
},
|
|
maxItems: { $ref: "#/definitions/nonNegativeInteger" },
|
|
minItems: { $ref: "#/definitions/nonNegativeIntegerDefault0" },
|
|
uniqueItems: {
|
|
type: "boolean",
|
|
default: false
|
|
},
|
|
contains: { $ref: "#" },
|
|
maxProperties: { $ref: "#/definitions/nonNegativeInteger" },
|
|
minProperties: { $ref: "#/definitions/nonNegativeIntegerDefault0" },
|
|
required: { $ref: "#/definitions/stringArray" },
|
|
additionalProperties: { $ref: "#" },
|
|
definitions: {
|
|
type: "object",
|
|
additionalProperties: { $ref: "#" },
|
|
default: {}
|
|
},
|
|
properties: {
|
|
type: "object",
|
|
additionalProperties: { $ref: "#" },
|
|
default: {}
|
|
},
|
|
patternProperties: {
|
|
type: "object",
|
|
additionalProperties: { $ref: "#" },
|
|
propertyNames: { format: "regex" },
|
|
default: {}
|
|
},
|
|
dependencies: {
|
|
type: "object",
|
|
additionalProperties: {
|
|
anyOf: [{ $ref: "#" }, { $ref: "#/definitions/stringArray" }]
|
|
}
|
|
},
|
|
propertyNames: { $ref: "#" },
|
|
const: true,
|
|
enum: {
|
|
type: "array",
|
|
items: true,
|
|
minItems: 1,
|
|
uniqueItems: true
|
|
},
|
|
type: {
|
|
anyOf: [
|
|
{ $ref: "#/definitions/simpleTypes" },
|
|
{
|
|
type: "array",
|
|
items: { $ref: "#/definitions/simpleTypes" },
|
|
minItems: 1,
|
|
uniqueItems: true
|
|
}
|
|
]
|
|
},
|
|
format: { type: "string" },
|
|
contentMediaType: { type: "string" },
|
|
contentEncoding: { type: "string" },
|
|
if: { $ref: "#" },
|
|
then: { $ref: "#" },
|
|
else: { $ref: "#" },
|
|
allOf: { $ref: "#/definitions/schemaArray" },
|
|
anyOf: { $ref: "#/definitions/schemaArray" },
|
|
oneOf: { $ref: "#/definitions/schemaArray" },
|
|
not: { $ref: "#" }
|
|
},
|
|
default: true
|
|
};
|
|
});
|
|
var require_ajv = __commonJS((exports, module2) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0;
|
|
var core_1 = require_core();
|
|
var draft7_1 = require_draft7();
|
|
var discriminator_1 = require_discriminator();
|
|
var draft7MetaSchema = require_json_schema_draft_07();
|
|
var META_SUPPORT_DATA = ["/properties"];
|
|
var META_SCHEMA_ID = "http://json-schema.org/draft-07/schema";
|
|
class Ajv extends core_1.default {
|
|
_addVocabularies() {
|
|
super._addVocabularies();
|
|
draft7_1.default.forEach((v) => this.addVocabulary(v));
|
|
if (this.opts.discriminator)
|
|
this.addKeyword(discriminator_1.default);
|
|
}
|
|
_addDefaultMetaSchema() {
|
|
super._addDefaultMetaSchema();
|
|
if (!this.opts.meta)
|
|
return;
|
|
const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema;
|
|
this.addMetaSchema(metaSchema, META_SCHEMA_ID, false);
|
|
this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID;
|
|
}
|
|
defaultMeta() {
|
|
return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0);
|
|
}
|
|
}
|
|
exports.Ajv = Ajv;
|
|
module2.exports = exports = Ajv;
|
|
module2.exports.Ajv = Ajv;
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.default = Ajv;
|
|
var validate_1 = require_validate();
|
|
Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() {
|
|
return validate_1.KeywordCxt;
|
|
} });
|
|
var codegen_1 = require_codegen();
|
|
Object.defineProperty(exports, "_", { enumerable: true, get: function() {
|
|
return codegen_1._;
|
|
} });
|
|
Object.defineProperty(exports, "str", { enumerable: true, get: function() {
|
|
return codegen_1.str;
|
|
} });
|
|
Object.defineProperty(exports, "stringify", { enumerable: true, get: function() {
|
|
return codegen_1.stringify;
|
|
} });
|
|
Object.defineProperty(exports, "nil", { enumerable: true, get: function() {
|
|
return codegen_1.nil;
|
|
} });
|
|
Object.defineProperty(exports, "Name", { enumerable: true, get: function() {
|
|
return codegen_1.Name;
|
|
} });
|
|
Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() {
|
|
return codegen_1.CodeGen;
|
|
} });
|
|
var validation_error_1 = require_validation_error();
|
|
Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function() {
|
|
return validation_error_1.default;
|
|
} });
|
|
var ref_error_1 = require_ref_error();
|
|
Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function() {
|
|
return ref_error_1.default;
|
|
} });
|
|
});
|
|
var require_formats = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.formatNames = exports.fastFormats = exports.fullFormats = void 0;
|
|
function fmtDef(validate, compare) {
|
|
return { validate, compare };
|
|
}
|
|
exports.fullFormats = {
|
|
date: fmtDef(date4, compareDate),
|
|
time: fmtDef(getTime(true), compareTime),
|
|
"date-time": fmtDef(getDateTime(true), compareDateTime),
|
|
"iso-time": fmtDef(getTime(), compareIsoTime),
|
|
"iso-date-time": fmtDef(getDateTime(), compareIsoDateTime),
|
|
duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,
|
|
uri,
|
|
"uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,
|
|
"uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,
|
|
url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,
|
|
email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,
|
|
hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,
|
|
ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,
|
|
ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,
|
|
regex,
|
|
uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,
|
|
"json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/,
|
|
"json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,
|
|
"relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,
|
|
byte,
|
|
int32: { type: "number", validate: validateInt32 },
|
|
int64: { type: "number", validate: validateInt64 },
|
|
float: { type: "number", validate: validateNumber },
|
|
double: { type: "number", validate: validateNumber },
|
|
password: true,
|
|
binary: true
|
|
};
|
|
exports.fastFormats = {
|
|
...exports.fullFormats,
|
|
date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate),
|
|
time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime),
|
|
"date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareDateTime),
|
|
"iso-time": fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime),
|
|
"iso-date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoDateTime),
|
|
uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,
|
|
"uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,
|
|
email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i
|
|
};
|
|
exports.formatNames = Object.keys(exports.fullFormats);
|
|
function isLeapYear(year) {
|
|
return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
|
}
|
|
var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
|
|
var DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
|
function date4(str) {
|
|
const matches = DATE.exec(str);
|
|
if (!matches)
|
|
return false;
|
|
const year = +matches[1];
|
|
const month = +matches[2];
|
|
const day = +matches[3];
|
|
return month >= 1 && month <= 12 && day >= 1 && day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]);
|
|
}
|
|
function compareDate(d1, d2) {
|
|
if (!(d1 && d2))
|
|
return;
|
|
if (d1 > d2)
|
|
return 1;
|
|
if (d1 < d2)
|
|
return -1;
|
|
return 0;
|
|
}
|
|
var TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;
|
|
function getTime(strictTimeZone) {
|
|
return function time3(str) {
|
|
const matches = TIME.exec(str);
|
|
if (!matches)
|
|
return false;
|
|
const hr = +matches[1];
|
|
const min = +matches[2];
|
|
const sec = +matches[3];
|
|
const tz = matches[4];
|
|
const tzSign = matches[5] === "-" ? -1 : 1;
|
|
const tzH = +(matches[6] || 0);
|
|
const tzM = +(matches[7] || 0);
|
|
if (tzH > 23 || tzM > 59 || strictTimeZone && !tz)
|
|
return false;
|
|
if (hr <= 23 && min <= 59 && sec < 60)
|
|
return true;
|
|
const utcMin = min - tzM * tzSign;
|
|
const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0);
|
|
return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61;
|
|
};
|
|
}
|
|
function compareTime(s1, s2) {
|
|
if (!(s1 && s2))
|
|
return;
|
|
const t1 = (/* @__PURE__ */ new Date("2020-01-01T" + s1)).valueOf();
|
|
const t2 = (/* @__PURE__ */ new Date("2020-01-01T" + s2)).valueOf();
|
|
if (!(t1 && t2))
|
|
return;
|
|
return t1 - t2;
|
|
}
|
|
function compareIsoTime(t1, t2) {
|
|
if (!(t1 && t2))
|
|
return;
|
|
const a1 = TIME.exec(t1);
|
|
const a2 = TIME.exec(t2);
|
|
if (!(a1 && a2))
|
|
return;
|
|
t1 = a1[1] + a1[2] + a1[3];
|
|
t2 = a2[1] + a2[2] + a2[3];
|
|
if (t1 > t2)
|
|
return 1;
|
|
if (t1 < t2)
|
|
return -1;
|
|
return 0;
|
|
}
|
|
var DATE_TIME_SEPARATOR = /t|\s/i;
|
|
function getDateTime(strictTimeZone) {
|
|
const time3 = getTime(strictTimeZone);
|
|
return function date_time(str) {
|
|
const dateTime = str.split(DATE_TIME_SEPARATOR);
|
|
return dateTime.length === 2 && date4(dateTime[0]) && time3(dateTime[1]);
|
|
};
|
|
}
|
|
function compareDateTime(dt1, dt2) {
|
|
if (!(dt1 && dt2))
|
|
return;
|
|
const d1 = new Date(dt1).valueOf();
|
|
const d2 = new Date(dt2).valueOf();
|
|
if (!(d1 && d2))
|
|
return;
|
|
return d1 - d2;
|
|
}
|
|
function compareIsoDateTime(dt1, dt2) {
|
|
if (!(dt1 && dt2))
|
|
return;
|
|
const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR);
|
|
const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR);
|
|
const res = compareDate(d1, d2);
|
|
if (res === void 0)
|
|
return;
|
|
return res || compareTime(t1, t2);
|
|
}
|
|
var NOT_URI_FRAGMENT = /\/|:/;
|
|
var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
|
|
function uri(str) {
|
|
return NOT_URI_FRAGMENT.test(str) && URI.test(str);
|
|
}
|
|
var BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;
|
|
function byte(str) {
|
|
BYTE.lastIndex = 0;
|
|
return BYTE.test(str);
|
|
}
|
|
var MIN_INT32 = -(2 ** 31);
|
|
var MAX_INT32 = 2 ** 31 - 1;
|
|
function validateInt32(value) {
|
|
return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32;
|
|
}
|
|
function validateInt64(value) {
|
|
return Number.isInteger(value);
|
|
}
|
|
function validateNumber() {
|
|
return true;
|
|
}
|
|
var Z_ANCHOR = /[^\\]\\Z/;
|
|
function regex(str) {
|
|
if (Z_ANCHOR.test(str))
|
|
return false;
|
|
try {
|
|
new RegExp(str);
|
|
return true;
|
|
} catch (e) {
|
|
return false;
|
|
}
|
|
}
|
|
});
|
|
var require_code3 = __commonJS((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;
|
|
class _CodeOrName {
|
|
}
|
|
exports._CodeOrName = _CodeOrName;
|
|
exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
|
|
class Name 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;
|
|
class _Code 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._ = _;
|
|
var 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)}`;
|
|
return;
|
|
}
|
|
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;
|
|
});
|
|
var require_scope2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0;
|
|
var code_1 = require_code3();
|
|
class ValueError extends Error {
|
|
constructor(name) {
|
|
super(`CodeGen: "code" for ${name} not defined`);
|
|
this.value = name.value;
|
|
}
|
|
}
|
|
var 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")
|
|
};
|
|
class Scope {
|
|
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;
|
|
class ValueScopeName 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`;
|
|
class ValueScope 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;
|
|
});
|
|
var require_codegen2 = __commonJS((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;
|
|
var code_1 = require_code3();
|
|
var scope_1 = require_scope2();
|
|
var code_2 = require_code3();
|
|
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_scope2();
|
|
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("+")
|
|
};
|
|
class Node {
|
|
optimizeNodes() {
|
|
return this;
|
|
}
|
|
optimizeNames(_names, _constants) {
|
|
return this;
|
|
}
|
|
}
|
|
class Def 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 : {};
|
|
}
|
|
}
|
|
class Assign 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() {
|
|
const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names };
|
|
return addExprNames(names, this.rhs);
|
|
}
|
|
}
|
|
class AssignOp extends Assign {
|
|
constructor(lhs, op, rhs, sideEffects) {
|
|
super(lhs, rhs, sideEffects);
|
|
this.op = op;
|
|
}
|
|
render({ _n }) {
|
|
return `${this.lhs} ${this.op}= ${this.rhs};` + _n;
|
|
}
|
|
}
|
|
class Label extends Node {
|
|
constructor(label) {
|
|
super();
|
|
this.label = label;
|
|
this.names = {};
|
|
}
|
|
render({ _n }) {
|
|
return `${this.label}:` + _n;
|
|
}
|
|
}
|
|
class Break extends Node {
|
|
constructor(label) {
|
|
super();
|
|
this.label = label;
|
|
this.names = {};
|
|
}
|
|
render({ _n }) {
|
|
const label = this.label ? ` ${this.label}` : "";
|
|
return `break${label};` + _n;
|
|
}
|
|
}
|
|
class Throw extends Node {
|
|
constructor(error2) {
|
|
super();
|
|
this.error = error2;
|
|
}
|
|
render({ _n }) {
|
|
return `throw ${this.error};` + _n;
|
|
}
|
|
get names() {
|
|
return this.error.names;
|
|
}
|
|
}
|
|
class AnyCode 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 : {};
|
|
}
|
|
}
|
|
class ParentNode 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), {});
|
|
}
|
|
}
|
|
class BlockNode extends ParentNode {
|
|
render(opts) {
|
|
return "{" + opts._n + super.render(opts) + "}" + opts._n;
|
|
}
|
|
}
|
|
class Root extends ParentNode {
|
|
}
|
|
class Else extends BlockNode {
|
|
}
|
|
Else.kind = "else";
|
|
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;
|
|
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";
|
|
class For extends BlockNode {
|
|
}
|
|
For.kind = "for";
|
|
class ForLoop 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);
|
|
}
|
|
}
|
|
class ForRange 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() {
|
|
const names = addExprNames(super.names, this.from);
|
|
return addExprNames(names, this.to);
|
|
}
|
|
}
|
|
class ForIter 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);
|
|
}
|
|
}
|
|
class Func extends BlockNode {
|
|
constructor(name, args, async) {
|
|
super();
|
|
this.name = name;
|
|
this.args = args;
|
|
this.async = async;
|
|
}
|
|
render(opts) {
|
|
const _async = this.async ? "async " : "";
|
|
return `${_async}function ${this.name}(${this.args})` + super.render(opts);
|
|
}
|
|
}
|
|
Func.kind = "func";
|
|
class Return extends ParentNode {
|
|
render(opts) {
|
|
return "return " + super.render(opts);
|
|
}
|
|
}
|
|
Return.kind = "return";
|
|
class Try 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;
|
|
}
|
|
}
|
|
class Catch extends BlockNode {
|
|
constructor(error2) {
|
|
super();
|
|
this.error = error2;
|
|
}
|
|
render(opts) {
|
|
return `catch(${this.error})` + super.render(opts);
|
|
}
|
|
}
|
|
Catch.kind = "catch";
|
|
class Finally extends BlockNode {
|
|
render(opts) {
|
|
return "finally" + super.render(opts);
|
|
}
|
|
}
|
|
Finally.kind = "finally";
|
|
class CodeGen {
|
|
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);
|
|
}
|
|
name(prefix) {
|
|
return this._scope.name(prefix);
|
|
}
|
|
scopeName(prefix) {
|
|
return this._extScope.name(prefix);
|
|
}
|
|
scopeValue(prefixOrName, value) {
|
|
const name = this._extScope.value(prefixOrName, value);
|
|
const vs = this._values[name.prefix] || (this._values[name.prefix] = /* @__PURE__ */ new Set());
|
|
vs.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 error2 = this.name("e");
|
|
this._currNode = node.catch = new Catch(error2);
|
|
catchCode(error2);
|
|
}
|
|
if (finallyCode) {
|
|
this._currNode = node.finally = new Finally();
|
|
this.code(finallyCode);
|
|
}
|
|
return this._endBlockNode(Catch, Finally);
|
|
}
|
|
throw(error2) {
|
|
return this._leafNode(new Throw(error2));
|
|
}
|
|
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;
|
|
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})`;
|
|
}
|
|
});
|
|
var require_util2 = __commonJS((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;
|
|
var codegen_1 = require_codegen2();
|
|
var code_1 = require_code3();
|
|
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: self2 } = it;
|
|
if (!opts.strictSchema)
|
|
return;
|
|
if (typeof schema === "boolean")
|
|
return;
|
|
const rules = self2.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: mergeValues3, 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) : mergeValues3(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;
|
|
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) {
|
|
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;
|
|
});
|
|
var require_names2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var codegen_1 = require_codegen2();
|
|
var names = {
|
|
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")
|
|
};
|
|
exports.default = names;
|
|
});
|
|
var require_errors2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0;
|
|
var codegen_1 = require_codegen2();
|
|
var util_1 = require_util2();
|
|
var names_1 = require_names2();
|
|
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, error2 = exports.keywordError, errorPaths, overrideAllErrors) {
|
|
const { it } = cxt;
|
|
const { gen, compositeRule, allErrors } = it;
|
|
const errObj = errorObjectCode(cxt, error2, 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, error2 = exports.keywordError, errorPaths) {
|
|
const { it } = cxt;
|
|
const { gen, compositeRule, allErrors } = it;
|
|
const errObj = errorObjectCode(cxt, error2, errorPaths);
|
|
addError(gen, errObj);
|
|
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 }) {
|
|
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);
|
|
}
|
|
}
|
|
var 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, error2, errorPaths) {
|
|
const { createErrors } = cxt.it;
|
|
if (createErrors === false)
|
|
return (0, codegen_1._)`{}`;
|
|
return errorObject(cxt, error2, errorPaths);
|
|
}
|
|
function errorObject(cxt, error2, errorPaths = {}) {
|
|
const { gen, it } = cxt;
|
|
const keyValues = [
|
|
errorInstancePath(it, errorPaths),
|
|
errorSchemaPath(cxt, errorPaths)
|
|
];
|
|
extraErrorProps(cxt, error2, 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]);
|
|
}
|
|
});
|
|
var require_boolSchema2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0;
|
|
var errors_1 = require_errors2();
|
|
var codegen_1 = require_codegen2();
|
|
var names_1 = require_names2();
|
|
var 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);
|
|
}
|
|
});
|
|
var require_rules2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.getRules = exports.isJSONType = void 0;
|
|
var _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"];
|
|
var jsonTypes = new Set(_jsonTypes);
|
|
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;
|
|
});
|
|
var require_applicability2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0;
|
|
function schemaHasRulesForType({ schema, self: self2 }, type) {
|
|
const group = self2.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;
|
|
});
|
|
var require_dataType2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0;
|
|
var rules_1 = require_rules2();
|
|
var applicability_1 = require_applicability2();
|
|
var errors_1 = require_errors2();
|
|
var codegen_1 = require_codegen2();
|
|
var util_1 = require_util2();
|
|
var DataType;
|
|
(function(DataType2) {
|
|
DataType2[DataType2["Correct"] = 0] = "Correct";
|
|
DataType2[DataType2["Wrong"] = 1] = "Wrong";
|
|
})(DataType || (exports.DataType = DataType = {}));
|
|
function getSchemaTypes(schema) {
|
|
const types = getJSONTypes(schema.type);
|
|
const hasNull = types.includes("null");
|
|
if (hasNull) {
|
|
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;
|
|
var 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" || ${dataType} === "number"
|
|
|| ${dataType} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`);
|
|
}
|
|
}
|
|
}
|
|
function assignParentData({ gen, parentData, parentDataProperty }, expr) {
|
|
gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr));
|
|
}
|
|
function checkDataType(dataType, data, strictNums, correct = DataType.Correct) {
|
|
const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ;
|
|
let cond;
|
|
switch (dataType) {
|
|
case "null":
|
|
return (0, codegen_1._)`${data} ${EQ} null`;
|
|
case "array":
|
|
cond = (0, codegen_1._)`Array.isArray(${data})`;
|
|
break;
|
|
case "object":
|
|
cond = (0, codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`;
|
|
break;
|
|
case "integer":
|
|
cond = numCond((0, codegen_1._)`!(${data} % 1) && !isNaN(${data})`);
|
|
break;
|
|
case "number":
|
|
cond = numCond();
|
|
break;
|
|
default:
|
|
return (0, codegen_1._)`typeof ${data} ${EQ} ${dataType}`;
|
|
}
|
|
return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond);
|
|
function numCond(_cond = codegen_1.nil) {
|
|
return (0, codegen_1.and)((0, codegen_1._)`typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data})` : codegen_1.nil);
|
|
}
|
|
}
|
|
exports.checkDataType = checkDataType;
|
|
function checkDataTypes(dataTypes, data, strictNums, correct) {
|
|
if (dataTypes.length === 1) {
|
|
return checkDataType(dataTypes[0], data, strictNums, correct);
|
|
}
|
|
let cond;
|
|
const types = (0, util_1.toHash)(dataTypes);
|
|
if (types.array && types.object) {
|
|
const notObj = (0, codegen_1._)`typeof ${data} != "object"`;
|
|
cond = types.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`;
|
|
delete types.null;
|
|
delete types.array;
|
|
delete types.object;
|
|
} else {
|
|
cond = codegen_1.nil;
|
|
}
|
|
if (types.number)
|
|
delete types.integer;
|
|
for (const t in types)
|
|
cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct));
|
|
return cond;
|
|
}
|
|
exports.checkDataTypes = checkDataTypes;
|
|
var typeError = {
|
|
message: ({ schema }) => `must be ${schema}`,
|
|
params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (0, codegen_1._)`{type: ${schemaValue}}`
|
|
};
|
|
function reportTypeError(it) {
|
|
const cxt = getTypeErrorContext(it);
|
|
(0, errors_1.reportError)(cxt, typeError);
|
|
}
|
|
exports.reportTypeError = reportTypeError;
|
|
function getTypeErrorContext(it) {
|
|
const { gen, data, schema } = it;
|
|
const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type");
|
|
return {
|
|
gen,
|
|
keyword: "type",
|
|
data,
|
|
schema: schema.type,
|
|
schemaCode,
|
|
schemaValue: schemaCode,
|
|
parentSchema: schema,
|
|
params: {},
|
|
it
|
|
};
|
|
}
|
|
});
|
|
var require_defaults2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.assignDefaults = void 0;
|
|
var codegen_1 = require_codegen2();
|
|
var util_1 = require_util2();
|
|
function assignDefaults(it, ty) {
|
|
const { properties, items } = it.schema;
|
|
if (ty === "object" && properties) {
|
|
for (const key in properties) {
|
|
assignDefault(it, key, properties[key].default);
|
|
}
|
|
} else if (ty === "array" && Array.isArray(items)) {
|
|
items.forEach((sch, i) => assignDefault(it, i, sch.default));
|
|
}
|
|
}
|
|
exports.assignDefaults = assignDefaults;
|
|
function assignDefault(it, prop, defaultValue) {
|
|
const { gen, compositeRule, data, opts } = it;
|
|
if (defaultValue === void 0)
|
|
return;
|
|
const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`;
|
|
if (compositeRule) {
|
|
(0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`);
|
|
return;
|
|
}
|
|
let condition = (0, codegen_1._)`${childData} === undefined`;
|
|
if (opts.useDefaults === "empty") {
|
|
condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`;
|
|
}
|
|
gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`);
|
|
}
|
|
});
|
|
var require_code4 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0;
|
|
var codegen_1 = require_codegen2();
|
|
var util_1 = require_util2();
|
|
var names_1 = require_names2();
|
|
var util_2 = require_util2();
|
|
function checkReportMissingProp(cxt, prop) {
|
|
const { gen, data, it } = cxt;
|
|
gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => {
|
|
cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true);
|
|
cxt.error();
|
|
});
|
|
}
|
|
exports.checkReportMissingProp = checkReportMissingProp;
|
|
function checkMissingProp({ gen, data, it: { opts } }, properties, missing) {
|
|
return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`)));
|
|
}
|
|
exports.checkMissingProp = checkMissingProp;
|
|
function reportMissingProp(cxt, missing) {
|
|
cxt.setParams({ missingProperty: missing }, true);
|
|
cxt.error();
|
|
}
|
|
exports.reportMissingProp = reportMissingProp;
|
|
function hasPropFunc(gen) {
|
|
return gen.scopeValue("func", {
|
|
ref: Object.prototype.hasOwnProperty,
|
|
code: (0, codegen_1._)`Object.prototype.hasOwnProperty`
|
|
});
|
|
}
|
|
exports.hasPropFunc = hasPropFunc;
|
|
function isOwnProperty(gen, data, property) {
|
|
return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`;
|
|
}
|
|
exports.isOwnProperty = isOwnProperty;
|
|
function propertyInData(gen, data, property, ownProperties) {
|
|
const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} !== undefined`;
|
|
return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data, property)}` : cond;
|
|
}
|
|
exports.propertyInData = propertyInData;
|
|
function noPropertyInData(gen, data, property, ownProperties) {
|
|
const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} === undefined`;
|
|
return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond;
|
|
}
|
|
exports.noPropertyInData = noPropertyInData;
|
|
function allSchemaProperties(schemaMap) {
|
|
return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : [];
|
|
}
|
|
exports.allSchemaProperties = allSchemaProperties;
|
|
function schemaProperties(it, schemaMap) {
|
|
return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p]));
|
|
}
|
|
exports.schemaProperties = schemaProperties;
|
|
function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) {
|
|
const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data;
|
|
const valCxt = [
|
|
[names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)],
|
|
[names_1.default.parentData, it.parentData],
|
|
[names_1.default.parentDataProperty, it.parentDataProperty],
|
|
[names_1.default.rootData, names_1.default.rootData]
|
|
];
|
|
if (it.opts.dynamicRef)
|
|
valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]);
|
|
const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`;
|
|
return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`;
|
|
}
|
|
exports.callValidateCode = callValidateCode;
|
|
var newRegExp = (0, codegen_1._)`new RegExp`;
|
|
function usePattern({ gen, it: { opts } }, pattern) {
|
|
const u = opts.unicodeRegExp ? "u" : "";
|
|
const { regExp } = opts.code;
|
|
const rx = regExp(pattern, u);
|
|
return gen.scopeValue("pattern", {
|
|
key: rx.toString(),
|
|
ref: rx,
|
|
code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})`
|
|
});
|
|
}
|
|
exports.usePattern = usePattern;
|
|
function validateArray(cxt) {
|
|
const { gen, data, keyword, it } = cxt;
|
|
const valid = gen.name("valid");
|
|
if (it.allErrors) {
|
|
const validArr = gen.let("valid", true);
|
|
validateItems(() => gen.assign(validArr, false));
|
|
return validArr;
|
|
}
|
|
gen.var(valid, true);
|
|
validateItems(() => gen.break());
|
|
return valid;
|
|
function validateItems(notValid) {
|
|
const len = gen.const("len", (0, codegen_1._)`${data}.length`);
|
|
gen.forRange("i", 0, len, (i) => {
|
|
cxt.subschema({
|
|
keyword,
|
|
dataProp: i,
|
|
dataPropType: util_1.Type.Num
|
|
}, valid);
|
|
gen.if((0, codegen_1.not)(valid), notValid);
|
|
});
|
|
}
|
|
}
|
|
exports.validateArray = validateArray;
|
|
function validateUnion(cxt) {
|
|
const { gen, schema, keyword, it } = cxt;
|
|
if (!Array.isArray(schema))
|
|
throw new Error("ajv implementation error");
|
|
const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch));
|
|
if (alwaysValid && !it.opts.unevaluated)
|
|
return;
|
|
const valid = gen.let("valid", false);
|
|
const schValid = gen.name("_valid");
|
|
gen.block(() => schema.forEach((_sch, i) => {
|
|
const schCxt = cxt.subschema({
|
|
keyword,
|
|
schemaProp: i,
|
|
compositeRule: true
|
|
}, schValid);
|
|
gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`);
|
|
const merged = cxt.mergeValidEvaluated(schCxt, schValid);
|
|
if (!merged)
|
|
gen.if((0, codegen_1.not)(valid));
|
|
}));
|
|
cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
|
|
}
|
|
exports.validateUnion = validateUnion;
|
|
});
|
|
var require_keyword2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0;
|
|
var codegen_1 = require_codegen2();
|
|
var names_1 = require_names2();
|
|
var code_1 = require_code4();
|
|
var errors_1 = require_errors2();
|
|
function macroKeywordCode(cxt, def) {
|
|
const { gen, keyword, schema, parentSchema, it } = cxt;
|
|
const macroSchema = def.macro.call(it.self, schema, parentSchema, it);
|
|
const schemaRef = useKeyword(gen, keyword, macroSchema);
|
|
if (it.opts.validateSchema !== false)
|
|
it.self.validateSchema(macroSchema, true);
|
|
const valid = gen.name("valid");
|
|
cxt.subschema({
|
|
schema: macroSchema,
|
|
schemaPath: codegen_1.nil,
|
|
errSchemaPath: `${it.errSchemaPath}/${keyword}`,
|
|
topSchemaRef: schemaRef,
|
|
compositeRule: true
|
|
}, valid);
|
|
cxt.pass(valid, () => cxt.error(true));
|
|
}
|
|
exports.macroKeywordCode = macroKeywordCode;
|
|
function funcKeywordCode(cxt, def) {
|
|
var _a;
|
|
const { gen, keyword, schema, parentSchema, $data, it } = cxt;
|
|
checkAsyncKeyword(it, def);
|
|
const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate;
|
|
const validateRef = useKeyword(gen, keyword, validate);
|
|
const valid = gen.let("valid");
|
|
cxt.block$data(valid, validateKeyword);
|
|
cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid);
|
|
function validateKeyword() {
|
|
if (def.errors === false) {
|
|
assignValid();
|
|
if (def.modifying)
|
|
modifyData(cxt);
|
|
reportErrs(() => cxt.error());
|
|
} else {
|
|
const ruleErrs = def.async ? validateAsync() : validateSync();
|
|
if (def.modifying)
|
|
modifyData(cxt);
|
|
reportErrs(() => addErrs(cxt, ruleErrs));
|
|
}
|
|
}
|
|
function validateAsync() {
|
|
const ruleErrs = gen.let("ruleErrs", null);
|
|
gen.try(() => assignValid((0, codegen_1._)`await `), (e) => gen.assign(valid, false).if((0, codegen_1._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e)));
|
|
return ruleErrs;
|
|
}
|
|
function validateSync() {
|
|
const validateErrs = (0, codegen_1._)`${validateRef}.errors`;
|
|
gen.assign(validateErrs, null);
|
|
assignValid(codegen_1.nil);
|
|
return validateErrs;
|
|
}
|
|
function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) {
|
|
const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self;
|
|
const passSchema = !("compile" in def && !$data || def.schema === false);
|
|
gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying);
|
|
}
|
|
function reportErrs(errors3) {
|
|
var _a2;
|
|
gen.if((0, codegen_1.not)((_a2 = def.valid) !== null && _a2 !== void 0 ? _a2 : valid), errors3);
|
|
}
|
|
}
|
|
exports.funcKeywordCode = funcKeywordCode;
|
|
function modifyData(cxt) {
|
|
const { gen, data, it } = cxt;
|
|
gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`));
|
|
}
|
|
function addErrs(cxt, errs) {
|
|
const { gen } = cxt;
|
|
gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => {
|
|
gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`);
|
|
(0, errors_1.extendErrors)(cxt);
|
|
}, () => cxt.error());
|
|
}
|
|
function checkAsyncKeyword({ schemaEnv }, def) {
|
|
if (def.async && !schemaEnv.$async)
|
|
throw new Error("async keyword in sync schema");
|
|
}
|
|
function useKeyword(gen, keyword, result) {
|
|
if (result === void 0)
|
|
throw new Error(`keyword "${keyword}" failed to compile`);
|
|
return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) });
|
|
}
|
|
function validSchemaType(schema, schemaType, allowUndefined = false) {
|
|
return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined");
|
|
}
|
|
exports.validSchemaType = validSchemaType;
|
|
function validateKeywordUsage({ schema, opts, self: self2, errSchemaPath }, def, keyword) {
|
|
if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) {
|
|
throw new Error("ajv implementation error");
|
|
}
|
|
const deps = def.dependencies;
|
|
if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) {
|
|
throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`);
|
|
}
|
|
if (def.validateSchema) {
|
|
const valid = def.validateSchema(schema[keyword]);
|
|
if (!valid) {
|
|
const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self2.errorsText(def.validateSchema.errors);
|
|
if (opts.validateSchema === "log")
|
|
self2.logger.error(msg);
|
|
else
|
|
throw new Error(msg);
|
|
}
|
|
}
|
|
}
|
|
exports.validateKeywordUsage = validateKeywordUsage;
|
|
});
|
|
var require_subschema2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0;
|
|
var codegen_1 = require_codegen2();
|
|
var util_1 = require_util2();
|
|
function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) {
|
|
if (keyword !== void 0 && schema !== void 0) {
|
|
throw new Error('both "keyword" and "schema" passed, only one allowed');
|
|
}
|
|
if (keyword !== void 0) {
|
|
const sch = it.schema[keyword];
|
|
return schemaProp === void 0 ? {
|
|
schema: sch,
|
|
schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`,
|
|
errSchemaPath: `${it.errSchemaPath}/${keyword}`
|
|
} : {
|
|
schema: sch[schemaProp],
|
|
schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`,
|
|
errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}`
|
|
};
|
|
}
|
|
if (schema !== void 0) {
|
|
if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) {
|
|
throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');
|
|
}
|
|
return {
|
|
schema,
|
|
schemaPath,
|
|
topSchemaRef,
|
|
errSchemaPath
|
|
};
|
|
}
|
|
throw new Error('either "keyword" or "schema" must be passed');
|
|
}
|
|
exports.getSubschema = getSubschema;
|
|
function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) {
|
|
if (data !== void 0 && dataProp !== void 0) {
|
|
throw new Error('both "data" and "dataProp" passed, only one allowed');
|
|
}
|
|
const { gen } = it;
|
|
if (dataProp !== void 0) {
|
|
const { errorPath, dataPathArr, opts } = it;
|
|
const nextData = gen.let("data", (0, codegen_1._)`${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true);
|
|
dataContextProps(nextData);
|
|
subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`;
|
|
subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`;
|
|
subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty];
|
|
}
|
|
if (data !== void 0) {
|
|
const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true);
|
|
dataContextProps(nextData);
|
|
if (propertyName !== void 0)
|
|
subschema.propertyName = propertyName;
|
|
}
|
|
if (dataTypes)
|
|
subschema.dataTypes = dataTypes;
|
|
function dataContextProps(_nextData) {
|
|
subschema.data = _nextData;
|
|
subschema.dataLevel = it.dataLevel + 1;
|
|
subschema.dataTypes = [];
|
|
it.definedProperties = /* @__PURE__ */ new Set();
|
|
subschema.parentData = it.data;
|
|
subschema.dataNames = [...it.dataNames, _nextData];
|
|
}
|
|
}
|
|
exports.extendSubschemaData = extendSubschemaData;
|
|
function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) {
|
|
if (compositeRule !== void 0)
|
|
subschema.compositeRule = compositeRule;
|
|
if (createErrors !== void 0)
|
|
subschema.createErrors = createErrors;
|
|
if (allErrors !== void 0)
|
|
subschema.allErrors = allErrors;
|
|
subschema.jtdDiscriminator = jtdDiscriminator;
|
|
subschema.jtdMetadata = jtdMetadata;
|
|
}
|
|
exports.extendSubschemaMode = extendSubschemaMode;
|
|
});
|
|
var require_json_schema_traverse2 = __commonJS((exports, module2) => {
|
|
var traverse = module2.exports = function(schema, opts, cb) {
|
|
if (typeof opts == "function") {
|
|
cb = opts;
|
|
opts = {};
|
|
}
|
|
cb = opts.cb || cb;
|
|
var pre = typeof cb == "function" ? cb : cb.pre || function() {
|
|
};
|
|
var post = cb.post || function() {
|
|
};
|
|
_traverse(opts, pre, post, schema, "", schema);
|
|
};
|
|
traverse.keywords = {
|
|
additionalItems: true,
|
|
items: true,
|
|
contains: true,
|
|
additionalProperties: true,
|
|
propertyNames: true,
|
|
not: true,
|
|
if: true,
|
|
then: true,
|
|
else: true
|
|
};
|
|
traverse.arrayKeywords = {
|
|
items: true,
|
|
allOf: true,
|
|
anyOf: true,
|
|
oneOf: true
|
|
};
|
|
traverse.propsKeywords = {
|
|
$defs: true,
|
|
definitions: true,
|
|
properties: true,
|
|
patternProperties: true,
|
|
dependencies: true
|
|
};
|
|
traverse.skipKeywords = {
|
|
default: true,
|
|
enum: true,
|
|
const: true,
|
|
required: true,
|
|
maximum: true,
|
|
minimum: true,
|
|
exclusiveMaximum: true,
|
|
exclusiveMinimum: true,
|
|
multipleOf: true,
|
|
maxLength: true,
|
|
minLength: true,
|
|
pattern: true,
|
|
format: true,
|
|
maxItems: true,
|
|
minItems: true,
|
|
uniqueItems: true,
|
|
maxProperties: true,
|
|
minProperties: true
|
|
};
|
|
function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
|
|
if (schema && typeof schema == "object" && !Array.isArray(schema)) {
|
|
pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
|
|
for (var key in schema) {
|
|
var sch = schema[key];
|
|
if (Array.isArray(sch)) {
|
|
if (key in traverse.arrayKeywords) {
|
|
for (var i = 0; i < sch.length; i++)
|
|
_traverse(opts, pre, post, sch[i], jsonPtr + "/" + key + "/" + i, rootSchema, jsonPtr, key, schema, i);
|
|
}
|
|
} else if (key in traverse.propsKeywords) {
|
|
if (sch && typeof sch == "object") {
|
|
for (var prop in sch)
|
|
_traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);
|
|
}
|
|
} else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) {
|
|
_traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema);
|
|
}
|
|
}
|
|
post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
|
|
}
|
|
}
|
|
function escapeJsonPtr(str) {
|
|
return str.replace(/~/g, "~0").replace(/\//g, "~1");
|
|
}
|
|
});
|
|
var require_resolve2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0;
|
|
var util_1 = require_util2();
|
|
var equal = require_fast_deep_equal();
|
|
var traverse = require_json_schema_traverse2();
|
|
var SIMPLE_INLINED = /* @__PURE__ */ new Set([
|
|
"type",
|
|
"format",
|
|
"pattern",
|
|
"maxLength",
|
|
"minLength",
|
|
"maxProperties",
|
|
"minProperties",
|
|
"maxItems",
|
|
"minItems",
|
|
"maximum",
|
|
"minimum",
|
|
"uniqueItems",
|
|
"multipleOf",
|
|
"required",
|
|
"enum",
|
|
"const"
|
|
]);
|
|
function inlineRef(schema, limit = true) {
|
|
if (typeof schema == "boolean")
|
|
return true;
|
|
if (limit === true)
|
|
return !hasRef(schema);
|
|
if (!limit)
|
|
return false;
|
|
return countKeys(schema) <= limit;
|
|
}
|
|
exports.inlineRef = inlineRef;
|
|
var REF_KEYWORDS = /* @__PURE__ */ new Set([
|
|
"$ref",
|
|
"$recursiveRef",
|
|
"$recursiveAnchor",
|
|
"$dynamicRef",
|
|
"$dynamicAnchor"
|
|
]);
|
|
function hasRef(schema) {
|
|
for (const key in schema) {
|
|
if (REF_KEYWORDS.has(key))
|
|
return true;
|
|
const sch = schema[key];
|
|
if (Array.isArray(sch) && sch.some(hasRef))
|
|
return true;
|
|
if (typeof sch == "object" && hasRef(sch))
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
function countKeys(schema) {
|
|
let count = 0;
|
|
for (const key in schema) {
|
|
if (key === "$ref")
|
|
return Infinity;
|
|
count++;
|
|
if (SIMPLE_INLINED.has(key))
|
|
continue;
|
|
if (typeof schema[key] == "object") {
|
|
(0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch));
|
|
}
|
|
if (count === Infinity)
|
|
return Infinity;
|
|
}
|
|
return count;
|
|
}
|
|
function getFullPath(resolver, id = "", normalize2) {
|
|
if (normalize2 !== false)
|
|
id = normalizeId(id);
|
|
const p = resolver.parse(id);
|
|
return _getFullPath(resolver, p);
|
|
}
|
|
exports.getFullPath = getFullPath;
|
|
function _getFullPath(resolver, p) {
|
|
const serialized = resolver.serialize(p);
|
|
return serialized.split("#")[0] + "#";
|
|
}
|
|
exports._getFullPath = _getFullPath;
|
|
var TRAILING_SLASH_HASH = /#\/?$/;
|
|
function normalizeId(id) {
|
|
return id ? id.replace(TRAILING_SLASH_HASH, "") : "";
|
|
}
|
|
exports.normalizeId = normalizeId;
|
|
function resolveUrl(resolver, baseId, id) {
|
|
id = normalizeId(id);
|
|
return resolver.resolve(baseId, id);
|
|
}
|
|
exports.resolveUrl = resolveUrl;
|
|
var ANCHOR = /^[a-z_][-a-z0-9._]*$/i;
|
|
function getSchemaRefs(schema, baseId) {
|
|
if (typeof schema == "boolean")
|
|
return {};
|
|
const { schemaId, uriResolver } = this.opts;
|
|
const schId = normalizeId(schema[schemaId] || baseId);
|
|
const baseIds = { "": schId };
|
|
const pathPrefix = getFullPath(uriResolver, schId, false);
|
|
const localRefs = {};
|
|
const schemaRefs = /* @__PURE__ */ new Set();
|
|
traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => {
|
|
if (parentJsonPtr === void 0)
|
|
return;
|
|
const fullPath = pathPrefix + jsonPtr;
|
|
let innerBaseId = baseIds[parentJsonPtr];
|
|
if (typeof sch[schemaId] == "string")
|
|
innerBaseId = addRef.call(this, sch[schemaId]);
|
|
addAnchor.call(this, sch.$anchor);
|
|
addAnchor.call(this, sch.$dynamicAnchor);
|
|
baseIds[jsonPtr] = innerBaseId;
|
|
function addRef(ref) {
|
|
const _resolve = this.opts.uriResolver.resolve;
|
|
ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref);
|
|
if (schemaRefs.has(ref))
|
|
throw ambiguos(ref);
|
|
schemaRefs.add(ref);
|
|
let schOrRef = this.refs[ref];
|
|
if (typeof schOrRef == "string")
|
|
schOrRef = this.refs[schOrRef];
|
|
if (typeof schOrRef == "object") {
|
|
checkAmbiguosRef(sch, schOrRef.schema, ref);
|
|
} else if (ref !== normalizeId(fullPath)) {
|
|
if (ref[0] === "#") {
|
|
checkAmbiguosRef(sch, localRefs[ref], ref);
|
|
localRefs[ref] = sch;
|
|
} else {
|
|
this.refs[ref] = fullPath;
|
|
}
|
|
}
|
|
return ref;
|
|
}
|
|
function addAnchor(anchor) {
|
|
if (typeof anchor == "string") {
|
|
if (!ANCHOR.test(anchor))
|
|
throw new Error(`invalid anchor "${anchor}"`);
|
|
addRef.call(this, `#${anchor}`);
|
|
}
|
|
}
|
|
});
|
|
return localRefs;
|
|
function checkAmbiguosRef(sch1, sch2, ref) {
|
|
if (sch2 !== void 0 && !equal(sch1, sch2))
|
|
throw ambiguos(ref);
|
|
}
|
|
function ambiguos(ref) {
|
|
return new Error(`reference "${ref}" resolves to more than one schema`);
|
|
}
|
|
}
|
|
exports.getSchemaRefs = getSchemaRefs;
|
|
});
|
|
var require_validate2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0;
|
|
var boolSchema_1 = require_boolSchema2();
|
|
var dataType_1 = require_dataType2();
|
|
var applicability_1 = require_applicability2();
|
|
var dataType_2 = require_dataType2();
|
|
var defaults_1 = require_defaults2();
|
|
var keyword_1 = require_keyword2();
|
|
var subschema_1 = require_subschema2();
|
|
var codegen_1 = require_codegen2();
|
|
var names_1 = require_names2();
|
|
var resolve_1 = require_resolve2();
|
|
var util_1 = require_util2();
|
|
var errors_1 = require_errors2();
|
|
function validateFunctionCode(it) {
|
|
if (isSchemaObj(it)) {
|
|
checkKeywords(it);
|
|
if (schemaCxtHasRules(it)) {
|
|
topSchemaObjCode(it);
|
|
return;
|
|
}
|
|
}
|
|
validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it));
|
|
}
|
|
exports.validateFunctionCode = validateFunctionCode;
|
|
function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) {
|
|
if (opts.code.es5) {
|
|
gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => {
|
|
gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`);
|
|
destructureValCxtES5(gen, opts);
|
|
gen.code(body);
|
|
});
|
|
} else {
|
|
gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body));
|
|
}
|
|
}
|
|
function destructureValCxt(opts) {
|
|
return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`;
|
|
}
|
|
function destructureValCxtES5(gen, opts) {
|
|
gen.if(names_1.default.valCxt, () => {
|
|
gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`);
|
|
gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`);
|
|
gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`);
|
|
gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`);
|
|
if (opts.dynamicRef)
|
|
gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`);
|
|
}, () => {
|
|
gen.var(names_1.default.instancePath, (0, codegen_1._)`""`);
|
|
gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`);
|
|
gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`);
|
|
gen.var(names_1.default.rootData, names_1.default.data);
|
|
if (opts.dynamicRef)
|
|
gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`);
|
|
});
|
|
}
|
|
function topSchemaObjCode(it) {
|
|
const { schema, opts, gen } = it;
|
|
validateFunction(it, () => {
|
|
if (opts.$comment && schema.$comment)
|
|
commentKeyword(it);
|
|
checkNoDefault(it);
|
|
gen.let(names_1.default.vErrors, null);
|
|
gen.let(names_1.default.errors, 0);
|
|
if (opts.unevaluated)
|
|
resetEvaluated(it);
|
|
typeAndKeywords(it);
|
|
returnResults(it);
|
|
});
|
|
return;
|
|
}
|
|
function resetEvaluated(it) {
|
|
const { gen, validateName } = it;
|
|
it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`);
|
|
gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`));
|
|
gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`));
|
|
}
|
|
function funcSourceUrl(schema, opts) {
|
|
const schId = typeof schema == "object" && schema[opts.schemaId];
|
|
return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil;
|
|
}
|
|
function subschemaCode(it, valid) {
|
|
if (isSchemaObj(it)) {
|
|
checkKeywords(it);
|
|
if (schemaCxtHasRules(it)) {
|
|
subSchemaObjCode(it, valid);
|
|
return;
|
|
}
|
|
}
|
|
(0, boolSchema_1.boolOrEmptySchema)(it, valid);
|
|
}
|
|
function schemaCxtHasRules({ schema, self: self2 }) {
|
|
if (typeof schema == "boolean")
|
|
return !schema;
|
|
for (const key in schema)
|
|
if (self2.RULES.all[key])
|
|
return true;
|
|
return false;
|
|
}
|
|
function isSchemaObj(it) {
|
|
return typeof it.schema != "boolean";
|
|
}
|
|
function subSchemaObjCode(it, valid) {
|
|
const { schema, gen, opts } = it;
|
|
if (opts.$comment && schema.$comment)
|
|
commentKeyword(it);
|
|
updateContext(it);
|
|
checkAsyncSchema(it);
|
|
const errsCount = gen.const("_errs", names_1.default.errors);
|
|
typeAndKeywords(it, errsCount);
|
|
gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`);
|
|
}
|
|
function checkKeywords(it) {
|
|
(0, util_1.checkUnknownRules)(it);
|
|
checkRefsAndKeywords(it);
|
|
}
|
|
function typeAndKeywords(it, errsCount) {
|
|
if (it.opts.jtd)
|
|
return schemaKeywords(it, [], false, errsCount);
|
|
const types = (0, dataType_1.getSchemaTypes)(it.schema);
|
|
const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types);
|
|
schemaKeywords(it, types, !checkedTypes, errsCount);
|
|
}
|
|
function checkRefsAndKeywords(it) {
|
|
const { schema, errSchemaPath, opts, self: self2 } = it;
|
|
if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self2.RULES)) {
|
|
self2.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`);
|
|
}
|
|
}
|
|
function checkNoDefault(it) {
|
|
const { schema, opts } = it;
|
|
if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) {
|
|
(0, util_1.checkStrictMode)(it, "default is ignored in the schema root");
|
|
}
|
|
}
|
|
function updateContext(it) {
|
|
const schId = it.schema[it.opts.schemaId];
|
|
if (schId)
|
|
it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId);
|
|
}
|
|
function checkAsyncSchema(it) {
|
|
if (it.schema.$async && !it.schemaEnv.$async)
|
|
throw new Error("async schema in sync schema");
|
|
}
|
|
function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) {
|
|
const msg = schema.$comment;
|
|
if (opts.$comment === true) {
|
|
gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`);
|
|
} else if (typeof opts.$comment == "function") {
|
|
const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`;
|
|
const rootName = gen.scopeValue("root", { ref: schemaEnv.root });
|
|
gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`);
|
|
}
|
|
}
|
|
function returnResults(it) {
|
|
const { gen, schemaEnv, validateName, ValidationError, opts } = it;
|
|
if (schemaEnv.$async) {
|
|
gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`));
|
|
} else {
|
|
gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors);
|
|
if (opts.unevaluated)
|
|
assignEvaluated(it);
|
|
gen.return((0, codegen_1._)`${names_1.default.errors} === 0`);
|
|
}
|
|
}
|
|
function assignEvaluated({ gen, evaluated, props, items }) {
|
|
if (props instanceof codegen_1.Name)
|
|
gen.assign((0, codegen_1._)`${evaluated}.props`, props);
|
|
if (items instanceof codegen_1.Name)
|
|
gen.assign((0, codegen_1._)`${evaluated}.items`, items);
|
|
}
|
|
function schemaKeywords(it, types, typeErrors, errsCount) {
|
|
const { gen, schema, data, allErrors, opts, self: self2 } = it;
|
|
const { RULES } = self2;
|
|
if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) {
|
|
gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition));
|
|
return;
|
|
}
|
|
if (!opts.jtd)
|
|
checkStrictTypes(it, types);
|
|
gen.block(() => {
|
|
for (const group of RULES.rules)
|
|
groupKeywords(group);
|
|
groupKeywords(RULES.post);
|
|
});
|
|
function groupKeywords(group) {
|
|
if (!(0, applicability_1.shouldUseGroup)(schema, group))
|
|
return;
|
|
if (group.type) {
|
|
gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers));
|
|
iterateKeywords(it, group);
|
|
if (types.length === 1 && types[0] === group.type && typeErrors) {
|
|
gen.else();
|
|
(0, dataType_2.reportTypeError)(it);
|
|
}
|
|
gen.endIf();
|
|
} else {
|
|
iterateKeywords(it, group);
|
|
}
|
|
if (!allErrors)
|
|
gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`);
|
|
}
|
|
}
|
|
function iterateKeywords(it, group) {
|
|
const { gen, schema, opts: { useDefaults } } = it;
|
|
if (useDefaults)
|
|
(0, defaults_1.assignDefaults)(it, group.type);
|
|
gen.block(() => {
|
|
for (const rule of group.rules) {
|
|
if ((0, applicability_1.shouldUseRule)(schema, rule)) {
|
|
keywordCode(it, rule.keyword, rule.definition, group.type);
|
|
}
|
|
}
|
|
});
|
|
}
|
|
function checkStrictTypes(it, types) {
|
|
if (it.schemaEnv.meta || !it.opts.strictTypes)
|
|
return;
|
|
checkContextTypes(it, types);
|
|
if (!it.opts.allowUnionTypes)
|
|
checkMultipleTypes(it, types);
|
|
checkKeywordTypes(it, it.dataTypes);
|
|
}
|
|
function checkContextTypes(it, types) {
|
|
if (!types.length)
|
|
return;
|
|
if (!it.dataTypes.length) {
|
|
it.dataTypes = types;
|
|
return;
|
|
}
|
|
types.forEach((t) => {
|
|
if (!includesType(it.dataTypes, t)) {
|
|
strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`);
|
|
}
|
|
});
|
|
narrowSchemaTypes(it, types);
|
|
}
|
|
function checkMultipleTypes(it, ts) {
|
|
if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) {
|
|
strictTypesError(it, "use allowUnionTypes to allow union type keyword");
|
|
}
|
|
}
|
|
function checkKeywordTypes(it, ts) {
|
|
const rules = it.self.RULES.all;
|
|
for (const keyword in rules) {
|
|
const rule = rules[keyword];
|
|
if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) {
|
|
const { type } = rule.definition;
|
|
if (type.length && !type.some((t) => hasApplicableType(ts, t))) {
|
|
strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
function hasApplicableType(schTs, kwdT) {
|
|
return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer");
|
|
}
|
|
function includesType(ts, t) {
|
|
return ts.includes(t) || t === "integer" && ts.includes("number");
|
|
}
|
|
function narrowSchemaTypes(it, withTypes) {
|
|
const ts = [];
|
|
for (const t of it.dataTypes) {
|
|
if (includesType(withTypes, t))
|
|
ts.push(t);
|
|
else if (withTypes.includes("integer") && t === "number")
|
|
ts.push("integer");
|
|
}
|
|
it.dataTypes = ts;
|
|
}
|
|
function strictTypesError(it, msg) {
|
|
const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;
|
|
msg += ` at "${schemaPath}" (strictTypes)`;
|
|
(0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes);
|
|
}
|
|
class KeywordCxt {
|
|
constructor(it, def, keyword) {
|
|
(0, keyword_1.validateKeywordUsage)(it, def, keyword);
|
|
this.gen = it.gen;
|
|
this.allErrors = it.allErrors;
|
|
this.keyword = keyword;
|
|
this.data = it.data;
|
|
this.schema = it.schema[keyword];
|
|
this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data;
|
|
this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data);
|
|
this.schemaType = def.schemaType;
|
|
this.parentSchema = it.schema;
|
|
this.params = {};
|
|
this.it = it;
|
|
this.def = def;
|
|
if (this.$data) {
|
|
this.schemaCode = it.gen.const("vSchema", getData(this.$data, it));
|
|
} else {
|
|
this.schemaCode = this.schemaValue;
|
|
if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) {
|
|
throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`);
|
|
}
|
|
}
|
|
if ("code" in def ? def.trackErrors : def.errors !== false) {
|
|
this.errsCount = it.gen.const("_errs", names_1.default.errors);
|
|
}
|
|
}
|
|
result(condition, successAction, failAction) {
|
|
this.failResult((0, codegen_1.not)(condition), successAction, failAction);
|
|
}
|
|
failResult(condition, successAction, failAction) {
|
|
this.gen.if(condition);
|
|
if (failAction)
|
|
failAction();
|
|
else
|
|
this.error();
|
|
if (successAction) {
|
|
this.gen.else();
|
|
successAction();
|
|
if (this.allErrors)
|
|
this.gen.endIf();
|
|
} else {
|
|
if (this.allErrors)
|
|
this.gen.endIf();
|
|
else
|
|
this.gen.else();
|
|
}
|
|
}
|
|
pass(condition, failAction) {
|
|
this.failResult((0, codegen_1.not)(condition), void 0, failAction);
|
|
}
|
|
fail(condition) {
|
|
if (condition === void 0) {
|
|
this.error();
|
|
if (!this.allErrors)
|
|
this.gen.if(false);
|
|
return;
|
|
}
|
|
this.gen.if(condition);
|
|
this.error();
|
|
if (this.allErrors)
|
|
this.gen.endIf();
|
|
else
|
|
this.gen.else();
|
|
}
|
|
fail$data(condition) {
|
|
if (!this.$data)
|
|
return this.fail(condition);
|
|
const { schemaCode } = this;
|
|
this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`);
|
|
}
|
|
error(append, errorParams, errorPaths) {
|
|
if (errorParams) {
|
|
this.setParams(errorParams);
|
|
this._error(append, errorPaths);
|
|
this.setParams({});
|
|
return;
|
|
}
|
|
this._error(append, errorPaths);
|
|
}
|
|
_error(append, errorPaths) {
|
|
(append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths);
|
|
}
|
|
$dataError() {
|
|
(0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError);
|
|
}
|
|
reset() {
|
|
if (this.errsCount === void 0)
|
|
throw new Error('add "trackErrors" to keyword definition');
|
|
(0, errors_1.resetErrorsCount)(this.gen, this.errsCount);
|
|
}
|
|
ok(cond) {
|
|
if (!this.allErrors)
|
|
this.gen.if(cond);
|
|
}
|
|
setParams(obj, assign) {
|
|
if (assign)
|
|
Object.assign(this.params, obj);
|
|
else
|
|
this.params = obj;
|
|
}
|
|
block$data(valid, codeBlock, $dataValid = codegen_1.nil) {
|
|
this.gen.block(() => {
|
|
this.check$data(valid, $dataValid);
|
|
codeBlock();
|
|
});
|
|
}
|
|
check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) {
|
|
if (!this.$data)
|
|
return;
|
|
const { gen, schemaCode, schemaType, def } = this;
|
|
gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid));
|
|
if (valid !== codegen_1.nil)
|
|
gen.assign(valid, true);
|
|
if (schemaType.length || def.validateSchema) {
|
|
gen.elseIf(this.invalid$data());
|
|
this.$dataError();
|
|
if (valid !== codegen_1.nil)
|
|
gen.assign(valid, false);
|
|
}
|
|
gen.else();
|
|
}
|
|
invalid$data() {
|
|
const { gen, schemaCode, schemaType, def, it } = this;
|
|
return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema());
|
|
function wrong$DataType() {
|
|
if (schemaType.length) {
|
|
if (!(schemaCode instanceof codegen_1.Name))
|
|
throw new Error("ajv implementation error");
|
|
const st = Array.isArray(schemaType) ? schemaType : [schemaType];
|
|
return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`;
|
|
}
|
|
return codegen_1.nil;
|
|
}
|
|
function invalid$DataSchema() {
|
|
if (def.validateSchema) {
|
|
const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema });
|
|
return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`;
|
|
}
|
|
return codegen_1.nil;
|
|
}
|
|
}
|
|
subschema(appl, valid) {
|
|
const subschema = (0, subschema_1.getSubschema)(this.it, appl);
|
|
(0, subschema_1.extendSubschemaData)(subschema, this.it, appl);
|
|
(0, subschema_1.extendSubschemaMode)(subschema, appl);
|
|
const nextContext = { ...this.it, ...subschema, items: void 0, props: void 0 };
|
|
subschemaCode(nextContext, valid);
|
|
return nextContext;
|
|
}
|
|
mergeEvaluated(schemaCxt, toName) {
|
|
const { it, gen } = this;
|
|
if (!it.opts.unevaluated)
|
|
return;
|
|
if (it.props !== true && schemaCxt.props !== void 0) {
|
|
it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName);
|
|
}
|
|
if (it.items !== true && schemaCxt.items !== void 0) {
|
|
it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName);
|
|
}
|
|
}
|
|
mergeValidEvaluated(schemaCxt, valid) {
|
|
const { it, gen } = this;
|
|
if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {
|
|
gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name));
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
exports.KeywordCxt = KeywordCxt;
|
|
function keywordCode(it, keyword, def, ruleType) {
|
|
const cxt = new KeywordCxt(it, def, keyword);
|
|
if ("code" in def) {
|
|
def.code(cxt, ruleType);
|
|
} else if (cxt.$data && def.validate) {
|
|
(0, keyword_1.funcKeywordCode)(cxt, def);
|
|
} else if ("macro" in def) {
|
|
(0, keyword_1.macroKeywordCode)(cxt, def);
|
|
} else if (def.compile || def.validate) {
|
|
(0, keyword_1.funcKeywordCode)(cxt, def);
|
|
}
|
|
}
|
|
var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
|
|
var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
|
|
function getData($data, { dataLevel, dataNames, dataPathArr }) {
|
|
let jsonPointer;
|
|
let data;
|
|
if ($data === "")
|
|
return names_1.default.rootData;
|
|
if ($data[0] === "/") {
|
|
if (!JSON_POINTER.test($data))
|
|
throw new Error(`Invalid JSON-pointer: ${$data}`);
|
|
jsonPointer = $data;
|
|
data = names_1.default.rootData;
|
|
} else {
|
|
const matches = RELATIVE_JSON_POINTER.exec($data);
|
|
if (!matches)
|
|
throw new Error(`Invalid JSON-pointer: ${$data}`);
|
|
const up = +matches[1];
|
|
jsonPointer = matches[2];
|
|
if (jsonPointer === "#") {
|
|
if (up >= dataLevel)
|
|
throw new Error(errorMsg("property/index", up));
|
|
return dataPathArr[dataLevel - up];
|
|
}
|
|
if (up > dataLevel)
|
|
throw new Error(errorMsg("data", up));
|
|
data = dataNames[dataLevel - up];
|
|
if (!jsonPointer)
|
|
return data;
|
|
}
|
|
let expr = data;
|
|
const segments = jsonPointer.split("/");
|
|
for (const segment of segments) {
|
|
if (segment) {
|
|
data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`;
|
|
expr = (0, codegen_1._)`${expr} && ${data}`;
|
|
}
|
|
}
|
|
return expr;
|
|
function errorMsg(pointerType, up) {
|
|
return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`;
|
|
}
|
|
}
|
|
exports.getData = getData;
|
|
});
|
|
var require_validation_error2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
class ValidationError extends Error {
|
|
constructor(errors3) {
|
|
super("validation failed");
|
|
this.errors = errors3;
|
|
this.ajv = this.validation = true;
|
|
}
|
|
}
|
|
exports.default = ValidationError;
|
|
});
|
|
var require_ref_error2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var resolve_1 = require_resolve2();
|
|
class MissingRefError extends Error {
|
|
constructor(resolver, baseId, ref, msg) {
|
|
super(msg || `can't resolve reference ${ref} from id ${baseId}`);
|
|
this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref);
|
|
this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef));
|
|
}
|
|
}
|
|
exports.default = MissingRefError;
|
|
});
|
|
var require_compile2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0;
|
|
var codegen_1 = require_codegen2();
|
|
var validation_error_1 = require_validation_error2();
|
|
var names_1 = require_names2();
|
|
var resolve_1 = require_resolve2();
|
|
var util_1 = require_util2();
|
|
var validate_1 = require_validate2();
|
|
class SchemaEnv {
|
|
constructor(env) {
|
|
var _a;
|
|
this.refs = {};
|
|
this.dynamicAnchors = {};
|
|
let schema;
|
|
if (typeof env.schema == "object")
|
|
schema = env.schema;
|
|
this.schema = env.schema;
|
|
this.schemaId = env.schemaId;
|
|
this.root = env.root || this;
|
|
this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]);
|
|
this.schemaPath = env.schemaPath;
|
|
this.localRefs = env.localRefs;
|
|
this.meta = env.meta;
|
|
this.$async = schema === null || schema === void 0 ? void 0 : schema.$async;
|
|
this.refs = {};
|
|
}
|
|
}
|
|
exports.SchemaEnv = SchemaEnv;
|
|
function compileSchema(sch) {
|
|
const _sch = getCompilingSchema.call(this, sch);
|
|
if (_sch)
|
|
return _sch;
|
|
const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId);
|
|
const { es5, lines } = this.opts.code;
|
|
const { ownProperties } = this.opts;
|
|
const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties });
|
|
let _ValidationError;
|
|
if (sch.$async) {
|
|
_ValidationError = gen.scopeValue("Error", {
|
|
ref: validation_error_1.default,
|
|
code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default`
|
|
});
|
|
}
|
|
const validateName = gen.scopeName("validate");
|
|
sch.validateName = validateName;
|
|
const schemaCxt = {
|
|
gen,
|
|
allErrors: this.opts.allErrors,
|
|
data: names_1.default.data,
|
|
parentData: names_1.default.parentData,
|
|
parentDataProperty: names_1.default.parentDataProperty,
|
|
dataNames: [names_1.default.data],
|
|
dataPathArr: [codegen_1.nil],
|
|
dataLevel: 0,
|
|
dataTypes: [],
|
|
definedProperties: /* @__PURE__ */ new Set(),
|
|
topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) } : { ref: sch.schema }),
|
|
validateName,
|
|
ValidationError: _ValidationError,
|
|
schema: sch.schema,
|
|
schemaEnv: sch,
|
|
rootId,
|
|
baseId: sch.baseId || rootId,
|
|
schemaPath: codegen_1.nil,
|
|
errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"),
|
|
errorPath: (0, codegen_1._)`""`,
|
|
opts: this.opts,
|
|
self: this
|
|
};
|
|
let sourceCode;
|
|
try {
|
|
this._compilations.add(sch);
|
|
(0, validate_1.validateFunctionCode)(schemaCxt);
|
|
gen.optimize(this.opts.code.optimize);
|
|
const validateCode = gen.toString();
|
|
sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`;
|
|
if (this.opts.code.process)
|
|
sourceCode = this.opts.code.process(sourceCode, sch);
|
|
const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode);
|
|
const validate = makeValidate(this, this.scope.get());
|
|
this.scope.value(validateName, { ref: validate });
|
|
validate.errors = null;
|
|
validate.schema = sch.schema;
|
|
validate.schemaEnv = sch;
|
|
if (sch.$async)
|
|
validate.$async = true;
|
|
if (this.opts.code.source === true) {
|
|
validate.source = { validateName, validateCode, scopeValues: gen._values };
|
|
}
|
|
if (this.opts.unevaluated) {
|
|
const { props, items } = schemaCxt;
|
|
validate.evaluated = {
|
|
props: props instanceof codegen_1.Name ? void 0 : props,
|
|
items: items instanceof codegen_1.Name ? void 0 : items,
|
|
dynamicProps: props instanceof codegen_1.Name,
|
|
dynamicItems: items instanceof codegen_1.Name
|
|
};
|
|
if (validate.source)
|
|
validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated);
|
|
}
|
|
sch.validate = validate;
|
|
return sch;
|
|
} catch (e) {
|
|
delete sch.validate;
|
|
delete sch.validateName;
|
|
if (sourceCode)
|
|
this.logger.error("Error compiling schema, function code:", sourceCode);
|
|
throw e;
|
|
} finally {
|
|
this._compilations.delete(sch);
|
|
}
|
|
}
|
|
exports.compileSchema = compileSchema;
|
|
function resolveRef(root2, baseId, ref) {
|
|
var _a;
|
|
ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref);
|
|
const schOrFunc = root2.refs[ref];
|
|
if (schOrFunc)
|
|
return schOrFunc;
|
|
let _sch = resolve7.call(this, root2, ref);
|
|
if (_sch === void 0) {
|
|
const schema = (_a = root2.localRefs) === null || _a === void 0 ? void 0 : _a[ref];
|
|
const { schemaId } = this.opts;
|
|
if (schema)
|
|
_sch = new SchemaEnv({ schema, schemaId, root: root2, baseId });
|
|
}
|
|
if (_sch === void 0)
|
|
return;
|
|
return root2.refs[ref] = inlineOrCompile.call(this, _sch);
|
|
}
|
|
exports.resolveRef = resolveRef;
|
|
function inlineOrCompile(sch) {
|
|
if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs))
|
|
return sch.schema;
|
|
return sch.validate ? sch : compileSchema.call(this, sch);
|
|
}
|
|
function getCompilingSchema(schEnv) {
|
|
for (const sch of this._compilations) {
|
|
if (sameSchemaEnv(sch, schEnv))
|
|
return sch;
|
|
}
|
|
}
|
|
exports.getCompilingSchema = getCompilingSchema;
|
|
function sameSchemaEnv(s1, s2) {
|
|
return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
|
|
}
|
|
function resolve7(root2, ref) {
|
|
let sch;
|
|
while (typeof (sch = this.refs[ref]) == "string")
|
|
ref = sch;
|
|
return sch || this.schemas[ref] || resolveSchema.call(this, root2, ref);
|
|
}
|
|
function resolveSchema(root2, ref) {
|
|
const p = this.opts.uriResolver.parse(ref);
|
|
const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p);
|
|
let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root2.baseId, void 0);
|
|
if (Object.keys(root2.schema).length > 0 && refPath === baseId) {
|
|
return getJsonPointer.call(this, p, root2);
|
|
}
|
|
const id = (0, resolve_1.normalizeId)(refPath);
|
|
const schOrRef = this.refs[id] || this.schemas[id];
|
|
if (typeof schOrRef == "string") {
|
|
const sch = resolveSchema.call(this, root2, schOrRef);
|
|
if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object")
|
|
return;
|
|
return getJsonPointer.call(this, p, sch);
|
|
}
|
|
if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object")
|
|
return;
|
|
if (!schOrRef.validate)
|
|
compileSchema.call(this, schOrRef);
|
|
if (id === (0, resolve_1.normalizeId)(ref)) {
|
|
const { schema } = schOrRef;
|
|
const { schemaId } = this.opts;
|
|
const schId = schema[schemaId];
|
|
if (schId)
|
|
baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);
|
|
return new SchemaEnv({ schema, schemaId, root: root2, baseId });
|
|
}
|
|
return getJsonPointer.call(this, p, schOrRef);
|
|
}
|
|
exports.resolveSchema = resolveSchema;
|
|
var PREVENT_SCOPE_CHANGE = /* @__PURE__ */ new Set([
|
|
"properties",
|
|
"patternProperties",
|
|
"enum",
|
|
"dependencies",
|
|
"definitions"
|
|
]);
|
|
function getJsonPointer(parsedRef, { baseId, schema, root: root2 }) {
|
|
var _a;
|
|
if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/")
|
|
return;
|
|
for (const part of parsedRef.fragment.slice(1).split("/")) {
|
|
if (typeof schema === "boolean")
|
|
return;
|
|
const partSchema = schema[(0, util_1.unescapeFragment)(part)];
|
|
if (partSchema === void 0)
|
|
return;
|
|
schema = partSchema;
|
|
const schId = typeof schema === "object" && schema[this.opts.schemaId];
|
|
if (!PREVENT_SCOPE_CHANGE.has(part) && schId) {
|
|
baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);
|
|
}
|
|
}
|
|
let env;
|
|
if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) {
|
|
const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref);
|
|
env = resolveSchema.call(this, root2, $ref);
|
|
}
|
|
const { schemaId } = this.opts;
|
|
env = env || new SchemaEnv({ schema, schemaId, root: root2, baseId });
|
|
if (env.schema !== env.root.schema)
|
|
return env;
|
|
return;
|
|
}
|
|
});
|
|
var require_data2 = __commonJS((exports, module2) => {
|
|
module2.exports = {
|
|
$id: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
|
|
description: "Meta-schema for $data reference (JSON AnySchema extension proposal)",
|
|
type: "object",
|
|
required: ["$data"],
|
|
properties: {
|
|
$data: {
|
|
type: "string",
|
|
anyOf: [{ format: "relative-json-pointer" }, { format: "json-pointer" }]
|
|
}
|
|
},
|
|
additionalProperties: false
|
|
};
|
|
});
|
|
var require_uri2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var uri = require_fast_uri();
|
|
uri.code = 'require("ajv/dist/runtime/uri").default';
|
|
exports.default = uri;
|
|
});
|
|
var require_core3 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0;
|
|
var validate_1 = require_validate2();
|
|
Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() {
|
|
return validate_1.KeywordCxt;
|
|
} });
|
|
var codegen_1 = require_codegen2();
|
|
Object.defineProperty(exports, "_", { enumerable: true, get: function() {
|
|
return codegen_1._;
|
|
} });
|
|
Object.defineProperty(exports, "str", { enumerable: true, get: function() {
|
|
return codegen_1.str;
|
|
} });
|
|
Object.defineProperty(exports, "stringify", { enumerable: true, get: function() {
|
|
return codegen_1.stringify;
|
|
} });
|
|
Object.defineProperty(exports, "nil", { enumerable: true, get: function() {
|
|
return codegen_1.nil;
|
|
} });
|
|
Object.defineProperty(exports, "Name", { enumerable: true, get: function() {
|
|
return codegen_1.Name;
|
|
} });
|
|
Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() {
|
|
return codegen_1.CodeGen;
|
|
} });
|
|
var validation_error_1 = require_validation_error2();
|
|
var ref_error_1 = require_ref_error2();
|
|
var rules_1 = require_rules2();
|
|
var compile_1 = require_compile2();
|
|
var codegen_2 = require_codegen2();
|
|
var resolve_1 = require_resolve2();
|
|
var dataType_1 = require_dataType2();
|
|
var util_1 = require_util2();
|
|
var $dataRefSchema = require_data2();
|
|
var uri_1 = require_uri2();
|
|
var defaultRegExp = (str, flags) => new RegExp(str, flags);
|
|
defaultRegExp.code = "new RegExp";
|
|
var META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"];
|
|
var EXT_SCOPE_NAMES = /* @__PURE__ */ new Set([
|
|
"validate",
|
|
"serialize",
|
|
"parse",
|
|
"wrapper",
|
|
"root",
|
|
"schema",
|
|
"keyword",
|
|
"pattern",
|
|
"formats",
|
|
"validate$data",
|
|
"func",
|
|
"obj",
|
|
"Error"
|
|
]);
|
|
var removedOptions = {
|
|
errorDataPath: "",
|
|
format: "`validateFormats: false` can be used instead.",
|
|
nullable: '"nullable" keyword is supported by default.',
|
|
jsonPointers: "Deprecated jsPropertySyntax can be used instead.",
|
|
extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.",
|
|
missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.",
|
|
processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`",
|
|
sourceCode: "Use option `code: {source: true}`",
|
|
strictDefaults: "It is default now, see option `strict`.",
|
|
strictKeywords: "It is default now, see option `strict`.",
|
|
uniqueItems: '"uniqueItems" keyword is always validated.',
|
|
unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",
|
|
cache: "Map is used as cache, schema object as key.",
|
|
serialize: "Map is used as cache, schema object as key.",
|
|
ajvErrors: "It is default now."
|
|
};
|
|
var deprecatedOptions = {
|
|
ignoreKeywordsWithRef: "",
|
|
jsPropertySyntax: "",
|
|
unicode: '"minLength"/"maxLength" account for unicode characters by default.'
|
|
};
|
|
var MAX_EXPRESSION = 200;
|
|
function requiredOptions(o) {
|
|
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0;
|
|
const s = o.strict;
|
|
const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize;
|
|
const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0;
|
|
const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp;
|
|
const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default;
|
|
return {
|
|
strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true,
|
|
strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true,
|
|
strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log",
|
|
strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log",
|
|
strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false,
|
|
code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp },
|
|
loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION,
|
|
loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION,
|
|
meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true,
|
|
messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true,
|
|
inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true,
|
|
schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id",
|
|
addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true,
|
|
validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true,
|
|
validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true,
|
|
unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true,
|
|
int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true,
|
|
uriResolver
|
|
};
|
|
}
|
|
class Ajv {
|
|
constructor(opts = {}) {
|
|
this.schemas = {};
|
|
this.refs = {};
|
|
this.formats = {};
|
|
this._compilations = /* @__PURE__ */ new Set();
|
|
this._loading = {};
|
|
this._cache = /* @__PURE__ */ new Map();
|
|
opts = this.opts = { ...opts, ...requiredOptions(opts) };
|
|
const { es5, lines } = this.opts.code;
|
|
this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines });
|
|
this.logger = getLogger(opts.logger);
|
|
const formatOpt = opts.validateFormats;
|
|
opts.validateFormats = false;
|
|
this.RULES = (0, rules_1.getRules)();
|
|
checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED");
|
|
checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn");
|
|
this._metaOpts = getMetaSchemaOptions.call(this);
|
|
if (opts.formats)
|
|
addInitialFormats.call(this);
|
|
this._addVocabularies();
|
|
this._addDefaultMetaSchema();
|
|
if (opts.keywords)
|
|
addInitialKeywords.call(this, opts.keywords);
|
|
if (typeof opts.meta == "object")
|
|
this.addMetaSchema(opts.meta);
|
|
addInitialSchemas.call(this);
|
|
opts.validateFormats = formatOpt;
|
|
}
|
|
_addVocabularies() {
|
|
this.addKeyword("$async");
|
|
}
|
|
_addDefaultMetaSchema() {
|
|
const { $data, meta, schemaId } = this.opts;
|
|
let _dataRefSchema = $dataRefSchema;
|
|
if (schemaId === "id") {
|
|
_dataRefSchema = { ...$dataRefSchema };
|
|
_dataRefSchema.id = _dataRefSchema.$id;
|
|
delete _dataRefSchema.$id;
|
|
}
|
|
if (meta && $data)
|
|
this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false);
|
|
}
|
|
defaultMeta() {
|
|
const { meta, schemaId } = this.opts;
|
|
return this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : void 0;
|
|
}
|
|
validate(schemaKeyRef, data) {
|
|
let v;
|
|
if (typeof schemaKeyRef == "string") {
|
|
v = this.getSchema(schemaKeyRef);
|
|
if (!v)
|
|
throw new Error(`no schema with key or ref "${schemaKeyRef}"`);
|
|
} else {
|
|
v = this.compile(schemaKeyRef);
|
|
}
|
|
const valid = v(data);
|
|
if (!("$async" in v))
|
|
this.errors = v.errors;
|
|
return valid;
|
|
}
|
|
compile(schema, _meta) {
|
|
const sch = this._addSchema(schema, _meta);
|
|
return sch.validate || this._compileSchemaEnv(sch);
|
|
}
|
|
compileAsync(schema, meta) {
|
|
if (typeof this.opts.loadSchema != "function") {
|
|
throw new Error("options.loadSchema should be a function");
|
|
}
|
|
const { loadSchema } = this.opts;
|
|
return runCompileAsync.call(this, schema, meta);
|
|
async function runCompileAsync(_schema, _meta) {
|
|
await loadMetaSchema.call(this, _schema.$schema);
|
|
const sch = this._addSchema(_schema, _meta);
|
|
return sch.validate || _compileAsync.call(this, sch);
|
|
}
|
|
async function loadMetaSchema($ref) {
|
|
if ($ref && !this.getSchema($ref)) {
|
|
await runCompileAsync.call(this, { $ref }, true);
|
|
}
|
|
}
|
|
async function _compileAsync(sch) {
|
|
try {
|
|
return this._compileSchemaEnv(sch);
|
|
} catch (e) {
|
|
if (!(e instanceof ref_error_1.default))
|
|
throw e;
|
|
checkLoaded.call(this, e);
|
|
await loadMissingSchema.call(this, e.missingSchema);
|
|
return _compileAsync.call(this, sch);
|
|
}
|
|
}
|
|
function checkLoaded({ missingSchema: ref, missingRef }) {
|
|
if (this.refs[ref]) {
|
|
throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`);
|
|
}
|
|
}
|
|
async function loadMissingSchema(ref) {
|
|
const _schema = await _loadSchema.call(this, ref);
|
|
if (!this.refs[ref])
|
|
await loadMetaSchema.call(this, _schema.$schema);
|
|
if (!this.refs[ref])
|
|
this.addSchema(_schema, ref, meta);
|
|
}
|
|
async function _loadSchema(ref) {
|
|
const p = this._loading[ref];
|
|
if (p)
|
|
return p;
|
|
try {
|
|
return await (this._loading[ref] = loadSchema(ref));
|
|
} finally {
|
|
delete this._loading[ref];
|
|
}
|
|
}
|
|
}
|
|
addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) {
|
|
if (Array.isArray(schema)) {
|
|
for (const sch of schema)
|
|
this.addSchema(sch, void 0, _meta, _validateSchema);
|
|
return this;
|
|
}
|
|
let id;
|
|
if (typeof schema === "object") {
|
|
const { schemaId } = this.opts;
|
|
id = schema[schemaId];
|
|
if (id !== void 0 && typeof id != "string") {
|
|
throw new Error(`schema ${schemaId} must be string`);
|
|
}
|
|
}
|
|
key = (0, resolve_1.normalizeId)(key || id);
|
|
this._checkUnique(key);
|
|
this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true);
|
|
return this;
|
|
}
|
|
addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) {
|
|
this.addSchema(schema, key, true, _validateSchema);
|
|
return this;
|
|
}
|
|
validateSchema(schema, throwOrLogError) {
|
|
if (typeof schema == "boolean")
|
|
return true;
|
|
let $schema;
|
|
$schema = schema.$schema;
|
|
if ($schema !== void 0 && typeof $schema != "string") {
|
|
throw new Error("$schema must be a string");
|
|
}
|
|
$schema = $schema || this.opts.defaultMeta || this.defaultMeta();
|
|
if (!$schema) {
|
|
this.logger.warn("meta-schema not available");
|
|
this.errors = null;
|
|
return true;
|
|
}
|
|
const valid = this.validate($schema, schema);
|
|
if (!valid && throwOrLogError) {
|
|
const message = "schema is invalid: " + this.errorsText();
|
|
if (this.opts.validateSchema === "log")
|
|
this.logger.error(message);
|
|
else
|
|
throw new Error(message);
|
|
}
|
|
return valid;
|
|
}
|
|
getSchema(keyRef) {
|
|
let sch;
|
|
while (typeof (sch = getSchEnv.call(this, keyRef)) == "string")
|
|
keyRef = sch;
|
|
if (sch === void 0) {
|
|
const { schemaId } = this.opts;
|
|
const root2 = new compile_1.SchemaEnv({ schema: {}, schemaId });
|
|
sch = compile_1.resolveSchema.call(this, root2, keyRef);
|
|
if (!sch)
|
|
return;
|
|
this.refs[keyRef] = sch;
|
|
}
|
|
return sch.validate || this._compileSchemaEnv(sch);
|
|
}
|
|
removeSchema(schemaKeyRef) {
|
|
if (schemaKeyRef instanceof RegExp) {
|
|
this._removeAllSchemas(this.schemas, schemaKeyRef);
|
|
this._removeAllSchemas(this.refs, schemaKeyRef);
|
|
return this;
|
|
}
|
|
switch (typeof schemaKeyRef) {
|
|
case "undefined":
|
|
this._removeAllSchemas(this.schemas);
|
|
this._removeAllSchemas(this.refs);
|
|
this._cache.clear();
|
|
return this;
|
|
case "string": {
|
|
const sch = getSchEnv.call(this, schemaKeyRef);
|
|
if (typeof sch == "object")
|
|
this._cache.delete(sch.schema);
|
|
delete this.schemas[schemaKeyRef];
|
|
delete this.refs[schemaKeyRef];
|
|
return this;
|
|
}
|
|
case "object": {
|
|
const cacheKey = schemaKeyRef;
|
|
this._cache.delete(cacheKey);
|
|
let id = schemaKeyRef[this.opts.schemaId];
|
|
if (id) {
|
|
id = (0, resolve_1.normalizeId)(id);
|
|
delete this.schemas[id];
|
|
delete this.refs[id];
|
|
}
|
|
return this;
|
|
}
|
|
default:
|
|
throw new Error("ajv.removeSchema: invalid parameter");
|
|
}
|
|
}
|
|
addVocabulary(definitions) {
|
|
for (const def of definitions)
|
|
this.addKeyword(def);
|
|
return this;
|
|
}
|
|
addKeyword(kwdOrDef, def) {
|
|
let keyword;
|
|
if (typeof kwdOrDef == "string") {
|
|
keyword = kwdOrDef;
|
|
if (typeof def == "object") {
|
|
this.logger.warn("these parameters are deprecated, see docs for addKeyword");
|
|
def.keyword = keyword;
|
|
}
|
|
} else if (typeof kwdOrDef == "object" && def === void 0) {
|
|
def = kwdOrDef;
|
|
keyword = def.keyword;
|
|
if (Array.isArray(keyword) && !keyword.length) {
|
|
throw new Error("addKeywords: keyword must be string or non-empty array");
|
|
}
|
|
} else {
|
|
throw new Error("invalid addKeywords parameters");
|
|
}
|
|
checkKeyword.call(this, keyword, def);
|
|
if (!def) {
|
|
(0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd));
|
|
return this;
|
|
}
|
|
keywordMetaschema.call(this, def);
|
|
const definition = {
|
|
...def,
|
|
type: (0, dataType_1.getJSONTypes)(def.type),
|
|
schemaType: (0, dataType_1.getJSONTypes)(def.schemaType)
|
|
};
|
|
(0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t)));
|
|
return this;
|
|
}
|
|
getKeyword(keyword) {
|
|
const rule = this.RULES.all[keyword];
|
|
return typeof rule == "object" ? rule.definition : !!rule;
|
|
}
|
|
removeKeyword(keyword) {
|
|
const { RULES } = this;
|
|
delete RULES.keywords[keyword];
|
|
delete RULES.all[keyword];
|
|
for (const group of RULES.rules) {
|
|
const i = group.rules.findIndex((rule) => rule.keyword === keyword);
|
|
if (i >= 0)
|
|
group.rules.splice(i, 1);
|
|
}
|
|
return this;
|
|
}
|
|
addFormat(name, format) {
|
|
if (typeof format == "string")
|
|
format = new RegExp(format);
|
|
this.formats[name] = format;
|
|
return this;
|
|
}
|
|
errorsText(errors3 = this.errors, { separator = ", ", dataVar = "data" } = {}) {
|
|
if (!errors3 || errors3.length === 0)
|
|
return "No errors";
|
|
return errors3.map((e) => `${dataVar}${e.instancePath} ${e.message}`).reduce((text, msg) => text + separator + msg);
|
|
}
|
|
$dataMetaSchema(metaSchema, keywordsJsonPointers) {
|
|
const rules = this.RULES.all;
|
|
metaSchema = JSON.parse(JSON.stringify(metaSchema));
|
|
for (const jsonPointer of keywordsJsonPointers) {
|
|
const segments = jsonPointer.split("/").slice(1);
|
|
let keywords = metaSchema;
|
|
for (const seg of segments)
|
|
keywords = keywords[seg];
|
|
for (const key in rules) {
|
|
const rule = rules[key];
|
|
if (typeof rule != "object")
|
|
continue;
|
|
const { $data } = rule.definition;
|
|
const schema = keywords[key];
|
|
if ($data && schema)
|
|
keywords[key] = schemaOrData(schema);
|
|
}
|
|
}
|
|
return metaSchema;
|
|
}
|
|
_removeAllSchemas(schemas4, regex) {
|
|
for (const keyRef in schemas4) {
|
|
const sch = schemas4[keyRef];
|
|
if (!regex || regex.test(keyRef)) {
|
|
if (typeof sch == "string") {
|
|
delete schemas4[keyRef];
|
|
} else if (sch && !sch.meta) {
|
|
this._cache.delete(sch.schema);
|
|
delete schemas4[keyRef];
|
|
}
|
|
}
|
|
}
|
|
}
|
|
_addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) {
|
|
let id;
|
|
const { schemaId } = this.opts;
|
|
if (typeof schema == "object") {
|
|
id = schema[schemaId];
|
|
} else {
|
|
if (this.opts.jtd)
|
|
throw new Error("schema must be object");
|
|
else if (typeof schema != "boolean")
|
|
throw new Error("schema must be object or boolean");
|
|
}
|
|
let sch = this._cache.get(schema);
|
|
if (sch !== void 0)
|
|
return sch;
|
|
baseId = (0, resolve_1.normalizeId)(id || baseId);
|
|
const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId);
|
|
sch = new compile_1.SchemaEnv({ schema, schemaId, meta, baseId, localRefs });
|
|
this._cache.set(sch.schema, sch);
|
|
if (addSchema && !baseId.startsWith("#")) {
|
|
if (baseId)
|
|
this._checkUnique(baseId);
|
|
this.refs[baseId] = sch;
|
|
}
|
|
if (validateSchema)
|
|
this.validateSchema(schema, true);
|
|
return sch;
|
|
}
|
|
_checkUnique(id) {
|
|
if (this.schemas[id] || this.refs[id]) {
|
|
throw new Error(`schema with key or id "${id}" already exists`);
|
|
}
|
|
}
|
|
_compileSchemaEnv(sch) {
|
|
if (sch.meta)
|
|
this._compileMetaSchema(sch);
|
|
else
|
|
compile_1.compileSchema.call(this, sch);
|
|
if (!sch.validate)
|
|
throw new Error("ajv implementation error");
|
|
return sch.validate;
|
|
}
|
|
_compileMetaSchema(sch) {
|
|
const currentOpts = this.opts;
|
|
this.opts = this._metaOpts;
|
|
try {
|
|
compile_1.compileSchema.call(this, sch);
|
|
} finally {
|
|
this.opts = currentOpts;
|
|
}
|
|
}
|
|
}
|
|
Ajv.ValidationError = validation_error_1.default;
|
|
Ajv.MissingRefError = ref_error_1.default;
|
|
exports.default = Ajv;
|
|
function checkOptions(checkOpts, options, msg, log = "error") {
|
|
for (const key in checkOpts) {
|
|
const opt = key;
|
|
if (opt in options)
|
|
this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`);
|
|
}
|
|
}
|
|
function getSchEnv(keyRef) {
|
|
keyRef = (0, resolve_1.normalizeId)(keyRef);
|
|
return this.schemas[keyRef] || this.refs[keyRef];
|
|
}
|
|
function addInitialSchemas() {
|
|
const optsSchemas = this.opts.schemas;
|
|
if (!optsSchemas)
|
|
return;
|
|
if (Array.isArray(optsSchemas))
|
|
this.addSchema(optsSchemas);
|
|
else
|
|
for (const key in optsSchemas)
|
|
this.addSchema(optsSchemas[key], key);
|
|
}
|
|
function addInitialFormats() {
|
|
for (const name in this.opts.formats) {
|
|
const format = this.opts.formats[name];
|
|
if (format)
|
|
this.addFormat(name, format);
|
|
}
|
|
}
|
|
function addInitialKeywords(defs) {
|
|
if (Array.isArray(defs)) {
|
|
this.addVocabulary(defs);
|
|
return;
|
|
}
|
|
this.logger.warn("keywords option as map is deprecated, pass array");
|
|
for (const keyword in defs) {
|
|
const def = defs[keyword];
|
|
if (!def.keyword)
|
|
def.keyword = keyword;
|
|
this.addKeyword(def);
|
|
}
|
|
}
|
|
function getMetaSchemaOptions() {
|
|
const metaOpts = { ...this.opts };
|
|
for (const opt of META_IGNORE_OPTIONS)
|
|
delete metaOpts[opt];
|
|
return metaOpts;
|
|
}
|
|
var noLogs = { log() {
|
|
}, warn() {
|
|
}, error() {
|
|
} };
|
|
function getLogger(logger) {
|
|
if (logger === false)
|
|
return noLogs;
|
|
if (logger === void 0)
|
|
return console;
|
|
if (logger.log && logger.warn && logger.error)
|
|
return logger;
|
|
throw new Error("logger must implement log, warn and error methods");
|
|
}
|
|
var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i;
|
|
function checkKeyword(keyword, def) {
|
|
const { RULES } = this;
|
|
(0, util_1.eachItem)(keyword, (kwd) => {
|
|
if (RULES.keywords[kwd])
|
|
throw new Error(`Keyword ${kwd} is already defined`);
|
|
if (!KEYWORD_NAME.test(kwd))
|
|
throw new Error(`Keyword ${kwd} has invalid name`);
|
|
});
|
|
if (!def)
|
|
return;
|
|
if (def.$data && !("code" in def || "validate" in def)) {
|
|
throw new Error('$data keyword must have "code" or "validate" function');
|
|
}
|
|
}
|
|
function addRule(keyword, definition, dataType) {
|
|
var _a;
|
|
const post = definition === null || definition === void 0 ? void 0 : definition.post;
|
|
if (dataType && post)
|
|
throw new Error('keyword with "post" flag cannot have "type"');
|
|
const { RULES } = this;
|
|
let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType);
|
|
if (!ruleGroup) {
|
|
ruleGroup = { type: dataType, rules: [] };
|
|
RULES.rules.push(ruleGroup);
|
|
}
|
|
RULES.keywords[keyword] = true;
|
|
if (!definition)
|
|
return;
|
|
const rule = {
|
|
keyword,
|
|
definition: {
|
|
...definition,
|
|
type: (0, dataType_1.getJSONTypes)(definition.type),
|
|
schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType)
|
|
}
|
|
};
|
|
if (definition.before)
|
|
addBeforeRule.call(this, ruleGroup, rule, definition.before);
|
|
else
|
|
ruleGroup.rules.push(rule);
|
|
RULES.all[keyword] = rule;
|
|
(_a = definition.implements) === null || _a === void 0 || _a.forEach((kwd) => this.addKeyword(kwd));
|
|
}
|
|
function addBeforeRule(ruleGroup, rule, before) {
|
|
const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);
|
|
if (i >= 0) {
|
|
ruleGroup.rules.splice(i, 0, rule);
|
|
} else {
|
|
ruleGroup.rules.push(rule);
|
|
this.logger.warn(`rule ${before} is not defined`);
|
|
}
|
|
}
|
|
function keywordMetaschema(def) {
|
|
let { metaSchema } = def;
|
|
if (metaSchema === void 0)
|
|
return;
|
|
if (def.$data && this.opts.$data)
|
|
metaSchema = schemaOrData(metaSchema);
|
|
def.validateSchema = this.compile(metaSchema, true);
|
|
}
|
|
var $dataRef = {
|
|
$ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"
|
|
};
|
|
function schemaOrData(schema) {
|
|
return { anyOf: [schema, $dataRef] };
|
|
}
|
|
});
|
|
var require_id2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var def = {
|
|
keyword: "id",
|
|
code() {
|
|
throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID');
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_ref2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.callRef = exports.getValidate = void 0;
|
|
var ref_error_1 = require_ref_error2();
|
|
var code_1 = require_code4();
|
|
var codegen_1 = require_codegen2();
|
|
var names_1 = require_names2();
|
|
var compile_1 = require_compile2();
|
|
var util_1 = require_util2();
|
|
var def = {
|
|
keyword: "$ref",
|
|
schemaType: "string",
|
|
code(cxt) {
|
|
const { gen, schema: $ref, it } = cxt;
|
|
const { baseId, schemaEnv: env, validateName, opts, self: self2 } = it;
|
|
const { root: root2 } = env;
|
|
if (($ref === "#" || $ref === "#/") && baseId === root2.baseId)
|
|
return callRootRef();
|
|
const schOrEnv = compile_1.resolveRef.call(self2, root2, baseId, $ref);
|
|
if (schOrEnv === void 0)
|
|
throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref);
|
|
if (schOrEnv instanceof compile_1.SchemaEnv)
|
|
return callValidate(schOrEnv);
|
|
return inlineRefSchema(schOrEnv);
|
|
function callRootRef() {
|
|
if (env === root2)
|
|
return callRef(cxt, validateName, env, env.$async);
|
|
const rootName = gen.scopeValue("root", { ref: root2 });
|
|
return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root2, root2.$async);
|
|
}
|
|
function callValidate(sch) {
|
|
const v = getValidate(cxt, sch);
|
|
callRef(cxt, v, sch, sch.$async);
|
|
}
|
|
function inlineRefSchema(sch) {
|
|
const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch });
|
|
const valid = gen.name("valid");
|
|
const schCxt = cxt.subschema({
|
|
schema: sch,
|
|
dataTypes: [],
|
|
schemaPath: codegen_1.nil,
|
|
topSchemaRef: schName,
|
|
errSchemaPath: $ref
|
|
}, valid);
|
|
cxt.mergeEvaluated(schCxt);
|
|
cxt.ok(valid);
|
|
}
|
|
}
|
|
};
|
|
function getValidate(cxt, sch) {
|
|
const { gen } = cxt;
|
|
return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`;
|
|
}
|
|
exports.getValidate = getValidate;
|
|
function callRef(cxt, v, sch, $async) {
|
|
const { gen, it } = cxt;
|
|
const { allErrors, schemaEnv: env, opts } = it;
|
|
const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil;
|
|
if ($async)
|
|
callAsyncRef();
|
|
else
|
|
callSyncRef();
|
|
function callAsyncRef() {
|
|
if (!env.$async)
|
|
throw new Error("async schema referenced by sync schema");
|
|
const valid = gen.let("valid");
|
|
gen.try(() => {
|
|
gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`);
|
|
addEvaluatedFrom(v);
|
|
if (!allErrors)
|
|
gen.assign(valid, true);
|
|
}, (e) => {
|
|
gen.if((0, codegen_1._)`!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e));
|
|
addErrorsFrom(e);
|
|
if (!allErrors)
|
|
gen.assign(valid, false);
|
|
});
|
|
cxt.ok(valid);
|
|
}
|
|
function callSyncRef() {
|
|
cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v));
|
|
}
|
|
function addErrorsFrom(source) {
|
|
const errs = (0, codegen_1._)`${source}.errors`;
|
|
gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`);
|
|
gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`);
|
|
}
|
|
function addEvaluatedFrom(source) {
|
|
var _a;
|
|
if (!it.opts.unevaluated)
|
|
return;
|
|
const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated;
|
|
if (it.props !== true) {
|
|
if (schEvaluated && !schEvaluated.dynamicProps) {
|
|
if (schEvaluated.props !== void 0) {
|
|
it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props);
|
|
}
|
|
} else {
|
|
const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`);
|
|
it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name);
|
|
}
|
|
}
|
|
if (it.items !== true) {
|
|
if (schEvaluated && !schEvaluated.dynamicItems) {
|
|
if (schEvaluated.items !== void 0) {
|
|
it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items);
|
|
}
|
|
} else {
|
|
const items = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`);
|
|
it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
exports.callRef = callRef;
|
|
exports.default = def;
|
|
});
|
|
var require_core4 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var id_1 = require_id2();
|
|
var ref_1 = require_ref2();
|
|
var core2 = [
|
|
"$schema",
|
|
"$id",
|
|
"$defs",
|
|
"$vocabulary",
|
|
{ keyword: "$comment" },
|
|
"definitions",
|
|
id_1.default,
|
|
ref_1.default
|
|
];
|
|
exports.default = core2;
|
|
});
|
|
var require_limitNumber2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var codegen_1 = require_codegen2();
|
|
var ops = codegen_1.operators;
|
|
var KWDs = {
|
|
maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT },
|
|
minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT },
|
|
exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE },
|
|
exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE }
|
|
};
|
|
var error2 = {
|
|
message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`,
|
|
params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`
|
|
};
|
|
var def = {
|
|
keyword: Object.keys(KWDs),
|
|
type: "number",
|
|
schemaType: "number",
|
|
$data: true,
|
|
error: error2,
|
|
code(cxt) {
|
|
const { keyword, data, schemaCode } = cxt;
|
|
cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`);
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_multipleOf2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var codegen_1 = require_codegen2();
|
|
var error2 = {
|
|
message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`,
|
|
params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}`
|
|
};
|
|
var def = {
|
|
keyword: "multipleOf",
|
|
type: "number",
|
|
schemaType: "number",
|
|
$data: true,
|
|
error: error2,
|
|
code(cxt) {
|
|
const { gen, data, schemaCode, it } = cxt;
|
|
const prec = it.opts.multipleOfPrecision;
|
|
const res = gen.let("res");
|
|
const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`;
|
|
cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`);
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_ucs2length2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
function ucs2length(str) {
|
|
const len = str.length;
|
|
let length = 0;
|
|
let pos = 0;
|
|
let value;
|
|
while (pos < len) {
|
|
length++;
|
|
value = str.charCodeAt(pos++);
|
|
if (value >= 55296 && value <= 56319 && pos < len) {
|
|
value = str.charCodeAt(pos);
|
|
if ((value & 64512) === 56320)
|
|
pos++;
|
|
}
|
|
}
|
|
return length;
|
|
}
|
|
exports.default = ucs2length;
|
|
ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default';
|
|
});
|
|
var require_limitLength2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var codegen_1 = require_codegen2();
|
|
var util_1 = require_util2();
|
|
var ucs2length_1 = require_ucs2length2();
|
|
var error2 = {
|
|
message({ keyword, schemaCode }) {
|
|
const comp = keyword === "maxLength" ? "more" : "fewer";
|
|
return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`;
|
|
},
|
|
params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}`
|
|
};
|
|
var def = {
|
|
keyword: ["maxLength", "minLength"],
|
|
type: "string",
|
|
schemaType: "number",
|
|
$data: true,
|
|
error: error2,
|
|
code(cxt) {
|
|
const { keyword, data, schemaCode, it } = cxt;
|
|
const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT;
|
|
const len = it.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`;
|
|
cxt.fail$data((0, codegen_1._)`${len} ${op} ${schemaCode}`);
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_pattern2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var code_1 = require_code4();
|
|
var codegen_1 = require_codegen2();
|
|
var error2 = {
|
|
message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`,
|
|
params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}`
|
|
};
|
|
var def = {
|
|
keyword: "pattern",
|
|
type: "string",
|
|
schemaType: "string",
|
|
$data: true,
|
|
error: error2,
|
|
code(cxt) {
|
|
const { data, $data, schema, schemaCode, it } = cxt;
|
|
const u = it.opts.unicodeRegExp ? "u" : "";
|
|
const regExp = $data ? (0, codegen_1._)`(new RegExp(${schemaCode}, ${u}))` : (0, code_1.usePattern)(cxt, schema);
|
|
cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`);
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_limitProperties2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var codegen_1 = require_codegen2();
|
|
var error2 = {
|
|
message({ keyword, schemaCode }) {
|
|
const comp = keyword === "maxProperties" ? "more" : "fewer";
|
|
return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`;
|
|
},
|
|
params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}`
|
|
};
|
|
var def = {
|
|
keyword: ["maxProperties", "minProperties"],
|
|
type: "object",
|
|
schemaType: "number",
|
|
$data: true,
|
|
error: error2,
|
|
code(cxt) {
|
|
const { keyword, data, schemaCode } = cxt;
|
|
const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT;
|
|
cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`);
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_required2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var code_1 = require_code4();
|
|
var codegen_1 = require_codegen2();
|
|
var util_1 = require_util2();
|
|
var error2 = {
|
|
message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`,
|
|
params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}`
|
|
};
|
|
var def = {
|
|
keyword: "required",
|
|
type: "object",
|
|
schemaType: "array",
|
|
$data: true,
|
|
error: error2,
|
|
code(cxt) {
|
|
const { gen, schema, schemaCode, data, $data, it } = cxt;
|
|
const { opts } = it;
|
|
if (!$data && schema.length === 0)
|
|
return;
|
|
const useLoop = schema.length >= opts.loopRequired;
|
|
if (it.allErrors)
|
|
allErrorsMode();
|
|
else
|
|
exitOnErrorMode();
|
|
if (opts.strictRequired) {
|
|
const props = cxt.parentSchema.properties;
|
|
const { definedProperties } = cxt.it;
|
|
for (const requiredKey of schema) {
|
|
if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) {
|
|
const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;
|
|
const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`;
|
|
(0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired);
|
|
}
|
|
}
|
|
}
|
|
function allErrorsMode() {
|
|
if (useLoop || $data) {
|
|
cxt.block$data(codegen_1.nil, loopAllRequired);
|
|
} else {
|
|
for (const prop of schema) {
|
|
(0, code_1.checkReportMissingProp)(cxt, prop);
|
|
}
|
|
}
|
|
}
|
|
function exitOnErrorMode() {
|
|
const missing = gen.let("missing");
|
|
if (useLoop || $data) {
|
|
const valid = gen.let("valid", true);
|
|
cxt.block$data(valid, () => loopUntilMissing(missing, valid));
|
|
cxt.ok(valid);
|
|
} else {
|
|
gen.if((0, code_1.checkMissingProp)(cxt, schema, missing));
|
|
(0, code_1.reportMissingProp)(cxt, missing);
|
|
gen.else();
|
|
}
|
|
}
|
|
function loopAllRequired() {
|
|
gen.forOf("prop", schemaCode, (prop) => {
|
|
cxt.setParams({ missingProperty: prop });
|
|
gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error());
|
|
});
|
|
}
|
|
function loopUntilMissing(missing, valid) {
|
|
cxt.setParams({ missingProperty: missing });
|
|
gen.forOf(missing, schemaCode, () => {
|
|
gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties));
|
|
gen.if((0, codegen_1.not)(valid), () => {
|
|
cxt.error();
|
|
gen.break();
|
|
});
|
|
}, codegen_1.nil);
|
|
}
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_limitItems2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var codegen_1 = require_codegen2();
|
|
var error2 = {
|
|
message({ keyword, schemaCode }) {
|
|
const comp = keyword === "maxItems" ? "more" : "fewer";
|
|
return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`;
|
|
},
|
|
params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}`
|
|
};
|
|
var def = {
|
|
keyword: ["maxItems", "minItems"],
|
|
type: "array",
|
|
schemaType: "number",
|
|
$data: true,
|
|
error: error2,
|
|
code(cxt) {
|
|
const { keyword, data, schemaCode } = cxt;
|
|
const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT;
|
|
cxt.fail$data((0, codegen_1._)`${data}.length ${op} ${schemaCode}`);
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_equal2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var equal = require_fast_deep_equal();
|
|
equal.code = 'require("ajv/dist/runtime/equal").default';
|
|
exports.default = equal;
|
|
});
|
|
var require_uniqueItems2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var dataType_1 = require_dataType2();
|
|
var codegen_1 = require_codegen2();
|
|
var util_1 = require_util2();
|
|
var equal_1 = require_equal2();
|
|
var error2 = {
|
|
message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`,
|
|
params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}`
|
|
};
|
|
var def = {
|
|
keyword: "uniqueItems",
|
|
type: "array",
|
|
schemaType: "boolean",
|
|
$data: true,
|
|
error: error2,
|
|
code(cxt) {
|
|
const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt;
|
|
if (!$data && !schema)
|
|
return;
|
|
const valid = gen.let("valid");
|
|
const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : [];
|
|
cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`);
|
|
cxt.ok(valid);
|
|
function validateUniqueItems() {
|
|
const i = gen.let("i", (0, codegen_1._)`${data}.length`);
|
|
const j = gen.let("j");
|
|
cxt.setParams({ i, j });
|
|
gen.assign(valid, true);
|
|
gen.if((0, codegen_1._)`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j));
|
|
}
|
|
function canOptimize() {
|
|
return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array");
|
|
}
|
|
function loopN(i, j) {
|
|
const item = gen.name("item");
|
|
const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong);
|
|
const indices = gen.const("indices", (0, codegen_1._)`{}`);
|
|
gen.for((0, codegen_1._)`;${i}--;`, () => {
|
|
gen.let(item, (0, codegen_1._)`${data}[${i}]`);
|
|
gen.if(wrongType, (0, codegen_1._)`continue`);
|
|
if (itemTypes.length > 1)
|
|
gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`);
|
|
gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => {
|
|
gen.assign(j, (0, codegen_1._)`${indices}[${item}]`);
|
|
cxt.error();
|
|
gen.assign(valid, false).break();
|
|
}).code((0, codegen_1._)`${indices}[${item}] = ${i}`);
|
|
});
|
|
}
|
|
function loopN2(i, j) {
|
|
const eql = (0, util_1.useFunc)(gen, equal_1.default);
|
|
const outer = gen.name("outer");
|
|
gen.label(outer).for((0, codegen_1._)`;${i}--;`, () => gen.for((0, codegen_1._)`${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i}], ${data}[${j}])`, () => {
|
|
cxt.error();
|
|
gen.assign(valid, false).break(outer);
|
|
})));
|
|
}
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_const2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var codegen_1 = require_codegen2();
|
|
var util_1 = require_util2();
|
|
var equal_1 = require_equal2();
|
|
var error2 = {
|
|
message: "must be equal to constant",
|
|
params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}`
|
|
};
|
|
var def = {
|
|
keyword: "const",
|
|
$data: true,
|
|
error: error2,
|
|
code(cxt) {
|
|
const { gen, data, $data, schemaCode, schema } = cxt;
|
|
if ($data || schema && typeof schema == "object") {
|
|
cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`);
|
|
} else {
|
|
cxt.fail((0, codegen_1._)`${schema} !== ${data}`);
|
|
}
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_enum2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var codegen_1 = require_codegen2();
|
|
var util_1 = require_util2();
|
|
var equal_1 = require_equal2();
|
|
var error2 = {
|
|
message: "must be equal to one of the allowed values",
|
|
params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}`
|
|
};
|
|
var def = {
|
|
keyword: "enum",
|
|
schemaType: "array",
|
|
$data: true,
|
|
error: error2,
|
|
code(cxt) {
|
|
const { gen, data, $data, schema, schemaCode, it } = cxt;
|
|
if (!$data && schema.length === 0)
|
|
throw new Error("enum must have non-empty array");
|
|
const useLoop = schema.length >= it.opts.loopEnum;
|
|
let eql;
|
|
const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default);
|
|
let valid;
|
|
if (useLoop || $data) {
|
|
valid = gen.let("valid");
|
|
cxt.block$data(valid, loopEnum);
|
|
} else {
|
|
if (!Array.isArray(schema))
|
|
throw new Error("ajv implementation error");
|
|
const vSchema = gen.const("vSchema", schemaCode);
|
|
valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i)));
|
|
}
|
|
cxt.pass(valid);
|
|
function loopEnum() {
|
|
gen.assign(valid, false);
|
|
gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break()));
|
|
}
|
|
function equalCode(vSchema, i) {
|
|
const sch = schema[i];
|
|
return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i}])` : (0, codegen_1._)`${data} === ${sch}`;
|
|
}
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_validation2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var limitNumber_1 = require_limitNumber2();
|
|
var multipleOf_1 = require_multipleOf2();
|
|
var limitLength_1 = require_limitLength2();
|
|
var pattern_1 = require_pattern2();
|
|
var limitProperties_1 = require_limitProperties2();
|
|
var required_1 = require_required2();
|
|
var limitItems_1 = require_limitItems2();
|
|
var uniqueItems_1 = require_uniqueItems2();
|
|
var const_1 = require_const2();
|
|
var enum_1 = require_enum2();
|
|
var validation = [
|
|
limitNumber_1.default,
|
|
multipleOf_1.default,
|
|
limitLength_1.default,
|
|
pattern_1.default,
|
|
limitProperties_1.default,
|
|
required_1.default,
|
|
limitItems_1.default,
|
|
uniqueItems_1.default,
|
|
{ keyword: "type", schemaType: ["string", "array"] },
|
|
{ keyword: "nullable", schemaType: "boolean" },
|
|
const_1.default,
|
|
enum_1.default
|
|
];
|
|
exports.default = validation;
|
|
});
|
|
var require_additionalItems2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.validateAdditionalItems = void 0;
|
|
var codegen_1 = require_codegen2();
|
|
var util_1 = require_util2();
|
|
var error2 = {
|
|
message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`,
|
|
params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}`
|
|
};
|
|
var def = {
|
|
keyword: "additionalItems",
|
|
type: "array",
|
|
schemaType: ["boolean", "object"],
|
|
before: "uniqueItems",
|
|
error: error2,
|
|
code(cxt) {
|
|
const { parentSchema, it } = cxt;
|
|
const { items } = parentSchema;
|
|
if (!Array.isArray(items)) {
|
|
(0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas');
|
|
return;
|
|
}
|
|
validateAdditionalItems(cxt, items);
|
|
}
|
|
};
|
|
function validateAdditionalItems(cxt, items) {
|
|
const { gen, schema, data, keyword, it } = cxt;
|
|
it.items = true;
|
|
const len = gen.const("len", (0, codegen_1._)`${data}.length`);
|
|
if (schema === false) {
|
|
cxt.setParams({ len: items.length });
|
|
cxt.pass((0, codegen_1._)`${len} <= ${items.length}`);
|
|
} else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
|
|
const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`);
|
|
gen.if((0, codegen_1.not)(valid), () => validateItems(valid));
|
|
cxt.ok(valid);
|
|
}
|
|
function validateItems(valid) {
|
|
gen.forRange("i", items.length, len, (i) => {
|
|
cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid);
|
|
if (!it.allErrors)
|
|
gen.if((0, codegen_1.not)(valid), () => gen.break());
|
|
});
|
|
}
|
|
}
|
|
exports.validateAdditionalItems = validateAdditionalItems;
|
|
exports.default = def;
|
|
});
|
|
var require_items2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.validateTuple = void 0;
|
|
var codegen_1 = require_codegen2();
|
|
var util_1 = require_util2();
|
|
var code_1 = require_code4();
|
|
var def = {
|
|
keyword: "items",
|
|
type: "array",
|
|
schemaType: ["object", "array", "boolean"],
|
|
before: "uniqueItems",
|
|
code(cxt) {
|
|
const { schema, it } = cxt;
|
|
if (Array.isArray(schema))
|
|
return validateTuple(cxt, "additionalItems", schema);
|
|
it.items = true;
|
|
if ((0, util_1.alwaysValidSchema)(it, schema))
|
|
return;
|
|
cxt.ok((0, code_1.validateArray)(cxt));
|
|
}
|
|
};
|
|
function validateTuple(cxt, extraItems, schArr = cxt.schema) {
|
|
const { gen, parentSchema, data, keyword, it } = cxt;
|
|
checkStrictTuple(parentSchema);
|
|
if (it.opts.unevaluated && schArr.length && it.items !== true) {
|
|
it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items);
|
|
}
|
|
const valid = gen.name("valid");
|
|
const len = gen.const("len", (0, codegen_1._)`${data}.length`);
|
|
schArr.forEach((sch, i) => {
|
|
if ((0, util_1.alwaysValidSchema)(it, sch))
|
|
return;
|
|
gen.if((0, codegen_1._)`${len} > ${i}`, () => cxt.subschema({
|
|
keyword,
|
|
schemaProp: i,
|
|
dataProp: i
|
|
}, valid));
|
|
cxt.ok(valid);
|
|
});
|
|
function checkStrictTuple(sch) {
|
|
const { opts, errSchemaPath } = it;
|
|
const l = schArr.length;
|
|
const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false);
|
|
if (opts.strictTuples && !fullTuple) {
|
|
const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`;
|
|
(0, util_1.checkStrictMode)(it, msg, opts.strictTuples);
|
|
}
|
|
}
|
|
}
|
|
exports.validateTuple = validateTuple;
|
|
exports.default = def;
|
|
});
|
|
var require_prefixItems2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var items_1 = require_items2();
|
|
var def = {
|
|
keyword: "prefixItems",
|
|
type: "array",
|
|
schemaType: ["array"],
|
|
before: "uniqueItems",
|
|
code: (cxt) => (0, items_1.validateTuple)(cxt, "items")
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_items20202 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var codegen_1 = require_codegen2();
|
|
var util_1 = require_util2();
|
|
var code_1 = require_code4();
|
|
var additionalItems_1 = require_additionalItems2();
|
|
var error2 = {
|
|
message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`,
|
|
params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}`
|
|
};
|
|
var def = {
|
|
keyword: "items",
|
|
type: "array",
|
|
schemaType: ["object", "boolean"],
|
|
before: "uniqueItems",
|
|
error: error2,
|
|
code(cxt) {
|
|
const { schema, parentSchema, it } = cxt;
|
|
const { prefixItems } = parentSchema;
|
|
it.items = true;
|
|
if ((0, util_1.alwaysValidSchema)(it, schema))
|
|
return;
|
|
if (prefixItems)
|
|
(0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems);
|
|
else
|
|
cxt.ok((0, code_1.validateArray)(cxt));
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_contains2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var codegen_1 = require_codegen2();
|
|
var util_1 = require_util2();
|
|
var error2 = {
|
|
message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`,
|
|
params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}`
|
|
};
|
|
var def = {
|
|
keyword: "contains",
|
|
type: "array",
|
|
schemaType: ["object", "boolean"],
|
|
before: "uniqueItems",
|
|
trackErrors: true,
|
|
error: error2,
|
|
code(cxt) {
|
|
const { gen, schema, parentSchema, data, it } = cxt;
|
|
let min;
|
|
let max;
|
|
const { minContains, maxContains } = parentSchema;
|
|
if (it.opts.next) {
|
|
min = minContains === void 0 ? 1 : minContains;
|
|
max = maxContains;
|
|
} else {
|
|
min = 1;
|
|
}
|
|
const len = gen.const("len", (0, codegen_1._)`${data}.length`);
|
|
cxt.setParams({ min, max });
|
|
if (max === void 0 && min === 0) {
|
|
(0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`);
|
|
return;
|
|
}
|
|
if (max !== void 0 && min > max) {
|
|
(0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`);
|
|
cxt.fail();
|
|
return;
|
|
}
|
|
if ((0, util_1.alwaysValidSchema)(it, schema)) {
|
|
let cond = (0, codegen_1._)`${len} >= ${min}`;
|
|
if (max !== void 0)
|
|
cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`;
|
|
cxt.pass(cond);
|
|
return;
|
|
}
|
|
it.items = true;
|
|
const valid = gen.name("valid");
|
|
if (max === void 0 && min === 1) {
|
|
validateItems(valid, () => gen.if(valid, () => gen.break()));
|
|
} else if (min === 0) {
|
|
gen.let(valid, true);
|
|
if (max !== void 0)
|
|
gen.if((0, codegen_1._)`${data}.length > 0`, validateItemsWithCount);
|
|
} else {
|
|
gen.let(valid, false);
|
|
validateItemsWithCount();
|
|
}
|
|
cxt.result(valid, () => cxt.reset());
|
|
function validateItemsWithCount() {
|
|
const schValid = gen.name("_valid");
|
|
const count = gen.let("count", 0);
|
|
validateItems(schValid, () => gen.if(schValid, () => checkLimits(count)));
|
|
}
|
|
function validateItems(_valid, block) {
|
|
gen.forRange("i", 0, len, (i) => {
|
|
cxt.subschema({
|
|
keyword: "contains",
|
|
dataProp: i,
|
|
dataPropType: util_1.Type.Num,
|
|
compositeRule: true
|
|
}, _valid);
|
|
block();
|
|
});
|
|
}
|
|
function checkLimits(count) {
|
|
gen.code((0, codegen_1._)`${count}++`);
|
|
if (max === void 0) {
|
|
gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break());
|
|
} else {
|
|
gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break());
|
|
if (min === 1)
|
|
gen.assign(valid, true);
|
|
else
|
|
gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true));
|
|
}
|
|
}
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_dependencies2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0;
|
|
var codegen_1 = require_codegen2();
|
|
var util_1 = require_util2();
|
|
var code_1 = require_code4();
|
|
exports.error = {
|
|
message: ({ params: { property, depsCount, deps } }) => {
|
|
const property_ies = depsCount === 1 ? "property" : "properties";
|
|
return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`;
|
|
},
|
|
params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property},
|
|
missingProperty: ${missingProperty},
|
|
depsCount: ${depsCount},
|
|
deps: ${deps}}`
|
|
};
|
|
var def = {
|
|
keyword: "dependencies",
|
|
type: "object",
|
|
schemaType: "object",
|
|
error: exports.error,
|
|
code(cxt) {
|
|
const [propDeps, schDeps] = splitDependencies(cxt);
|
|
validatePropertyDeps(cxt, propDeps);
|
|
validateSchemaDeps(cxt, schDeps);
|
|
}
|
|
};
|
|
function splitDependencies({ schema }) {
|
|
const propertyDeps = {};
|
|
const schemaDeps = {};
|
|
for (const key in schema) {
|
|
if (key === "__proto__")
|
|
continue;
|
|
const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps;
|
|
deps[key] = schema[key];
|
|
}
|
|
return [propertyDeps, schemaDeps];
|
|
}
|
|
function validatePropertyDeps(cxt, propertyDeps = cxt.schema) {
|
|
const { gen, data, it } = cxt;
|
|
if (Object.keys(propertyDeps).length === 0)
|
|
return;
|
|
const missing = gen.let("missing");
|
|
for (const prop in propertyDeps) {
|
|
const deps = propertyDeps[prop];
|
|
if (deps.length === 0)
|
|
continue;
|
|
const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties);
|
|
cxt.setParams({
|
|
property: prop,
|
|
depsCount: deps.length,
|
|
deps: deps.join(", ")
|
|
});
|
|
if (it.allErrors) {
|
|
gen.if(hasProperty, () => {
|
|
for (const depProp of deps) {
|
|
(0, code_1.checkReportMissingProp)(cxt, depProp);
|
|
}
|
|
});
|
|
} else {
|
|
gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`);
|
|
(0, code_1.reportMissingProp)(cxt, missing);
|
|
gen.else();
|
|
}
|
|
}
|
|
}
|
|
exports.validatePropertyDeps = validatePropertyDeps;
|
|
function validateSchemaDeps(cxt, schemaDeps = cxt.schema) {
|
|
const { gen, data, keyword, it } = cxt;
|
|
const valid = gen.name("valid");
|
|
for (const prop in schemaDeps) {
|
|
if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop]))
|
|
continue;
|
|
gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => {
|
|
const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid);
|
|
cxt.mergeValidEvaluated(schCxt, valid);
|
|
}, () => gen.var(valid, true));
|
|
cxt.ok(valid);
|
|
}
|
|
}
|
|
exports.validateSchemaDeps = validateSchemaDeps;
|
|
exports.default = def;
|
|
});
|
|
var require_propertyNames2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var codegen_1 = require_codegen2();
|
|
var util_1 = require_util2();
|
|
var error2 = {
|
|
message: "property name must be valid",
|
|
params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}`
|
|
};
|
|
var def = {
|
|
keyword: "propertyNames",
|
|
type: "object",
|
|
schemaType: ["object", "boolean"],
|
|
error: error2,
|
|
code(cxt) {
|
|
const { gen, schema, data, it } = cxt;
|
|
if ((0, util_1.alwaysValidSchema)(it, schema))
|
|
return;
|
|
const valid = gen.name("valid");
|
|
gen.forIn("key", data, (key) => {
|
|
cxt.setParams({ propertyName: key });
|
|
cxt.subschema({
|
|
keyword: "propertyNames",
|
|
data: key,
|
|
dataTypes: ["string"],
|
|
propertyName: key,
|
|
compositeRule: true
|
|
}, valid);
|
|
gen.if((0, codegen_1.not)(valid), () => {
|
|
cxt.error(true);
|
|
if (!it.allErrors)
|
|
gen.break();
|
|
});
|
|
});
|
|
cxt.ok(valid);
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_additionalProperties2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var code_1 = require_code4();
|
|
var codegen_1 = require_codegen2();
|
|
var names_1 = require_names2();
|
|
var util_1 = require_util2();
|
|
var error2 = {
|
|
message: "must NOT have additional properties",
|
|
params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}`
|
|
};
|
|
var def = {
|
|
keyword: "additionalProperties",
|
|
type: ["object"],
|
|
schemaType: ["boolean", "object"],
|
|
allowUndefined: true,
|
|
trackErrors: true,
|
|
error: error2,
|
|
code(cxt) {
|
|
const { gen, schema, parentSchema, data, errsCount, it } = cxt;
|
|
if (!errsCount)
|
|
throw new Error("ajv implementation error");
|
|
const { allErrors, opts } = it;
|
|
it.props = true;
|
|
if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema))
|
|
return;
|
|
const props = (0, code_1.allSchemaProperties)(parentSchema.properties);
|
|
const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties);
|
|
checkAdditionalProperties();
|
|
cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`);
|
|
function checkAdditionalProperties() {
|
|
gen.forIn("key", data, (key) => {
|
|
if (!props.length && !patProps.length)
|
|
additionalPropertyCode(key);
|
|
else
|
|
gen.if(isAdditional(key), () => additionalPropertyCode(key));
|
|
});
|
|
}
|
|
function isAdditional(key) {
|
|
let definedProp;
|
|
if (props.length > 8) {
|
|
const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties");
|
|
definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key);
|
|
} else if (props.length) {
|
|
definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._)`${key} === ${p}`));
|
|
} else {
|
|
definedProp = codegen_1.nil;
|
|
}
|
|
if (patProps.length) {
|
|
definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p)}.test(${key})`));
|
|
}
|
|
return (0, codegen_1.not)(definedProp);
|
|
}
|
|
function deleteAdditional(key) {
|
|
gen.code((0, codegen_1._)`delete ${data}[${key}]`);
|
|
}
|
|
function additionalPropertyCode(key) {
|
|
if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) {
|
|
deleteAdditional(key);
|
|
return;
|
|
}
|
|
if (schema === false) {
|
|
cxt.setParams({ additionalProperty: key });
|
|
cxt.error();
|
|
if (!allErrors)
|
|
gen.break();
|
|
return;
|
|
}
|
|
if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
|
|
const valid = gen.name("valid");
|
|
if (opts.removeAdditional === "failing") {
|
|
applyAdditionalSchema(key, valid, false);
|
|
gen.if((0, codegen_1.not)(valid), () => {
|
|
cxt.reset();
|
|
deleteAdditional(key);
|
|
});
|
|
} else {
|
|
applyAdditionalSchema(key, valid);
|
|
if (!allErrors)
|
|
gen.if((0, codegen_1.not)(valid), () => gen.break());
|
|
}
|
|
}
|
|
}
|
|
function applyAdditionalSchema(key, valid, errors3) {
|
|
const subschema = {
|
|
keyword: "additionalProperties",
|
|
dataProp: key,
|
|
dataPropType: util_1.Type.Str
|
|
};
|
|
if (errors3 === false) {
|
|
Object.assign(subschema, {
|
|
compositeRule: true,
|
|
createErrors: false,
|
|
allErrors: false
|
|
});
|
|
}
|
|
cxt.subschema(subschema, valid);
|
|
}
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_properties2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var validate_1 = require_validate2();
|
|
var code_1 = require_code4();
|
|
var util_1 = require_util2();
|
|
var additionalProperties_1 = require_additionalProperties2();
|
|
var def = {
|
|
keyword: "properties",
|
|
type: "object",
|
|
schemaType: "object",
|
|
code(cxt) {
|
|
const { gen, schema, parentSchema, data, it } = cxt;
|
|
if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) {
|
|
additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties"));
|
|
}
|
|
const allProps = (0, code_1.allSchemaProperties)(schema);
|
|
for (const prop of allProps) {
|
|
it.definedProperties.add(prop);
|
|
}
|
|
if (it.opts.unevaluated && allProps.length && it.props !== true) {
|
|
it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props);
|
|
}
|
|
const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p]));
|
|
if (properties.length === 0)
|
|
return;
|
|
const valid = gen.name("valid");
|
|
for (const prop of properties) {
|
|
if (hasDefault(prop)) {
|
|
applyPropertySchema(prop);
|
|
} else {
|
|
gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties));
|
|
applyPropertySchema(prop);
|
|
if (!it.allErrors)
|
|
gen.else().var(valid, true);
|
|
gen.endIf();
|
|
}
|
|
cxt.it.definedProperties.add(prop);
|
|
cxt.ok(valid);
|
|
}
|
|
function hasDefault(prop) {
|
|
return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== void 0;
|
|
}
|
|
function applyPropertySchema(prop) {
|
|
cxt.subschema({
|
|
keyword: "properties",
|
|
schemaProp: prop,
|
|
dataProp: prop
|
|
}, valid);
|
|
}
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_patternProperties2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var code_1 = require_code4();
|
|
var codegen_1 = require_codegen2();
|
|
var util_1 = require_util2();
|
|
var util_2 = require_util2();
|
|
var def = {
|
|
keyword: "patternProperties",
|
|
type: "object",
|
|
schemaType: "object",
|
|
code(cxt) {
|
|
const { gen, schema, data, parentSchema, it } = cxt;
|
|
const { opts } = it;
|
|
const patterns = (0, code_1.allSchemaProperties)(schema);
|
|
const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p]));
|
|
if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) {
|
|
return;
|
|
}
|
|
const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties;
|
|
const valid = gen.name("valid");
|
|
if (it.props !== true && !(it.props instanceof codegen_1.Name)) {
|
|
it.props = (0, util_2.evaluatedPropsToName)(gen, it.props);
|
|
}
|
|
const { props } = it;
|
|
validatePatternProperties();
|
|
function validatePatternProperties() {
|
|
for (const pat of patterns) {
|
|
if (checkProperties)
|
|
checkMatchingProperties(pat);
|
|
if (it.allErrors) {
|
|
validateProperties(pat);
|
|
} else {
|
|
gen.var(valid, true);
|
|
validateProperties(pat);
|
|
gen.if(valid);
|
|
}
|
|
}
|
|
}
|
|
function checkMatchingProperties(pat) {
|
|
for (const prop in checkProperties) {
|
|
if (new RegExp(pat).test(prop)) {
|
|
(0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`);
|
|
}
|
|
}
|
|
}
|
|
function validateProperties(pat) {
|
|
gen.forIn("key", data, (key) => {
|
|
gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => {
|
|
const alwaysValid = alwaysValidPatterns.includes(pat);
|
|
if (!alwaysValid) {
|
|
cxt.subschema({
|
|
keyword: "patternProperties",
|
|
schemaProp: pat,
|
|
dataProp: key,
|
|
dataPropType: util_2.Type.Str
|
|
}, valid);
|
|
}
|
|
if (it.opts.unevaluated && props !== true) {
|
|
gen.assign((0, codegen_1._)`${props}[${key}]`, true);
|
|
} else if (!alwaysValid && !it.allErrors) {
|
|
gen.if((0, codegen_1.not)(valid), () => gen.break());
|
|
}
|
|
});
|
|
});
|
|
}
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_not2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var util_1 = require_util2();
|
|
var def = {
|
|
keyword: "not",
|
|
schemaType: ["object", "boolean"],
|
|
trackErrors: true,
|
|
code(cxt) {
|
|
const { gen, schema, it } = cxt;
|
|
if ((0, util_1.alwaysValidSchema)(it, schema)) {
|
|
cxt.fail();
|
|
return;
|
|
}
|
|
const valid = gen.name("valid");
|
|
cxt.subschema({
|
|
keyword: "not",
|
|
compositeRule: true,
|
|
createErrors: false,
|
|
allErrors: false
|
|
}, valid);
|
|
cxt.failResult(valid, () => cxt.reset(), () => cxt.error());
|
|
},
|
|
error: { message: "must NOT be valid" }
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_anyOf2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var code_1 = require_code4();
|
|
var def = {
|
|
keyword: "anyOf",
|
|
schemaType: "array",
|
|
trackErrors: true,
|
|
code: code_1.validateUnion,
|
|
error: { message: "must match a schema in anyOf" }
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_oneOf2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var codegen_1 = require_codegen2();
|
|
var util_1 = require_util2();
|
|
var error2 = {
|
|
message: "must match exactly one schema in oneOf",
|
|
params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}`
|
|
};
|
|
var def = {
|
|
keyword: "oneOf",
|
|
schemaType: "array",
|
|
trackErrors: true,
|
|
error: error2,
|
|
code(cxt) {
|
|
const { gen, schema, parentSchema, it } = cxt;
|
|
if (!Array.isArray(schema))
|
|
throw new Error("ajv implementation error");
|
|
if (it.opts.discriminator && parentSchema.discriminator)
|
|
return;
|
|
const schArr = schema;
|
|
const valid = gen.let("valid", false);
|
|
const passing = gen.let("passing", null);
|
|
const schValid = gen.name("_valid");
|
|
cxt.setParams({ passing });
|
|
gen.block(validateOneOf);
|
|
cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
|
|
function validateOneOf() {
|
|
schArr.forEach((sch, i) => {
|
|
let schCxt;
|
|
if ((0, util_1.alwaysValidSchema)(it, sch)) {
|
|
gen.var(schValid, true);
|
|
} else {
|
|
schCxt = cxt.subschema({
|
|
keyword: "oneOf",
|
|
schemaProp: i,
|
|
compositeRule: true
|
|
}, schValid);
|
|
}
|
|
if (i > 0) {
|
|
gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i}]`).else();
|
|
}
|
|
gen.if(schValid, () => {
|
|
gen.assign(valid, true);
|
|
gen.assign(passing, i);
|
|
if (schCxt)
|
|
cxt.mergeEvaluated(schCxt, codegen_1.Name);
|
|
});
|
|
});
|
|
}
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_allOf2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var util_1 = require_util2();
|
|
var def = {
|
|
keyword: "allOf",
|
|
schemaType: "array",
|
|
code(cxt) {
|
|
const { gen, schema, it } = cxt;
|
|
if (!Array.isArray(schema))
|
|
throw new Error("ajv implementation error");
|
|
const valid = gen.name("valid");
|
|
schema.forEach((sch, i) => {
|
|
if ((0, util_1.alwaysValidSchema)(it, sch))
|
|
return;
|
|
const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i }, valid);
|
|
cxt.ok(valid);
|
|
cxt.mergeEvaluated(schCxt);
|
|
});
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_if2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var codegen_1 = require_codegen2();
|
|
var util_1 = require_util2();
|
|
var error2 = {
|
|
message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`,
|
|
params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}`
|
|
};
|
|
var def = {
|
|
keyword: "if",
|
|
schemaType: ["object", "boolean"],
|
|
trackErrors: true,
|
|
error: error2,
|
|
code(cxt) {
|
|
const { gen, parentSchema, it } = cxt;
|
|
if (parentSchema.then === void 0 && parentSchema.else === void 0) {
|
|
(0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored');
|
|
}
|
|
const hasThen = hasSchema(it, "then");
|
|
const hasElse = hasSchema(it, "else");
|
|
if (!hasThen && !hasElse)
|
|
return;
|
|
const valid = gen.let("valid", true);
|
|
const schValid = gen.name("_valid");
|
|
validateIf();
|
|
cxt.reset();
|
|
if (hasThen && hasElse) {
|
|
const ifClause = gen.let("ifClause");
|
|
cxt.setParams({ ifClause });
|
|
gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause));
|
|
} else if (hasThen) {
|
|
gen.if(schValid, validateClause("then"));
|
|
} else {
|
|
gen.if((0, codegen_1.not)(schValid), validateClause("else"));
|
|
}
|
|
cxt.pass(valid, () => cxt.error(true));
|
|
function validateIf() {
|
|
const schCxt = cxt.subschema({
|
|
keyword: "if",
|
|
compositeRule: true,
|
|
createErrors: false,
|
|
allErrors: false
|
|
}, schValid);
|
|
cxt.mergeEvaluated(schCxt);
|
|
}
|
|
function validateClause(keyword, ifClause) {
|
|
return () => {
|
|
const schCxt = cxt.subschema({ keyword }, schValid);
|
|
gen.assign(valid, schValid);
|
|
cxt.mergeValidEvaluated(schCxt, valid);
|
|
if (ifClause)
|
|
gen.assign(ifClause, (0, codegen_1._)`${keyword}`);
|
|
else
|
|
cxt.setParams({ ifClause: keyword });
|
|
};
|
|
}
|
|
}
|
|
};
|
|
function hasSchema(it, keyword) {
|
|
const schema = it.schema[keyword];
|
|
return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema);
|
|
}
|
|
exports.default = def;
|
|
});
|
|
var require_thenElse2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var util_1 = require_util2();
|
|
var def = {
|
|
keyword: ["then", "else"],
|
|
schemaType: ["object", "boolean"],
|
|
code({ keyword, parentSchema, it }) {
|
|
if (parentSchema.if === void 0)
|
|
(0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`);
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_applicator2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var additionalItems_1 = require_additionalItems2();
|
|
var prefixItems_1 = require_prefixItems2();
|
|
var items_1 = require_items2();
|
|
var items2020_1 = require_items20202();
|
|
var contains_1 = require_contains2();
|
|
var dependencies_1 = require_dependencies2();
|
|
var propertyNames_1 = require_propertyNames2();
|
|
var additionalProperties_1 = require_additionalProperties2();
|
|
var properties_1 = require_properties2();
|
|
var patternProperties_1 = require_patternProperties2();
|
|
var not_1 = require_not2();
|
|
var anyOf_1 = require_anyOf2();
|
|
var oneOf_1 = require_oneOf2();
|
|
var allOf_1 = require_allOf2();
|
|
var if_1 = require_if2();
|
|
var thenElse_1 = require_thenElse2();
|
|
function getApplicator(draft2020 = false) {
|
|
const applicator = [
|
|
not_1.default,
|
|
anyOf_1.default,
|
|
oneOf_1.default,
|
|
allOf_1.default,
|
|
if_1.default,
|
|
thenElse_1.default,
|
|
propertyNames_1.default,
|
|
additionalProperties_1.default,
|
|
dependencies_1.default,
|
|
properties_1.default,
|
|
patternProperties_1.default
|
|
];
|
|
if (draft2020)
|
|
applicator.push(prefixItems_1.default, items2020_1.default);
|
|
else
|
|
applicator.push(additionalItems_1.default, items_1.default);
|
|
applicator.push(contains_1.default);
|
|
return applicator;
|
|
}
|
|
exports.default = getApplicator;
|
|
});
|
|
var require_format3 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var codegen_1 = require_codegen2();
|
|
var error2 = {
|
|
message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`,
|
|
params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}`
|
|
};
|
|
var def = {
|
|
keyword: "format",
|
|
type: ["number", "string"],
|
|
schemaType: "string",
|
|
$data: true,
|
|
error: error2,
|
|
code(cxt, ruleType) {
|
|
const { gen, data, $data, schema, schemaCode, it } = cxt;
|
|
const { opts, errSchemaPath, schemaEnv, self: self2 } = it;
|
|
if (!opts.validateFormats)
|
|
return;
|
|
if ($data)
|
|
validate$DataFormat();
|
|
else
|
|
validateFormat();
|
|
function validate$DataFormat() {
|
|
const fmts = gen.scopeValue("formats", {
|
|
ref: self2.formats,
|
|
code: opts.code.formats
|
|
});
|
|
const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`);
|
|
const fType = gen.let("fType");
|
|
const format = gen.let("format");
|
|
gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format, fDef));
|
|
cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt()));
|
|
function unknownFmt() {
|
|
if (opts.strictSchema === false)
|
|
return codegen_1.nil;
|
|
return (0, codegen_1._)`${schemaCode} && !${format}`;
|
|
}
|
|
function invalidFmt() {
|
|
const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` : (0, codegen_1._)`${format}(${data})`;
|
|
const validData = (0, codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`;
|
|
return (0, codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`;
|
|
}
|
|
}
|
|
function validateFormat() {
|
|
const formatDef = self2.formats[schema];
|
|
if (!formatDef) {
|
|
unknownFormat();
|
|
return;
|
|
}
|
|
if (formatDef === true)
|
|
return;
|
|
const [fmtType, format, fmtRef] = getFormat(formatDef);
|
|
if (fmtType === ruleType)
|
|
cxt.pass(validCondition());
|
|
function unknownFormat() {
|
|
if (opts.strictSchema === false) {
|
|
self2.logger.warn(unknownMsg());
|
|
return;
|
|
}
|
|
throw new Error(unknownMsg());
|
|
function unknownMsg() {
|
|
return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`;
|
|
}
|
|
}
|
|
function getFormat(fmtDef) {
|
|
const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : void 0;
|
|
const fmt = gen.scopeValue("formats", { key: schema, ref: fmtDef, code });
|
|
if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) {
|
|
return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._)`${fmt}.validate`];
|
|
}
|
|
return ["string", fmtDef, fmt];
|
|
}
|
|
function validCondition() {
|
|
if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) {
|
|
if (!schemaEnv.$async)
|
|
throw new Error("async format in sync schema");
|
|
return (0, codegen_1._)`await ${fmtRef}(${data})`;
|
|
}
|
|
return typeof format == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`;
|
|
}
|
|
}
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_format4 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var format_1 = require_format3();
|
|
var format = [format_1.default];
|
|
exports.default = format;
|
|
});
|
|
var require_metadata2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.contentVocabulary = exports.metadataVocabulary = void 0;
|
|
exports.metadataVocabulary = [
|
|
"title",
|
|
"description",
|
|
"default",
|
|
"deprecated",
|
|
"readOnly",
|
|
"writeOnly",
|
|
"examples"
|
|
];
|
|
exports.contentVocabulary = [
|
|
"contentMediaType",
|
|
"contentEncoding",
|
|
"contentSchema"
|
|
];
|
|
});
|
|
var require_draft72 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var core_1 = require_core4();
|
|
var validation_1 = require_validation2();
|
|
var applicator_1 = require_applicator2();
|
|
var format_1 = require_format4();
|
|
var metadata_1 = require_metadata2();
|
|
var draft7Vocabularies = [
|
|
core_1.default,
|
|
validation_1.default,
|
|
(0, applicator_1.default)(),
|
|
format_1.default,
|
|
metadata_1.metadataVocabulary,
|
|
metadata_1.contentVocabulary
|
|
];
|
|
exports.default = draft7Vocabularies;
|
|
});
|
|
var require_types2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.DiscrError = void 0;
|
|
var DiscrError;
|
|
(function(DiscrError2) {
|
|
DiscrError2["Tag"] = "tag";
|
|
DiscrError2["Mapping"] = "mapping";
|
|
})(DiscrError || (exports.DiscrError = DiscrError = {}));
|
|
});
|
|
var require_discriminator2 = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var codegen_1 = require_codegen2();
|
|
var types_1 = require_types2();
|
|
var compile_1 = require_compile2();
|
|
var ref_error_1 = require_ref_error2();
|
|
var util_1 = require_util2();
|
|
var error2 = {
|
|
message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`,
|
|
params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`
|
|
};
|
|
var def = {
|
|
keyword: "discriminator",
|
|
type: "object",
|
|
schemaType: "object",
|
|
error: error2,
|
|
code(cxt) {
|
|
const { gen, data, schema, parentSchema, it } = cxt;
|
|
const { oneOf } = parentSchema;
|
|
if (!it.opts.discriminator) {
|
|
throw new Error("discriminator: requires discriminator option");
|
|
}
|
|
const tagName = schema.propertyName;
|
|
if (typeof tagName != "string")
|
|
throw new Error("discriminator: requires propertyName");
|
|
if (schema.mapping)
|
|
throw new Error("discriminator: mapping is not supported");
|
|
if (!oneOf)
|
|
throw new Error("discriminator: requires oneOf keyword");
|
|
const valid = gen.let("valid", false);
|
|
const tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`);
|
|
gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName }));
|
|
cxt.ok(valid);
|
|
function validateMapping() {
|
|
const mapping = getMapping();
|
|
gen.if(false);
|
|
for (const tagValue in mapping) {
|
|
gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`);
|
|
gen.assign(valid, applyTagSchema(mapping[tagValue]));
|
|
}
|
|
gen.else();
|
|
cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName });
|
|
gen.endIf();
|
|
}
|
|
function applyTagSchema(schemaProp) {
|
|
const _valid = gen.name("valid");
|
|
const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid);
|
|
cxt.mergeEvaluated(schCxt, codegen_1.Name);
|
|
return _valid;
|
|
}
|
|
function getMapping() {
|
|
var _a;
|
|
const oneOfMapping = {};
|
|
const topRequired = hasRequired(parentSchema);
|
|
let tagRequired = true;
|
|
for (let i = 0; i < oneOf.length; i++) {
|
|
let sch = oneOf[i];
|
|
if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) {
|
|
const ref = sch.$ref;
|
|
sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref);
|
|
if (sch instanceof compile_1.SchemaEnv)
|
|
sch = sch.schema;
|
|
if (sch === void 0)
|
|
throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref);
|
|
}
|
|
const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName];
|
|
if (typeof propSch != "object") {
|
|
throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`);
|
|
}
|
|
tagRequired = tagRequired && (topRequired || hasRequired(sch));
|
|
addMappings(propSch, i);
|
|
}
|
|
if (!tagRequired)
|
|
throw new Error(`discriminator: "${tagName}" must be required`);
|
|
return oneOfMapping;
|
|
function hasRequired({ required: required2 }) {
|
|
return Array.isArray(required2) && required2.includes(tagName);
|
|
}
|
|
function addMappings(sch, i) {
|
|
if (sch.const) {
|
|
addMapping(sch.const, i);
|
|
} else if (sch.enum) {
|
|
for (const tagValue of sch.enum) {
|
|
addMapping(tagValue, i);
|
|
}
|
|
} else {
|
|
throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`);
|
|
}
|
|
}
|
|
function addMapping(tagValue, i) {
|
|
if (typeof tagValue != "string" || tagValue in oneOfMapping) {
|
|
throw new Error(`discriminator: "${tagName}" values must be unique strings`);
|
|
}
|
|
oneOfMapping[tagValue] = i;
|
|
}
|
|
}
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
var require_json_schema_draft_072 = __commonJS((exports, module2) => {
|
|
module2.exports = {
|
|
$schema: "http://json-schema.org/draft-07/schema#",
|
|
$id: "http://json-schema.org/draft-07/schema#",
|
|
title: "Core schema meta-schema",
|
|
definitions: {
|
|
schemaArray: {
|
|
type: "array",
|
|
minItems: 1,
|
|
items: { $ref: "#" }
|
|
},
|
|
nonNegativeInteger: {
|
|
type: "integer",
|
|
minimum: 0
|
|
},
|
|
nonNegativeIntegerDefault0: {
|
|
allOf: [{ $ref: "#/definitions/nonNegativeInteger" }, { default: 0 }]
|
|
},
|
|
simpleTypes: {
|
|
enum: ["array", "boolean", "integer", "null", "number", "object", "string"]
|
|
},
|
|
stringArray: {
|
|
type: "array",
|
|
items: { type: "string" },
|
|
uniqueItems: true,
|
|
default: []
|
|
}
|
|
},
|
|
type: ["object", "boolean"],
|
|
properties: {
|
|
$id: {
|
|
type: "string",
|
|
format: "uri-reference"
|
|
},
|
|
$schema: {
|
|
type: "string",
|
|
format: "uri"
|
|
},
|
|
$ref: {
|
|
type: "string",
|
|
format: "uri-reference"
|
|
},
|
|
$comment: {
|
|
type: "string"
|
|
},
|
|
title: {
|
|
type: "string"
|
|
},
|
|
description: {
|
|
type: "string"
|
|
},
|
|
default: true,
|
|
readOnly: {
|
|
type: "boolean",
|
|
default: false
|
|
},
|
|
examples: {
|
|
type: "array",
|
|
items: true
|
|
},
|
|
multipleOf: {
|
|
type: "number",
|
|
exclusiveMinimum: 0
|
|
},
|
|
maximum: {
|
|
type: "number"
|
|
},
|
|
exclusiveMaximum: {
|
|
type: "number"
|
|
},
|
|
minimum: {
|
|
type: "number"
|
|
},
|
|
exclusiveMinimum: {
|
|
type: "number"
|
|
},
|
|
maxLength: { $ref: "#/definitions/nonNegativeInteger" },
|
|
minLength: { $ref: "#/definitions/nonNegativeIntegerDefault0" },
|
|
pattern: {
|
|
type: "string",
|
|
format: "regex"
|
|
},
|
|
additionalItems: { $ref: "#" },
|
|
items: {
|
|
anyOf: [{ $ref: "#" }, { $ref: "#/definitions/schemaArray" }],
|
|
default: true
|
|
},
|
|
maxItems: { $ref: "#/definitions/nonNegativeInteger" },
|
|
minItems: { $ref: "#/definitions/nonNegativeIntegerDefault0" },
|
|
uniqueItems: {
|
|
type: "boolean",
|
|
default: false
|
|
},
|
|
contains: { $ref: "#" },
|
|
maxProperties: { $ref: "#/definitions/nonNegativeInteger" },
|
|
minProperties: { $ref: "#/definitions/nonNegativeIntegerDefault0" },
|
|
required: { $ref: "#/definitions/stringArray" },
|
|
additionalProperties: { $ref: "#" },
|
|
definitions: {
|
|
type: "object",
|
|
additionalProperties: { $ref: "#" },
|
|
default: {}
|
|
},
|
|
properties: {
|
|
type: "object",
|
|
additionalProperties: { $ref: "#" },
|
|
default: {}
|
|
},
|
|
patternProperties: {
|
|
type: "object",
|
|
additionalProperties: { $ref: "#" },
|
|
propertyNames: { format: "regex" },
|
|
default: {}
|
|
},
|
|
dependencies: {
|
|
type: "object",
|
|
additionalProperties: {
|
|
anyOf: [{ $ref: "#" }, { $ref: "#/definitions/stringArray" }]
|
|
}
|
|
},
|
|
propertyNames: { $ref: "#" },
|
|
const: true,
|
|
enum: {
|
|
type: "array",
|
|
items: true,
|
|
minItems: 1,
|
|
uniqueItems: true
|
|
},
|
|
type: {
|
|
anyOf: [
|
|
{ $ref: "#/definitions/simpleTypes" },
|
|
{
|
|
type: "array",
|
|
items: { $ref: "#/definitions/simpleTypes" },
|
|
minItems: 1,
|
|
uniqueItems: true
|
|
}
|
|
]
|
|
},
|
|
format: { type: "string" },
|
|
contentMediaType: { type: "string" },
|
|
contentEncoding: { type: "string" },
|
|
if: { $ref: "#" },
|
|
then: { $ref: "#" },
|
|
else: { $ref: "#" },
|
|
allOf: { $ref: "#/definitions/schemaArray" },
|
|
anyOf: { $ref: "#/definitions/schemaArray" },
|
|
oneOf: { $ref: "#/definitions/schemaArray" },
|
|
not: { $ref: "#" }
|
|
},
|
|
default: true
|
|
};
|
|
});
|
|
var require_ajv2 = __commonJS((exports, module2) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0;
|
|
var core_1 = require_core3();
|
|
var draft7_1 = require_draft72();
|
|
var discriminator_1 = require_discriminator2();
|
|
var draft7MetaSchema = require_json_schema_draft_072();
|
|
var META_SUPPORT_DATA = ["/properties"];
|
|
var META_SCHEMA_ID = "http://json-schema.org/draft-07/schema";
|
|
class Ajv extends core_1.default {
|
|
_addVocabularies() {
|
|
super._addVocabularies();
|
|
draft7_1.default.forEach((v) => this.addVocabulary(v));
|
|
if (this.opts.discriminator)
|
|
this.addKeyword(discriminator_1.default);
|
|
}
|
|
_addDefaultMetaSchema() {
|
|
super._addDefaultMetaSchema();
|
|
if (!this.opts.meta)
|
|
return;
|
|
const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema;
|
|
this.addMetaSchema(metaSchema, META_SCHEMA_ID, false);
|
|
this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID;
|
|
}
|
|
defaultMeta() {
|
|
return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0);
|
|
}
|
|
}
|
|
exports.Ajv = Ajv;
|
|
module2.exports = exports = Ajv;
|
|
module2.exports.Ajv = Ajv;
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.default = Ajv;
|
|
var validate_1 = require_validate2();
|
|
Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() {
|
|
return validate_1.KeywordCxt;
|
|
} });
|
|
var codegen_1 = require_codegen2();
|
|
Object.defineProperty(exports, "_", { enumerable: true, get: function() {
|
|
return codegen_1._;
|
|
} });
|
|
Object.defineProperty(exports, "str", { enumerable: true, get: function() {
|
|
return codegen_1.str;
|
|
} });
|
|
Object.defineProperty(exports, "stringify", { enumerable: true, get: function() {
|
|
return codegen_1.stringify;
|
|
} });
|
|
Object.defineProperty(exports, "nil", { enumerable: true, get: function() {
|
|
return codegen_1.nil;
|
|
} });
|
|
Object.defineProperty(exports, "Name", { enumerable: true, get: function() {
|
|
return codegen_1.Name;
|
|
} });
|
|
Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() {
|
|
return codegen_1.CodeGen;
|
|
} });
|
|
var validation_error_1 = require_validation_error2();
|
|
Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function() {
|
|
return validation_error_1.default;
|
|
} });
|
|
var ref_error_1 = require_ref_error2();
|
|
Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function() {
|
|
return ref_error_1.default;
|
|
} });
|
|
});
|
|
var require_limit = __commonJS((exports) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.formatLimitDefinition = void 0;
|
|
var ajv_1 = require_ajv2();
|
|
var codegen_1 = require_codegen2();
|
|
var ops = codegen_1.operators;
|
|
var KWDs = {
|
|
formatMaximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT },
|
|
formatMinimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT },
|
|
formatExclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE },
|
|
formatExclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE }
|
|
};
|
|
var error2 = {
|
|
message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`,
|
|
params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`
|
|
};
|
|
exports.formatLimitDefinition = {
|
|
keyword: Object.keys(KWDs),
|
|
type: "string",
|
|
schemaType: "string",
|
|
$data: true,
|
|
error: error2,
|
|
code(cxt) {
|
|
const { gen, data, schemaCode, keyword, it } = cxt;
|
|
const { opts, self: self2 } = it;
|
|
if (!opts.validateFormats)
|
|
return;
|
|
const fCxt = new ajv_1.KeywordCxt(it, self2.RULES.all.format.definition, "format");
|
|
if (fCxt.$data)
|
|
validate$DataFormat();
|
|
else
|
|
validateFormat();
|
|
function validate$DataFormat() {
|
|
const fmts = gen.scopeValue("formats", {
|
|
ref: self2.formats,
|
|
code: opts.code.formats
|
|
});
|
|
const fmt = gen.const("fmt", (0, codegen_1._)`${fmts}[${fCxt.schemaCode}]`);
|
|
cxt.fail$data((0, codegen_1.or)((0, codegen_1._)`typeof ${fmt} != "object"`, (0, codegen_1._)`${fmt} instanceof RegExp`, (0, codegen_1._)`typeof ${fmt}.compare != "function"`, compareCode(fmt)));
|
|
}
|
|
function validateFormat() {
|
|
const format = fCxt.schema;
|
|
const fmtDef = self2.formats[format];
|
|
if (!fmtDef || fmtDef === true)
|
|
return;
|
|
if (typeof fmtDef != "object" || fmtDef instanceof RegExp || typeof fmtDef.compare != "function") {
|
|
throw new Error(`"${keyword}": format "${format}" does not define "compare" function`);
|
|
}
|
|
const fmt = gen.scopeValue("formats", {
|
|
key: format,
|
|
ref: fmtDef,
|
|
code: opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(format)}` : void 0
|
|
});
|
|
cxt.fail$data(compareCode(fmt));
|
|
}
|
|
function compareCode(fmt) {
|
|
return (0, codegen_1._)`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`;
|
|
}
|
|
},
|
|
dependencies: ["format"]
|
|
};
|
|
var formatLimitPlugin = (ajv) => {
|
|
ajv.addKeyword(exports.formatLimitDefinition);
|
|
return ajv;
|
|
};
|
|
exports.default = formatLimitPlugin;
|
|
});
|
|
var require_dist = __commonJS((exports, module2) => {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var formats_1 = require_formats();
|
|
var limit_1 = require_limit();
|
|
var codegen_1 = require_codegen2();
|
|
var fullName = new codegen_1.Name("fullFormats");
|
|
var fastName = new codegen_1.Name("fastFormats");
|
|
var formatsPlugin = (ajv, opts = { keywords: true }) => {
|
|
if (Array.isArray(opts)) {
|
|
addFormats(ajv, opts, formats_1.fullFormats, fullName);
|
|
return ajv;
|
|
}
|
|
const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName];
|
|
const list = opts.formats || formats_1.formatNames;
|
|
addFormats(ajv, list, formats, exportName);
|
|
if (opts.keywords)
|
|
(0, limit_1.default)(ajv);
|
|
return ajv;
|
|
};
|
|
formatsPlugin.get = (name, mode = "full") => {
|
|
const formats = mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats;
|
|
const f = formats[name];
|
|
if (!f)
|
|
throw new Error(`Unknown format "${name}"`);
|
|
return f;
|
|
};
|
|
function addFormats(ajv, list, fs22, exportName) {
|
|
var _a;
|
|
var _b;
|
|
(_a = (_b = ajv.opts.code).formats) !== null && _a !== void 0 || (_b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`);
|
|
for (const f of list)
|
|
ajv.addFormat(f, fs22[f]);
|
|
}
|
|
module2.exports = exports = formatsPlugin;
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.default = formatsPlugin;
|
|
});
|
|
var DEFAULT_MAX_LISTENERS = 50;
|
|
function createAbortController(maxListeners = DEFAULT_MAX_LISTENERS) {
|
|
const controller = new AbortController();
|
|
(0, import_events.setMaxListeners)(maxListeners, controller.signal);
|
|
return controller;
|
|
}
|
|
var freeGlobal = typeof global == "object" && global && global.Object === Object && global;
|
|
var _freeGlobal_default = freeGlobal;
|
|
var freeSelf = typeof self == "object" && self && self.Object === Object && self;
|
|
var root = _freeGlobal_default || freeSelf || Function("return this")();
|
|
var _root_default = root;
|
|
var Symbol2 = _root_default.Symbol;
|
|
var _Symbol_default = Symbol2;
|
|
var objectProto = Object.prototype;
|
|
var hasOwnProperty = objectProto.hasOwnProperty;
|
|
var nativeObjectToString = objectProto.toString;
|
|
var symToStringTag = _Symbol_default ? _Symbol_default.toStringTag : void 0;
|
|
function getRawTag(value) {
|
|
var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag];
|
|
try {
|
|
value[symToStringTag] = void 0;
|
|
var unmasked = true;
|
|
} catch (e) {
|
|
}
|
|
var result = nativeObjectToString.call(value);
|
|
if (unmasked) {
|
|
if (isOwn) {
|
|
value[symToStringTag] = tag;
|
|
} else {
|
|
delete value[symToStringTag];
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
var _getRawTag_default = getRawTag;
|
|
var objectProto2 = Object.prototype;
|
|
var nativeObjectToString2 = objectProto2.toString;
|
|
function objectToString(value) {
|
|
return nativeObjectToString2.call(value);
|
|
}
|
|
var _objectToString_default = objectToString;
|
|
var nullTag = "[object Null]";
|
|
var undefinedTag = "[object Undefined]";
|
|
var symToStringTag2 = _Symbol_default ? _Symbol_default.toStringTag : void 0;
|
|
function baseGetTag(value) {
|
|
if (value == null) {
|
|
return value === void 0 ? undefinedTag : nullTag;
|
|
}
|
|
return symToStringTag2 && symToStringTag2 in Object(value) ? _getRawTag_default(value) : _objectToString_default(value);
|
|
}
|
|
var _baseGetTag_default = baseGetTag;
|
|
function isObject(value) {
|
|
var type = typeof value;
|
|
return value != null && (type == "object" || type == "function");
|
|
}
|
|
var isObject_default = isObject;
|
|
var asyncTag = "[object AsyncFunction]";
|
|
var funcTag = "[object Function]";
|
|
var genTag = "[object GeneratorFunction]";
|
|
var proxyTag = "[object Proxy]";
|
|
function isFunction(value) {
|
|
if (!isObject_default(value)) {
|
|
return false;
|
|
}
|
|
var tag = _baseGetTag_default(value);
|
|
return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
|
|
}
|
|
var isFunction_default = isFunction;
|
|
var coreJsData = _root_default["__core-js_shared__"];
|
|
var _coreJsData_default = coreJsData;
|
|
var maskSrcKey = (function() {
|
|
var uid = /[^.]+$/.exec(_coreJsData_default && _coreJsData_default.keys && _coreJsData_default.keys.IE_PROTO || "");
|
|
return uid ? "Symbol(src)_1." + uid : "";
|
|
})();
|
|
function isMasked(func) {
|
|
return !!maskSrcKey && maskSrcKey in func;
|
|
}
|
|
var _isMasked_default = isMasked;
|
|
var funcProto = Function.prototype;
|
|
var funcToString = funcProto.toString;
|
|
function toSource(func) {
|
|
if (func != null) {
|
|
try {
|
|
return funcToString.call(func);
|
|
} catch (e) {
|
|
}
|
|
try {
|
|
return func + "";
|
|
} catch (e) {
|
|
}
|
|
}
|
|
return "";
|
|
}
|
|
var _toSource_default = toSource;
|
|
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
|
|
var reIsHostCtor = /^\[object .+?Constructor\]$/;
|
|
var funcProto2 = Function.prototype;
|
|
var objectProto3 = Object.prototype;
|
|
var funcToString2 = funcProto2.toString;
|
|
var hasOwnProperty2 = objectProto3.hasOwnProperty;
|
|
var reIsNative = RegExp("^" + funcToString2.call(hasOwnProperty2).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$");
|
|
function baseIsNative(value) {
|
|
if (!isObject_default(value) || _isMasked_default(value)) {
|
|
return false;
|
|
}
|
|
var pattern = isFunction_default(value) ? reIsNative : reIsHostCtor;
|
|
return pattern.test(_toSource_default(value));
|
|
}
|
|
var _baseIsNative_default = baseIsNative;
|
|
function getValue(object, key) {
|
|
return object == null ? void 0 : object[key];
|
|
}
|
|
var _getValue_default = getValue;
|
|
function getNative(object, key) {
|
|
var value = _getValue_default(object, key);
|
|
return _baseIsNative_default(value) ? value : void 0;
|
|
}
|
|
var _getNative_default = getNative;
|
|
var nativeCreate = _getNative_default(Object, "create");
|
|
var _nativeCreate_default = nativeCreate;
|
|
function hashClear() {
|
|
this.__data__ = _nativeCreate_default ? _nativeCreate_default(null) : {};
|
|
this.size = 0;
|
|
}
|
|
var _hashClear_default = hashClear;
|
|
function hashDelete(key) {
|
|
var result = this.has(key) && delete this.__data__[key];
|
|
this.size -= result ? 1 : 0;
|
|
return result;
|
|
}
|
|
var _hashDelete_default = hashDelete;
|
|
var HASH_UNDEFINED = "__lodash_hash_undefined__";
|
|
var objectProto4 = Object.prototype;
|
|
var hasOwnProperty3 = objectProto4.hasOwnProperty;
|
|
function hashGet(key) {
|
|
var data = this.__data__;
|
|
if (_nativeCreate_default) {
|
|
var result = data[key];
|
|
return result === HASH_UNDEFINED ? void 0 : result;
|
|
}
|
|
return hasOwnProperty3.call(data, key) ? data[key] : void 0;
|
|
}
|
|
var _hashGet_default = hashGet;
|
|
var objectProto5 = Object.prototype;
|
|
var hasOwnProperty4 = objectProto5.hasOwnProperty;
|
|
function hashHas(key) {
|
|
var data = this.__data__;
|
|
return _nativeCreate_default ? data[key] !== void 0 : hasOwnProperty4.call(data, key);
|
|
}
|
|
var _hashHas_default = hashHas;
|
|
var HASH_UNDEFINED2 = "__lodash_hash_undefined__";
|
|
function hashSet(key, value) {
|
|
var data = this.__data__;
|
|
this.size += this.has(key) ? 0 : 1;
|
|
data[key] = _nativeCreate_default && value === void 0 ? HASH_UNDEFINED2 : value;
|
|
return this;
|
|
}
|
|
var _hashSet_default = hashSet;
|
|
function Hash(entries) {
|
|
var index = -1, length = entries == null ? 0 : entries.length;
|
|
this.clear();
|
|
while (++index < length) {
|
|
var entry = entries[index];
|
|
this.set(entry[0], entry[1]);
|
|
}
|
|
}
|
|
Hash.prototype.clear = _hashClear_default;
|
|
Hash.prototype["delete"] = _hashDelete_default;
|
|
Hash.prototype.get = _hashGet_default;
|
|
Hash.prototype.has = _hashHas_default;
|
|
Hash.prototype.set = _hashSet_default;
|
|
var _Hash_default = Hash;
|
|
function listCacheClear() {
|
|
this.__data__ = [];
|
|
this.size = 0;
|
|
}
|
|
var _listCacheClear_default = listCacheClear;
|
|
function eq(value, other) {
|
|
return value === other || value !== value && other !== other;
|
|
}
|
|
var eq_default = eq;
|
|
function assocIndexOf(array2, key) {
|
|
var length = array2.length;
|
|
while (length--) {
|
|
if (eq_default(array2[length][0], key)) {
|
|
return length;
|
|
}
|
|
}
|
|
return -1;
|
|
}
|
|
var _assocIndexOf_default = assocIndexOf;
|
|
var arrayProto = Array.prototype;
|
|
var splice = arrayProto.splice;
|
|
function listCacheDelete(key) {
|
|
var data = this.__data__, index = _assocIndexOf_default(data, key);
|
|
if (index < 0) {
|
|
return false;
|
|
}
|
|
var lastIndex = data.length - 1;
|
|
if (index == lastIndex) {
|
|
data.pop();
|
|
} else {
|
|
splice.call(data, index, 1);
|
|
}
|
|
--this.size;
|
|
return true;
|
|
}
|
|
var _listCacheDelete_default = listCacheDelete;
|
|
function listCacheGet(key) {
|
|
var data = this.__data__, index = _assocIndexOf_default(data, key);
|
|
return index < 0 ? void 0 : data[index][1];
|
|
}
|
|
var _listCacheGet_default = listCacheGet;
|
|
function listCacheHas(key) {
|
|
return _assocIndexOf_default(this.__data__, key) > -1;
|
|
}
|
|
var _listCacheHas_default = listCacheHas;
|
|
function listCacheSet(key, value) {
|
|
var data = this.__data__, index = _assocIndexOf_default(data, key);
|
|
if (index < 0) {
|
|
++this.size;
|
|
data.push([key, value]);
|
|
} else {
|
|
data[index][1] = value;
|
|
}
|
|
return this;
|
|
}
|
|
var _listCacheSet_default = listCacheSet;
|
|
function ListCache(entries) {
|
|
var index = -1, length = entries == null ? 0 : entries.length;
|
|
this.clear();
|
|
while (++index < length) {
|
|
var entry = entries[index];
|
|
this.set(entry[0], entry[1]);
|
|
}
|
|
}
|
|
ListCache.prototype.clear = _listCacheClear_default;
|
|
ListCache.prototype["delete"] = _listCacheDelete_default;
|
|
ListCache.prototype.get = _listCacheGet_default;
|
|
ListCache.prototype.has = _listCacheHas_default;
|
|
ListCache.prototype.set = _listCacheSet_default;
|
|
var _ListCache_default = ListCache;
|
|
var Map2 = _getNative_default(_root_default, "Map");
|
|
var _Map_default = Map2;
|
|
function mapCacheClear() {
|
|
this.size = 0;
|
|
this.__data__ = {
|
|
hash: new _Hash_default(),
|
|
map: new (_Map_default || _ListCache_default)(),
|
|
string: new _Hash_default()
|
|
};
|
|
}
|
|
var _mapCacheClear_default = mapCacheClear;
|
|
function isKeyable(value) {
|
|
var type = typeof value;
|
|
return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null;
|
|
}
|
|
var _isKeyable_default = isKeyable;
|
|
function getMapData(map, key) {
|
|
var data = map.__data__;
|
|
return _isKeyable_default(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map;
|
|
}
|
|
var _getMapData_default = getMapData;
|
|
function mapCacheDelete(key) {
|
|
var result = _getMapData_default(this, key)["delete"](key);
|
|
this.size -= result ? 1 : 0;
|
|
return result;
|
|
}
|
|
var _mapCacheDelete_default = mapCacheDelete;
|
|
function mapCacheGet(key) {
|
|
return _getMapData_default(this, key).get(key);
|
|
}
|
|
var _mapCacheGet_default = mapCacheGet;
|
|
function mapCacheHas(key) {
|
|
return _getMapData_default(this, key).has(key);
|
|
}
|
|
var _mapCacheHas_default = mapCacheHas;
|
|
function mapCacheSet(key, value) {
|
|
var data = _getMapData_default(this, key), size = data.size;
|
|
data.set(key, value);
|
|
this.size += data.size == size ? 0 : 1;
|
|
return this;
|
|
}
|
|
var _mapCacheSet_default = mapCacheSet;
|
|
function MapCache(entries) {
|
|
var index = -1, length = entries == null ? 0 : entries.length;
|
|
this.clear();
|
|
while (++index < length) {
|
|
var entry = entries[index];
|
|
this.set(entry[0], entry[1]);
|
|
}
|
|
}
|
|
MapCache.prototype.clear = _mapCacheClear_default;
|
|
MapCache.prototype["delete"] = _mapCacheDelete_default;
|
|
MapCache.prototype.get = _mapCacheGet_default;
|
|
MapCache.prototype.has = _mapCacheHas_default;
|
|
MapCache.prototype.set = _mapCacheSet_default;
|
|
var _MapCache_default = MapCache;
|
|
var FUNC_ERROR_TEXT = "Expected a function";
|
|
function memoize(func, resolver) {
|
|
if (typeof func != "function" || resolver != null && typeof resolver != "function") {
|
|
throw new TypeError(FUNC_ERROR_TEXT);
|
|
}
|
|
var memoized = function() {
|
|
var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache;
|
|
if (cache.has(key)) {
|
|
return cache.get(key);
|
|
}
|
|
var result = func.apply(this, args);
|
|
memoized.cache = cache.set(key, result) || cache;
|
|
return result;
|
|
};
|
|
memoized.cache = new (memoize.Cache || _MapCache_default)();
|
|
return memoized;
|
|
}
|
|
memoize.Cache = _MapCache_default;
|
|
var memoize_default = memoize;
|
|
var CHUNK_SIZE = 2e3;
|
|
function writeToStderr(data) {
|
|
for (let i = 0; i < data.length; i += CHUNK_SIZE) {
|
|
process.stderr.write(data.substring(i, i + CHUNK_SIZE));
|
|
}
|
|
}
|
|
var parseDebugFilter = memoize_default((filterString) => {
|
|
if (!filterString || filterString.trim() === "") {
|
|
return null;
|
|
}
|
|
const filters = filterString.split(",").map((f) => f.trim()).filter(Boolean);
|
|
if (filters.length === 0) {
|
|
return null;
|
|
}
|
|
const hasExclusive = filters.some((f) => f.startsWith("!"));
|
|
const hasInclusive = filters.some((f) => !f.startsWith("!"));
|
|
if (hasExclusive && hasInclusive) {
|
|
return null;
|
|
}
|
|
const cleanFilters = filters.map((f) => f.replace(/^!/, "").toLowerCase());
|
|
return {
|
|
include: hasExclusive ? [] : cleanFilters,
|
|
exclude: hasExclusive ? cleanFilters : [],
|
|
isExclusive: hasExclusive
|
|
};
|
|
});
|
|
function extractDebugCategories(message) {
|
|
const categories = [];
|
|
const mcpMatch = message.match(/^MCP server ["']([^"']+)["']/);
|
|
if (mcpMatch && mcpMatch[1]) {
|
|
categories.push("mcp");
|
|
categories.push(mcpMatch[1].toLowerCase());
|
|
} else {
|
|
const prefixMatch = message.match(/^([^:[]+):/);
|
|
if (prefixMatch && prefixMatch[1]) {
|
|
categories.push(prefixMatch[1].trim().toLowerCase());
|
|
}
|
|
}
|
|
const bracketMatch = message.match(/^\[([^\]]+)]/);
|
|
if (bracketMatch && bracketMatch[1]) {
|
|
categories.push(bracketMatch[1].trim().toLowerCase());
|
|
}
|
|
if (message.toLowerCase().includes("statsig event:")) {
|
|
categories.push("statsig");
|
|
}
|
|
const secondaryMatch = message.match(/:\s*([^:]+?)(?:\s+(?:type|mode|status|event))?:/);
|
|
if (secondaryMatch && secondaryMatch[1]) {
|
|
const secondary = secondaryMatch[1].trim().toLowerCase();
|
|
if (secondary.length < 30 && !secondary.includes(" ")) {
|
|
categories.push(secondary);
|
|
}
|
|
}
|
|
return Array.from(new Set(categories));
|
|
}
|
|
function shouldShowDebugCategories(categories, filter) {
|
|
if (!filter) {
|
|
return true;
|
|
}
|
|
if (categories.length === 0) {
|
|
return false;
|
|
}
|
|
if (filter.isExclusive) {
|
|
return !categories.some((cat) => filter.exclude.includes(cat));
|
|
} else {
|
|
return categories.some((cat) => filter.include.includes(cat));
|
|
}
|
|
}
|
|
function shouldShowDebugMessage(message, filter) {
|
|
if (!filter) {
|
|
return true;
|
|
}
|
|
const categories = extractDebugCategories(message);
|
|
return shouldShowDebugCategories(categories, filter);
|
|
}
|
|
function getClaudeConfigHomeDir() {
|
|
var _a;
|
|
return (_a = process.env.CLAUDE_CONFIG_DIR) != null ? _a : (0, import_path2.join)((0, import_os.homedir)(), ".claude");
|
|
}
|
|
function isEnvTruthy(envVar) {
|
|
if (!envVar)
|
|
return false;
|
|
if (typeof envVar === "boolean")
|
|
return envVar;
|
|
const normalizedValue = envVar.toLowerCase().trim();
|
|
return ["1", "true", "yes", "on"].includes(normalizedValue);
|
|
}
|
|
var bashMaxOutputLengthValidator = {
|
|
name: "BASH_MAX_OUTPUT_LENGTH",
|
|
default: 3e4,
|
|
validate: (value) => {
|
|
const MAX_OUTPUT_LENGTH = 15e4;
|
|
const DEFAULT_MAX_OUTPUT_LENGTH = 3e4;
|
|
if (!value) {
|
|
return {
|
|
effective: DEFAULT_MAX_OUTPUT_LENGTH,
|
|
status: "valid"
|
|
};
|
|
}
|
|
const parsed = parseInt(value, 10);
|
|
if (isNaN(parsed) || parsed <= 0) {
|
|
return {
|
|
effective: DEFAULT_MAX_OUTPUT_LENGTH,
|
|
status: "invalid",
|
|
message: `Invalid value "${value}" (using default: ${DEFAULT_MAX_OUTPUT_LENGTH})`
|
|
};
|
|
}
|
|
if (parsed > MAX_OUTPUT_LENGTH) {
|
|
return {
|
|
effective: MAX_OUTPUT_LENGTH,
|
|
status: "capped",
|
|
message: `Capped from ${parsed} to ${MAX_OUTPUT_LENGTH}`
|
|
};
|
|
}
|
|
return { effective: parsed, status: "valid" };
|
|
}
|
|
};
|
|
var maxOutputTokensValidator = {
|
|
name: "CLAUDE_CODE_MAX_OUTPUT_TOKENS",
|
|
default: 32e3,
|
|
validate: (value) => {
|
|
const MAX_OUTPUT_TOKENS = 64e3;
|
|
const DEFAULT_MAX_OUTPUT_TOKENS = 32e3;
|
|
if (!value) {
|
|
return { effective: DEFAULT_MAX_OUTPUT_TOKENS, status: "valid" };
|
|
}
|
|
const parsed = parseInt(value, 10);
|
|
if (isNaN(parsed) || parsed <= 0) {
|
|
return {
|
|
effective: DEFAULT_MAX_OUTPUT_TOKENS,
|
|
status: "invalid",
|
|
message: `Invalid value "${value}" (using default: ${DEFAULT_MAX_OUTPUT_TOKENS})`
|
|
};
|
|
}
|
|
if (parsed > MAX_OUTPUT_TOKENS) {
|
|
return {
|
|
effective: MAX_OUTPUT_TOKENS,
|
|
status: "capped",
|
|
message: `Capped from ${parsed} to ${MAX_OUTPUT_TOKENS}`
|
|
};
|
|
}
|
|
return { effective: parsed, status: "valid" };
|
|
}
|
|
};
|
|
function getInitialState() {
|
|
let resolvedCwd = "";
|
|
if (typeof process !== "undefined" && typeof process.cwd === "function") {
|
|
resolvedCwd = (0, import_fs.realpathSync)((0, import_process.cwd)());
|
|
}
|
|
return {
|
|
originalCwd: resolvedCwd,
|
|
totalCostUSD: 0,
|
|
totalAPIDuration: 0,
|
|
totalAPIDurationWithoutRetries: 0,
|
|
totalToolDuration: 0,
|
|
startTime: Date.now(),
|
|
lastInteractionTime: Date.now(),
|
|
totalLinesAdded: 0,
|
|
totalLinesRemoved: 0,
|
|
hasUnknownModelCost: false,
|
|
cwd: resolvedCwd,
|
|
modelUsage: {},
|
|
mainLoopModelOverride: void 0,
|
|
initialMainLoopModel: null,
|
|
modelStrings: null,
|
|
isInteractive: false,
|
|
clientType: "cli",
|
|
sessionIngressToken: void 0,
|
|
oauthTokenFromFd: void 0,
|
|
apiKeyFromFd: void 0,
|
|
flagSettingsPath: void 0,
|
|
allowedSettingSources: [
|
|
"userSettings",
|
|
"projectSettings",
|
|
"localSettings",
|
|
"flagSettings",
|
|
"policySettings"
|
|
],
|
|
meter: null,
|
|
sessionCounter: null,
|
|
locCounter: null,
|
|
prCounter: null,
|
|
commitCounter: null,
|
|
costCounter: null,
|
|
tokenCounter: null,
|
|
codeEditToolDecisionCounter: null,
|
|
activeTimeCounter: null,
|
|
sessionId: (0, import_crypto.randomUUID)(),
|
|
loggerProvider: null,
|
|
eventLogger: null,
|
|
meterProvider: null,
|
|
tracerProvider: null,
|
|
agentColorMap: /* @__PURE__ */ new Map(),
|
|
agentColorIndex: 0,
|
|
envVarValidators: [bashMaxOutputLengthValidator, maxOutputTokensValidator],
|
|
lastAPIRequest: null,
|
|
inMemoryErrorLog: [],
|
|
inlinePlugins: [],
|
|
sessionBypassPermissionsMode: false,
|
|
sessionPersistenceDisabled: false,
|
|
hasExitedPlanMode: false,
|
|
needsPlanModeExitAttachment: false,
|
|
hasExitedDelegateMode: false,
|
|
needsDelegateModeExitAttachment: false,
|
|
lspRecommendationShownThisSession: false,
|
|
initJsonSchema: null,
|
|
registeredHooks: null,
|
|
planSlugCache: /* @__PURE__ */ new Map(),
|
|
teleportedSessionInfo: null,
|
|
invokedSkills: /* @__PURE__ */ new Map()
|
|
};
|
|
}
|
|
var STATE = getInitialState();
|
|
function getSessionId() {
|
|
return STATE.sessionId;
|
|
}
|
|
function createBufferedWriter({
|
|
writeFn,
|
|
flushIntervalMs = 1e3,
|
|
maxBufferSize = 100,
|
|
immediateMode = false
|
|
}) {
|
|
let buffer = [];
|
|
let flushTimer = null;
|
|
function clearTimer() {
|
|
if (flushTimer) {
|
|
clearTimeout(flushTimer);
|
|
flushTimer = null;
|
|
}
|
|
}
|
|
function flush() {
|
|
if (buffer.length === 0)
|
|
return;
|
|
writeFn(buffer.join(""));
|
|
buffer = [];
|
|
clearTimer();
|
|
}
|
|
function scheduleFlush() {
|
|
if (!flushTimer) {
|
|
flushTimer = setTimeout(flush, flushIntervalMs);
|
|
}
|
|
}
|
|
return {
|
|
write(content) {
|
|
if (immediateMode) {
|
|
writeFn(content);
|
|
return;
|
|
}
|
|
buffer.push(content);
|
|
scheduleFlush();
|
|
if (buffer.length >= maxBufferSize) {
|
|
flush();
|
|
}
|
|
},
|
|
flush,
|
|
dispose() {
|
|
flush();
|
|
}
|
|
};
|
|
}
|
|
var cleanupFunctions = /* @__PURE__ */ new Set();
|
|
function registerCleanup(cleanupFn) {
|
|
cleanupFunctions.add(cleanupFn);
|
|
return () => cleanupFunctions.delete(cleanupFn);
|
|
}
|
|
var isDebugMode = memoize_default(() => {
|
|
return isEnvTruthy(process.env.DEBUG) || isEnvTruthy(process.env.DEBUG_SDK) || process.argv.includes("--debug") || process.argv.includes("-d") || isDebugToStdErr() || process.argv.some((arg) => arg.startsWith("--debug="));
|
|
});
|
|
var getDebugFilter = memoize_default(() => {
|
|
const debugArg = process.argv.find((arg) => arg.startsWith("--debug="));
|
|
if (!debugArg) {
|
|
return null;
|
|
}
|
|
const filterPattern = debugArg.substring("--debug=".length);
|
|
return parseDebugFilter(filterPattern);
|
|
});
|
|
var isDebugToStdErr = memoize_default(() => {
|
|
return process.argv.includes("--debug-to-stderr") || process.argv.includes("-d2e");
|
|
});
|
|
function shouldLogDebugMessage(message) {
|
|
if (false) {
|
|
}
|
|
if (typeof process === "undefined" || typeof process.versions === "undefined" || typeof process.versions.node === "undefined") {
|
|
return false;
|
|
}
|
|
const filter = getDebugFilter();
|
|
return shouldShowDebugMessage(message, filter);
|
|
}
|
|
var hasFormattedOutput = false;
|
|
var debugWriter = null;
|
|
function getDebugWriter() {
|
|
if (!debugWriter) {
|
|
debugWriter = createBufferedWriter({
|
|
writeFn: (content) => {
|
|
const path12 = getDebugLogPath();
|
|
if (!getFsImplementation().existsSync((0, import_path3.dirname)(path12))) {
|
|
getFsImplementation().mkdirSync((0, import_path3.dirname)(path12));
|
|
}
|
|
getFsImplementation().appendFileSync(path12, content);
|
|
updateLatestDebugLogSymlink();
|
|
},
|
|
flushIntervalMs: 1e3,
|
|
maxBufferSize: 100,
|
|
immediateMode: isDebugMode()
|
|
});
|
|
registerCleanup(async () => debugWriter == null ? void 0 : debugWriter.dispose());
|
|
}
|
|
return debugWriter;
|
|
}
|
|
function logForDebugging(message, { level } = {
|
|
level: "debug"
|
|
}) {
|
|
if (!shouldLogDebugMessage(message)) {
|
|
return;
|
|
}
|
|
if (hasFormattedOutput && message.includes(`
|
|
`)) {
|
|
message = JSON.stringify(message);
|
|
}
|
|
const timestamp = (/* @__PURE__ */ new Date()).toISOString();
|
|
const output = `${timestamp} [${level.toUpperCase()}] ${message.trim()}
|
|
`;
|
|
if (isDebugToStdErr()) {
|
|
writeToStderr(output);
|
|
return;
|
|
}
|
|
getDebugWriter().write(output);
|
|
}
|
|
function getDebugLogPath() {
|
|
var _a;
|
|
return (_a = process.env.CLAUDE_CODE_DEBUG_LOGS_DIR) != null ? _a : (0, import_path3.join)(getClaudeConfigHomeDir(), "debug", `${getSessionId()}.txt`);
|
|
}
|
|
var updateLatestDebugLogSymlink = memoize_default(() => {
|
|
if (process.argv[2] === "--ripgrep") {
|
|
return;
|
|
}
|
|
try {
|
|
const debugLogPath = getDebugLogPath();
|
|
const debugLogsDir = (0, import_path3.dirname)(debugLogPath);
|
|
const latestSymlinkPath = (0, import_path3.join)(debugLogsDir, "latest");
|
|
if (!getFsImplementation().existsSync(debugLogsDir)) {
|
|
getFsImplementation().mkdirSync(debugLogsDir);
|
|
}
|
|
if (getFsImplementation().existsSync(latestSymlinkPath)) {
|
|
try {
|
|
getFsImplementation().unlinkSync(latestSymlinkPath);
|
|
} catch (e) {
|
|
}
|
|
}
|
|
getFsImplementation().symlinkSync(debugLogPath, latestSymlinkPath);
|
|
} catch (e) {
|
|
}
|
|
});
|
|
var SLOW_SYNC_THRESHOLD_MS = 5;
|
|
function withSlowLogging(operation, fn) {
|
|
const startTime = performance.now();
|
|
try {
|
|
return fn();
|
|
} finally {
|
|
const duration3 = performance.now() - startTime;
|
|
if (duration3 > SLOW_SYNC_THRESHOLD_MS) {
|
|
logForDebugging(`[SLOW OPERATION DETECTED] fs.${operation} (${duration3.toFixed(1)}ms)`);
|
|
}
|
|
}
|
|
}
|
|
var NodeFsOperations = {
|
|
cwd() {
|
|
return process.cwd();
|
|
},
|
|
existsSync(fsPath) {
|
|
return withSlowLogging("existsSync", () => fs.existsSync(fsPath));
|
|
},
|
|
async stat(fsPath) {
|
|
return (0, import_promises.stat)(fsPath);
|
|
},
|
|
statSync(fsPath) {
|
|
return withSlowLogging("statSync", () => fs.statSync(fsPath));
|
|
},
|
|
lstatSync(fsPath) {
|
|
return withSlowLogging("lstatSync", () => fs.lstatSync(fsPath));
|
|
},
|
|
readFileSync(fsPath, options) {
|
|
return withSlowLogging("readFileSync", () => fs.readFileSync(fsPath, { encoding: options.encoding }));
|
|
},
|
|
readFileBytesSync(fsPath) {
|
|
return withSlowLogging("readFileBytesSync", () => fs.readFileSync(fsPath));
|
|
},
|
|
readSync(fsPath, options) {
|
|
return withSlowLogging("readSync", () => {
|
|
let fd = void 0;
|
|
try {
|
|
fd = fs.openSync(fsPath, "r");
|
|
const buffer = Buffer.alloc(options.length);
|
|
const bytesRead = fs.readSync(fd, buffer, 0, options.length, 0);
|
|
return { buffer, bytesRead };
|
|
} finally {
|
|
if (fd)
|
|
fs.closeSync(fd);
|
|
}
|
|
});
|
|
},
|
|
writeFileSync(fsPath, data, options) {
|
|
return withSlowLogging("writeFileSync", () => {
|
|
var _a, _b;
|
|
const fileExists = fs.existsSync(fsPath);
|
|
if (!options.flush) {
|
|
const writeOptions = {
|
|
encoding: options.encoding
|
|
};
|
|
if (!fileExists) {
|
|
writeOptions.mode = (_a = options.mode) != null ? _a : 384;
|
|
} else if (options.mode !== void 0) {
|
|
writeOptions.mode = options.mode;
|
|
}
|
|
fs.writeFileSync(fsPath, data, writeOptions);
|
|
return;
|
|
}
|
|
let fd;
|
|
try {
|
|
const mode = !fileExists ? (_b = options.mode) != null ? _b : 384 : options.mode;
|
|
fd = fs.openSync(fsPath, "w", mode);
|
|
fs.writeFileSync(fd, data, { encoding: options.encoding });
|
|
fs.fsyncSync(fd);
|
|
} finally {
|
|
if (fd) {
|
|
fs.closeSync(fd);
|
|
}
|
|
}
|
|
});
|
|
},
|
|
appendFileSync(path12, data, options) {
|
|
return withSlowLogging("appendFileSync", () => {
|
|
var _a;
|
|
if (!fs.existsSync(path12)) {
|
|
const mode = (_a = options == null ? void 0 : options.mode) != null ? _a : 384;
|
|
const fd = fs.openSync(path12, "a", mode);
|
|
try {
|
|
fs.appendFileSync(fd, data);
|
|
} finally {
|
|
fs.closeSync(fd);
|
|
}
|
|
} else {
|
|
fs.appendFileSync(path12, data);
|
|
}
|
|
});
|
|
},
|
|
copyFileSync(src, dest) {
|
|
return withSlowLogging("copyFileSync", () => fs.copyFileSync(src, dest));
|
|
},
|
|
unlinkSync(path12) {
|
|
return withSlowLogging("unlinkSync", () => fs.unlinkSync(path12));
|
|
},
|
|
renameSync(oldPath, newPath) {
|
|
return withSlowLogging("renameSync", () => fs.renameSync(oldPath, newPath));
|
|
},
|
|
linkSync(target, path12) {
|
|
return withSlowLogging("linkSync", () => fs.linkSync(target, path12));
|
|
},
|
|
symlinkSync(target, path12) {
|
|
return withSlowLogging("symlinkSync", () => fs.symlinkSync(target, path12));
|
|
},
|
|
readlinkSync(path12) {
|
|
return withSlowLogging("readlinkSync", () => fs.readlinkSync(path12));
|
|
},
|
|
realpathSync(path12) {
|
|
return withSlowLogging("realpathSync", () => fs.realpathSync(path12));
|
|
},
|
|
mkdirSync(dirPath) {
|
|
return withSlowLogging("mkdirSync", () => {
|
|
if (!fs.existsSync(dirPath)) {
|
|
fs.mkdirSync(dirPath, { recursive: true, mode: 448 });
|
|
}
|
|
});
|
|
},
|
|
readdirSync(dirPath) {
|
|
return withSlowLogging("readdirSync", () => fs.readdirSync(dirPath, { withFileTypes: true }));
|
|
},
|
|
readdirStringSync(dirPath) {
|
|
return withSlowLogging("readdirStringSync", () => fs.readdirSync(dirPath));
|
|
},
|
|
isDirEmptySync(dirPath) {
|
|
return withSlowLogging("isDirEmptySync", () => {
|
|
const files = this.readdirSync(dirPath);
|
|
return files.length === 0;
|
|
});
|
|
},
|
|
rmdirSync(dirPath) {
|
|
return withSlowLogging("rmdirSync", () => fs.rmdirSync(dirPath));
|
|
},
|
|
rmSync(path12, options) {
|
|
return withSlowLogging("rmSync", () => fs.rmSync(path12, options));
|
|
},
|
|
createWriteStream(path12) {
|
|
return fs.createWriteStream(path12);
|
|
}
|
|
};
|
|
var activeFs = NodeFsOperations;
|
|
function getFsImplementation() {
|
|
return activeFs;
|
|
}
|
|
var AbortError = class extends Error {
|
|
};
|
|
function isRunningWithBun() {
|
|
return process.versions.bun !== void 0;
|
|
}
|
|
var debugFilePath = null;
|
|
var initialized = false;
|
|
function getOrCreateDebugFile() {
|
|
if (initialized) {
|
|
return debugFilePath;
|
|
}
|
|
initialized = true;
|
|
if (!process.env.DEBUG_CLAUDE_AGENT_SDK) {
|
|
return null;
|
|
}
|
|
const debugDir = (0, import_path4.join)(getClaudeConfigHomeDir(), "debug");
|
|
debugFilePath = (0, import_path4.join)(debugDir, `sdk-${(0, import_crypto2.randomUUID)()}.txt`);
|
|
if (!(0, import_fs2.existsSync)(debugDir)) {
|
|
(0, import_fs2.mkdirSync)(debugDir, { recursive: true });
|
|
}
|
|
process.stderr.write(`SDK debug logs: ${debugFilePath}
|
|
`);
|
|
return debugFilePath;
|
|
}
|
|
function logForSdkDebugging(message) {
|
|
const path12 = getOrCreateDebugFile();
|
|
if (!path12) {
|
|
return;
|
|
}
|
|
const timestamp = (/* @__PURE__ */ new Date()).toISOString();
|
|
const output = `${timestamp} ${message}
|
|
`;
|
|
(0, import_fs2.appendFileSync)(path12, output);
|
|
}
|
|
function mergeSandboxIntoExtraArgs(extraArgs, sandbox) {
|
|
const effectiveExtraArgs = { ...extraArgs };
|
|
if (sandbox) {
|
|
let settingsObj = { sandbox };
|
|
if (effectiveExtraArgs.settings) {
|
|
try {
|
|
const existingSettings = JSON.parse(effectiveExtraArgs.settings);
|
|
settingsObj = { ...existingSettings, sandbox };
|
|
} catch (e) {
|
|
}
|
|
}
|
|
effectiveExtraArgs.settings = JSON.stringify(settingsObj);
|
|
}
|
|
return effectiveExtraArgs;
|
|
}
|
|
var ProcessTransport = class {
|
|
constructor(options) {
|
|
__publicField(this, "options");
|
|
__publicField(this, "process");
|
|
__publicField(this, "processStdin");
|
|
__publicField(this, "processStdout");
|
|
__publicField(this, "ready", false);
|
|
__publicField(this, "abortController");
|
|
__publicField(this, "exitError");
|
|
__publicField(this, "exitListeners", []);
|
|
__publicField(this, "processExitHandler");
|
|
__publicField(this, "abortHandler");
|
|
this.options = options;
|
|
this.abortController = options.abortController || createAbortController();
|
|
this.initialize();
|
|
}
|
|
getDefaultExecutable() {
|
|
return isRunningWithBun() ? "bun" : "node";
|
|
}
|
|
spawnLocalProcess(spawnOptions) {
|
|
const { command, args, cwd: cwd2, env, signal } = spawnOptions;
|
|
const stderrMode = env.DEBUG_CLAUDE_AGENT_SDK || this.options.stderr ? "pipe" : "ignore";
|
|
const childProcess = (0, import_child_process.spawn)(command, args, {
|
|
cwd: cwd2,
|
|
stdio: ["pipe", "pipe", stderrMode],
|
|
signal,
|
|
env,
|
|
windowsHide: true
|
|
});
|
|
if (env.DEBUG_CLAUDE_AGENT_SDK || this.options.stderr) {
|
|
childProcess.stderr.on("data", (data) => {
|
|
const message = data.toString();
|
|
logForSdkDebugging(message);
|
|
if (this.options.stderr) {
|
|
this.options.stderr(message);
|
|
}
|
|
});
|
|
}
|
|
const mappedProcess = {
|
|
stdin: childProcess.stdin,
|
|
stdout: childProcess.stdout,
|
|
get killed() {
|
|
return childProcess.killed;
|
|
},
|
|
get exitCode() {
|
|
return childProcess.exitCode;
|
|
},
|
|
kill: childProcess.kill.bind(childProcess),
|
|
on: childProcess.on.bind(childProcess),
|
|
once: childProcess.once.bind(childProcess),
|
|
off: childProcess.off.bind(childProcess)
|
|
};
|
|
return mappedProcess;
|
|
}
|
|
initialize() {
|
|
try {
|
|
const {
|
|
additionalDirectories = [],
|
|
betas,
|
|
cwd: cwd2,
|
|
executable = this.getDefaultExecutable(),
|
|
executableArgs = [],
|
|
extraArgs = {},
|
|
pathToClaudeCodeExecutable,
|
|
env = { ...process.env },
|
|
maxThinkingTokens,
|
|
maxTurns,
|
|
maxBudgetUsd,
|
|
model,
|
|
fallbackModel,
|
|
jsonSchema,
|
|
permissionMode,
|
|
allowDangerouslySkipPermissions,
|
|
permissionPromptToolName,
|
|
continueConversation,
|
|
resume,
|
|
settingSources,
|
|
allowedTools = [],
|
|
disallowedTools = [],
|
|
tools,
|
|
mcpServers,
|
|
strictMcpConfig,
|
|
canUseTool,
|
|
includePartialMessages,
|
|
plugins,
|
|
sandbox
|
|
} = this.options;
|
|
const args = [
|
|
"--output-format",
|
|
"stream-json",
|
|
"--verbose",
|
|
"--input-format",
|
|
"stream-json"
|
|
];
|
|
if (maxThinkingTokens !== void 0) {
|
|
args.push("--max-thinking-tokens", maxThinkingTokens.toString());
|
|
}
|
|
if (maxTurns)
|
|
args.push("--max-turns", maxTurns.toString());
|
|
if (maxBudgetUsd !== void 0) {
|
|
args.push("--max-budget-usd", maxBudgetUsd.toString());
|
|
}
|
|
if (model)
|
|
args.push("--model", model);
|
|
if (betas && betas.length > 0) {
|
|
args.push("--betas", betas.join(","));
|
|
}
|
|
if (jsonSchema) {
|
|
args.push("--json-schema", JSON.stringify(jsonSchema));
|
|
}
|
|
if (env.DEBUG_CLAUDE_AGENT_SDK) {
|
|
args.push("--debug-to-stderr");
|
|
}
|
|
if (canUseTool) {
|
|
if (permissionPromptToolName) {
|
|
throw new Error("canUseTool callback cannot be used with permissionPromptToolName. Please use one or the other.");
|
|
}
|
|
args.push("--permission-prompt-tool", "stdio");
|
|
} else if (permissionPromptToolName) {
|
|
args.push("--permission-prompt-tool", permissionPromptToolName);
|
|
}
|
|
if (continueConversation)
|
|
args.push("--continue");
|
|
if (resume)
|
|
args.push("--resume", resume);
|
|
if (allowedTools.length > 0) {
|
|
args.push("--allowedTools", allowedTools.join(","));
|
|
}
|
|
if (disallowedTools.length > 0) {
|
|
args.push("--disallowedTools", disallowedTools.join(","));
|
|
}
|
|
if (tools !== void 0) {
|
|
if (Array.isArray(tools)) {
|
|
if (tools.length === 0) {
|
|
args.push("--tools", "");
|
|
} else {
|
|
args.push("--tools", tools.join(","));
|
|
}
|
|
} else {
|
|
args.push("--tools", "default");
|
|
}
|
|
}
|
|
if (mcpServers && Object.keys(mcpServers).length > 0) {
|
|
args.push("--mcp-config", JSON.stringify({ mcpServers }));
|
|
}
|
|
if (settingSources) {
|
|
args.push("--setting-sources", settingSources.join(","));
|
|
}
|
|
if (strictMcpConfig) {
|
|
args.push("--strict-mcp-config");
|
|
}
|
|
if (permissionMode) {
|
|
args.push("--permission-mode", permissionMode);
|
|
}
|
|
if (allowDangerouslySkipPermissions) {
|
|
args.push("--allow-dangerously-skip-permissions");
|
|
}
|
|
if (fallbackModel) {
|
|
if (model && fallbackModel === model) {
|
|
throw new Error("Fallback model cannot be the same as the main model. Please specify a different model for fallbackModel option.");
|
|
}
|
|
args.push("--fallback-model", fallbackModel);
|
|
}
|
|
if (includePartialMessages) {
|
|
args.push("--include-partial-messages");
|
|
}
|
|
for (const dir of additionalDirectories) {
|
|
args.push("--add-dir", dir);
|
|
}
|
|
if (plugins && plugins.length > 0) {
|
|
for (const plugin of plugins) {
|
|
if (plugin.type === "local") {
|
|
args.push("--plugin-dir", plugin.path);
|
|
} else {
|
|
throw new Error(`Unsupported plugin type: ${plugin.type}`);
|
|
}
|
|
}
|
|
}
|
|
if (this.options.forkSession) {
|
|
args.push("--fork-session");
|
|
}
|
|
if (this.options.resumeSessionAt) {
|
|
args.push("--resume-session-at", this.options.resumeSessionAt);
|
|
}
|
|
if (this.options.persistSession === false) {
|
|
args.push("--no-session-persistence");
|
|
}
|
|
const effectiveExtraArgs = mergeSandboxIntoExtraArgs(extraArgs != null ? extraArgs : {}, sandbox);
|
|
for (const [flag, value] of Object.entries(effectiveExtraArgs)) {
|
|
if (value === null) {
|
|
args.push(`--${flag}`);
|
|
} else {
|
|
args.push(`--${flag}`, value);
|
|
}
|
|
}
|
|
if (!env.CLAUDE_CODE_ENTRYPOINT) {
|
|
env.CLAUDE_CODE_ENTRYPOINT = "sdk-ts";
|
|
}
|
|
delete env.NODE_OPTIONS;
|
|
if (env.DEBUG_CLAUDE_AGENT_SDK) {
|
|
env.DEBUG = "1";
|
|
} else {
|
|
delete env.DEBUG;
|
|
}
|
|
const isNative = isNativeBinary(pathToClaudeCodeExecutable);
|
|
const spawnCommand = isNative ? pathToClaudeCodeExecutable : executable;
|
|
const spawnArgs = isNative ? [...executableArgs, ...args] : [...executableArgs, pathToClaudeCodeExecutable, ...args];
|
|
const spawnOptions = {
|
|
command: spawnCommand,
|
|
args: spawnArgs,
|
|
cwd: cwd2,
|
|
env,
|
|
signal: this.abortController.signal
|
|
};
|
|
if (this.options.spawnClaudeCodeProcess) {
|
|
logForSdkDebugging(`Spawning Claude Code (custom): ${spawnCommand} ${spawnArgs.join(" ")}`);
|
|
this.process = this.options.spawnClaudeCodeProcess(spawnOptions);
|
|
} else {
|
|
const fs22 = getFsImplementation();
|
|
if (!fs22.existsSync(pathToClaudeCodeExecutable)) {
|
|
const errorMessage = isNative ? `Claude Code native binary not found at ${pathToClaudeCodeExecutable}. Please ensure Claude Code is installed via native installer or specify a valid path with options.pathToClaudeCodeExecutable.` : `Claude Code executable not found at ${pathToClaudeCodeExecutable}. Is options.pathToClaudeCodeExecutable set?`;
|
|
throw new ReferenceError(errorMessage);
|
|
}
|
|
logForSdkDebugging(`Spawning Claude Code: ${spawnCommand} ${spawnArgs.join(" ")}`);
|
|
this.process = this.spawnLocalProcess(spawnOptions);
|
|
}
|
|
this.processStdin = this.process.stdin;
|
|
this.processStdout = this.process.stdout;
|
|
const cleanup = () => {
|
|
if (this.process && !this.process.killed) {
|
|
this.process.kill("SIGTERM");
|
|
}
|
|
};
|
|
this.processExitHandler = cleanup;
|
|
this.abortHandler = cleanup;
|
|
process.on("exit", this.processExitHandler);
|
|
this.abortController.signal.addEventListener("abort", this.abortHandler);
|
|
this.process.on("error", (error2) => {
|
|
this.ready = false;
|
|
if (this.abortController.signal.aborted) {
|
|
this.exitError = new AbortError("Claude Code process aborted by user");
|
|
} else {
|
|
this.exitError = new Error(`Failed to spawn Claude Code process: ${error2.message}`);
|
|
logForSdkDebugging(this.exitError.message);
|
|
}
|
|
});
|
|
this.process.on("exit", (code, signal) => {
|
|
this.ready = false;
|
|
if (this.abortController.signal.aborted) {
|
|
this.exitError = new AbortError("Claude Code process aborted by user");
|
|
} else {
|
|
const error2 = this.getProcessExitError(code, signal);
|
|
if (error2) {
|
|
this.exitError = error2;
|
|
logForSdkDebugging(error2.message);
|
|
}
|
|
}
|
|
});
|
|
this.ready = true;
|
|
} catch (error2) {
|
|
this.ready = false;
|
|
throw error2;
|
|
}
|
|
}
|
|
getProcessExitError(code, signal) {
|
|
if (code !== 0 && code !== null) {
|
|
return new Error(`Claude Code process exited with code ${code}`);
|
|
} else if (signal) {
|
|
return new Error(`Claude Code process terminated by signal ${signal}`);
|
|
}
|
|
return;
|
|
}
|
|
write(data) {
|
|
var _a, _b;
|
|
if (this.abortController.signal.aborted) {
|
|
throw new AbortError("Operation aborted");
|
|
}
|
|
if (!this.ready || !this.processStdin) {
|
|
throw new Error("ProcessTransport is not ready for writing");
|
|
}
|
|
if (((_a = this.process) == null ? void 0 : _a.killed) || ((_b = this.process) == null ? void 0 : _b.exitCode) !== null) {
|
|
throw new Error("Cannot write to terminated process");
|
|
}
|
|
if (this.exitError) {
|
|
throw new Error(`Cannot write to process that exited with error: ${this.exitError.message}`);
|
|
}
|
|
logForSdkDebugging(`[ProcessTransport] Writing to stdin: ${data.substring(0, 100)}`);
|
|
try {
|
|
const written = this.processStdin.write(data);
|
|
if (!written) {
|
|
logForSdkDebugging("[ProcessTransport] Write buffer full, data queued");
|
|
}
|
|
} catch (error2) {
|
|
this.ready = false;
|
|
throw new Error(`Failed to write to process stdin: ${error2.message}`);
|
|
}
|
|
}
|
|
close() {
|
|
var _a;
|
|
if (this.processStdin) {
|
|
this.processStdin.end();
|
|
this.processStdin = void 0;
|
|
}
|
|
if (this.abortHandler) {
|
|
this.abortController.signal.removeEventListener("abort", this.abortHandler);
|
|
this.abortHandler = void 0;
|
|
}
|
|
for (const { handler } of this.exitListeners) {
|
|
(_a = this.process) == null ? void 0 : _a.off("exit", handler);
|
|
}
|
|
this.exitListeners = [];
|
|
if (this.process && !this.process.killed) {
|
|
this.process.kill("SIGTERM");
|
|
setTimeout(() => {
|
|
if (this.process && !this.process.killed) {
|
|
this.process.kill("SIGKILL");
|
|
}
|
|
}, 5e3);
|
|
}
|
|
this.ready = false;
|
|
if (this.processExitHandler) {
|
|
process.off("exit", this.processExitHandler);
|
|
this.processExitHandler = void 0;
|
|
}
|
|
}
|
|
isReady() {
|
|
return this.ready;
|
|
}
|
|
async *readMessages() {
|
|
if (!this.processStdout) {
|
|
throw new Error("ProcessTransport output stream not available");
|
|
}
|
|
const rl = (0, import_readline.createInterface)({ input: this.processStdout });
|
|
try {
|
|
for await (const line of rl) {
|
|
if (line.trim()) {
|
|
const message = JSON.parse(line);
|
|
yield message;
|
|
}
|
|
}
|
|
await this.waitForExit();
|
|
} catch (error2) {
|
|
throw error2;
|
|
} finally {
|
|
rl.close();
|
|
}
|
|
}
|
|
endInput() {
|
|
if (this.processStdin) {
|
|
this.processStdin.end();
|
|
}
|
|
}
|
|
getInputStream() {
|
|
return this.processStdin;
|
|
}
|
|
onExit(callback) {
|
|
if (!this.process)
|
|
return () => {
|
|
};
|
|
const handler = (code, signal) => {
|
|
const error2 = this.getProcessExitError(code, signal);
|
|
callback(error2);
|
|
};
|
|
this.process.on("exit", handler);
|
|
this.exitListeners.push({ callback, handler });
|
|
return () => {
|
|
if (this.process) {
|
|
this.process.off("exit", handler);
|
|
}
|
|
const index = this.exitListeners.findIndex((l) => l.handler === handler);
|
|
if (index !== -1) {
|
|
this.exitListeners.splice(index, 1);
|
|
}
|
|
};
|
|
}
|
|
async waitForExit() {
|
|
if (!this.process) {
|
|
if (this.exitError) {
|
|
throw this.exitError;
|
|
}
|
|
return;
|
|
}
|
|
if (this.process.exitCode !== null || this.process.killed) {
|
|
if (this.exitError) {
|
|
throw this.exitError;
|
|
}
|
|
return;
|
|
}
|
|
return new Promise((resolve7, reject) => {
|
|
const exitHandler = (code, signal) => {
|
|
if (this.abortController.signal.aborted) {
|
|
reject(new AbortError("Operation aborted"));
|
|
return;
|
|
}
|
|
const error2 = this.getProcessExitError(code, signal);
|
|
if (error2) {
|
|
reject(error2);
|
|
} else {
|
|
resolve7();
|
|
}
|
|
};
|
|
this.process.once("exit", exitHandler);
|
|
const errorHandler = (error2) => {
|
|
this.process.off("exit", exitHandler);
|
|
reject(error2);
|
|
};
|
|
this.process.once("error", errorHandler);
|
|
this.process.once("exit", () => {
|
|
this.process.off("error", errorHandler);
|
|
});
|
|
});
|
|
}
|
|
};
|
|
function isNativeBinary(executablePath) {
|
|
const jsExtensions = [".js", ".mjs", ".tsx", ".ts", ".jsx"];
|
|
return !jsExtensions.some((ext) => executablePath.endsWith(ext));
|
|
}
|
|
var Stream = class {
|
|
constructor(returned) {
|
|
__publicField(this, "returned");
|
|
__publicField(this, "queue", []);
|
|
__publicField(this, "readResolve");
|
|
__publicField(this, "readReject");
|
|
__publicField(this, "isDone", false);
|
|
__publicField(this, "hasError");
|
|
__publicField(this, "started", false);
|
|
this.returned = returned;
|
|
}
|
|
[Symbol.asyncIterator]() {
|
|
if (this.started) {
|
|
throw new Error("Stream can only be iterated once");
|
|
}
|
|
this.started = true;
|
|
return this;
|
|
}
|
|
next() {
|
|
if (this.queue.length > 0) {
|
|
return Promise.resolve({
|
|
done: false,
|
|
value: this.queue.shift()
|
|
});
|
|
}
|
|
if (this.isDone) {
|
|
return Promise.resolve({ done: true, value: void 0 });
|
|
}
|
|
if (this.hasError) {
|
|
return Promise.reject(this.hasError);
|
|
}
|
|
return new Promise((resolve7, reject) => {
|
|
this.readResolve = resolve7;
|
|
this.readReject = reject;
|
|
});
|
|
}
|
|
enqueue(value) {
|
|
if (this.readResolve) {
|
|
const resolve7 = this.readResolve;
|
|
this.readResolve = void 0;
|
|
this.readReject = void 0;
|
|
resolve7({ done: false, value });
|
|
} else {
|
|
this.queue.push(value);
|
|
}
|
|
}
|
|
done() {
|
|
this.isDone = true;
|
|
if (this.readResolve) {
|
|
const resolve7 = this.readResolve;
|
|
this.readResolve = void 0;
|
|
this.readReject = void 0;
|
|
resolve7({ done: true, value: void 0 });
|
|
}
|
|
}
|
|
error(error2) {
|
|
this.hasError = error2;
|
|
if (this.readReject) {
|
|
const reject = this.readReject;
|
|
this.readResolve = void 0;
|
|
this.readReject = void 0;
|
|
reject(error2);
|
|
}
|
|
}
|
|
return() {
|
|
this.isDone = true;
|
|
if (this.returned) {
|
|
this.returned();
|
|
}
|
|
return Promise.resolve({ done: true, value: void 0 });
|
|
}
|
|
};
|
|
var SdkControlServerTransport = class {
|
|
constructor(sendMcpMessage) {
|
|
__publicField(this, "sendMcpMessage");
|
|
__publicField(this, "isClosed", false);
|
|
__publicField(this, "onclose");
|
|
__publicField(this, "onerror");
|
|
__publicField(this, "onmessage");
|
|
this.sendMcpMessage = sendMcpMessage;
|
|
}
|
|
async start() {
|
|
}
|
|
async send(message) {
|
|
if (this.isClosed) {
|
|
throw new Error("Transport is closed");
|
|
}
|
|
this.sendMcpMessage(message);
|
|
}
|
|
async close() {
|
|
var _a;
|
|
if (this.isClosed) {
|
|
return;
|
|
}
|
|
this.isClosed = true;
|
|
(_a = this.onclose) == null ? void 0 : _a.call(this);
|
|
}
|
|
};
|
|
var Query = class {
|
|
constructor(transport, isSingleUserTurn, canUseTool, hooks, abortController, sdkMcpServers = /* @__PURE__ */ new Map(), jsonSchema, initConfig) {
|
|
__publicField(this, "transport");
|
|
__publicField(this, "isSingleUserTurn");
|
|
__publicField(this, "canUseTool");
|
|
__publicField(this, "hooks");
|
|
__publicField(this, "abortController");
|
|
__publicField(this, "jsonSchema");
|
|
__publicField(this, "initConfig");
|
|
__publicField(this, "pendingControlResponses", /* @__PURE__ */ new Map());
|
|
__publicField(this, "cleanupPerformed", false);
|
|
__publicField(this, "sdkMessages");
|
|
__publicField(this, "inputStream", new Stream());
|
|
__publicField(this, "initialization");
|
|
__publicField(this, "cancelControllers", /* @__PURE__ */ new Map());
|
|
__publicField(this, "hookCallbacks", /* @__PURE__ */ new Map());
|
|
__publicField(this, "nextCallbackId", 0);
|
|
__publicField(this, "sdkMcpTransports", /* @__PURE__ */ new Map());
|
|
__publicField(this, "sdkMcpServerInstances", /* @__PURE__ */ new Map());
|
|
__publicField(this, "pendingMcpResponses", /* @__PURE__ */ new Map());
|
|
__publicField(this, "firstResultReceivedResolve");
|
|
__publicField(this, "firstResultReceived", false);
|
|
this.transport = transport;
|
|
this.isSingleUserTurn = isSingleUserTurn;
|
|
this.canUseTool = canUseTool;
|
|
this.hooks = hooks;
|
|
this.abortController = abortController;
|
|
this.jsonSchema = jsonSchema;
|
|
this.initConfig = initConfig;
|
|
for (const [name, server] of sdkMcpServers) {
|
|
this.connectSdkMcpServer(name, server);
|
|
}
|
|
this.sdkMessages = this.readSdkMessages();
|
|
this.readMessages();
|
|
this.initialization = this.initialize();
|
|
this.initialization.catch(() => {
|
|
});
|
|
}
|
|
hasBidirectionalNeeds() {
|
|
return this.sdkMcpTransports.size > 0 || this.hooks !== void 0 && Object.keys(this.hooks).length > 0 || this.canUseTool !== void 0;
|
|
}
|
|
setError(error2) {
|
|
this.inputStream.error(error2);
|
|
}
|
|
cleanup(error2) {
|
|
if (this.cleanupPerformed)
|
|
return;
|
|
this.cleanupPerformed = true;
|
|
try {
|
|
this.transport.close();
|
|
this.pendingControlResponses.clear();
|
|
this.pendingMcpResponses.clear();
|
|
this.cancelControllers.clear();
|
|
this.hookCallbacks.clear();
|
|
for (const transport of this.sdkMcpTransports.values()) {
|
|
try {
|
|
transport.close();
|
|
} catch (e) {
|
|
}
|
|
}
|
|
this.sdkMcpTransports.clear();
|
|
if (error2) {
|
|
this.inputStream.error(error2);
|
|
} else {
|
|
this.inputStream.done();
|
|
}
|
|
} catch (_error) {
|
|
}
|
|
}
|
|
next(...[value]) {
|
|
return this.sdkMessages.next(...[value]);
|
|
}
|
|
return(value) {
|
|
return this.sdkMessages.return(value);
|
|
}
|
|
throw(e) {
|
|
return this.sdkMessages.throw(e);
|
|
}
|
|
[Symbol.asyncIterator]() {
|
|
return this.sdkMessages;
|
|
}
|
|
[Symbol.asyncDispose]() {
|
|
return this.sdkMessages[Symbol.asyncDispose]();
|
|
}
|
|
async readMessages() {
|
|
try {
|
|
for await (const message of this.transport.readMessages()) {
|
|
if (message.type === "control_response") {
|
|
const handler = this.pendingControlResponses.get(message.response.request_id);
|
|
if (handler) {
|
|
handler(message.response);
|
|
}
|
|
continue;
|
|
} else if (message.type === "control_request") {
|
|
this.handleControlRequest(message);
|
|
continue;
|
|
} else if (message.type === "control_cancel_request") {
|
|
this.handleControlCancelRequest(message);
|
|
continue;
|
|
} else if (message.type === "keep_alive") {
|
|
continue;
|
|
}
|
|
if (message.type === "result") {
|
|
this.firstResultReceived = true;
|
|
if (this.firstResultReceivedResolve) {
|
|
this.firstResultReceivedResolve();
|
|
}
|
|
if (this.isSingleUserTurn) {
|
|
logForDebugging(`[Query.readMessages] First result received for single-turn query, closing stdin`);
|
|
this.transport.endInput();
|
|
}
|
|
}
|
|
this.inputStream.enqueue(message);
|
|
}
|
|
if (this.firstResultReceivedResolve) {
|
|
this.firstResultReceivedResolve();
|
|
}
|
|
this.inputStream.done();
|
|
this.cleanup();
|
|
} catch (error2) {
|
|
if (this.firstResultReceivedResolve) {
|
|
this.firstResultReceivedResolve();
|
|
}
|
|
this.inputStream.error(error2);
|
|
this.cleanup(error2);
|
|
}
|
|
}
|
|
async handleControlRequest(request) {
|
|
const controller = new AbortController();
|
|
this.cancelControllers.set(request.request_id, controller);
|
|
try {
|
|
const response = await this.processControlRequest(request, controller.signal);
|
|
const controlResponse = {
|
|
type: "control_response",
|
|
response: {
|
|
subtype: "success",
|
|
request_id: request.request_id,
|
|
response
|
|
}
|
|
};
|
|
await Promise.resolve(this.transport.write(JSON.stringify(controlResponse) + `
|
|
`));
|
|
} catch (error2) {
|
|
const controlErrorResponse = {
|
|
type: "control_response",
|
|
response: {
|
|
subtype: "error",
|
|
request_id: request.request_id,
|
|
error: error2.message || String(error2)
|
|
}
|
|
};
|
|
await Promise.resolve(this.transport.write(JSON.stringify(controlErrorResponse) + `
|
|
`));
|
|
} finally {
|
|
this.cancelControllers.delete(request.request_id);
|
|
}
|
|
}
|
|
handleControlCancelRequest(request) {
|
|
const controller = this.cancelControllers.get(request.request_id);
|
|
if (controller) {
|
|
controller.abort();
|
|
this.cancelControllers.delete(request.request_id);
|
|
}
|
|
}
|
|
async processControlRequest(request, signal) {
|
|
if (request.request.subtype === "can_use_tool") {
|
|
if (!this.canUseTool) {
|
|
throw new Error("canUseTool callback is not provided.");
|
|
}
|
|
const result = await this.canUseTool(request.request.tool_name, request.request.input, {
|
|
signal,
|
|
suggestions: request.request.permission_suggestions,
|
|
blockedPath: request.request.blocked_path,
|
|
decisionReason: request.request.decision_reason,
|
|
toolUseID: request.request.tool_use_id,
|
|
agentID: request.request.agent_id
|
|
});
|
|
return {
|
|
...result,
|
|
toolUseID: request.request.tool_use_id
|
|
};
|
|
} else if (request.request.subtype === "hook_callback") {
|
|
const result = await this.handleHookCallbacks(request.request.callback_id, request.request.input, request.request.tool_use_id, signal);
|
|
return result;
|
|
} else if (request.request.subtype === "mcp_message") {
|
|
const mcpRequest = request.request;
|
|
const transport = this.sdkMcpTransports.get(mcpRequest.server_name);
|
|
if (!transport) {
|
|
throw new Error(`SDK MCP server not found: ${mcpRequest.server_name}`);
|
|
}
|
|
if ("method" in mcpRequest.message && "id" in mcpRequest.message && mcpRequest.message.id !== null) {
|
|
const response = await this.handleMcpControlRequest(mcpRequest.server_name, mcpRequest, transport);
|
|
return { mcp_response: response };
|
|
} else {
|
|
if (transport.onmessage) {
|
|
transport.onmessage(mcpRequest.message);
|
|
}
|
|
return { mcp_response: { jsonrpc: "2.0", result: {}, id: 0 } };
|
|
}
|
|
}
|
|
throw new Error("Unsupported control request subtype: " + request.request.subtype);
|
|
}
|
|
async *readSdkMessages() {
|
|
for await (const message of this.inputStream) {
|
|
yield message;
|
|
}
|
|
}
|
|
async initialize() {
|
|
var _a, _b, _c;
|
|
let hooks;
|
|
if (this.hooks) {
|
|
hooks = {};
|
|
for (const [event, matchers] of Object.entries(this.hooks)) {
|
|
if (matchers.length > 0) {
|
|
hooks[event] = matchers.map((matcher) => {
|
|
const callbackIds = [];
|
|
for (const callback of matcher.hooks) {
|
|
const callbackId = `hook_${this.nextCallbackId++}`;
|
|
this.hookCallbacks.set(callbackId, callback);
|
|
callbackIds.push(callbackId);
|
|
}
|
|
return {
|
|
matcher: matcher.matcher,
|
|
hookCallbackIds: callbackIds,
|
|
timeout: matcher.timeout
|
|
};
|
|
});
|
|
}
|
|
}
|
|
}
|
|
const sdkMcpServers = this.sdkMcpTransports.size > 0 ? Array.from(this.sdkMcpTransports.keys()) : void 0;
|
|
const initRequest = {
|
|
subtype: "initialize",
|
|
hooks,
|
|
sdkMcpServers,
|
|
jsonSchema: this.jsonSchema,
|
|
systemPrompt: (_a = this.initConfig) == null ? void 0 : _a.systemPrompt,
|
|
appendSystemPrompt: (_b = this.initConfig) == null ? void 0 : _b.appendSystemPrompt,
|
|
agents: (_c = this.initConfig) == null ? void 0 : _c.agents
|
|
};
|
|
const response = await this.request(initRequest);
|
|
return response.response;
|
|
}
|
|
async interrupt() {
|
|
await this.request({
|
|
subtype: "interrupt"
|
|
});
|
|
}
|
|
async setPermissionMode(mode) {
|
|
await this.request({
|
|
subtype: "set_permission_mode",
|
|
mode
|
|
});
|
|
}
|
|
async setModel(model) {
|
|
await this.request({
|
|
subtype: "set_model",
|
|
model
|
|
});
|
|
}
|
|
async setMaxThinkingTokens(maxThinkingTokens) {
|
|
await this.request({
|
|
subtype: "set_max_thinking_tokens",
|
|
max_thinking_tokens: maxThinkingTokens
|
|
});
|
|
}
|
|
async rewindFiles(userMessageId) {
|
|
await this.request({
|
|
subtype: "rewind_files",
|
|
user_message_id: userMessageId
|
|
});
|
|
}
|
|
async processPendingPermissionRequests(pendingPermissionRequests) {
|
|
for (const request of pendingPermissionRequests) {
|
|
if (request.request.subtype === "can_use_tool") {
|
|
this.handleControlRequest(request).catch(() => {
|
|
});
|
|
}
|
|
}
|
|
}
|
|
request(request) {
|
|
const requestId = Math.random().toString(36).substring(2, 15);
|
|
const sdkRequest = {
|
|
request_id: requestId,
|
|
type: "control_request",
|
|
request
|
|
};
|
|
return new Promise((resolve7, reject) => {
|
|
this.pendingControlResponses.set(requestId, (response) => {
|
|
if (response.subtype === "success") {
|
|
resolve7(response);
|
|
} else {
|
|
reject(new Error(response.error));
|
|
if (response.pending_permission_requests) {
|
|
this.processPendingPermissionRequests(response.pending_permission_requests);
|
|
}
|
|
}
|
|
});
|
|
Promise.resolve(this.transport.write(JSON.stringify(sdkRequest) + `
|
|
`));
|
|
});
|
|
}
|
|
async supportedCommands() {
|
|
return (await this.initialization).commands;
|
|
}
|
|
async supportedModels() {
|
|
return (await this.initialization).models;
|
|
}
|
|
async mcpServerStatus() {
|
|
const response = await this.request({
|
|
subtype: "mcp_status"
|
|
});
|
|
const mcpStatusResponse = response.response;
|
|
return mcpStatusResponse.mcpServers;
|
|
}
|
|
async setMcpServers(servers) {
|
|
const sdkServers = {};
|
|
const processServers = {};
|
|
for (const [name, config2] of Object.entries(servers)) {
|
|
if (config2.type === "sdk" && "instance" in config2) {
|
|
sdkServers[name] = config2.instance;
|
|
} else {
|
|
processServers[name] = config2;
|
|
}
|
|
}
|
|
const currentSdkNames = new Set(this.sdkMcpServerInstances.keys());
|
|
const newSdkNames = new Set(Object.keys(sdkServers));
|
|
for (const name of currentSdkNames) {
|
|
if (!newSdkNames.has(name)) {
|
|
await this.disconnectSdkMcpServer(name);
|
|
}
|
|
}
|
|
for (const [name, server] of Object.entries(sdkServers)) {
|
|
if (!currentSdkNames.has(name)) {
|
|
this.connectSdkMcpServer(name, server);
|
|
}
|
|
}
|
|
const sdkServerConfigs = {};
|
|
for (const name of Object.keys(sdkServers)) {
|
|
sdkServerConfigs[name] = { type: "sdk", name };
|
|
}
|
|
const response = await this.request({
|
|
subtype: "mcp_set_servers",
|
|
servers: { ...processServers, ...sdkServerConfigs }
|
|
});
|
|
return response.response;
|
|
}
|
|
async accountInfo() {
|
|
return (await this.initialization).account;
|
|
}
|
|
async streamInput(stream) {
|
|
var _a;
|
|
logForDebugging(`[Query.streamInput] Starting to process input stream`);
|
|
try {
|
|
let messageCount = 0;
|
|
for await (const message of stream) {
|
|
messageCount++;
|
|
logForDebugging(`[Query.streamInput] Processing message ${messageCount}: ${message.type}`);
|
|
if ((_a = this.abortController) == null ? void 0 : _a.signal.aborted)
|
|
break;
|
|
await Promise.resolve(this.transport.write(JSON.stringify(message) + `
|
|
`));
|
|
}
|
|
logForDebugging(`[Query.streamInput] Finished processing ${messageCount} messages from input stream`);
|
|
if (this.hasBidirectionalNeeds()) {
|
|
logForDebugging(`[Query.streamInput] Has bidirectional needs, waiting for first result`);
|
|
await this.waitForFirstResult();
|
|
}
|
|
logForDebugging(`[Query] Calling transport.endInput() to close stdin to CLI process`);
|
|
this.transport.endInput();
|
|
} catch (error2) {
|
|
if (!(error2 instanceof AbortError)) {
|
|
throw error2;
|
|
}
|
|
}
|
|
}
|
|
waitForFirstResult() {
|
|
if (this.firstResultReceived) {
|
|
logForDebugging(`[Query.waitForFirstResult] Result already received, returning immediately`);
|
|
return Promise.resolve();
|
|
}
|
|
return new Promise((resolve7) => {
|
|
var _a, _b;
|
|
if ((_a = this.abortController) == null ? void 0 : _a.signal.aborted) {
|
|
resolve7();
|
|
return;
|
|
}
|
|
(_b = this.abortController) == null ? void 0 : _b.signal.addEventListener("abort", () => resolve7(), {
|
|
once: true
|
|
});
|
|
this.firstResultReceivedResolve = resolve7;
|
|
});
|
|
}
|
|
handleHookCallbacks(callbackId, input, toolUseID, abortSignal) {
|
|
const callback = this.hookCallbacks.get(callbackId);
|
|
if (!callback) {
|
|
throw new Error(`No hook callback found for ID: ${callbackId}`);
|
|
}
|
|
return callback(input, toolUseID, {
|
|
signal: abortSignal
|
|
});
|
|
}
|
|
connectSdkMcpServer(name, server) {
|
|
const sdkTransport = new SdkControlServerTransport((message) => this.sendMcpServerMessageToCli(name, message));
|
|
this.sdkMcpTransports.set(name, sdkTransport);
|
|
this.sdkMcpServerInstances.set(name, server);
|
|
server.connect(sdkTransport);
|
|
}
|
|
async disconnectSdkMcpServer(name) {
|
|
const transport = this.sdkMcpTransports.get(name);
|
|
if (transport) {
|
|
await transport.close();
|
|
this.sdkMcpTransports.delete(name);
|
|
}
|
|
this.sdkMcpServerInstances.delete(name);
|
|
}
|
|
sendMcpServerMessageToCli(serverName, message) {
|
|
if ("id" in message && message.id !== null && message.id !== void 0) {
|
|
const key = `${serverName}:${message.id}`;
|
|
const pending = this.pendingMcpResponses.get(key);
|
|
if (pending) {
|
|
pending.resolve(message);
|
|
this.pendingMcpResponses.delete(key);
|
|
return;
|
|
}
|
|
}
|
|
const controlRequest = {
|
|
type: "control_request",
|
|
request_id: (0, import_crypto3.randomUUID)(),
|
|
request: {
|
|
subtype: "mcp_message",
|
|
server_name: serverName,
|
|
message
|
|
}
|
|
};
|
|
this.transport.write(JSON.stringify(controlRequest) + `
|
|
`);
|
|
}
|
|
handleMcpControlRequest(serverName, mcpRequest, transport) {
|
|
const messageId = "id" in mcpRequest.message ? mcpRequest.message.id : null;
|
|
const key = `${serverName}:${messageId}`;
|
|
return new Promise((resolve7, reject) => {
|
|
const cleanup = () => {
|
|
this.pendingMcpResponses.delete(key);
|
|
};
|
|
const resolveAndCleanup = (response) => {
|
|
cleanup();
|
|
resolve7(response);
|
|
};
|
|
const rejectAndCleanup = (error2) => {
|
|
cleanup();
|
|
reject(error2);
|
|
};
|
|
this.pendingMcpResponses.set(key, {
|
|
resolve: resolveAndCleanup,
|
|
reject: rejectAndCleanup
|
|
});
|
|
if (transport.onmessage) {
|
|
transport.onmessage(mcpRequest.message);
|
|
} else {
|
|
cleanup();
|
|
reject(new Error("No message handler registered"));
|
|
return;
|
|
}
|
|
});
|
|
}
|
|
};
|
|
var util;
|
|
(function(util2) {
|
|
util2.assertEqual = (_) => {
|
|
};
|
|
function assertIs2(_arg) {
|
|
}
|
|
util2.assertIs = assertIs2;
|
|
function assertNever2(_x) {
|
|
throw new Error();
|
|
}
|
|
util2.assertNever = assertNever2;
|
|
util2.arrayToEnum = (items) => {
|
|
const obj = {};
|
|
for (const item of items) {
|
|
obj[item] = item;
|
|
}
|
|
return obj;
|
|
};
|
|
util2.getValidEnumValues = (obj) => {
|
|
const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
|
|
const filtered = {};
|
|
for (const k of validKeys) {
|
|
filtered[k] = obj[k];
|
|
}
|
|
return util2.objectValues(filtered);
|
|
};
|
|
util2.objectValues = (obj) => {
|
|
return util2.objectKeys(obj).map(function(e) {
|
|
return obj[e];
|
|
});
|
|
};
|
|
util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
|
|
const keys = [];
|
|
for (const key in object) {
|
|
if (Object.prototype.hasOwnProperty.call(object, key)) {
|
|
keys.push(key);
|
|
}
|
|
}
|
|
return keys;
|
|
};
|
|
util2.find = (arr, checker) => {
|
|
for (const item of arr) {
|
|
if (checker(item))
|
|
return item;
|
|
}
|
|
return;
|
|
};
|
|
util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
|
|
function joinValues2(array2, separator = " | ") {
|
|
return array2.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
|
|
}
|
|
util2.joinValues = joinValues2;
|
|
util2.jsonStringifyReplacer = (_, value) => {
|
|
if (typeof value === "bigint") {
|
|
return value.toString();
|
|
}
|
|
return value;
|
|
};
|
|
})(util || (util = {}));
|
|
var objectUtil;
|
|
(function(objectUtil2) {
|
|
objectUtil2.mergeShapes = (first, second) => {
|
|
return {
|
|
...first,
|
|
...second
|
|
};
|
|
};
|
|
})(objectUtil || (objectUtil = {}));
|
|
var ZodParsedType = util.arrayToEnum([
|
|
"string",
|
|
"nan",
|
|
"number",
|
|
"integer",
|
|
"float",
|
|
"boolean",
|
|
"date",
|
|
"bigint",
|
|
"symbol",
|
|
"function",
|
|
"undefined",
|
|
"null",
|
|
"array",
|
|
"object",
|
|
"unknown",
|
|
"promise",
|
|
"void",
|
|
"never",
|
|
"map",
|
|
"set"
|
|
]);
|
|
var getParsedType = (data) => {
|
|
const t = typeof data;
|
|
switch (t) {
|
|
case "undefined":
|
|
return ZodParsedType.undefined;
|
|
case "string":
|
|
return ZodParsedType.string;
|
|
case "number":
|
|
return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
|
|
case "boolean":
|
|
return ZodParsedType.boolean;
|
|
case "function":
|
|
return ZodParsedType.function;
|
|
case "bigint":
|
|
return ZodParsedType.bigint;
|
|
case "symbol":
|
|
return ZodParsedType.symbol;
|
|
case "object":
|
|
if (Array.isArray(data)) {
|
|
return ZodParsedType.array;
|
|
}
|
|
if (data === null) {
|
|
return ZodParsedType.null;
|
|
}
|
|
if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
|
|
return ZodParsedType.promise;
|
|
}
|
|
if (typeof Map !== "undefined" && data instanceof Map) {
|
|
return ZodParsedType.map;
|
|
}
|
|
if (typeof Set !== "undefined" && data instanceof Set) {
|
|
return ZodParsedType.set;
|
|
}
|
|
if (typeof Date !== "undefined" && data instanceof Date) {
|
|
return ZodParsedType.date;
|
|
}
|
|
return ZodParsedType.object;
|
|
default:
|
|
return ZodParsedType.unknown;
|
|
}
|
|
};
|
|
var ZodIssueCode = util.arrayToEnum([
|
|
"invalid_type",
|
|
"invalid_literal",
|
|
"custom",
|
|
"invalid_union",
|
|
"invalid_union_discriminator",
|
|
"invalid_enum_value",
|
|
"unrecognized_keys",
|
|
"invalid_arguments",
|
|
"invalid_return_type",
|
|
"invalid_date",
|
|
"invalid_string",
|
|
"too_small",
|
|
"too_big",
|
|
"invalid_intersection_types",
|
|
"not_multiple_of",
|
|
"not_finite"
|
|
]);
|
|
var ZodError = class _ZodError extends Error {
|
|
get errors() {
|
|
return this.issues;
|
|
}
|
|
constructor(issues) {
|
|
super();
|
|
this.issues = [];
|
|
this.addIssue = (sub) => {
|
|
this.issues = [...this.issues, sub];
|
|
};
|
|
this.addIssues = (subs = []) => {
|
|
this.issues = [...this.issues, ...subs];
|
|
};
|
|
const actualProto = new.target.prototype;
|
|
if (Object.setPrototypeOf) {
|
|
Object.setPrototypeOf(this, actualProto);
|
|
} else {
|
|
this.__proto__ = actualProto;
|
|
}
|
|
this.name = "ZodError";
|
|
this.issues = issues;
|
|
}
|
|
format(_mapper) {
|
|
const mapper = _mapper || function(issue2) {
|
|
return issue2.message;
|
|
};
|
|
const fieldErrors = { _errors: [] };
|
|
const processError = (error2) => {
|
|
for (const issue2 of error2.issues) {
|
|
if (issue2.code === "invalid_union") {
|
|
issue2.unionErrors.map(processError);
|
|
} else if (issue2.code === "invalid_return_type") {
|
|
processError(issue2.returnTypeError);
|
|
} else if (issue2.code === "invalid_arguments") {
|
|
processError(issue2.argumentsError);
|
|
} else if (issue2.path.length === 0) {
|
|
fieldErrors._errors.push(mapper(issue2));
|
|
} else {
|
|
let curr = fieldErrors;
|
|
let i = 0;
|
|
while (i < issue2.path.length) {
|
|
const el = issue2.path[i];
|
|
const terminal = i === issue2.path.length - 1;
|
|
if (!terminal) {
|
|
curr[el] = curr[el] || { _errors: [] };
|
|
} else {
|
|
curr[el] = curr[el] || { _errors: [] };
|
|
curr[el]._errors.push(mapper(issue2));
|
|
}
|
|
curr = curr[el];
|
|
i++;
|
|
}
|
|
}
|
|
}
|
|
};
|
|
processError(this);
|
|
return fieldErrors;
|
|
}
|
|
static assert(value) {
|
|
if (!(value instanceof _ZodError)) {
|
|
throw new Error(`Not a ZodError: ${value}`);
|
|
}
|
|
}
|
|
toString() {
|
|
return this.message;
|
|
}
|
|
get message() {
|
|
return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
|
|
}
|
|
get isEmpty() {
|
|
return this.issues.length === 0;
|
|
}
|
|
flatten(mapper = (issue2) => issue2.message) {
|
|
const fieldErrors = {};
|
|
const formErrors = [];
|
|
for (const sub of this.issues) {
|
|
if (sub.path.length > 0) {
|
|
const firstEl = sub.path[0];
|
|
fieldErrors[firstEl] = fieldErrors[firstEl] || [];
|
|
fieldErrors[firstEl].push(mapper(sub));
|
|
} else {
|
|
formErrors.push(mapper(sub));
|
|
}
|
|
}
|
|
return { formErrors, fieldErrors };
|
|
}
|
|
get formErrors() {
|
|
return this.flatten();
|
|
}
|
|
};
|
|
ZodError.create = (issues) => {
|
|
const error2 = new ZodError(issues);
|
|
return error2;
|
|
};
|
|
var errorMap = (issue2, _ctx) => {
|
|
let message;
|
|
switch (issue2.code) {
|
|
case ZodIssueCode.invalid_type:
|
|
if (issue2.received === ZodParsedType.undefined) {
|
|
message = "Required";
|
|
} else {
|
|
message = `Expected ${issue2.expected}, received ${issue2.received}`;
|
|
}
|
|
break;
|
|
case ZodIssueCode.invalid_literal:
|
|
message = `Invalid literal value, expected ${JSON.stringify(issue2.expected, util.jsonStringifyReplacer)}`;
|
|
break;
|
|
case ZodIssueCode.unrecognized_keys:
|
|
message = `Unrecognized key(s) in object: ${util.joinValues(issue2.keys, ", ")}`;
|
|
break;
|
|
case ZodIssueCode.invalid_union:
|
|
message = `Invalid input`;
|
|
break;
|
|
case ZodIssueCode.invalid_union_discriminator:
|
|
message = `Invalid discriminator value. Expected ${util.joinValues(issue2.options)}`;
|
|
break;
|
|
case ZodIssueCode.invalid_enum_value:
|
|
message = `Invalid enum value. Expected ${util.joinValues(issue2.options)}, received '${issue2.received}'`;
|
|
break;
|
|
case ZodIssueCode.invalid_arguments:
|
|
message = `Invalid function arguments`;
|
|
break;
|
|
case ZodIssueCode.invalid_return_type:
|
|
message = `Invalid function return type`;
|
|
break;
|
|
case ZodIssueCode.invalid_date:
|
|
message = `Invalid date`;
|
|
break;
|
|
case ZodIssueCode.invalid_string:
|
|
if (typeof issue2.validation === "object") {
|
|
if ("includes" in issue2.validation) {
|
|
message = `Invalid input: must include "${issue2.validation.includes}"`;
|
|
if (typeof issue2.validation.position === "number") {
|
|
message = `${message} at one or more positions greater than or equal to ${issue2.validation.position}`;
|
|
}
|
|
} else if ("startsWith" in issue2.validation) {
|
|
message = `Invalid input: must start with "${issue2.validation.startsWith}"`;
|
|
} else if ("endsWith" in issue2.validation) {
|
|
message = `Invalid input: must end with "${issue2.validation.endsWith}"`;
|
|
} else {
|
|
util.assertNever(issue2.validation);
|
|
}
|
|
} else if (issue2.validation !== "regex") {
|
|
message = `Invalid ${issue2.validation}`;
|
|
} else {
|
|
message = "Invalid";
|
|
}
|
|
break;
|
|
case ZodIssueCode.too_small:
|
|
if (issue2.type === "array")
|
|
message = `Array must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `more than`} ${issue2.minimum} element(s)`;
|
|
else if (issue2.type === "string")
|
|
message = `String must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `over`} ${issue2.minimum} character(s)`;
|
|
else if (issue2.type === "number")
|
|
message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`;
|
|
else if (issue2.type === "bigint")
|
|
message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`;
|
|
else if (issue2.type === "date")
|
|
message = `Date must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue2.minimum))}`;
|
|
else
|
|
message = "Invalid input";
|
|
break;
|
|
case ZodIssueCode.too_big:
|
|
if (issue2.type === "array")
|
|
message = `Array must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `less than`} ${issue2.maximum} element(s)`;
|
|
else if (issue2.type === "string")
|
|
message = `String must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `under`} ${issue2.maximum} character(s)`;
|
|
else if (issue2.type === "number")
|
|
message = `Number must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`;
|
|
else if (issue2.type === "bigint")
|
|
message = `BigInt must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`;
|
|
else if (issue2.type === "date")
|
|
message = `Date must be ${issue2.exact ? `exactly` : issue2.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue2.maximum))}`;
|
|
else
|
|
message = "Invalid input";
|
|
break;
|
|
case ZodIssueCode.custom:
|
|
message = `Invalid input`;
|
|
break;
|
|
case ZodIssueCode.invalid_intersection_types:
|
|
message = `Intersection results could not be merged`;
|
|
break;
|
|
case ZodIssueCode.not_multiple_of:
|
|
message = `Number must be a multiple of ${issue2.multipleOf}`;
|
|
break;
|
|
case ZodIssueCode.not_finite:
|
|
message = "Number must be finite";
|
|
break;
|
|
default:
|
|
message = _ctx.defaultError;
|
|
util.assertNever(issue2);
|
|
}
|
|
return { message };
|
|
};
|
|
var en_default = errorMap;
|
|
var overrideErrorMap = en_default;
|
|
function getErrorMap() {
|
|
return overrideErrorMap;
|
|
}
|
|
var makeIssue = (params) => {
|
|
const { data, path: path12, errorMaps, issueData } = params;
|
|
const fullPath = [...path12, ...issueData.path || []];
|
|
const fullIssue = {
|
|
...issueData,
|
|
path: fullPath
|
|
};
|
|
if (issueData.message !== void 0) {
|
|
return {
|
|
...issueData,
|
|
path: fullPath,
|
|
message: issueData.message
|
|
};
|
|
}
|
|
let errorMessage = "";
|
|
const maps = errorMaps.filter((m) => !!m).slice().reverse();
|
|
for (const map of maps) {
|
|
errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
|
|
}
|
|
return {
|
|
...issueData,
|
|
path: fullPath,
|
|
message: errorMessage
|
|
};
|
|
};
|
|
function addIssueToContext(ctx, issueData) {
|
|
const overrideMap = getErrorMap();
|
|
const issue2 = makeIssue({
|
|
issueData,
|
|
data: ctx.data,
|
|
path: ctx.path,
|
|
errorMaps: [
|
|
ctx.common.contextualErrorMap,
|
|
ctx.schemaErrorMap,
|
|
overrideMap,
|
|
overrideMap === en_default ? void 0 : en_default
|
|
].filter((x) => !!x)
|
|
});
|
|
ctx.common.issues.push(issue2);
|
|
}
|
|
var ParseStatus = class _ParseStatus {
|
|
constructor() {
|
|
this.value = "valid";
|
|
}
|
|
dirty() {
|
|
if (this.value === "valid")
|
|
this.value = "dirty";
|
|
}
|
|
abort() {
|
|
if (this.value !== "aborted")
|
|
this.value = "aborted";
|
|
}
|
|
static mergeArray(status, results) {
|
|
const arrayValue = [];
|
|
for (const s of results) {
|
|
if (s.status === "aborted")
|
|
return INVALID;
|
|
if (s.status === "dirty")
|
|
status.dirty();
|
|
arrayValue.push(s.value);
|
|
}
|
|
return { status: status.value, value: arrayValue };
|
|
}
|
|
static async mergeObjectAsync(status, pairs) {
|
|
const syncPairs = [];
|
|
for (const pair of pairs) {
|
|
const key = await pair.key;
|
|
const value = await pair.value;
|
|
syncPairs.push({
|
|
key,
|
|
value
|
|
});
|
|
}
|
|
return _ParseStatus.mergeObjectSync(status, syncPairs);
|
|
}
|
|
static mergeObjectSync(status, pairs) {
|
|
const finalObject = {};
|
|
for (const pair of pairs) {
|
|
const { key, value } = pair;
|
|
if (key.status === "aborted")
|
|
return INVALID;
|
|
if (value.status === "aborted")
|
|
return INVALID;
|
|
if (key.status === "dirty")
|
|
status.dirty();
|
|
if (value.status === "dirty")
|
|
status.dirty();
|
|
if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
|
|
finalObject[key.value] = value.value;
|
|
}
|
|
}
|
|
return { status: status.value, value: finalObject };
|
|
}
|
|
};
|
|
var INVALID = Object.freeze({
|
|
status: "aborted"
|
|
});
|
|
var DIRTY = (value) => ({ status: "dirty", value });
|
|
var OK = (value) => ({ status: "valid", value });
|
|
var isAborted = (x) => x.status === "aborted";
|
|
var isDirty = (x) => x.status === "dirty";
|
|
var isValid = (x) => x.status === "valid";
|
|
var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
|
|
var errorUtil;
|
|
(function(errorUtil2) {
|
|
errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
|
|
errorUtil2.toString = (message) => typeof message === "string" ? message : message == null ? void 0 : message.message;
|
|
})(errorUtil || (errorUtil = {}));
|
|
var ParseInputLazyPath = class {
|
|
constructor(parent, value, path12, key) {
|
|
this._cachedPath = [];
|
|
this.parent = parent;
|
|
this.data = value;
|
|
this._path = path12;
|
|
this._key = key;
|
|
}
|
|
get path() {
|
|
if (!this._cachedPath.length) {
|
|
if (Array.isArray(this._key)) {
|
|
this._cachedPath.push(...this._path, ...this._key);
|
|
} else {
|
|
this._cachedPath.push(...this._path, this._key);
|
|
}
|
|
}
|
|
return this._cachedPath;
|
|
}
|
|
};
|
|
var handleResult = (ctx, result) => {
|
|
if (isValid(result)) {
|
|
return { success: true, data: result.value };
|
|
} else {
|
|
if (!ctx.common.issues.length) {
|
|
throw new Error("Validation failed but no issues detected.");
|
|
}
|
|
return {
|
|
success: false,
|
|
get error() {
|
|
if (this._error)
|
|
return this._error;
|
|
const error2 = new ZodError(ctx.common.issues);
|
|
this._error = error2;
|
|
return this._error;
|
|
}
|
|
};
|
|
}
|
|
};
|
|
function processCreateParams(params) {
|
|
if (!params)
|
|
return {};
|
|
const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
|
|
if (errorMap2 && (invalid_type_error || required_error)) {
|
|
throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
|
|
}
|
|
if (errorMap2)
|
|
return { errorMap: errorMap2, description };
|
|
const customMap = (iss, ctx) => {
|
|
var _a, _b;
|
|
const { message } = params;
|
|
if (iss.code === "invalid_enum_value") {
|
|
return { message: message != null ? message : ctx.defaultError };
|
|
}
|
|
if (typeof ctx.data === "undefined") {
|
|
return { message: (_a = message != null ? message : required_error) != null ? _a : ctx.defaultError };
|
|
}
|
|
if (iss.code !== "invalid_type")
|
|
return { message: ctx.defaultError };
|
|
return { message: (_b = message != null ? message : invalid_type_error) != null ? _b : ctx.defaultError };
|
|
};
|
|
return { errorMap: customMap, description };
|
|
}
|
|
var ZodType = class {
|
|
get description() {
|
|
return this._def.description;
|
|
}
|
|
_getType(input) {
|
|
return getParsedType(input.data);
|
|
}
|
|
_getOrReturnCtx(input, ctx) {
|
|
return ctx || {
|
|
common: input.parent.common,
|
|
data: input.data,
|
|
parsedType: getParsedType(input.data),
|
|
schemaErrorMap: this._def.errorMap,
|
|
path: input.path,
|
|
parent: input.parent
|
|
};
|
|
}
|
|
_processInputParams(input) {
|
|
return {
|
|
status: new ParseStatus(),
|
|
ctx: {
|
|
common: input.parent.common,
|
|
data: input.data,
|
|
parsedType: getParsedType(input.data),
|
|
schemaErrorMap: this._def.errorMap,
|
|
path: input.path,
|
|
parent: input.parent
|
|
}
|
|
};
|
|
}
|
|
_parseSync(input) {
|
|
const result = this._parse(input);
|
|
if (isAsync(result)) {
|
|
throw new Error("Synchronous parse encountered promise.");
|
|
}
|
|
return result;
|
|
}
|
|
_parseAsync(input) {
|
|
const result = this._parse(input);
|
|
return Promise.resolve(result);
|
|
}
|
|
parse(data, params) {
|
|
const result = this.safeParse(data, params);
|
|
if (result.success)
|
|
return result.data;
|
|
throw result.error;
|
|
}
|
|
safeParse(data, params) {
|
|
var _a;
|
|
const ctx = {
|
|
common: {
|
|
issues: [],
|
|
async: (_a = params == null ? void 0 : params.async) != null ? _a : false,
|
|
contextualErrorMap: params == null ? void 0 : params.errorMap
|
|
},
|
|
path: (params == null ? void 0 : params.path) || [],
|
|
schemaErrorMap: this._def.errorMap,
|
|
parent: null,
|
|
data,
|
|
parsedType: getParsedType(data)
|
|
};
|
|
const result = this._parseSync({ data, path: ctx.path, parent: ctx });
|
|
return handleResult(ctx, result);
|
|
}
|
|
"~validate"(data) {
|
|
var _a, _b;
|
|
const ctx = {
|
|
common: {
|
|
issues: [],
|
|
async: !!this["~standard"].async
|
|
},
|
|
path: [],
|
|
schemaErrorMap: this._def.errorMap,
|
|
parent: null,
|
|
data,
|
|
parsedType: getParsedType(data)
|
|
};
|
|
if (!this["~standard"].async) {
|
|
try {
|
|
const result = this._parseSync({ data, path: [], parent: ctx });
|
|
return isValid(result) ? {
|
|
value: result.value
|
|
} : {
|
|
issues: ctx.common.issues
|
|
};
|
|
} catch (err) {
|
|
if ((_b = (_a = err == null ? void 0 : err.message) == null ? void 0 : _a.toLowerCase()) == null ? void 0 : _b.includes("encountered")) {
|
|
this["~standard"].async = true;
|
|
}
|
|
ctx.common = {
|
|
issues: [],
|
|
async: true
|
|
};
|
|
}
|
|
}
|
|
return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
|
|
value: result.value
|
|
} : {
|
|
issues: ctx.common.issues
|
|
});
|
|
}
|
|
async parseAsync(data, params) {
|
|
const result = await this.safeParseAsync(data, params);
|
|
if (result.success)
|
|
return result.data;
|
|
throw result.error;
|
|
}
|
|
async safeParseAsync(data, params) {
|
|
const ctx = {
|
|
common: {
|
|
issues: [],
|
|
contextualErrorMap: params == null ? void 0 : params.errorMap,
|
|
async: true
|
|
},
|
|
path: (params == null ? void 0 : params.path) || [],
|
|
schemaErrorMap: this._def.errorMap,
|
|
parent: null,
|
|
data,
|
|
parsedType: getParsedType(data)
|
|
};
|
|
const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
|
|
const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
|
|
return handleResult(ctx, result);
|
|
}
|
|
refine(check2, message) {
|
|
const getIssueProperties = (val) => {
|
|
if (typeof message === "string" || typeof message === "undefined") {
|
|
return { message };
|
|
} else if (typeof message === "function") {
|
|
return message(val);
|
|
} else {
|
|
return message;
|
|
}
|
|
};
|
|
return this._refinement((val, ctx) => {
|
|
const result = check2(val);
|
|
const setError = () => ctx.addIssue({
|
|
code: ZodIssueCode.custom,
|
|
...getIssueProperties(val)
|
|
});
|
|
if (typeof Promise !== "undefined" && result instanceof Promise) {
|
|
return result.then((data) => {
|
|
if (!data) {
|
|
setError();
|
|
return false;
|
|
} else {
|
|
return true;
|
|
}
|
|
});
|
|
}
|
|
if (!result) {
|
|
setError();
|
|
return false;
|
|
} else {
|
|
return true;
|
|
}
|
|
});
|
|
}
|
|
refinement(check2, refinementData) {
|
|
return this._refinement((val, ctx) => {
|
|
if (!check2(val)) {
|
|
ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
|
|
return false;
|
|
} else {
|
|
return true;
|
|
}
|
|
});
|
|
}
|
|
_refinement(refinement) {
|
|
return new ZodEffects({
|
|
schema: this,
|
|
typeName: ZodFirstPartyTypeKind.ZodEffects,
|
|
effect: { type: "refinement", refinement }
|
|
});
|
|
}
|
|
superRefine(refinement) {
|
|
return this._refinement(refinement);
|
|
}
|
|
constructor(def) {
|
|
this.spa = this.safeParseAsync;
|
|
this._def = def;
|
|
this.parse = this.parse.bind(this);
|
|
this.safeParse = this.safeParse.bind(this);
|
|
this.parseAsync = this.parseAsync.bind(this);
|
|
this.safeParseAsync = this.safeParseAsync.bind(this);
|
|
this.spa = this.spa.bind(this);
|
|
this.refine = this.refine.bind(this);
|
|
this.refinement = this.refinement.bind(this);
|
|
this.superRefine = this.superRefine.bind(this);
|
|
this.optional = this.optional.bind(this);
|
|
this.nullable = this.nullable.bind(this);
|
|
this.nullish = this.nullish.bind(this);
|
|
this.array = this.array.bind(this);
|
|
this.promise = this.promise.bind(this);
|
|
this.or = this.or.bind(this);
|
|
this.and = this.and.bind(this);
|
|
this.transform = this.transform.bind(this);
|
|
this.brand = this.brand.bind(this);
|
|
this.default = this.default.bind(this);
|
|
this.catch = this.catch.bind(this);
|
|
this.describe = this.describe.bind(this);
|
|
this.pipe = this.pipe.bind(this);
|
|
this.readonly = this.readonly.bind(this);
|
|
this.isNullable = this.isNullable.bind(this);
|
|
this.isOptional = this.isOptional.bind(this);
|
|
this["~standard"] = {
|
|
version: 1,
|
|
vendor: "zod",
|
|
validate: (data) => this["~validate"](data)
|
|
};
|
|
}
|
|
optional() {
|
|
return ZodOptional.create(this, this._def);
|
|
}
|
|
nullable() {
|
|
return ZodNullable.create(this, this._def);
|
|
}
|
|
nullish() {
|
|
return this.nullable().optional();
|
|
}
|
|
array() {
|
|
return ZodArray.create(this);
|
|
}
|
|
promise() {
|
|
return ZodPromise.create(this, this._def);
|
|
}
|
|
or(option) {
|
|
return ZodUnion.create([this, option], this._def);
|
|
}
|
|
and(incoming) {
|
|
return ZodIntersection.create(this, incoming, this._def);
|
|
}
|
|
transform(transform2) {
|
|
return new ZodEffects({
|
|
...processCreateParams(this._def),
|
|
schema: this,
|
|
typeName: ZodFirstPartyTypeKind.ZodEffects,
|
|
effect: { type: "transform", transform: transform2 }
|
|
});
|
|
}
|
|
default(def) {
|
|
const defaultValueFunc = typeof def === "function" ? def : () => def;
|
|
return new ZodDefault({
|
|
...processCreateParams(this._def),
|
|
innerType: this,
|
|
defaultValue: defaultValueFunc,
|
|
typeName: ZodFirstPartyTypeKind.ZodDefault
|
|
});
|
|
}
|
|
brand() {
|
|
return new ZodBranded({
|
|
typeName: ZodFirstPartyTypeKind.ZodBranded,
|
|
type: this,
|
|
...processCreateParams(this._def)
|
|
});
|
|
}
|
|
catch(def) {
|
|
const catchValueFunc = typeof def === "function" ? def : () => def;
|
|
return new ZodCatch({
|
|
...processCreateParams(this._def),
|
|
innerType: this,
|
|
catchValue: catchValueFunc,
|
|
typeName: ZodFirstPartyTypeKind.ZodCatch
|
|
});
|
|
}
|
|
describe(description) {
|
|
const This = this.constructor;
|
|
return new This({
|
|
...this._def,
|
|
description
|
|
});
|
|
}
|
|
pipe(target) {
|
|
return ZodPipeline.create(this, target);
|
|
}
|
|
readonly() {
|
|
return ZodReadonly.create(this);
|
|
}
|
|
isOptional() {
|
|
return this.safeParse(void 0).success;
|
|
}
|
|
isNullable() {
|
|
return this.safeParse(null).success;
|
|
}
|
|
};
|
|
var cuidRegex = /^c[^\s-]{8,}$/i;
|
|
var cuid2Regex = /^[0-9a-z]+$/;
|
|
var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
|
|
var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
|
|
var nanoidRegex = /^[a-z0-9_-]{21}$/i;
|
|
var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
|
|
var durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
|
|
var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
|
|
var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
|
|
var emojiRegex;
|
|
var ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
|
|
var ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
|
|
var ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
|
|
var ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
|
|
var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
|
|
var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
|
|
var dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
|
|
var dateRegex = new RegExp(`^${dateRegexSource}$`);
|
|
function timeRegexSource(args) {
|
|
let secondsRegexSource = `[0-5]\\d`;
|
|
if (args.precision) {
|
|
secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
|
|
} else if (args.precision == null) {
|
|
secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
|
|
}
|
|
const secondsQuantifier = args.precision ? "+" : "?";
|
|
return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
|
|
}
|
|
function timeRegex(args) {
|
|
return new RegExp(`^${timeRegexSource(args)}$`);
|
|
}
|
|
function datetimeRegex(args) {
|
|
let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
|
|
const opts = [];
|
|
opts.push(args.local ? `Z?` : `Z`);
|
|
if (args.offset)
|
|
opts.push(`([+-]\\d{2}:?\\d{2})`);
|
|
regex = `${regex}(${opts.join("|")})`;
|
|
return new RegExp(`^${regex}$`);
|
|
}
|
|
function isValidIP(ip, version2) {
|
|
if ((version2 === "v4" || !version2) && ipv4Regex.test(ip)) {
|
|
return true;
|
|
}
|
|
if ((version2 === "v6" || !version2) && ipv6Regex.test(ip)) {
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
function isValidJWT(jwt, alg) {
|
|
if (!jwtRegex.test(jwt))
|
|
return false;
|
|
try {
|
|
const [header] = jwt.split(".");
|
|
if (!header)
|
|
return false;
|
|
const base642 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
|
|
const decoded = JSON.parse(atob(base642));
|
|
if (typeof decoded !== "object" || decoded === null)
|
|
return false;
|
|
if ("typ" in decoded && (decoded == null ? void 0 : decoded.typ) !== "JWT")
|
|
return false;
|
|
if (!decoded.alg)
|
|
return false;
|
|
if (alg && decoded.alg !== alg)
|
|
return false;
|
|
return true;
|
|
} catch (e) {
|
|
return false;
|
|
}
|
|
}
|
|
function isValidCidr(ip, version2) {
|
|
if ((version2 === "v4" || !version2) && ipv4CidrRegex.test(ip)) {
|
|
return true;
|
|
}
|
|
if ((version2 === "v6" || !version2) && ipv6CidrRegex.test(ip)) {
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
var ZodString = class _ZodString2 extends ZodType {
|
|
_parse(input) {
|
|
if (this._def.coerce) {
|
|
input.data = String(input.data);
|
|
}
|
|
const parsedType2 = this._getType(input);
|
|
if (parsedType2 !== ZodParsedType.string) {
|
|
const ctx2 = this._getOrReturnCtx(input);
|
|
addIssueToContext(ctx2, {
|
|
code: ZodIssueCode.invalid_type,
|
|
expected: ZodParsedType.string,
|
|
received: ctx2.parsedType
|
|
});
|
|
return INVALID;
|
|
}
|
|
const status = new ParseStatus();
|
|
let ctx = void 0;
|
|
for (const check2 of this._def.checks) {
|
|
if (check2.kind === "min") {
|
|
if (input.data.length < check2.value) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.too_small,
|
|
minimum: check2.value,
|
|
type: "string",
|
|
inclusive: true,
|
|
exact: false,
|
|
message: check2.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check2.kind === "max") {
|
|
if (input.data.length > check2.value) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.too_big,
|
|
maximum: check2.value,
|
|
type: "string",
|
|
inclusive: true,
|
|
exact: false,
|
|
message: check2.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check2.kind === "length") {
|
|
const tooBig = input.data.length > check2.value;
|
|
const tooSmall = input.data.length < check2.value;
|
|
if (tooBig || tooSmall) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
if (tooBig) {
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.too_big,
|
|
maximum: check2.value,
|
|
type: "string",
|
|
inclusive: true,
|
|
exact: true,
|
|
message: check2.message
|
|
});
|
|
} else if (tooSmall) {
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.too_small,
|
|
minimum: check2.value,
|
|
type: "string",
|
|
inclusive: true,
|
|
exact: true,
|
|
message: check2.message
|
|
});
|
|
}
|
|
status.dirty();
|
|
}
|
|
} else if (check2.kind === "email") {
|
|
if (!emailRegex.test(input.data)) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
validation: "email",
|
|
code: ZodIssueCode.invalid_string,
|
|
message: check2.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check2.kind === "emoji") {
|
|
if (!emojiRegex) {
|
|
emojiRegex = new RegExp(_emojiRegex, "u");
|
|
}
|
|
if (!emojiRegex.test(input.data)) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
validation: "emoji",
|
|
code: ZodIssueCode.invalid_string,
|
|
message: check2.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check2.kind === "uuid") {
|
|
if (!uuidRegex.test(input.data)) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
validation: "uuid",
|
|
code: ZodIssueCode.invalid_string,
|
|
message: check2.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check2.kind === "nanoid") {
|
|
if (!nanoidRegex.test(input.data)) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
validation: "nanoid",
|
|
code: ZodIssueCode.invalid_string,
|
|
message: check2.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check2.kind === "cuid") {
|
|
if (!cuidRegex.test(input.data)) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
validation: "cuid",
|
|
code: ZodIssueCode.invalid_string,
|
|
message: check2.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check2.kind === "cuid2") {
|
|
if (!cuid2Regex.test(input.data)) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
validation: "cuid2",
|
|
code: ZodIssueCode.invalid_string,
|
|
message: check2.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check2.kind === "ulid") {
|
|
if (!ulidRegex.test(input.data)) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
validation: "ulid",
|
|
code: ZodIssueCode.invalid_string,
|
|
message: check2.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check2.kind === "url") {
|
|
try {
|
|
new URL(input.data);
|
|
} catch (e) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
validation: "url",
|
|
code: ZodIssueCode.invalid_string,
|
|
message: check2.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check2.kind === "regex") {
|
|
check2.regex.lastIndex = 0;
|
|
const testResult = check2.regex.test(input.data);
|
|
if (!testResult) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
validation: "regex",
|
|
code: ZodIssueCode.invalid_string,
|
|
message: check2.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check2.kind === "trim") {
|
|
input.data = input.data.trim();
|
|
} else if (check2.kind === "includes") {
|
|
if (!input.data.includes(check2.value, check2.position)) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_string,
|
|
validation: { includes: check2.value, position: check2.position },
|
|
message: check2.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check2.kind === "toLowerCase") {
|
|
input.data = input.data.toLowerCase();
|
|
} else if (check2.kind === "toUpperCase") {
|
|
input.data = input.data.toUpperCase();
|
|
} else if (check2.kind === "startsWith") {
|
|
if (!input.data.startsWith(check2.value)) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_string,
|
|
validation: { startsWith: check2.value },
|
|
message: check2.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check2.kind === "endsWith") {
|
|
if (!input.data.endsWith(check2.value)) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_string,
|
|
validation: { endsWith: check2.value },
|
|
message: check2.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check2.kind === "datetime") {
|
|
const regex = datetimeRegex(check2);
|
|
if (!regex.test(input.data)) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_string,
|
|
validation: "datetime",
|
|
message: check2.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check2.kind === "date") {
|
|
const regex = dateRegex;
|
|
if (!regex.test(input.data)) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_string,
|
|
validation: "date",
|
|
message: check2.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check2.kind === "time") {
|
|
const regex = timeRegex(check2);
|
|
if (!regex.test(input.data)) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_string,
|
|
validation: "time",
|
|
message: check2.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check2.kind === "duration") {
|
|
if (!durationRegex.test(input.data)) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
validation: "duration",
|
|
code: ZodIssueCode.invalid_string,
|
|
message: check2.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check2.kind === "ip") {
|
|
if (!isValidIP(input.data, check2.version)) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
validation: "ip",
|
|
code: ZodIssueCode.invalid_string,
|
|
message: check2.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check2.kind === "jwt") {
|
|
if (!isValidJWT(input.data, check2.alg)) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
validation: "jwt",
|
|
code: ZodIssueCode.invalid_string,
|
|
message: check2.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check2.kind === "cidr") {
|
|
if (!isValidCidr(input.data, check2.version)) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
validation: "cidr",
|
|
code: ZodIssueCode.invalid_string,
|
|
message: check2.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check2.kind === "base64") {
|
|
if (!base64Regex.test(input.data)) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
validation: "base64",
|
|
code: ZodIssueCode.invalid_string,
|
|
message: check2.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check2.kind === "base64url") {
|
|
if (!base64urlRegex.test(input.data)) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
validation: "base64url",
|
|
code: ZodIssueCode.invalid_string,
|
|
message: check2.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else {
|
|
util.assertNever(check2);
|
|
}
|
|
}
|
|
return { status: status.value, value: input.data };
|
|
}
|
|
_regex(regex, validation, message) {
|
|
return this.refinement((data) => regex.test(data), {
|
|
validation,
|
|
code: ZodIssueCode.invalid_string,
|
|
...errorUtil.errToObj(message)
|
|
});
|
|
}
|
|
_addCheck(check2) {
|
|
return new _ZodString2({
|
|
...this._def,
|
|
checks: [...this._def.checks, check2]
|
|
});
|
|
}
|
|
email(message) {
|
|
return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
|
|
}
|
|
url(message) {
|
|
return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
|
|
}
|
|
emoji(message) {
|
|
return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
|
|
}
|
|
uuid(message) {
|
|
return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
|
|
}
|
|
nanoid(message) {
|
|
return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
|
|
}
|
|
cuid(message) {
|
|
return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
|
|
}
|
|
cuid2(message) {
|
|
return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
|
|
}
|
|
ulid(message) {
|
|
return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
|
|
}
|
|
base64(message) {
|
|
return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
|
|
}
|
|
base64url(message) {
|
|
return this._addCheck({
|
|
kind: "base64url",
|
|
...errorUtil.errToObj(message)
|
|
});
|
|
}
|
|
jwt(options) {
|
|
return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
|
|
}
|
|
ip(options) {
|
|
return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
|
|
}
|
|
cidr(options) {
|
|
return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
|
|
}
|
|
datetime(options) {
|
|
var _a, _b;
|
|
if (typeof options === "string") {
|
|
return this._addCheck({
|
|
kind: "datetime",
|
|
precision: null,
|
|
offset: false,
|
|
local: false,
|
|
message: options
|
|
});
|
|
}
|
|
return this._addCheck({
|
|
kind: "datetime",
|
|
precision: typeof (options == null ? void 0 : options.precision) === "undefined" ? null : options == null ? void 0 : options.precision,
|
|
offset: (_a = options == null ? void 0 : options.offset) != null ? _a : false,
|
|
local: (_b = options == null ? void 0 : options.local) != null ? _b : false,
|
|
...errorUtil.errToObj(options == null ? void 0 : options.message)
|
|
});
|
|
}
|
|
date(message) {
|
|
return this._addCheck({ kind: "date", message });
|
|
}
|
|
time(options) {
|
|
if (typeof options === "string") {
|
|
return this._addCheck({
|
|
kind: "time",
|
|
precision: null,
|
|
message: options
|
|
});
|
|
}
|
|
return this._addCheck({
|
|
kind: "time",
|
|
precision: typeof (options == null ? void 0 : options.precision) === "undefined" ? null : options == null ? void 0 : options.precision,
|
|
...errorUtil.errToObj(options == null ? void 0 : options.message)
|
|
});
|
|
}
|
|
duration(message) {
|
|
return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
|
|
}
|
|
regex(regex, message) {
|
|
return this._addCheck({
|
|
kind: "regex",
|
|
regex,
|
|
...errorUtil.errToObj(message)
|
|
});
|
|
}
|
|
includes(value, options) {
|
|
return this._addCheck({
|
|
kind: "includes",
|
|
value,
|
|
position: options == null ? void 0 : options.position,
|
|
...errorUtil.errToObj(options == null ? void 0 : options.message)
|
|
});
|
|
}
|
|
startsWith(value, message) {
|
|
return this._addCheck({
|
|
kind: "startsWith",
|
|
value,
|
|
...errorUtil.errToObj(message)
|
|
});
|
|
}
|
|
endsWith(value, message) {
|
|
return this._addCheck({
|
|
kind: "endsWith",
|
|
value,
|
|
...errorUtil.errToObj(message)
|
|
});
|
|
}
|
|
min(minLength, message) {
|
|
return this._addCheck({
|
|
kind: "min",
|
|
value: minLength,
|
|
...errorUtil.errToObj(message)
|
|
});
|
|
}
|
|
max(maxLength, message) {
|
|
return this._addCheck({
|
|
kind: "max",
|
|
value: maxLength,
|
|
...errorUtil.errToObj(message)
|
|
});
|
|
}
|
|
length(len, message) {
|
|
return this._addCheck({
|
|
kind: "length",
|
|
value: len,
|
|
...errorUtil.errToObj(message)
|
|
});
|
|
}
|
|
nonempty(message) {
|
|
return this.min(1, errorUtil.errToObj(message));
|
|
}
|
|
trim() {
|
|
return new _ZodString2({
|
|
...this._def,
|
|
checks: [...this._def.checks, { kind: "trim" }]
|
|
});
|
|
}
|
|
toLowerCase() {
|
|
return new _ZodString2({
|
|
...this._def,
|
|
checks: [...this._def.checks, { kind: "toLowerCase" }]
|
|
});
|
|
}
|
|
toUpperCase() {
|
|
return new _ZodString2({
|
|
...this._def,
|
|
checks: [...this._def.checks, { kind: "toUpperCase" }]
|
|
});
|
|
}
|
|
get isDatetime() {
|
|
return !!this._def.checks.find((ch) => ch.kind === "datetime");
|
|
}
|
|
get isDate() {
|
|
return !!this._def.checks.find((ch) => ch.kind === "date");
|
|
}
|
|
get isTime() {
|
|
return !!this._def.checks.find((ch) => ch.kind === "time");
|
|
}
|
|
get isDuration() {
|
|
return !!this._def.checks.find((ch) => ch.kind === "duration");
|
|
}
|
|
get isEmail() {
|
|
return !!this._def.checks.find((ch) => ch.kind === "email");
|
|
}
|
|
get isURL() {
|
|
return !!this._def.checks.find((ch) => ch.kind === "url");
|
|
}
|
|
get isEmoji() {
|
|
return !!this._def.checks.find((ch) => ch.kind === "emoji");
|
|
}
|
|
get isUUID() {
|
|
return !!this._def.checks.find((ch) => ch.kind === "uuid");
|
|
}
|
|
get isNANOID() {
|
|
return !!this._def.checks.find((ch) => ch.kind === "nanoid");
|
|
}
|
|
get isCUID() {
|
|
return !!this._def.checks.find((ch) => ch.kind === "cuid");
|
|
}
|
|
get isCUID2() {
|
|
return !!this._def.checks.find((ch) => ch.kind === "cuid2");
|
|
}
|
|
get isULID() {
|
|
return !!this._def.checks.find((ch) => ch.kind === "ulid");
|
|
}
|
|
get isIP() {
|
|
return !!this._def.checks.find((ch) => ch.kind === "ip");
|
|
}
|
|
get isCIDR() {
|
|
return !!this._def.checks.find((ch) => ch.kind === "cidr");
|
|
}
|
|
get isBase64() {
|
|
return !!this._def.checks.find((ch) => ch.kind === "base64");
|
|
}
|
|
get isBase64url() {
|
|
return !!this._def.checks.find((ch) => ch.kind === "base64url");
|
|
}
|
|
get minLength() {
|
|
let min = null;
|
|
for (const ch of this._def.checks) {
|
|
if (ch.kind === "min") {
|
|
if (min === null || ch.value > min)
|
|
min = ch.value;
|
|
}
|
|
}
|
|
return min;
|
|
}
|
|
get maxLength() {
|
|
let max = null;
|
|
for (const ch of this._def.checks) {
|
|
if (ch.kind === "max") {
|
|
if (max === null || ch.value < max)
|
|
max = ch.value;
|
|
}
|
|
}
|
|
return max;
|
|
}
|
|
};
|
|
ZodString.create = (params) => {
|
|
var _a;
|
|
return new ZodString({
|
|
checks: [],
|
|
typeName: ZodFirstPartyTypeKind.ZodString,
|
|
coerce: (_a = params == null ? void 0 : params.coerce) != null ? _a : false,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
function floatSafeRemainder(val, step) {
|
|
const valDecCount = (val.toString().split(".")[1] || "").length;
|
|
const stepDecCount = (step.toString().split(".")[1] || "").length;
|
|
const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
|
|
const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
|
|
const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
|
|
return valInt % stepInt / 10 ** decCount;
|
|
}
|
|
var ZodNumber = class _ZodNumber extends ZodType {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.min = this.gte;
|
|
this.max = this.lte;
|
|
this.step = this.multipleOf;
|
|
}
|
|
_parse(input) {
|
|
if (this._def.coerce) {
|
|
input.data = Number(input.data);
|
|
}
|
|
const parsedType2 = this._getType(input);
|
|
if (parsedType2 !== ZodParsedType.number) {
|
|
const ctx2 = this._getOrReturnCtx(input);
|
|
addIssueToContext(ctx2, {
|
|
code: ZodIssueCode.invalid_type,
|
|
expected: ZodParsedType.number,
|
|
received: ctx2.parsedType
|
|
});
|
|
return INVALID;
|
|
}
|
|
let ctx = void 0;
|
|
const status = new ParseStatus();
|
|
for (const check2 of this._def.checks) {
|
|
if (check2.kind === "int") {
|
|
if (!util.isInteger(input.data)) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_type,
|
|
expected: "integer",
|
|
received: "float",
|
|
message: check2.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check2.kind === "min") {
|
|
const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value;
|
|
if (tooSmall) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.too_small,
|
|
minimum: check2.value,
|
|
type: "number",
|
|
inclusive: check2.inclusive,
|
|
exact: false,
|
|
message: check2.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check2.kind === "max") {
|
|
const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value;
|
|
if (tooBig) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.too_big,
|
|
maximum: check2.value,
|
|
type: "number",
|
|
inclusive: check2.inclusive,
|
|
exact: false,
|
|
message: check2.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check2.kind === "multipleOf") {
|
|
if (floatSafeRemainder(input.data, check2.value) !== 0) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.not_multiple_of,
|
|
multipleOf: check2.value,
|
|
message: check2.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check2.kind === "finite") {
|
|
if (!Number.isFinite(input.data)) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.not_finite,
|
|
message: check2.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else {
|
|
util.assertNever(check2);
|
|
}
|
|
}
|
|
return { status: status.value, value: input.data };
|
|
}
|
|
gte(value, message) {
|
|
return this.setLimit("min", value, true, errorUtil.toString(message));
|
|
}
|
|
gt(value, message) {
|
|
return this.setLimit("min", value, false, errorUtil.toString(message));
|
|
}
|
|
lte(value, message) {
|
|
return this.setLimit("max", value, true, errorUtil.toString(message));
|
|
}
|
|
lt(value, message) {
|
|
return this.setLimit("max", value, false, errorUtil.toString(message));
|
|
}
|
|
setLimit(kind, value, inclusive, message) {
|
|
return new _ZodNumber({
|
|
...this._def,
|
|
checks: [
|
|
...this._def.checks,
|
|
{
|
|
kind,
|
|
value,
|
|
inclusive,
|
|
message: errorUtil.toString(message)
|
|
}
|
|
]
|
|
});
|
|
}
|
|
_addCheck(check2) {
|
|
return new _ZodNumber({
|
|
...this._def,
|
|
checks: [...this._def.checks, check2]
|
|
});
|
|
}
|
|
int(message) {
|
|
return this._addCheck({
|
|
kind: "int",
|
|
message: errorUtil.toString(message)
|
|
});
|
|
}
|
|
positive(message) {
|
|
return this._addCheck({
|
|
kind: "min",
|
|
value: 0,
|
|
inclusive: false,
|
|
message: errorUtil.toString(message)
|
|
});
|
|
}
|
|
negative(message) {
|
|
return this._addCheck({
|
|
kind: "max",
|
|
value: 0,
|
|
inclusive: false,
|
|
message: errorUtil.toString(message)
|
|
});
|
|
}
|
|
nonpositive(message) {
|
|
return this._addCheck({
|
|
kind: "max",
|
|
value: 0,
|
|
inclusive: true,
|
|
message: errorUtil.toString(message)
|
|
});
|
|
}
|
|
nonnegative(message) {
|
|
return this._addCheck({
|
|
kind: "min",
|
|
value: 0,
|
|
inclusive: true,
|
|
message: errorUtil.toString(message)
|
|
});
|
|
}
|
|
multipleOf(value, message) {
|
|
return this._addCheck({
|
|
kind: "multipleOf",
|
|
value,
|
|
message: errorUtil.toString(message)
|
|
});
|
|
}
|
|
finite(message) {
|
|
return this._addCheck({
|
|
kind: "finite",
|
|
message: errorUtil.toString(message)
|
|
});
|
|
}
|
|
safe(message) {
|
|
return this._addCheck({
|
|
kind: "min",
|
|
inclusive: true,
|
|
value: Number.MIN_SAFE_INTEGER,
|
|
message: errorUtil.toString(message)
|
|
})._addCheck({
|
|
kind: "max",
|
|
inclusive: true,
|
|
value: Number.MAX_SAFE_INTEGER,
|
|
message: errorUtil.toString(message)
|
|
});
|
|
}
|
|
get minValue() {
|
|
let min = null;
|
|
for (const ch of this._def.checks) {
|
|
if (ch.kind === "min") {
|
|
if (min === null || ch.value > min)
|
|
min = ch.value;
|
|
}
|
|
}
|
|
return min;
|
|
}
|
|
get maxValue() {
|
|
let max = null;
|
|
for (const ch of this._def.checks) {
|
|
if (ch.kind === "max") {
|
|
if (max === null || ch.value < max)
|
|
max = ch.value;
|
|
}
|
|
}
|
|
return max;
|
|
}
|
|
get isInt() {
|
|
return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
|
|
}
|
|
get isFinite() {
|
|
let max = null;
|
|
let min = null;
|
|
for (const ch of this._def.checks) {
|
|
if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
|
|
return true;
|
|
} else if (ch.kind === "min") {
|
|
if (min === null || ch.value > min)
|
|
min = ch.value;
|
|
} else if (ch.kind === "max") {
|
|
if (max === null || ch.value < max)
|
|
max = ch.value;
|
|
}
|
|
}
|
|
return Number.isFinite(min) && Number.isFinite(max);
|
|
}
|
|
};
|
|
ZodNumber.create = (params) => {
|
|
return new ZodNumber({
|
|
checks: [],
|
|
typeName: ZodFirstPartyTypeKind.ZodNumber,
|
|
coerce: (params == null ? void 0 : params.coerce) || false,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
var ZodBigInt = class _ZodBigInt extends ZodType {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.min = this.gte;
|
|
this.max = this.lte;
|
|
}
|
|
_parse(input) {
|
|
if (this._def.coerce) {
|
|
try {
|
|
input.data = BigInt(input.data);
|
|
} catch (e) {
|
|
return this._getInvalidInput(input);
|
|
}
|
|
}
|
|
const parsedType2 = this._getType(input);
|
|
if (parsedType2 !== ZodParsedType.bigint) {
|
|
return this._getInvalidInput(input);
|
|
}
|
|
let ctx = void 0;
|
|
const status = new ParseStatus();
|
|
for (const check2 of this._def.checks) {
|
|
if (check2.kind === "min") {
|
|
const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value;
|
|
if (tooSmall) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.too_small,
|
|
type: "bigint",
|
|
minimum: check2.value,
|
|
inclusive: check2.inclusive,
|
|
message: check2.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check2.kind === "max") {
|
|
const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value;
|
|
if (tooBig) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.too_big,
|
|
type: "bigint",
|
|
maximum: check2.value,
|
|
inclusive: check2.inclusive,
|
|
message: check2.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check2.kind === "multipleOf") {
|
|
if (input.data % check2.value !== BigInt(0)) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.not_multiple_of,
|
|
multipleOf: check2.value,
|
|
message: check2.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else {
|
|
util.assertNever(check2);
|
|
}
|
|
}
|
|
return { status: status.value, value: input.data };
|
|
}
|
|
_getInvalidInput(input) {
|
|
const ctx = this._getOrReturnCtx(input);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_type,
|
|
expected: ZodParsedType.bigint,
|
|
received: ctx.parsedType
|
|
});
|
|
return INVALID;
|
|
}
|
|
gte(value, message) {
|
|
return this.setLimit("min", value, true, errorUtil.toString(message));
|
|
}
|
|
gt(value, message) {
|
|
return this.setLimit("min", value, false, errorUtil.toString(message));
|
|
}
|
|
lte(value, message) {
|
|
return this.setLimit("max", value, true, errorUtil.toString(message));
|
|
}
|
|
lt(value, message) {
|
|
return this.setLimit("max", value, false, errorUtil.toString(message));
|
|
}
|
|
setLimit(kind, value, inclusive, message) {
|
|
return new _ZodBigInt({
|
|
...this._def,
|
|
checks: [
|
|
...this._def.checks,
|
|
{
|
|
kind,
|
|
value,
|
|
inclusive,
|
|
message: errorUtil.toString(message)
|
|
}
|
|
]
|
|
});
|
|
}
|
|
_addCheck(check2) {
|
|
return new _ZodBigInt({
|
|
...this._def,
|
|
checks: [...this._def.checks, check2]
|
|
});
|
|
}
|
|
positive(message) {
|
|
return this._addCheck({
|
|
kind: "min",
|
|
value: BigInt(0),
|
|
inclusive: false,
|
|
message: errorUtil.toString(message)
|
|
});
|
|
}
|
|
negative(message) {
|
|
return this._addCheck({
|
|
kind: "max",
|
|
value: BigInt(0),
|
|
inclusive: false,
|
|
message: errorUtil.toString(message)
|
|
});
|
|
}
|
|
nonpositive(message) {
|
|
return this._addCheck({
|
|
kind: "max",
|
|
value: BigInt(0),
|
|
inclusive: true,
|
|
message: errorUtil.toString(message)
|
|
});
|
|
}
|
|
nonnegative(message) {
|
|
return this._addCheck({
|
|
kind: "min",
|
|
value: BigInt(0),
|
|
inclusive: true,
|
|
message: errorUtil.toString(message)
|
|
});
|
|
}
|
|
multipleOf(value, message) {
|
|
return this._addCheck({
|
|
kind: "multipleOf",
|
|
value,
|
|
message: errorUtil.toString(message)
|
|
});
|
|
}
|
|
get minValue() {
|
|
let min = null;
|
|
for (const ch of this._def.checks) {
|
|
if (ch.kind === "min") {
|
|
if (min === null || ch.value > min)
|
|
min = ch.value;
|
|
}
|
|
}
|
|
return min;
|
|
}
|
|
get maxValue() {
|
|
let max = null;
|
|
for (const ch of this._def.checks) {
|
|
if (ch.kind === "max") {
|
|
if (max === null || ch.value < max)
|
|
max = ch.value;
|
|
}
|
|
}
|
|
return max;
|
|
}
|
|
};
|
|
ZodBigInt.create = (params) => {
|
|
var _a;
|
|
return new ZodBigInt({
|
|
checks: [],
|
|
typeName: ZodFirstPartyTypeKind.ZodBigInt,
|
|
coerce: (_a = params == null ? void 0 : params.coerce) != null ? _a : false,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
var ZodBoolean = class extends ZodType {
|
|
_parse(input) {
|
|
if (this._def.coerce) {
|
|
input.data = Boolean(input.data);
|
|
}
|
|
const parsedType2 = this._getType(input);
|
|
if (parsedType2 !== ZodParsedType.boolean) {
|
|
const ctx = this._getOrReturnCtx(input);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_type,
|
|
expected: ZodParsedType.boolean,
|
|
received: ctx.parsedType
|
|
});
|
|
return INVALID;
|
|
}
|
|
return OK(input.data);
|
|
}
|
|
};
|
|
ZodBoolean.create = (params) => {
|
|
return new ZodBoolean({
|
|
typeName: ZodFirstPartyTypeKind.ZodBoolean,
|
|
coerce: (params == null ? void 0 : params.coerce) || false,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
var ZodDate = class _ZodDate extends ZodType {
|
|
_parse(input) {
|
|
if (this._def.coerce) {
|
|
input.data = new Date(input.data);
|
|
}
|
|
const parsedType2 = this._getType(input);
|
|
if (parsedType2 !== ZodParsedType.date) {
|
|
const ctx2 = this._getOrReturnCtx(input);
|
|
addIssueToContext(ctx2, {
|
|
code: ZodIssueCode.invalid_type,
|
|
expected: ZodParsedType.date,
|
|
received: ctx2.parsedType
|
|
});
|
|
return INVALID;
|
|
}
|
|
if (Number.isNaN(input.data.getTime())) {
|
|
const ctx2 = this._getOrReturnCtx(input);
|
|
addIssueToContext(ctx2, {
|
|
code: ZodIssueCode.invalid_date
|
|
});
|
|
return INVALID;
|
|
}
|
|
const status = new ParseStatus();
|
|
let ctx = void 0;
|
|
for (const check2 of this._def.checks) {
|
|
if (check2.kind === "min") {
|
|
if (input.data.getTime() < check2.value) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.too_small,
|
|
message: check2.message,
|
|
inclusive: true,
|
|
exact: false,
|
|
minimum: check2.value,
|
|
type: "date"
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check2.kind === "max") {
|
|
if (input.data.getTime() > check2.value) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.too_big,
|
|
message: check2.message,
|
|
inclusive: true,
|
|
exact: false,
|
|
maximum: check2.value,
|
|
type: "date"
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else {
|
|
util.assertNever(check2);
|
|
}
|
|
}
|
|
return {
|
|
status: status.value,
|
|
value: new Date(input.data.getTime())
|
|
};
|
|
}
|
|
_addCheck(check2) {
|
|
return new _ZodDate({
|
|
...this._def,
|
|
checks: [...this._def.checks, check2]
|
|
});
|
|
}
|
|
min(minDate, message) {
|
|
return this._addCheck({
|
|
kind: "min",
|
|
value: minDate.getTime(),
|
|
message: errorUtil.toString(message)
|
|
});
|
|
}
|
|
max(maxDate, message) {
|
|
return this._addCheck({
|
|
kind: "max",
|
|
value: maxDate.getTime(),
|
|
message: errorUtil.toString(message)
|
|
});
|
|
}
|
|
get minDate() {
|
|
let min = null;
|
|
for (const ch of this._def.checks) {
|
|
if (ch.kind === "min") {
|
|
if (min === null || ch.value > min)
|
|
min = ch.value;
|
|
}
|
|
}
|
|
return min != null ? new Date(min) : null;
|
|
}
|
|
get maxDate() {
|
|
let max = null;
|
|
for (const ch of this._def.checks) {
|
|
if (ch.kind === "max") {
|
|
if (max === null || ch.value < max)
|
|
max = ch.value;
|
|
}
|
|
}
|
|
return max != null ? new Date(max) : null;
|
|
}
|
|
};
|
|
ZodDate.create = (params) => {
|
|
return new ZodDate({
|
|
checks: [],
|
|
coerce: (params == null ? void 0 : params.coerce) || false,
|
|
typeName: ZodFirstPartyTypeKind.ZodDate,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
var ZodSymbol = class extends ZodType {
|
|
_parse(input) {
|
|
const parsedType2 = this._getType(input);
|
|
if (parsedType2 !== ZodParsedType.symbol) {
|
|
const ctx = this._getOrReturnCtx(input);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_type,
|
|
expected: ZodParsedType.symbol,
|
|
received: ctx.parsedType
|
|
});
|
|
return INVALID;
|
|
}
|
|
return OK(input.data);
|
|
}
|
|
};
|
|
ZodSymbol.create = (params) => {
|
|
return new ZodSymbol({
|
|
typeName: ZodFirstPartyTypeKind.ZodSymbol,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
var ZodUndefined = class extends ZodType {
|
|
_parse(input) {
|
|
const parsedType2 = this._getType(input);
|
|
if (parsedType2 !== ZodParsedType.undefined) {
|
|
const ctx = this._getOrReturnCtx(input);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_type,
|
|
expected: ZodParsedType.undefined,
|
|
received: ctx.parsedType
|
|
});
|
|
return INVALID;
|
|
}
|
|
return OK(input.data);
|
|
}
|
|
};
|
|
ZodUndefined.create = (params) => {
|
|
return new ZodUndefined({
|
|
typeName: ZodFirstPartyTypeKind.ZodUndefined,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
var ZodNull = class extends ZodType {
|
|
_parse(input) {
|
|
const parsedType2 = this._getType(input);
|
|
if (parsedType2 !== ZodParsedType.null) {
|
|
const ctx = this._getOrReturnCtx(input);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_type,
|
|
expected: ZodParsedType.null,
|
|
received: ctx.parsedType
|
|
});
|
|
return INVALID;
|
|
}
|
|
return OK(input.data);
|
|
}
|
|
};
|
|
ZodNull.create = (params) => {
|
|
return new ZodNull({
|
|
typeName: ZodFirstPartyTypeKind.ZodNull,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
var ZodAny = class extends ZodType {
|
|
constructor() {
|
|
super(...arguments);
|
|
this._any = true;
|
|
}
|
|
_parse(input) {
|
|
return OK(input.data);
|
|
}
|
|
};
|
|
ZodAny.create = (params) => {
|
|
return new ZodAny({
|
|
typeName: ZodFirstPartyTypeKind.ZodAny,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
var ZodUnknown = class extends ZodType {
|
|
constructor() {
|
|
super(...arguments);
|
|
this._unknown = true;
|
|
}
|
|
_parse(input) {
|
|
return OK(input.data);
|
|
}
|
|
};
|
|
ZodUnknown.create = (params) => {
|
|
return new ZodUnknown({
|
|
typeName: ZodFirstPartyTypeKind.ZodUnknown,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
var ZodNever = class extends ZodType {
|
|
_parse(input) {
|
|
const ctx = this._getOrReturnCtx(input);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_type,
|
|
expected: ZodParsedType.never,
|
|
received: ctx.parsedType
|
|
});
|
|
return INVALID;
|
|
}
|
|
};
|
|
ZodNever.create = (params) => {
|
|
return new ZodNever({
|
|
typeName: ZodFirstPartyTypeKind.ZodNever,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
var ZodVoid = class extends ZodType {
|
|
_parse(input) {
|
|
const parsedType2 = this._getType(input);
|
|
if (parsedType2 !== ZodParsedType.undefined) {
|
|
const ctx = this._getOrReturnCtx(input);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_type,
|
|
expected: ZodParsedType.void,
|
|
received: ctx.parsedType
|
|
});
|
|
return INVALID;
|
|
}
|
|
return OK(input.data);
|
|
}
|
|
};
|
|
ZodVoid.create = (params) => {
|
|
return new ZodVoid({
|
|
typeName: ZodFirstPartyTypeKind.ZodVoid,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
var ZodArray = class _ZodArray extends ZodType {
|
|
_parse(input) {
|
|
const { ctx, status } = this._processInputParams(input);
|
|
const def = this._def;
|
|
if (ctx.parsedType !== ZodParsedType.array) {
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_type,
|
|
expected: ZodParsedType.array,
|
|
received: ctx.parsedType
|
|
});
|
|
return INVALID;
|
|
}
|
|
if (def.exactLength !== null) {
|
|
const tooBig = ctx.data.length > def.exactLength.value;
|
|
const tooSmall = ctx.data.length < def.exactLength.value;
|
|
if (tooBig || tooSmall) {
|
|
addIssueToContext(ctx, {
|
|
code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
|
|
minimum: tooSmall ? def.exactLength.value : void 0,
|
|
maximum: tooBig ? def.exactLength.value : void 0,
|
|
type: "array",
|
|
inclusive: true,
|
|
exact: true,
|
|
message: def.exactLength.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
}
|
|
if (def.minLength !== null) {
|
|
if (ctx.data.length < def.minLength.value) {
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.too_small,
|
|
minimum: def.minLength.value,
|
|
type: "array",
|
|
inclusive: true,
|
|
exact: false,
|
|
message: def.minLength.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
}
|
|
if (def.maxLength !== null) {
|
|
if (ctx.data.length > def.maxLength.value) {
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.too_big,
|
|
maximum: def.maxLength.value,
|
|
type: "array",
|
|
inclusive: true,
|
|
exact: false,
|
|
message: def.maxLength.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
}
|
|
if (ctx.common.async) {
|
|
return Promise.all([...ctx.data].map((item, i) => {
|
|
return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
|
|
})).then((result2) => {
|
|
return ParseStatus.mergeArray(status, result2);
|
|
});
|
|
}
|
|
const result = [...ctx.data].map((item, i) => {
|
|
return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
|
|
});
|
|
return ParseStatus.mergeArray(status, result);
|
|
}
|
|
get element() {
|
|
return this._def.type;
|
|
}
|
|
min(minLength, message) {
|
|
return new _ZodArray({
|
|
...this._def,
|
|
minLength: { value: minLength, message: errorUtil.toString(message) }
|
|
});
|
|
}
|
|
max(maxLength, message) {
|
|
return new _ZodArray({
|
|
...this._def,
|
|
maxLength: { value: maxLength, message: errorUtil.toString(message) }
|
|
});
|
|
}
|
|
length(len, message) {
|
|
return new _ZodArray({
|
|
...this._def,
|
|
exactLength: { value: len, message: errorUtil.toString(message) }
|
|
});
|
|
}
|
|
nonempty(message) {
|
|
return this.min(1, message);
|
|
}
|
|
};
|
|
ZodArray.create = (schema, params) => {
|
|
return new ZodArray({
|
|
type: schema,
|
|
minLength: null,
|
|
maxLength: null,
|
|
exactLength: null,
|
|
typeName: ZodFirstPartyTypeKind.ZodArray,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
function deepPartialify(schema) {
|
|
if (schema instanceof ZodObject) {
|
|
const newShape = {};
|
|
for (const key in schema.shape) {
|
|
const fieldSchema = schema.shape[key];
|
|
newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
|
|
}
|
|
return new ZodObject({
|
|
...schema._def,
|
|
shape: () => newShape
|
|
});
|
|
} else if (schema instanceof ZodArray) {
|
|
return new ZodArray({
|
|
...schema._def,
|
|
type: deepPartialify(schema.element)
|
|
});
|
|
} else if (schema instanceof ZodOptional) {
|
|
return ZodOptional.create(deepPartialify(schema.unwrap()));
|
|
} else if (schema instanceof ZodNullable) {
|
|
return ZodNullable.create(deepPartialify(schema.unwrap()));
|
|
} else if (schema instanceof ZodTuple) {
|
|
return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
|
|
} else {
|
|
return schema;
|
|
}
|
|
}
|
|
var ZodObject = class _ZodObject extends ZodType {
|
|
constructor() {
|
|
super(...arguments);
|
|
this._cached = null;
|
|
this.nonstrict = this.passthrough;
|
|
this.augment = this.extend;
|
|
}
|
|
_getCached() {
|
|
if (this._cached !== null)
|
|
return this._cached;
|
|
const shape = this._def.shape();
|
|
const keys = util.objectKeys(shape);
|
|
this._cached = { shape, keys };
|
|
return this._cached;
|
|
}
|
|
_parse(input) {
|
|
const parsedType2 = this._getType(input);
|
|
if (parsedType2 !== ZodParsedType.object) {
|
|
const ctx2 = this._getOrReturnCtx(input);
|
|
addIssueToContext(ctx2, {
|
|
code: ZodIssueCode.invalid_type,
|
|
expected: ZodParsedType.object,
|
|
received: ctx2.parsedType
|
|
});
|
|
return INVALID;
|
|
}
|
|
const { status, ctx } = this._processInputParams(input);
|
|
const { shape, keys: shapeKeys } = this._getCached();
|
|
const extraKeys = [];
|
|
if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
|
|
for (const key in ctx.data) {
|
|
if (!shapeKeys.includes(key)) {
|
|
extraKeys.push(key);
|
|
}
|
|
}
|
|
}
|
|
const pairs = [];
|
|
for (const key of shapeKeys) {
|
|
const keyValidator = shape[key];
|
|
const value = ctx.data[key];
|
|
pairs.push({
|
|
key: { status: "valid", value: key },
|
|
value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
|
|
alwaysSet: key in ctx.data
|
|
});
|
|
}
|
|
if (this._def.catchall instanceof ZodNever) {
|
|
const unknownKeys = this._def.unknownKeys;
|
|
if (unknownKeys === "passthrough") {
|
|
for (const key of extraKeys) {
|
|
pairs.push({
|
|
key: { status: "valid", value: key },
|
|
value: { status: "valid", value: ctx.data[key] }
|
|
});
|
|
}
|
|
} else if (unknownKeys === "strict") {
|
|
if (extraKeys.length > 0) {
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.unrecognized_keys,
|
|
keys: extraKeys
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (unknownKeys === "strip") {
|
|
} else {
|
|
throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
|
|
}
|
|
} else {
|
|
const catchall = this._def.catchall;
|
|
for (const key of extraKeys) {
|
|
const value = ctx.data[key];
|
|
pairs.push({
|
|
key: { status: "valid", value: key },
|
|
value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
|
|
alwaysSet: key in ctx.data
|
|
});
|
|
}
|
|
}
|
|
if (ctx.common.async) {
|
|
return Promise.resolve().then(async () => {
|
|
const syncPairs = [];
|
|
for (const pair of pairs) {
|
|
const key = await pair.key;
|
|
const value = await pair.value;
|
|
syncPairs.push({
|
|
key,
|
|
value,
|
|
alwaysSet: pair.alwaysSet
|
|
});
|
|
}
|
|
return syncPairs;
|
|
}).then((syncPairs) => {
|
|
return ParseStatus.mergeObjectSync(status, syncPairs);
|
|
});
|
|
} else {
|
|
return ParseStatus.mergeObjectSync(status, pairs);
|
|
}
|
|
}
|
|
get shape() {
|
|
return this._def.shape();
|
|
}
|
|
strict(message) {
|
|
errorUtil.errToObj;
|
|
return new _ZodObject({
|
|
...this._def,
|
|
unknownKeys: "strict",
|
|
...message !== void 0 ? {
|
|
errorMap: (issue2, ctx) => {
|
|
var _a, _b, _c, _d;
|
|
const defaultError = (_c = (_b = (_a = this._def).errorMap) == null ? void 0 : _b.call(_a, issue2, ctx).message) != null ? _c : ctx.defaultError;
|
|
if (issue2.code === "unrecognized_keys")
|
|
return {
|
|
message: (_d = errorUtil.errToObj(message).message) != null ? _d : defaultError
|
|
};
|
|
return {
|
|
message: defaultError
|
|
};
|
|
}
|
|
} : {}
|
|
});
|
|
}
|
|
strip() {
|
|
return new _ZodObject({
|
|
...this._def,
|
|
unknownKeys: "strip"
|
|
});
|
|
}
|
|
passthrough() {
|
|
return new _ZodObject({
|
|
...this._def,
|
|
unknownKeys: "passthrough"
|
|
});
|
|
}
|
|
extend(augmentation) {
|
|
return new _ZodObject({
|
|
...this._def,
|
|
shape: () => ({
|
|
...this._def.shape(),
|
|
...augmentation
|
|
})
|
|
});
|
|
}
|
|
merge(merging) {
|
|
const merged = new _ZodObject({
|
|
unknownKeys: merging._def.unknownKeys,
|
|
catchall: merging._def.catchall,
|
|
shape: () => ({
|
|
...this._def.shape(),
|
|
...merging._def.shape()
|
|
}),
|
|
typeName: ZodFirstPartyTypeKind.ZodObject
|
|
});
|
|
return merged;
|
|
}
|
|
setKey(key, schema) {
|
|
return this.augment({ [key]: schema });
|
|
}
|
|
catchall(index) {
|
|
return new _ZodObject({
|
|
...this._def,
|
|
catchall: index
|
|
});
|
|
}
|
|
pick(mask) {
|
|
const shape = {};
|
|
for (const key of util.objectKeys(mask)) {
|
|
if (mask[key] && this.shape[key]) {
|
|
shape[key] = this.shape[key];
|
|
}
|
|
}
|
|
return new _ZodObject({
|
|
...this._def,
|
|
shape: () => shape
|
|
});
|
|
}
|
|
omit(mask) {
|
|
const shape = {};
|
|
for (const key of util.objectKeys(this.shape)) {
|
|
if (!mask[key]) {
|
|
shape[key] = this.shape[key];
|
|
}
|
|
}
|
|
return new _ZodObject({
|
|
...this._def,
|
|
shape: () => shape
|
|
});
|
|
}
|
|
deepPartial() {
|
|
return deepPartialify(this);
|
|
}
|
|
partial(mask) {
|
|
const newShape = {};
|
|
for (const key of util.objectKeys(this.shape)) {
|
|
const fieldSchema = this.shape[key];
|
|
if (mask && !mask[key]) {
|
|
newShape[key] = fieldSchema;
|
|
} else {
|
|
newShape[key] = fieldSchema.optional();
|
|
}
|
|
}
|
|
return new _ZodObject({
|
|
...this._def,
|
|
shape: () => newShape
|
|
});
|
|
}
|
|
required(mask) {
|
|
const newShape = {};
|
|
for (const key of util.objectKeys(this.shape)) {
|
|
if (mask && !mask[key]) {
|
|
newShape[key] = this.shape[key];
|
|
} else {
|
|
const fieldSchema = this.shape[key];
|
|
let newField = fieldSchema;
|
|
while (newField instanceof ZodOptional) {
|
|
newField = newField._def.innerType;
|
|
}
|
|
newShape[key] = newField;
|
|
}
|
|
}
|
|
return new _ZodObject({
|
|
...this._def,
|
|
shape: () => newShape
|
|
});
|
|
}
|
|
keyof() {
|
|
return createZodEnum(util.objectKeys(this.shape));
|
|
}
|
|
};
|
|
ZodObject.create = (shape, params) => {
|
|
return new ZodObject({
|
|
shape: () => shape,
|
|
unknownKeys: "strip",
|
|
catchall: ZodNever.create(),
|
|
typeName: ZodFirstPartyTypeKind.ZodObject,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
ZodObject.strictCreate = (shape, params) => {
|
|
return new ZodObject({
|
|
shape: () => shape,
|
|
unknownKeys: "strict",
|
|
catchall: ZodNever.create(),
|
|
typeName: ZodFirstPartyTypeKind.ZodObject,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
ZodObject.lazycreate = (shape, params) => {
|
|
return new ZodObject({
|
|
shape,
|
|
unknownKeys: "strip",
|
|
catchall: ZodNever.create(),
|
|
typeName: ZodFirstPartyTypeKind.ZodObject,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
var ZodUnion = class extends ZodType {
|
|
_parse(input) {
|
|
const { ctx } = this._processInputParams(input);
|
|
const options = this._def.options;
|
|
function handleResults(results) {
|
|
for (const result of results) {
|
|
if (result.result.status === "valid") {
|
|
return result.result;
|
|
}
|
|
}
|
|
for (const result of results) {
|
|
if (result.result.status === "dirty") {
|
|
ctx.common.issues.push(...result.ctx.common.issues);
|
|
return result.result;
|
|
}
|
|
}
|
|
const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_union,
|
|
unionErrors
|
|
});
|
|
return INVALID;
|
|
}
|
|
if (ctx.common.async) {
|
|
return Promise.all(options.map(async (option) => {
|
|
const childCtx = {
|
|
...ctx,
|
|
common: {
|
|
...ctx.common,
|
|
issues: []
|
|
},
|
|
parent: null
|
|
};
|
|
return {
|
|
result: await option._parseAsync({
|
|
data: ctx.data,
|
|
path: ctx.path,
|
|
parent: childCtx
|
|
}),
|
|
ctx: childCtx
|
|
};
|
|
})).then(handleResults);
|
|
} else {
|
|
let dirty = void 0;
|
|
const issues = [];
|
|
for (const option of options) {
|
|
const childCtx = {
|
|
...ctx,
|
|
common: {
|
|
...ctx.common,
|
|
issues: []
|
|
},
|
|
parent: null
|
|
};
|
|
const result = option._parseSync({
|
|
data: ctx.data,
|
|
path: ctx.path,
|
|
parent: childCtx
|
|
});
|
|
if (result.status === "valid") {
|
|
return result;
|
|
} else if (result.status === "dirty" && !dirty) {
|
|
dirty = { result, ctx: childCtx };
|
|
}
|
|
if (childCtx.common.issues.length) {
|
|
issues.push(childCtx.common.issues);
|
|
}
|
|
}
|
|
if (dirty) {
|
|
ctx.common.issues.push(...dirty.ctx.common.issues);
|
|
return dirty.result;
|
|
}
|
|
const unionErrors = issues.map((issues2) => new ZodError(issues2));
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_union,
|
|
unionErrors
|
|
});
|
|
return INVALID;
|
|
}
|
|
}
|
|
get options() {
|
|
return this._def.options;
|
|
}
|
|
};
|
|
ZodUnion.create = (types, params) => {
|
|
return new ZodUnion({
|
|
options: types,
|
|
typeName: ZodFirstPartyTypeKind.ZodUnion,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
var getDiscriminator = (type) => {
|
|
if (type instanceof ZodLazy) {
|
|
return getDiscriminator(type.schema);
|
|
} else if (type instanceof ZodEffects) {
|
|
return getDiscriminator(type.innerType());
|
|
} else if (type instanceof ZodLiteral) {
|
|
return [type.value];
|
|
} else if (type instanceof ZodEnum) {
|
|
return type.options;
|
|
} else if (type instanceof ZodNativeEnum) {
|
|
return util.objectValues(type.enum);
|
|
} else if (type instanceof ZodDefault) {
|
|
return getDiscriminator(type._def.innerType);
|
|
} else if (type instanceof ZodUndefined) {
|
|
return [void 0];
|
|
} else if (type instanceof ZodNull) {
|
|
return [null];
|
|
} else if (type instanceof ZodOptional) {
|
|
return [void 0, ...getDiscriminator(type.unwrap())];
|
|
} else if (type instanceof ZodNullable) {
|
|
return [null, ...getDiscriminator(type.unwrap())];
|
|
} else if (type instanceof ZodBranded) {
|
|
return getDiscriminator(type.unwrap());
|
|
} else if (type instanceof ZodReadonly) {
|
|
return getDiscriminator(type.unwrap());
|
|
} else if (type instanceof ZodCatch) {
|
|
return getDiscriminator(type._def.innerType);
|
|
} else {
|
|
return [];
|
|
}
|
|
};
|
|
var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
|
|
_parse(input) {
|
|
const { ctx } = this._processInputParams(input);
|
|
if (ctx.parsedType !== ZodParsedType.object) {
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_type,
|
|
expected: ZodParsedType.object,
|
|
received: ctx.parsedType
|
|
});
|
|
return INVALID;
|
|
}
|
|
const discriminator = this.discriminator;
|
|
const discriminatorValue = ctx.data[discriminator];
|
|
const option = this.optionsMap.get(discriminatorValue);
|
|
if (!option) {
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_union_discriminator,
|
|
options: Array.from(this.optionsMap.keys()),
|
|
path: [discriminator]
|
|
});
|
|
return INVALID;
|
|
}
|
|
if (ctx.common.async) {
|
|
return option._parseAsync({
|
|
data: ctx.data,
|
|
path: ctx.path,
|
|
parent: ctx
|
|
});
|
|
} else {
|
|
return option._parseSync({
|
|
data: ctx.data,
|
|
path: ctx.path,
|
|
parent: ctx
|
|
});
|
|
}
|
|
}
|
|
get discriminator() {
|
|
return this._def.discriminator;
|
|
}
|
|
get options() {
|
|
return this._def.options;
|
|
}
|
|
get optionsMap() {
|
|
return this._def.optionsMap;
|
|
}
|
|
static create(discriminator, options, params) {
|
|
const optionsMap = /* @__PURE__ */ new Map();
|
|
for (const type of options) {
|
|
const discriminatorValues = getDiscriminator(type.shape[discriminator]);
|
|
if (!discriminatorValues.length) {
|
|
throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
|
|
}
|
|
for (const value of discriminatorValues) {
|
|
if (optionsMap.has(value)) {
|
|
throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
|
|
}
|
|
optionsMap.set(value, type);
|
|
}
|
|
}
|
|
return new _ZodDiscriminatedUnion({
|
|
typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
|
|
discriminator,
|
|
options,
|
|
optionsMap,
|
|
...processCreateParams(params)
|
|
});
|
|
}
|
|
};
|
|
function mergeValues(a, b) {
|
|
const aType = getParsedType(a);
|
|
const bType = getParsedType(b);
|
|
if (a === b) {
|
|
return { valid: true, data: a };
|
|
} else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
|
|
const bKeys = util.objectKeys(b);
|
|
const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
|
|
const newObj = { ...a, ...b };
|
|
for (const key of sharedKeys) {
|
|
const sharedValue = mergeValues(a[key], b[key]);
|
|
if (!sharedValue.valid) {
|
|
return { valid: false };
|
|
}
|
|
newObj[key] = sharedValue.data;
|
|
}
|
|
return { valid: true, data: newObj };
|
|
} else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
|
|
if (a.length !== b.length) {
|
|
return { valid: false };
|
|
}
|
|
const newArray = [];
|
|
for (let index = 0; index < a.length; index++) {
|
|
const itemA = a[index];
|
|
const itemB = b[index];
|
|
const sharedValue = mergeValues(itemA, itemB);
|
|
if (!sharedValue.valid) {
|
|
return { valid: false };
|
|
}
|
|
newArray.push(sharedValue.data);
|
|
}
|
|
return { valid: true, data: newArray };
|
|
} else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
|
|
return { valid: true, data: a };
|
|
} else {
|
|
return { valid: false };
|
|
}
|
|
}
|
|
var ZodIntersection = class extends ZodType {
|
|
_parse(input) {
|
|
const { status, ctx } = this._processInputParams(input);
|
|
const handleParsed = (parsedLeft, parsedRight) => {
|
|
if (isAborted(parsedLeft) || isAborted(parsedRight)) {
|
|
return INVALID;
|
|
}
|
|
const merged = mergeValues(parsedLeft.value, parsedRight.value);
|
|
if (!merged.valid) {
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_intersection_types
|
|
});
|
|
return INVALID;
|
|
}
|
|
if (isDirty(parsedLeft) || isDirty(parsedRight)) {
|
|
status.dirty();
|
|
}
|
|
return { status: status.value, value: merged.data };
|
|
};
|
|
if (ctx.common.async) {
|
|
return Promise.all([
|
|
this._def.left._parseAsync({
|
|
data: ctx.data,
|
|
path: ctx.path,
|
|
parent: ctx
|
|
}),
|
|
this._def.right._parseAsync({
|
|
data: ctx.data,
|
|
path: ctx.path,
|
|
parent: ctx
|
|
})
|
|
]).then(([left, right]) => handleParsed(left, right));
|
|
} else {
|
|
return handleParsed(this._def.left._parseSync({
|
|
data: ctx.data,
|
|
path: ctx.path,
|
|
parent: ctx
|
|
}), this._def.right._parseSync({
|
|
data: ctx.data,
|
|
path: ctx.path,
|
|
parent: ctx
|
|
}));
|
|
}
|
|
}
|
|
};
|
|
ZodIntersection.create = (left, right, params) => {
|
|
return new ZodIntersection({
|
|
left,
|
|
right,
|
|
typeName: ZodFirstPartyTypeKind.ZodIntersection,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
var ZodTuple = class _ZodTuple extends ZodType {
|
|
_parse(input) {
|
|
const { status, ctx } = this._processInputParams(input);
|
|
if (ctx.parsedType !== ZodParsedType.array) {
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_type,
|
|
expected: ZodParsedType.array,
|
|
received: ctx.parsedType
|
|
});
|
|
return INVALID;
|
|
}
|
|
if (ctx.data.length < this._def.items.length) {
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.too_small,
|
|
minimum: this._def.items.length,
|
|
inclusive: true,
|
|
exact: false,
|
|
type: "array"
|
|
});
|
|
return INVALID;
|
|
}
|
|
const rest = this._def.rest;
|
|
if (!rest && ctx.data.length > this._def.items.length) {
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.too_big,
|
|
maximum: this._def.items.length,
|
|
inclusive: true,
|
|
exact: false,
|
|
type: "array"
|
|
});
|
|
status.dirty();
|
|
}
|
|
const items = [...ctx.data].map((item, itemIndex) => {
|
|
const schema = this._def.items[itemIndex] || this._def.rest;
|
|
if (!schema)
|
|
return null;
|
|
return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
|
|
}).filter((x) => !!x);
|
|
if (ctx.common.async) {
|
|
return Promise.all(items).then((results) => {
|
|
return ParseStatus.mergeArray(status, results);
|
|
});
|
|
} else {
|
|
return ParseStatus.mergeArray(status, items);
|
|
}
|
|
}
|
|
get items() {
|
|
return this._def.items;
|
|
}
|
|
rest(rest) {
|
|
return new _ZodTuple({
|
|
...this._def,
|
|
rest
|
|
});
|
|
}
|
|
};
|
|
ZodTuple.create = (schemas, params) => {
|
|
if (!Array.isArray(schemas)) {
|
|
throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
|
|
}
|
|
return new ZodTuple({
|
|
items: schemas,
|
|
typeName: ZodFirstPartyTypeKind.ZodTuple,
|
|
rest: null,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
var ZodRecord = class _ZodRecord extends ZodType {
|
|
get keySchema() {
|
|
return this._def.keyType;
|
|
}
|
|
get valueSchema() {
|
|
return this._def.valueType;
|
|
}
|
|
_parse(input) {
|
|
const { status, ctx } = this._processInputParams(input);
|
|
if (ctx.parsedType !== ZodParsedType.object) {
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_type,
|
|
expected: ZodParsedType.object,
|
|
received: ctx.parsedType
|
|
});
|
|
return INVALID;
|
|
}
|
|
const pairs = [];
|
|
const keyType = this._def.keyType;
|
|
const valueType = this._def.valueType;
|
|
for (const key in ctx.data) {
|
|
pairs.push({
|
|
key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
|
|
value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
|
|
alwaysSet: key in ctx.data
|
|
});
|
|
}
|
|
if (ctx.common.async) {
|
|
return ParseStatus.mergeObjectAsync(status, pairs);
|
|
} else {
|
|
return ParseStatus.mergeObjectSync(status, pairs);
|
|
}
|
|
}
|
|
get element() {
|
|
return this._def.valueType;
|
|
}
|
|
static create(first, second, third) {
|
|
if (second instanceof ZodType) {
|
|
return new _ZodRecord({
|
|
keyType: first,
|
|
valueType: second,
|
|
typeName: ZodFirstPartyTypeKind.ZodRecord,
|
|
...processCreateParams(third)
|
|
});
|
|
}
|
|
return new _ZodRecord({
|
|
keyType: ZodString.create(),
|
|
valueType: first,
|
|
typeName: ZodFirstPartyTypeKind.ZodRecord,
|
|
...processCreateParams(second)
|
|
});
|
|
}
|
|
};
|
|
var ZodMap = class extends ZodType {
|
|
get keySchema() {
|
|
return this._def.keyType;
|
|
}
|
|
get valueSchema() {
|
|
return this._def.valueType;
|
|
}
|
|
_parse(input) {
|
|
const { status, ctx } = this._processInputParams(input);
|
|
if (ctx.parsedType !== ZodParsedType.map) {
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_type,
|
|
expected: ZodParsedType.map,
|
|
received: ctx.parsedType
|
|
});
|
|
return INVALID;
|
|
}
|
|
const keyType = this._def.keyType;
|
|
const valueType = this._def.valueType;
|
|
const pairs = [...ctx.data.entries()].map(([key, value], index) => {
|
|
return {
|
|
key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
|
|
value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
|
|
};
|
|
});
|
|
if (ctx.common.async) {
|
|
const finalMap = /* @__PURE__ */ new Map();
|
|
return Promise.resolve().then(async () => {
|
|
for (const pair of pairs) {
|
|
const key = await pair.key;
|
|
const value = await pair.value;
|
|
if (key.status === "aborted" || value.status === "aborted") {
|
|
return INVALID;
|
|
}
|
|
if (key.status === "dirty" || value.status === "dirty") {
|
|
status.dirty();
|
|
}
|
|
finalMap.set(key.value, value.value);
|
|
}
|
|
return { status: status.value, value: finalMap };
|
|
});
|
|
} else {
|
|
const finalMap = /* @__PURE__ */ new Map();
|
|
for (const pair of pairs) {
|
|
const key = pair.key;
|
|
const value = pair.value;
|
|
if (key.status === "aborted" || value.status === "aborted") {
|
|
return INVALID;
|
|
}
|
|
if (key.status === "dirty" || value.status === "dirty") {
|
|
status.dirty();
|
|
}
|
|
finalMap.set(key.value, value.value);
|
|
}
|
|
return { status: status.value, value: finalMap };
|
|
}
|
|
}
|
|
};
|
|
ZodMap.create = (keyType, valueType, params) => {
|
|
return new ZodMap({
|
|
valueType,
|
|
keyType,
|
|
typeName: ZodFirstPartyTypeKind.ZodMap,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
var ZodSet = class _ZodSet extends ZodType {
|
|
_parse(input) {
|
|
const { status, ctx } = this._processInputParams(input);
|
|
if (ctx.parsedType !== ZodParsedType.set) {
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_type,
|
|
expected: ZodParsedType.set,
|
|
received: ctx.parsedType
|
|
});
|
|
return INVALID;
|
|
}
|
|
const def = this._def;
|
|
if (def.minSize !== null) {
|
|
if (ctx.data.size < def.minSize.value) {
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.too_small,
|
|
minimum: def.minSize.value,
|
|
type: "set",
|
|
inclusive: true,
|
|
exact: false,
|
|
message: def.minSize.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
}
|
|
if (def.maxSize !== null) {
|
|
if (ctx.data.size > def.maxSize.value) {
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.too_big,
|
|
maximum: def.maxSize.value,
|
|
type: "set",
|
|
inclusive: true,
|
|
exact: false,
|
|
message: def.maxSize.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
}
|
|
const valueType = this._def.valueType;
|
|
function finalizeSet(elements2) {
|
|
const parsedSet = /* @__PURE__ */ new Set();
|
|
for (const element of elements2) {
|
|
if (element.status === "aborted")
|
|
return INVALID;
|
|
if (element.status === "dirty")
|
|
status.dirty();
|
|
parsedSet.add(element.value);
|
|
}
|
|
return { status: status.value, value: parsedSet };
|
|
}
|
|
const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
|
|
if (ctx.common.async) {
|
|
return Promise.all(elements).then((elements2) => finalizeSet(elements2));
|
|
} else {
|
|
return finalizeSet(elements);
|
|
}
|
|
}
|
|
min(minSize, message) {
|
|
return new _ZodSet({
|
|
...this._def,
|
|
minSize: { value: minSize, message: errorUtil.toString(message) }
|
|
});
|
|
}
|
|
max(maxSize, message) {
|
|
return new _ZodSet({
|
|
...this._def,
|
|
maxSize: { value: maxSize, message: errorUtil.toString(message) }
|
|
});
|
|
}
|
|
size(size, message) {
|
|
return this.min(size, message).max(size, message);
|
|
}
|
|
nonempty(message) {
|
|
return this.min(1, message);
|
|
}
|
|
};
|
|
ZodSet.create = (valueType, params) => {
|
|
return new ZodSet({
|
|
valueType,
|
|
minSize: null,
|
|
maxSize: null,
|
|
typeName: ZodFirstPartyTypeKind.ZodSet,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
var ZodFunction = class _ZodFunction extends ZodType {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.validate = this.implement;
|
|
}
|
|
_parse(input) {
|
|
const { ctx } = this._processInputParams(input);
|
|
if (ctx.parsedType !== ZodParsedType.function) {
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_type,
|
|
expected: ZodParsedType.function,
|
|
received: ctx.parsedType
|
|
});
|
|
return INVALID;
|
|
}
|
|
function makeArgsIssue(args, error2) {
|
|
return makeIssue({
|
|
data: args,
|
|
path: ctx.path,
|
|
errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
|
|
issueData: {
|
|
code: ZodIssueCode.invalid_arguments,
|
|
argumentsError: error2
|
|
}
|
|
});
|
|
}
|
|
function makeReturnsIssue(returns, error2) {
|
|
return makeIssue({
|
|
data: returns,
|
|
path: ctx.path,
|
|
errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
|
|
issueData: {
|
|
code: ZodIssueCode.invalid_return_type,
|
|
returnTypeError: error2
|
|
}
|
|
});
|
|
}
|
|
const params = { errorMap: ctx.common.contextualErrorMap };
|
|
const fn = ctx.data;
|
|
if (this._def.returns instanceof ZodPromise) {
|
|
const me = this;
|
|
return OK(async function(...args) {
|
|
const error2 = new ZodError([]);
|
|
const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
|
|
error2.addIssue(makeArgsIssue(args, e));
|
|
throw error2;
|
|
});
|
|
const result = await Reflect.apply(fn, this, parsedArgs);
|
|
const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
|
|
error2.addIssue(makeReturnsIssue(result, e));
|
|
throw error2;
|
|
});
|
|
return parsedReturns;
|
|
});
|
|
} else {
|
|
const me = this;
|
|
return OK(function(...args) {
|
|
const parsedArgs = me._def.args.safeParse(args, params);
|
|
if (!parsedArgs.success) {
|
|
throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
|
|
}
|
|
const result = Reflect.apply(fn, this, parsedArgs.data);
|
|
const parsedReturns = me._def.returns.safeParse(result, params);
|
|
if (!parsedReturns.success) {
|
|
throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
|
|
}
|
|
return parsedReturns.data;
|
|
});
|
|
}
|
|
}
|
|
parameters() {
|
|
return this._def.args;
|
|
}
|
|
returnType() {
|
|
return this._def.returns;
|
|
}
|
|
args(...items) {
|
|
return new _ZodFunction({
|
|
...this._def,
|
|
args: ZodTuple.create(items).rest(ZodUnknown.create())
|
|
});
|
|
}
|
|
returns(returnType) {
|
|
return new _ZodFunction({
|
|
...this._def,
|
|
returns: returnType
|
|
});
|
|
}
|
|
implement(func) {
|
|
const validatedFunc = this.parse(func);
|
|
return validatedFunc;
|
|
}
|
|
strictImplement(func) {
|
|
const validatedFunc = this.parse(func);
|
|
return validatedFunc;
|
|
}
|
|
static create(args, returns, params) {
|
|
return new _ZodFunction({
|
|
args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
|
|
returns: returns || ZodUnknown.create(),
|
|
typeName: ZodFirstPartyTypeKind.ZodFunction,
|
|
...processCreateParams(params)
|
|
});
|
|
}
|
|
};
|
|
var ZodLazy = class extends ZodType {
|
|
get schema() {
|
|
return this._def.getter();
|
|
}
|
|
_parse(input) {
|
|
const { ctx } = this._processInputParams(input);
|
|
const lazySchema = this._def.getter();
|
|
return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
|
|
}
|
|
};
|
|
ZodLazy.create = (getter, params) => {
|
|
return new ZodLazy({
|
|
getter,
|
|
typeName: ZodFirstPartyTypeKind.ZodLazy,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
var ZodLiteral = class extends ZodType {
|
|
_parse(input) {
|
|
if (input.data !== this._def.value) {
|
|
const ctx = this._getOrReturnCtx(input);
|
|
addIssueToContext(ctx, {
|
|
received: ctx.data,
|
|
code: ZodIssueCode.invalid_literal,
|
|
expected: this._def.value
|
|
});
|
|
return INVALID;
|
|
}
|
|
return { status: "valid", value: input.data };
|
|
}
|
|
get value() {
|
|
return this._def.value;
|
|
}
|
|
};
|
|
ZodLiteral.create = (value, params) => {
|
|
return new ZodLiteral({
|
|
value,
|
|
typeName: ZodFirstPartyTypeKind.ZodLiteral,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
function createZodEnum(values, params) {
|
|
return new ZodEnum({
|
|
values,
|
|
typeName: ZodFirstPartyTypeKind.ZodEnum,
|
|
...processCreateParams(params)
|
|
});
|
|
}
|
|
var ZodEnum = class _ZodEnum extends ZodType {
|
|
_parse(input) {
|
|
if (typeof input.data !== "string") {
|
|
const ctx = this._getOrReturnCtx(input);
|
|
const expectedValues = this._def.values;
|
|
addIssueToContext(ctx, {
|
|
expected: util.joinValues(expectedValues),
|
|
received: ctx.parsedType,
|
|
code: ZodIssueCode.invalid_type
|
|
});
|
|
return INVALID;
|
|
}
|
|
if (!this._cache) {
|
|
this._cache = new Set(this._def.values);
|
|
}
|
|
if (!this._cache.has(input.data)) {
|
|
const ctx = this._getOrReturnCtx(input);
|
|
const expectedValues = this._def.values;
|
|
addIssueToContext(ctx, {
|
|
received: ctx.data,
|
|
code: ZodIssueCode.invalid_enum_value,
|
|
options: expectedValues
|
|
});
|
|
return INVALID;
|
|
}
|
|
return OK(input.data);
|
|
}
|
|
get options() {
|
|
return this._def.values;
|
|
}
|
|
get enum() {
|
|
const enumValues = {};
|
|
for (const val of this._def.values) {
|
|
enumValues[val] = val;
|
|
}
|
|
return enumValues;
|
|
}
|
|
get Values() {
|
|
const enumValues = {};
|
|
for (const val of this._def.values) {
|
|
enumValues[val] = val;
|
|
}
|
|
return enumValues;
|
|
}
|
|
get Enum() {
|
|
const enumValues = {};
|
|
for (const val of this._def.values) {
|
|
enumValues[val] = val;
|
|
}
|
|
return enumValues;
|
|
}
|
|
extract(values, newDef = this._def) {
|
|
return _ZodEnum.create(values, {
|
|
...this._def,
|
|
...newDef
|
|
});
|
|
}
|
|
exclude(values, newDef = this._def) {
|
|
return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
|
|
...this._def,
|
|
...newDef
|
|
});
|
|
}
|
|
};
|
|
ZodEnum.create = createZodEnum;
|
|
var ZodNativeEnum = class extends ZodType {
|
|
_parse(input) {
|
|
const nativeEnumValues = util.getValidEnumValues(this._def.values);
|
|
const ctx = this._getOrReturnCtx(input);
|
|
if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
|
|
const expectedValues = util.objectValues(nativeEnumValues);
|
|
addIssueToContext(ctx, {
|
|
expected: util.joinValues(expectedValues),
|
|
received: ctx.parsedType,
|
|
code: ZodIssueCode.invalid_type
|
|
});
|
|
return INVALID;
|
|
}
|
|
if (!this._cache) {
|
|
this._cache = new Set(util.getValidEnumValues(this._def.values));
|
|
}
|
|
if (!this._cache.has(input.data)) {
|
|
const expectedValues = util.objectValues(nativeEnumValues);
|
|
addIssueToContext(ctx, {
|
|
received: ctx.data,
|
|
code: ZodIssueCode.invalid_enum_value,
|
|
options: expectedValues
|
|
});
|
|
return INVALID;
|
|
}
|
|
return OK(input.data);
|
|
}
|
|
get enum() {
|
|
return this._def.values;
|
|
}
|
|
};
|
|
ZodNativeEnum.create = (values, params) => {
|
|
return new ZodNativeEnum({
|
|
values,
|
|
typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
var ZodPromise = class extends ZodType {
|
|
unwrap() {
|
|
return this._def.type;
|
|
}
|
|
_parse(input) {
|
|
const { ctx } = this._processInputParams(input);
|
|
if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_type,
|
|
expected: ZodParsedType.promise,
|
|
received: ctx.parsedType
|
|
});
|
|
return INVALID;
|
|
}
|
|
const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
|
|
return OK(promisified.then((data) => {
|
|
return this._def.type.parseAsync(data, {
|
|
path: ctx.path,
|
|
errorMap: ctx.common.contextualErrorMap
|
|
});
|
|
}));
|
|
}
|
|
};
|
|
ZodPromise.create = (schema, params) => {
|
|
return new ZodPromise({
|
|
type: schema,
|
|
typeName: ZodFirstPartyTypeKind.ZodPromise,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
var ZodEffects = class extends ZodType {
|
|
innerType() {
|
|
return this._def.schema;
|
|
}
|
|
sourceType() {
|
|
return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
|
|
}
|
|
_parse(input) {
|
|
const { status, ctx } = this._processInputParams(input);
|
|
const effect = this._def.effect || null;
|
|
const checkCtx = {
|
|
addIssue: (arg) => {
|
|
addIssueToContext(ctx, arg);
|
|
if (arg.fatal) {
|
|
status.abort();
|
|
} else {
|
|
status.dirty();
|
|
}
|
|
},
|
|
get path() {
|
|
return ctx.path;
|
|
}
|
|
};
|
|
checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
|
|
if (effect.type === "preprocess") {
|
|
const processed = effect.transform(ctx.data, checkCtx);
|
|
if (ctx.common.async) {
|
|
return Promise.resolve(processed).then(async (processed2) => {
|
|
if (status.value === "aborted")
|
|
return INVALID;
|
|
const result = await this._def.schema._parseAsync({
|
|
data: processed2,
|
|
path: ctx.path,
|
|
parent: ctx
|
|
});
|
|
if (result.status === "aborted")
|
|
return INVALID;
|
|
if (result.status === "dirty")
|
|
return DIRTY(result.value);
|
|
if (status.value === "dirty")
|
|
return DIRTY(result.value);
|
|
return result;
|
|
});
|
|
} else {
|
|
if (status.value === "aborted")
|
|
return INVALID;
|
|
const result = this._def.schema._parseSync({
|
|
data: processed,
|
|
path: ctx.path,
|
|
parent: ctx
|
|
});
|
|
if (result.status === "aborted")
|
|
return INVALID;
|
|
if (result.status === "dirty")
|
|
return DIRTY(result.value);
|
|
if (status.value === "dirty")
|
|
return DIRTY(result.value);
|
|
return result;
|
|
}
|
|
}
|
|
if (effect.type === "refinement") {
|
|
const executeRefinement = (acc) => {
|
|
const result = effect.refinement(acc, checkCtx);
|
|
if (ctx.common.async) {
|
|
return Promise.resolve(result);
|
|
}
|
|
if (result instanceof Promise) {
|
|
throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
|
|
}
|
|
return acc;
|
|
};
|
|
if (ctx.common.async === false) {
|
|
const inner = this._def.schema._parseSync({
|
|
data: ctx.data,
|
|
path: ctx.path,
|
|
parent: ctx
|
|
});
|
|
if (inner.status === "aborted")
|
|
return INVALID;
|
|
if (inner.status === "dirty")
|
|
status.dirty();
|
|
executeRefinement(inner.value);
|
|
return { status: status.value, value: inner.value };
|
|
} else {
|
|
return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
|
|
if (inner.status === "aborted")
|
|
return INVALID;
|
|
if (inner.status === "dirty")
|
|
status.dirty();
|
|
return executeRefinement(inner.value).then(() => {
|
|
return { status: status.value, value: inner.value };
|
|
});
|
|
});
|
|
}
|
|
}
|
|
if (effect.type === "transform") {
|
|
if (ctx.common.async === false) {
|
|
const base = this._def.schema._parseSync({
|
|
data: ctx.data,
|
|
path: ctx.path,
|
|
parent: ctx
|
|
});
|
|
if (!isValid(base))
|
|
return INVALID;
|
|
const result = effect.transform(base.value, checkCtx);
|
|
if (result instanceof Promise) {
|
|
throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
|
|
}
|
|
return { status: status.value, value: result };
|
|
} else {
|
|
return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
|
|
if (!isValid(base))
|
|
return INVALID;
|
|
return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
|
|
status: status.value,
|
|
value: result
|
|
}));
|
|
});
|
|
}
|
|
}
|
|
util.assertNever(effect);
|
|
}
|
|
};
|
|
ZodEffects.create = (schema, effect, params) => {
|
|
return new ZodEffects({
|
|
schema,
|
|
typeName: ZodFirstPartyTypeKind.ZodEffects,
|
|
effect,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
ZodEffects.createWithPreprocess = (preprocess2, schema, params) => {
|
|
return new ZodEffects({
|
|
schema,
|
|
effect: { type: "preprocess", transform: preprocess2 },
|
|
typeName: ZodFirstPartyTypeKind.ZodEffects,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
var ZodOptional = class extends ZodType {
|
|
_parse(input) {
|
|
const parsedType2 = this._getType(input);
|
|
if (parsedType2 === ZodParsedType.undefined) {
|
|
return OK(void 0);
|
|
}
|
|
return this._def.innerType._parse(input);
|
|
}
|
|
unwrap() {
|
|
return this._def.innerType;
|
|
}
|
|
};
|
|
ZodOptional.create = (type, params) => {
|
|
return new ZodOptional({
|
|
innerType: type,
|
|
typeName: ZodFirstPartyTypeKind.ZodOptional,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
var ZodNullable = class extends ZodType {
|
|
_parse(input) {
|
|
const parsedType2 = this._getType(input);
|
|
if (parsedType2 === ZodParsedType.null) {
|
|
return OK(null);
|
|
}
|
|
return this._def.innerType._parse(input);
|
|
}
|
|
unwrap() {
|
|
return this._def.innerType;
|
|
}
|
|
};
|
|
ZodNullable.create = (type, params) => {
|
|
return new ZodNullable({
|
|
innerType: type,
|
|
typeName: ZodFirstPartyTypeKind.ZodNullable,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
var ZodDefault = class extends ZodType {
|
|
_parse(input) {
|
|
const { ctx } = this._processInputParams(input);
|
|
let data = ctx.data;
|
|
if (ctx.parsedType === ZodParsedType.undefined) {
|
|
data = this._def.defaultValue();
|
|
}
|
|
return this._def.innerType._parse({
|
|
data,
|
|
path: ctx.path,
|
|
parent: ctx
|
|
});
|
|
}
|
|
removeDefault() {
|
|
return this._def.innerType;
|
|
}
|
|
};
|
|
ZodDefault.create = (type, params) => {
|
|
return new ZodDefault({
|
|
innerType: type,
|
|
typeName: ZodFirstPartyTypeKind.ZodDefault,
|
|
defaultValue: typeof params.default === "function" ? params.default : () => params.default,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
var ZodCatch = class extends ZodType {
|
|
_parse(input) {
|
|
const { ctx } = this._processInputParams(input);
|
|
const newCtx = {
|
|
...ctx,
|
|
common: {
|
|
...ctx.common,
|
|
issues: []
|
|
}
|
|
};
|
|
const result = this._def.innerType._parse({
|
|
data: newCtx.data,
|
|
path: newCtx.path,
|
|
parent: {
|
|
...newCtx
|
|
}
|
|
});
|
|
if (isAsync(result)) {
|
|
return result.then((result2) => {
|
|
return {
|
|
status: "valid",
|
|
value: result2.status === "valid" ? result2.value : this._def.catchValue({
|
|
get error() {
|
|
return new ZodError(newCtx.common.issues);
|
|
},
|
|
input: newCtx.data
|
|
})
|
|
};
|
|
});
|
|
} else {
|
|
return {
|
|
status: "valid",
|
|
value: result.status === "valid" ? result.value : this._def.catchValue({
|
|
get error() {
|
|
return new ZodError(newCtx.common.issues);
|
|
},
|
|
input: newCtx.data
|
|
})
|
|
};
|
|
}
|
|
}
|
|
removeCatch() {
|
|
return this._def.innerType;
|
|
}
|
|
};
|
|
ZodCatch.create = (type, params) => {
|
|
return new ZodCatch({
|
|
innerType: type,
|
|
typeName: ZodFirstPartyTypeKind.ZodCatch,
|
|
catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
var ZodNaN = class extends ZodType {
|
|
_parse(input) {
|
|
const parsedType2 = this._getType(input);
|
|
if (parsedType2 !== ZodParsedType.nan) {
|
|
const ctx = this._getOrReturnCtx(input);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_type,
|
|
expected: ZodParsedType.nan,
|
|
received: ctx.parsedType
|
|
});
|
|
return INVALID;
|
|
}
|
|
return { status: "valid", value: input.data };
|
|
}
|
|
};
|
|
ZodNaN.create = (params) => {
|
|
return new ZodNaN({
|
|
typeName: ZodFirstPartyTypeKind.ZodNaN,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
var ZodBranded = class extends ZodType {
|
|
_parse(input) {
|
|
const { ctx } = this._processInputParams(input);
|
|
const data = ctx.data;
|
|
return this._def.type._parse({
|
|
data,
|
|
path: ctx.path,
|
|
parent: ctx
|
|
});
|
|
}
|
|
unwrap() {
|
|
return this._def.type;
|
|
}
|
|
};
|
|
var ZodPipeline = class _ZodPipeline extends ZodType {
|
|
_parse(input) {
|
|
const { status, ctx } = this._processInputParams(input);
|
|
if (ctx.common.async) {
|
|
const handleAsync = async () => {
|
|
const inResult = await this._def.in._parseAsync({
|
|
data: ctx.data,
|
|
path: ctx.path,
|
|
parent: ctx
|
|
});
|
|
if (inResult.status === "aborted")
|
|
return INVALID;
|
|
if (inResult.status === "dirty") {
|
|
status.dirty();
|
|
return DIRTY(inResult.value);
|
|
} else {
|
|
return this._def.out._parseAsync({
|
|
data: inResult.value,
|
|
path: ctx.path,
|
|
parent: ctx
|
|
});
|
|
}
|
|
};
|
|
return handleAsync();
|
|
} else {
|
|
const inResult = this._def.in._parseSync({
|
|
data: ctx.data,
|
|
path: ctx.path,
|
|
parent: ctx
|
|
});
|
|
if (inResult.status === "aborted")
|
|
return INVALID;
|
|
if (inResult.status === "dirty") {
|
|
status.dirty();
|
|
return {
|
|
status: "dirty",
|
|
value: inResult.value
|
|
};
|
|
} else {
|
|
return this._def.out._parseSync({
|
|
data: inResult.value,
|
|
path: ctx.path,
|
|
parent: ctx
|
|
});
|
|
}
|
|
}
|
|
}
|
|
static create(a, b) {
|
|
return new _ZodPipeline({
|
|
in: a,
|
|
out: b,
|
|
typeName: ZodFirstPartyTypeKind.ZodPipeline
|
|
});
|
|
}
|
|
};
|
|
var ZodReadonly = class extends ZodType {
|
|
_parse(input) {
|
|
const result = this._def.innerType._parse(input);
|
|
const freeze = (data) => {
|
|
if (isValid(data)) {
|
|
data.value = Object.freeze(data.value);
|
|
}
|
|
return data;
|
|
};
|
|
return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
|
|
}
|
|
unwrap() {
|
|
return this._def.innerType;
|
|
}
|
|
};
|
|
ZodReadonly.create = (type, params) => {
|
|
return new ZodReadonly({
|
|
innerType: type,
|
|
typeName: ZodFirstPartyTypeKind.ZodReadonly,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
var late = {
|
|
object: ZodObject.lazycreate
|
|
};
|
|
var ZodFirstPartyTypeKind;
|
|
(function(ZodFirstPartyTypeKind2) {
|
|
ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
|
|
ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
|
|
ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
|
|
ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
|
|
ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
|
|
ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
|
|
ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
|
|
ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
|
|
ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
|
|
ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
|
|
ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
|
|
ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
|
|
ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
|
|
ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
|
|
ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
|
|
ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
|
|
ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
|
|
ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
|
|
ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
|
|
ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
|
|
ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
|
|
ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
|
|
ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
|
|
ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
|
|
ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
|
|
ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
|
|
ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
|
|
ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
|
|
ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
|
|
ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
|
|
ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
|
|
ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
|
|
ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
|
|
ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
|
|
ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
|
|
ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
|
|
})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
|
|
var stringType = ZodString.create;
|
|
var numberType = ZodNumber.create;
|
|
var nanType = ZodNaN.create;
|
|
var bigIntType = ZodBigInt.create;
|
|
var booleanType = ZodBoolean.create;
|
|
var dateType = ZodDate.create;
|
|
var symbolType = ZodSymbol.create;
|
|
var undefinedType = ZodUndefined.create;
|
|
var nullType = ZodNull.create;
|
|
var anyType = ZodAny.create;
|
|
var unknownType = ZodUnknown.create;
|
|
var neverType = ZodNever.create;
|
|
var voidType = ZodVoid.create;
|
|
var arrayType = ZodArray.create;
|
|
var objectType = ZodObject.create;
|
|
var strictObjectType = ZodObject.strictCreate;
|
|
var unionType = ZodUnion.create;
|
|
var discriminatedUnionType = ZodDiscriminatedUnion.create;
|
|
var intersectionType = ZodIntersection.create;
|
|
var tupleType = ZodTuple.create;
|
|
var recordType = ZodRecord.create;
|
|
var mapType = ZodMap.create;
|
|
var setType = ZodSet.create;
|
|
var functionType = ZodFunction.create;
|
|
var lazyType = ZodLazy.create;
|
|
var literalType = ZodLiteral.create;
|
|
var enumType = ZodEnum.create;
|
|
var nativeEnumType = ZodNativeEnum.create;
|
|
var promiseType = ZodPromise.create;
|
|
var effectsType = ZodEffects.create;
|
|
var optionalType = ZodOptional.create;
|
|
var nullableType = ZodNullable.create;
|
|
var preprocessType = ZodEffects.createWithPreprocess;
|
|
var pipelineType = ZodPipeline.create;
|
|
var NEVER = Object.freeze({
|
|
status: "aborted"
|
|
});
|
|
function $constructor(name, initializer3, params) {
|
|
var _a;
|
|
function init(inst, def) {
|
|
var _a3, _b;
|
|
var _a2;
|
|
Object.defineProperty(inst, "_zod", {
|
|
value: (_a3 = inst._zod) != null ? _a3 : {},
|
|
enumerable: false
|
|
});
|
|
(_b = (_a2 = inst._zod).traits) != null ? _b : _a2.traits = /* @__PURE__ */ new Set();
|
|
inst._zod.traits.add(name);
|
|
initializer3(inst, def);
|
|
for (const k in _.prototype) {
|
|
if (!(k in inst))
|
|
Object.defineProperty(inst, k, { value: _.prototype[k].bind(inst) });
|
|
}
|
|
inst._zod.constr = _;
|
|
inst._zod.def = def;
|
|
}
|
|
const Parent = (_a = params == null ? void 0 : params.Parent) != null ? _a : Object;
|
|
class Definition extends Parent {
|
|
}
|
|
Object.defineProperty(Definition, "name", { value: name });
|
|
function _(def) {
|
|
var _a3;
|
|
var _a2;
|
|
const inst = (params == null ? void 0 : params.Parent) ? new Definition() : this;
|
|
init(inst, def);
|
|
(_a3 = (_a2 = inst._zod).deferred) != null ? _a3 : _a2.deferred = [];
|
|
for (const fn of inst._zod.deferred) {
|
|
fn();
|
|
}
|
|
return inst;
|
|
}
|
|
Object.defineProperty(_, "init", { value: init });
|
|
Object.defineProperty(_, Symbol.hasInstance, {
|
|
value: (inst) => {
|
|
var _a2, _b;
|
|
if ((params == null ? void 0 : params.Parent) && inst instanceof params.Parent)
|
|
return true;
|
|
return (_b = (_a2 = inst == null ? void 0 : inst._zod) == null ? void 0 : _a2.traits) == null ? void 0 : _b.has(name);
|
|
}
|
|
});
|
|
Object.defineProperty(_, "name", { value: name });
|
|
return _;
|
|
}
|
|
var $ZodAsyncError = class extends Error {
|
|
constructor() {
|
|
super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
|
|
}
|
|
};
|
|
var globalConfig = {};
|
|
function config(newConfig) {
|
|
if (newConfig)
|
|
Object.assign(globalConfig, newConfig);
|
|
return globalConfig;
|
|
}
|
|
var exports_util = {};
|
|
__export2(exports_util, {
|
|
unwrapMessage: () => unwrapMessage,
|
|
stringifyPrimitive: () => stringifyPrimitive,
|
|
required: () => required,
|
|
randomString: () => randomString,
|
|
propertyKeyTypes: () => propertyKeyTypes,
|
|
promiseAllObject: () => promiseAllObject,
|
|
primitiveTypes: () => primitiveTypes,
|
|
prefixIssues: () => prefixIssues,
|
|
pick: () => pick,
|
|
partial: () => partial,
|
|
optionalKeys: () => optionalKeys,
|
|
omit: () => omit,
|
|
numKeys: () => numKeys,
|
|
nullish: () => nullish,
|
|
normalizeParams: () => normalizeParams,
|
|
merge: () => merge,
|
|
jsonStringifyReplacer: () => jsonStringifyReplacer,
|
|
joinValues: () => joinValues,
|
|
issue: () => issue,
|
|
isPlainObject: () => isPlainObject,
|
|
isObject: () => isObject2,
|
|
getSizableOrigin: () => getSizableOrigin,
|
|
getParsedType: () => getParsedType2,
|
|
getLengthableOrigin: () => getLengthableOrigin,
|
|
getEnumValues: () => getEnumValues,
|
|
getElementAtPath: () => getElementAtPath,
|
|
floatSafeRemainder: () => floatSafeRemainder2,
|
|
finalizeIssue: () => finalizeIssue,
|
|
extend: () => extend,
|
|
escapeRegex: () => escapeRegex,
|
|
esc: () => esc,
|
|
defineLazy: () => defineLazy,
|
|
createTransparentProxy: () => createTransparentProxy,
|
|
clone: () => clone,
|
|
cleanRegex: () => cleanRegex,
|
|
cleanEnum: () => cleanEnum,
|
|
captureStackTrace: () => captureStackTrace,
|
|
cached: () => cached,
|
|
assignProp: () => assignProp,
|
|
assertNotEqual: () => assertNotEqual,
|
|
assertNever: () => assertNever,
|
|
assertIs: () => assertIs,
|
|
assertEqual: () => assertEqual,
|
|
assert: () => assert,
|
|
allowsEval: () => allowsEval,
|
|
aborted: () => aborted,
|
|
NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES,
|
|
Class: () => Class,
|
|
BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES
|
|
});
|
|
function assertEqual(val) {
|
|
return val;
|
|
}
|
|
function assertNotEqual(val) {
|
|
return val;
|
|
}
|
|
function assertIs(_arg) {
|
|
}
|
|
function assertNever(_x) {
|
|
throw new Error();
|
|
}
|
|
function assert(_) {
|
|
}
|
|
function getEnumValues(entries) {
|
|
const numericValues = Object.values(entries).filter((v) => typeof v === "number");
|
|
const values = Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v);
|
|
return values;
|
|
}
|
|
function joinValues(array2, separator = "|") {
|
|
return array2.map((val) => stringifyPrimitive(val)).join(separator);
|
|
}
|
|
function jsonStringifyReplacer(_, value) {
|
|
if (typeof value === "bigint")
|
|
return value.toString();
|
|
return value;
|
|
}
|
|
function cached(getter) {
|
|
const set = false;
|
|
return {
|
|
get value() {
|
|
if (!set) {
|
|
const value = getter();
|
|
Object.defineProperty(this, "value", { value });
|
|
return value;
|
|
}
|
|
throw new Error("cached value already set");
|
|
}
|
|
};
|
|
}
|
|
function nullish(input) {
|
|
return input === null || input === void 0;
|
|
}
|
|
function cleanRegex(source) {
|
|
const start = source.startsWith("^") ? 1 : 0;
|
|
const end = source.endsWith("$") ? source.length - 1 : source.length;
|
|
return source.slice(start, end);
|
|
}
|
|
function floatSafeRemainder2(val, step) {
|
|
const valDecCount = (val.toString().split(".")[1] || "").length;
|
|
const stepDecCount = (step.toString().split(".")[1] || "").length;
|
|
const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
|
|
const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
|
|
const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
|
|
return valInt % stepInt / 10 ** decCount;
|
|
}
|
|
function defineLazy(object, key, getter) {
|
|
const set = false;
|
|
Object.defineProperty(object, key, {
|
|
get() {
|
|
if (!set) {
|
|
const value = getter();
|
|
object[key] = value;
|
|
return value;
|
|
}
|
|
throw new Error("cached value already set");
|
|
},
|
|
set(v) {
|
|
Object.defineProperty(object, key, {
|
|
value: v
|
|
});
|
|
},
|
|
configurable: true
|
|
});
|
|
}
|
|
function assignProp(target, prop, value) {
|
|
Object.defineProperty(target, prop, {
|
|
value,
|
|
writable: true,
|
|
enumerable: true,
|
|
configurable: true
|
|
});
|
|
}
|
|
function getElementAtPath(obj, path12) {
|
|
if (!path12)
|
|
return obj;
|
|
return path12.reduce((acc, key) => acc == null ? void 0 : acc[key], obj);
|
|
}
|
|
function promiseAllObject(promisesObj) {
|
|
const keys = Object.keys(promisesObj);
|
|
const promises = keys.map((key) => promisesObj[key]);
|
|
return Promise.all(promises).then((results) => {
|
|
const resolvedObj = {};
|
|
for (let i = 0; i < keys.length; i++) {
|
|
resolvedObj[keys[i]] = results[i];
|
|
}
|
|
return resolvedObj;
|
|
});
|
|
}
|
|
function randomString(length = 10) {
|
|
const chars = "abcdefghijklmnopqrstuvwxyz";
|
|
let str = "";
|
|
for (let i = 0; i < length; i++) {
|
|
str += chars[Math.floor(Math.random() * chars.length)];
|
|
}
|
|
return str;
|
|
}
|
|
function esc(str) {
|
|
return JSON.stringify(str);
|
|
}
|
|
var captureStackTrace = Error.captureStackTrace ? Error.captureStackTrace : (..._args) => {
|
|
};
|
|
function isObject2(data) {
|
|
return typeof data === "object" && data !== null && !Array.isArray(data);
|
|
}
|
|
var allowsEval = cached(() => {
|
|
var _a;
|
|
if (typeof navigator !== "undefined" && ((_a = navigator == null ? void 0 : navigator.userAgent) == null ? void 0 : _a.includes("Cloudflare"))) {
|
|
return false;
|
|
}
|
|
try {
|
|
const F = Function;
|
|
new F("");
|
|
return true;
|
|
} catch (_) {
|
|
return false;
|
|
}
|
|
});
|
|
function isPlainObject(o) {
|
|
if (isObject2(o) === false)
|
|
return false;
|
|
const ctor = o.constructor;
|
|
if (ctor === void 0)
|
|
return true;
|
|
const prot = ctor.prototype;
|
|
if (isObject2(prot) === false)
|
|
return false;
|
|
if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) {
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
function numKeys(data) {
|
|
let keyCount = 0;
|
|
for (const key in data) {
|
|
if (Object.prototype.hasOwnProperty.call(data, key)) {
|
|
keyCount++;
|
|
}
|
|
}
|
|
return keyCount;
|
|
}
|
|
var getParsedType2 = (data) => {
|
|
const t = typeof data;
|
|
switch (t) {
|
|
case "undefined":
|
|
return "undefined";
|
|
case "string":
|
|
return "string";
|
|
case "number":
|
|
return Number.isNaN(data) ? "nan" : "number";
|
|
case "boolean":
|
|
return "boolean";
|
|
case "function":
|
|
return "function";
|
|
case "bigint":
|
|
return "bigint";
|
|
case "symbol":
|
|
return "symbol";
|
|
case "object":
|
|
if (Array.isArray(data)) {
|
|
return "array";
|
|
}
|
|
if (data === null) {
|
|
return "null";
|
|
}
|
|
if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
|
|
return "promise";
|
|
}
|
|
if (typeof Map !== "undefined" && data instanceof Map) {
|
|
return "map";
|
|
}
|
|
if (typeof Set !== "undefined" && data instanceof Set) {
|
|
return "set";
|
|
}
|
|
if (typeof Date !== "undefined" && data instanceof Date) {
|
|
return "date";
|
|
}
|
|
if (typeof File !== "undefined" && data instanceof File) {
|
|
return "file";
|
|
}
|
|
return "object";
|
|
default:
|
|
throw new Error(`Unknown data type: ${t}`);
|
|
}
|
|
};
|
|
var propertyKeyTypes = /* @__PURE__ */ new Set(["string", "number", "symbol"]);
|
|
var primitiveTypes = /* @__PURE__ */ new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]);
|
|
function escapeRegex(str) {
|
|
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
}
|
|
function clone(inst, def, params) {
|
|
const cl = new inst._zod.constr(def != null ? def : inst._zod.def);
|
|
if (!def || (params == null ? void 0 : params.parent))
|
|
cl._zod.parent = inst;
|
|
return cl;
|
|
}
|
|
function normalizeParams(_params) {
|
|
const params = _params;
|
|
if (!params)
|
|
return {};
|
|
if (typeof params === "string")
|
|
return { error: () => params };
|
|
if ((params == null ? void 0 : params.message) !== void 0) {
|
|
if ((params == null ? void 0 : params.error) !== void 0)
|
|
throw new Error("Cannot specify both `message` and `error` params");
|
|
params.error = params.message;
|
|
}
|
|
delete params.message;
|
|
if (typeof params.error === "string")
|
|
return { ...params, error: () => params.error };
|
|
return params;
|
|
}
|
|
function createTransparentProxy(getter) {
|
|
let target;
|
|
return new Proxy({}, {
|
|
get(_, prop, receiver) {
|
|
target != null ? target : target = getter();
|
|
return Reflect.get(target, prop, receiver);
|
|
},
|
|
set(_, prop, value, receiver) {
|
|
target != null ? target : target = getter();
|
|
return Reflect.set(target, prop, value, receiver);
|
|
},
|
|
has(_, prop) {
|
|
target != null ? target : target = getter();
|
|
return Reflect.has(target, prop);
|
|
},
|
|
deleteProperty(_, prop) {
|
|
target != null ? target : target = getter();
|
|
return Reflect.deleteProperty(target, prop);
|
|
},
|
|
ownKeys(_) {
|
|
target != null ? target : target = getter();
|
|
return Reflect.ownKeys(target);
|
|
},
|
|
getOwnPropertyDescriptor(_, prop) {
|
|
target != null ? target : target = getter();
|
|
return Reflect.getOwnPropertyDescriptor(target, prop);
|
|
},
|
|
defineProperty(_, prop, descriptor) {
|
|
target != null ? target : target = getter();
|
|
return Reflect.defineProperty(target, prop, descriptor);
|
|
}
|
|
});
|
|
}
|
|
function stringifyPrimitive(value) {
|
|
if (typeof value === "bigint")
|
|
return value.toString() + "n";
|
|
if (typeof value === "string")
|
|
return `"${value}"`;
|
|
return `${value}`;
|
|
}
|
|
function optionalKeys(shape) {
|
|
return Object.keys(shape).filter((k) => {
|
|
return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional";
|
|
});
|
|
}
|
|
var NUMBER_FORMAT_RANGES = {
|
|
safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
|
|
int32: [-2147483648, 2147483647],
|
|
uint32: [0, 4294967295],
|
|
float32: [-34028234663852886e22, 34028234663852886e22],
|
|
float64: [-Number.MAX_VALUE, Number.MAX_VALUE]
|
|
};
|
|
var BIGINT_FORMAT_RANGES = {
|
|
int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")],
|
|
uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")]
|
|
};
|
|
function pick(schema, mask) {
|
|
const newShape = {};
|
|
const currDef = schema._zod.def;
|
|
for (const key in mask) {
|
|
if (!(key in currDef.shape)) {
|
|
throw new Error(`Unrecognized key: "${key}"`);
|
|
}
|
|
if (!mask[key])
|
|
continue;
|
|
newShape[key] = currDef.shape[key];
|
|
}
|
|
return clone(schema, {
|
|
...schema._zod.def,
|
|
shape: newShape,
|
|
checks: []
|
|
});
|
|
}
|
|
function omit(schema, mask) {
|
|
const newShape = { ...schema._zod.def.shape };
|
|
const currDef = schema._zod.def;
|
|
for (const key in mask) {
|
|
if (!(key in currDef.shape)) {
|
|
throw new Error(`Unrecognized key: "${key}"`);
|
|
}
|
|
if (!mask[key])
|
|
continue;
|
|
delete newShape[key];
|
|
}
|
|
return clone(schema, {
|
|
...schema._zod.def,
|
|
shape: newShape,
|
|
checks: []
|
|
});
|
|
}
|
|
function extend(schema, shape) {
|
|
if (!isPlainObject(shape)) {
|
|
throw new Error("Invalid input to extend: expected a plain object");
|
|
}
|
|
const def = {
|
|
...schema._zod.def,
|
|
get shape() {
|
|
const _shape = { ...schema._zod.def.shape, ...shape };
|
|
assignProp(this, "shape", _shape);
|
|
return _shape;
|
|
},
|
|
checks: []
|
|
};
|
|
return clone(schema, def);
|
|
}
|
|
function merge(a, b) {
|
|
return clone(a, {
|
|
...a._zod.def,
|
|
get shape() {
|
|
const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };
|
|
assignProp(this, "shape", _shape);
|
|
return _shape;
|
|
},
|
|
catchall: b._zod.def.catchall,
|
|
checks: []
|
|
});
|
|
}
|
|
function partial(Class2, schema, mask) {
|
|
const oldShape = schema._zod.def.shape;
|
|
const shape = { ...oldShape };
|
|
if (mask) {
|
|
for (const key in mask) {
|
|
if (!(key in oldShape)) {
|
|
throw new Error(`Unrecognized key: "${key}"`);
|
|
}
|
|
if (!mask[key])
|
|
continue;
|
|
shape[key] = Class2 ? new Class2({
|
|
type: "optional",
|
|
innerType: oldShape[key]
|
|
}) : oldShape[key];
|
|
}
|
|
} else {
|
|
for (const key in oldShape) {
|
|
shape[key] = Class2 ? new Class2({
|
|
type: "optional",
|
|
innerType: oldShape[key]
|
|
}) : oldShape[key];
|
|
}
|
|
}
|
|
return clone(schema, {
|
|
...schema._zod.def,
|
|
shape,
|
|
checks: []
|
|
});
|
|
}
|
|
function required(Class2, schema, mask) {
|
|
const oldShape = schema._zod.def.shape;
|
|
const shape = { ...oldShape };
|
|
if (mask) {
|
|
for (const key in mask) {
|
|
if (!(key in shape)) {
|
|
throw new Error(`Unrecognized key: "${key}"`);
|
|
}
|
|
if (!mask[key])
|
|
continue;
|
|
shape[key] = new Class2({
|
|
type: "nonoptional",
|
|
innerType: oldShape[key]
|
|
});
|
|
}
|
|
} else {
|
|
for (const key in oldShape) {
|
|
shape[key] = new Class2({
|
|
type: "nonoptional",
|
|
innerType: oldShape[key]
|
|
});
|
|
}
|
|
}
|
|
return clone(schema, {
|
|
...schema._zod.def,
|
|
shape,
|
|
checks: []
|
|
});
|
|
}
|
|
function aborted(x, startIndex = 0) {
|
|
var _a;
|
|
for (let i = startIndex; i < x.issues.length; i++) {
|
|
if (((_a = x.issues[i]) == null ? void 0 : _a.continue) !== true)
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
function prefixIssues(path12, issues) {
|
|
return issues.map((iss) => {
|
|
var _a2;
|
|
var _a;
|
|
(_a2 = (_a = iss).path) != null ? _a2 : _a.path = [];
|
|
iss.path.unshift(path12);
|
|
return iss;
|
|
});
|
|
}
|
|
function unwrapMessage(message) {
|
|
return typeof message === "string" ? message : message == null ? void 0 : message.message;
|
|
}
|
|
function finalizeIssue(iss, ctx, config2) {
|
|
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
|
|
const full = { ...iss, path: (_a = iss.path) != null ? _a : [] };
|
|
if (!iss.message) {
|
|
const message = (_k = (_j = (_h = (_f = unwrapMessage((_d = (_c = (_b = iss.inst) == null ? void 0 : _b._zod.def) == null ? void 0 : _c.error) == null ? void 0 : _d.call(_c, iss))) != null ? _f : unwrapMessage((_e = ctx == null ? void 0 : ctx.error) == null ? void 0 : _e.call(ctx, iss))) != null ? _h : unwrapMessage((_g = config2.customError) == null ? void 0 : _g.call(config2, iss))) != null ? _j : unwrapMessage((_i = config2.localeError) == null ? void 0 : _i.call(config2, iss))) != null ? _k : "Invalid input";
|
|
full.message = message;
|
|
}
|
|
delete full.inst;
|
|
delete full.continue;
|
|
if (!(ctx == null ? void 0 : ctx.reportInput)) {
|
|
delete full.input;
|
|
}
|
|
return full;
|
|
}
|
|
function getSizableOrigin(input) {
|
|
if (input instanceof Set)
|
|
return "set";
|
|
if (input instanceof Map)
|
|
return "map";
|
|
if (input instanceof File)
|
|
return "file";
|
|
return "unknown";
|
|
}
|
|
function getLengthableOrigin(input) {
|
|
if (Array.isArray(input))
|
|
return "array";
|
|
if (typeof input === "string")
|
|
return "string";
|
|
return "unknown";
|
|
}
|
|
function issue(...args) {
|
|
const [iss, input, inst] = args;
|
|
if (typeof iss === "string") {
|
|
return {
|
|
message: iss,
|
|
code: "custom",
|
|
input,
|
|
inst
|
|
};
|
|
}
|
|
return { ...iss };
|
|
}
|
|
function cleanEnum(obj) {
|
|
return Object.entries(obj).filter(([k, _]) => {
|
|
return Number.isNaN(Number.parseInt(k, 10));
|
|
}).map((el) => el[1]);
|
|
}
|
|
var Class = class {
|
|
constructor(..._args) {
|
|
}
|
|
};
|
|
var initializer = (inst, def) => {
|
|
inst.name = "$ZodError";
|
|
Object.defineProperty(inst, "_zod", {
|
|
value: inst._zod,
|
|
enumerable: false
|
|
});
|
|
Object.defineProperty(inst, "issues", {
|
|
value: def,
|
|
enumerable: false
|
|
});
|
|
Object.defineProperty(inst, "message", {
|
|
get() {
|
|
return JSON.stringify(def, jsonStringifyReplacer, 2);
|
|
},
|
|
enumerable: true
|
|
});
|
|
};
|
|
var $ZodError = $constructor("$ZodError", initializer);
|
|
var $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error });
|
|
function flattenError(error2, mapper = (issue2) => issue2.message) {
|
|
const fieldErrors = {};
|
|
const formErrors = [];
|
|
for (const sub of error2.issues) {
|
|
if (sub.path.length > 0) {
|
|
fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
|
|
fieldErrors[sub.path[0]].push(mapper(sub));
|
|
} else {
|
|
formErrors.push(mapper(sub));
|
|
}
|
|
}
|
|
return { formErrors, fieldErrors };
|
|
}
|
|
function formatError(error2, _mapper) {
|
|
const mapper = _mapper || function(issue2) {
|
|
return issue2.message;
|
|
};
|
|
const fieldErrors = { _errors: [] };
|
|
const processError = (error22) => {
|
|
for (const issue2 of error22.issues) {
|
|
if (issue2.code === "invalid_union" && issue2.errors.length) {
|
|
issue2.errors.map((issues) => processError({ issues }));
|
|
} else if (issue2.code === "invalid_key") {
|
|
processError({ issues: issue2.issues });
|
|
} else if (issue2.code === "invalid_element") {
|
|
processError({ issues: issue2.issues });
|
|
} else if (issue2.path.length === 0) {
|
|
fieldErrors._errors.push(mapper(issue2));
|
|
} else {
|
|
let curr = fieldErrors;
|
|
let i = 0;
|
|
while (i < issue2.path.length) {
|
|
const el = issue2.path[i];
|
|
const terminal = i === issue2.path.length - 1;
|
|
if (!terminal) {
|
|
curr[el] = curr[el] || { _errors: [] };
|
|
} else {
|
|
curr[el] = curr[el] || { _errors: [] };
|
|
curr[el]._errors.push(mapper(issue2));
|
|
}
|
|
curr = curr[el];
|
|
i++;
|
|
}
|
|
}
|
|
}
|
|
};
|
|
processError(error2);
|
|
return fieldErrors;
|
|
}
|
|
var _parse = (_Err) => (schema, value, _ctx, _params) => {
|
|
var _a;
|
|
const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false };
|
|
const result = schema._zod.run({ value, issues: [] }, ctx);
|
|
if (result instanceof Promise) {
|
|
throw new $ZodAsyncError();
|
|
}
|
|
if (result.issues.length) {
|
|
const e = new ((_a = _params == null ? void 0 : _params.Err) != null ? _a : _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
|
|
captureStackTrace(e, _params == null ? void 0 : _params.callee);
|
|
throw e;
|
|
}
|
|
return result.value;
|
|
};
|
|
var _parseAsync = (_Err) => async (schema, value, _ctx, params) => {
|
|
var _a;
|
|
const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
|
|
let result = schema._zod.run({ value, issues: [] }, ctx);
|
|
if (result instanceof Promise)
|
|
result = await result;
|
|
if (result.issues.length) {
|
|
const e = new ((_a = params == null ? void 0 : params.Err) != null ? _a : _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
|
|
captureStackTrace(e, params == null ? void 0 : params.callee);
|
|
throw e;
|
|
}
|
|
return result.value;
|
|
};
|
|
var _safeParse = (_Err) => (schema, value, _ctx) => {
|
|
const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
|
|
const result = schema._zod.run({ value, issues: [] }, ctx);
|
|
if (result instanceof Promise) {
|
|
throw new $ZodAsyncError();
|
|
}
|
|
return result.issues.length ? {
|
|
success: false,
|
|
error: new (_Err != null ? _Err : $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
|
|
} : { success: true, data: result.value };
|
|
};
|
|
var safeParse = /* @__PURE__ */ _safeParse($ZodRealError);
|
|
var _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
|
|
const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
|
|
let result = schema._zod.run({ value, issues: [] }, ctx);
|
|
if (result instanceof Promise)
|
|
result = await result;
|
|
return result.issues.length ? {
|
|
success: false,
|
|
error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
|
|
} : { success: true, data: result.value };
|
|
};
|
|
var safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError);
|
|
var cuid = /^[cC][^\s-]{8,}$/;
|
|
var cuid2 = /^[0-9a-z]+$/;
|
|
var ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;
|
|
var xid = /^[0-9a-vA-V]{20}$/;
|
|
var ksuid = /^[A-Za-z0-9]{27}$/;
|
|
var nanoid = /^[a-zA-Z0-9_-]{21}$/;
|
|
var duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
|
|
var guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
|
|
var uuid = (version2) => {
|
|
if (!version2)
|
|
return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;
|
|
return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version2}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
|
|
};
|
|
var email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
|
|
var _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
|
|
function emoji() {
|
|
return new RegExp(_emoji, "u");
|
|
}
|
|
var ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
|
|
var ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/;
|
|
var cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/;
|
|
var cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
|
|
var base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
|
|
var base64url = /^[A-Za-z0-9_-]*$/;
|
|
var hostname = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;
|
|
var e164 = /^\+(?:[0-9]){6,14}[0-9]$/;
|
|
var dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;
|
|
var date = /* @__PURE__ */ new RegExp(`^${dateSource}$`);
|
|
function timeSource(args) {
|
|
const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
|
|
const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;
|
|
return regex;
|
|
}
|
|
function time(args) {
|
|
return new RegExp(`^${timeSource(args)}$`);
|
|
}
|
|
function datetime(args) {
|
|
const time22 = timeSource({ precision: args.precision });
|
|
const opts = ["Z"];
|
|
if (args.local)
|
|
opts.push("");
|
|
if (args.offset)
|
|
opts.push(`([+-]\\d{2}:\\d{2})`);
|
|
const timeRegex2 = `${time22}(?:${opts.join("|")})`;
|
|
return new RegExp(`^${dateSource}T(?:${timeRegex2})$`);
|
|
}
|
|
var string = (params) => {
|
|
var _a, _b;
|
|
const regex = params ? `[\\s\\S]{${(_a = params == null ? void 0 : params.minimum) != null ? _a : 0},${(_b = params == null ? void 0 : params.maximum) != null ? _b : ""}}` : `[\\s\\S]*`;
|
|
return new RegExp(`^${regex}$`);
|
|
};
|
|
var integer = /^\d+$/;
|
|
var number = /^-?\d+(?:\.\d+)?/i;
|
|
var boolean = /true|false/i;
|
|
var _null = /null/i;
|
|
var lowercase = /^[^A-Z]*$/;
|
|
var uppercase = /^[^a-z]*$/;
|
|
var $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => {
|
|
var _a2, _b;
|
|
var _a;
|
|
(_a2 = inst._zod) != null ? _a2 : inst._zod = {};
|
|
inst._zod.def = def;
|
|
(_b = (_a = inst._zod).onattach) != null ? _b : _a.onattach = [];
|
|
});
|
|
var numericOriginMap = {
|
|
number: "number",
|
|
bigint: "bigint",
|
|
object: "date"
|
|
};
|
|
var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => {
|
|
$ZodCheck.init(inst, def);
|
|
const origin = numericOriginMap[typeof def.value];
|
|
inst._zod.onattach.push((inst2) => {
|
|
var _a;
|
|
const bag = inst2._zod.bag;
|
|
const curr = (_a = def.inclusive ? bag.maximum : bag.exclusiveMaximum) != null ? _a : Number.POSITIVE_INFINITY;
|
|
if (def.value < curr) {
|
|
if (def.inclusive)
|
|
bag.maximum = def.value;
|
|
else
|
|
bag.exclusiveMaximum = def.value;
|
|
}
|
|
});
|
|
inst._zod.check = (payload) => {
|
|
if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {
|
|
return;
|
|
}
|
|
payload.issues.push({
|
|
origin,
|
|
code: "too_big",
|
|
maximum: def.value,
|
|
input: payload.value,
|
|
inclusive: def.inclusive,
|
|
inst,
|
|
continue: !def.abort
|
|
});
|
|
};
|
|
});
|
|
var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => {
|
|
$ZodCheck.init(inst, def);
|
|
const origin = numericOriginMap[typeof def.value];
|
|
inst._zod.onattach.push((inst2) => {
|
|
var _a;
|
|
const bag = inst2._zod.bag;
|
|
const curr = (_a = def.inclusive ? bag.minimum : bag.exclusiveMinimum) != null ? _a : Number.NEGATIVE_INFINITY;
|
|
if (def.value > curr) {
|
|
if (def.inclusive)
|
|
bag.minimum = def.value;
|
|
else
|
|
bag.exclusiveMinimum = def.value;
|
|
}
|
|
});
|
|
inst._zod.check = (payload) => {
|
|
if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {
|
|
return;
|
|
}
|
|
payload.issues.push({
|
|
origin,
|
|
code: "too_small",
|
|
minimum: def.value,
|
|
input: payload.value,
|
|
inclusive: def.inclusive,
|
|
inst,
|
|
continue: !def.abort
|
|
});
|
|
};
|
|
});
|
|
var $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => {
|
|
$ZodCheck.init(inst, def);
|
|
inst._zod.onattach.push((inst2) => {
|
|
var _a2;
|
|
var _a;
|
|
(_a2 = (_a = inst2._zod.bag).multipleOf) != null ? _a2 : _a.multipleOf = def.value;
|
|
});
|
|
inst._zod.check = (payload) => {
|
|
if (typeof payload.value !== typeof def.value)
|
|
throw new Error("Cannot mix number and bigint in multiple_of check.");
|
|
const isMultiple = typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder2(payload.value, def.value) === 0;
|
|
if (isMultiple)
|
|
return;
|
|
payload.issues.push({
|
|
origin: typeof payload.value,
|
|
code: "not_multiple_of",
|
|
divisor: def.value,
|
|
input: payload.value,
|
|
inst,
|
|
continue: !def.abort
|
|
});
|
|
};
|
|
});
|
|
var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat", (inst, def) => {
|
|
var _a;
|
|
$ZodCheck.init(inst, def);
|
|
def.format = def.format || "float64";
|
|
const isInt = (_a = def.format) == null ? void 0 : _a.includes("int");
|
|
const origin = isInt ? "int" : "number";
|
|
const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format];
|
|
inst._zod.onattach.push((inst2) => {
|
|
const bag = inst2._zod.bag;
|
|
bag.format = def.format;
|
|
bag.minimum = minimum;
|
|
bag.maximum = maximum;
|
|
if (isInt)
|
|
bag.pattern = integer;
|
|
});
|
|
inst._zod.check = (payload) => {
|
|
const input = payload.value;
|
|
if (isInt) {
|
|
if (!Number.isInteger(input)) {
|
|
payload.issues.push({
|
|
expected: origin,
|
|
format: def.format,
|
|
code: "invalid_type",
|
|
input,
|
|
inst
|
|
});
|
|
return;
|
|
}
|
|
if (!Number.isSafeInteger(input)) {
|
|
if (input > 0) {
|
|
payload.issues.push({
|
|
input,
|
|
code: "too_big",
|
|
maximum: Number.MAX_SAFE_INTEGER,
|
|
note: "Integers must be within the safe integer range.",
|
|
inst,
|
|
origin,
|
|
continue: !def.abort
|
|
});
|
|
} else {
|
|
payload.issues.push({
|
|
input,
|
|
code: "too_small",
|
|
minimum: Number.MIN_SAFE_INTEGER,
|
|
note: "Integers must be within the safe integer range.",
|
|
inst,
|
|
origin,
|
|
continue: !def.abort
|
|
});
|
|
}
|
|
return;
|
|
}
|
|
}
|
|
if (input < minimum) {
|
|
payload.issues.push({
|
|
origin: "number",
|
|
input,
|
|
code: "too_small",
|
|
minimum,
|
|
inclusive: true,
|
|
inst,
|
|
continue: !def.abort
|
|
});
|
|
}
|
|
if (input > maximum) {
|
|
payload.issues.push({
|
|
origin: "number",
|
|
input,
|
|
code: "too_big",
|
|
maximum,
|
|
inst
|
|
});
|
|
}
|
|
};
|
|
});
|
|
var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => {
|
|
$ZodCheck.init(inst, def);
|
|
inst._zod.when = (payload) => {
|
|
const val = payload.value;
|
|
return !nullish(val) && val.length !== void 0;
|
|
};
|
|
inst._zod.onattach.push((inst2) => {
|
|
var _a;
|
|
const curr = (_a = inst2._zod.bag.maximum) != null ? _a : Number.POSITIVE_INFINITY;
|
|
if (def.maximum < curr)
|
|
inst2._zod.bag.maximum = def.maximum;
|
|
});
|
|
inst._zod.check = (payload) => {
|
|
const input = payload.value;
|
|
const length = input.length;
|
|
if (length <= def.maximum)
|
|
return;
|
|
const origin = getLengthableOrigin(input);
|
|
payload.issues.push({
|
|
origin,
|
|
code: "too_big",
|
|
maximum: def.maximum,
|
|
inclusive: true,
|
|
input,
|
|
inst,
|
|
continue: !def.abort
|
|
});
|
|
};
|
|
});
|
|
var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => {
|
|
$ZodCheck.init(inst, def);
|
|
inst._zod.when = (payload) => {
|
|
const val = payload.value;
|
|
return !nullish(val) && val.length !== void 0;
|
|
};
|
|
inst._zod.onattach.push((inst2) => {
|
|
var _a;
|
|
const curr = (_a = inst2._zod.bag.minimum) != null ? _a : Number.NEGATIVE_INFINITY;
|
|
if (def.minimum > curr)
|
|
inst2._zod.bag.minimum = def.minimum;
|
|
});
|
|
inst._zod.check = (payload) => {
|
|
const input = payload.value;
|
|
const length = input.length;
|
|
if (length >= def.minimum)
|
|
return;
|
|
const origin = getLengthableOrigin(input);
|
|
payload.issues.push({
|
|
origin,
|
|
code: "too_small",
|
|
minimum: def.minimum,
|
|
inclusive: true,
|
|
input,
|
|
inst,
|
|
continue: !def.abort
|
|
});
|
|
};
|
|
});
|
|
var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => {
|
|
$ZodCheck.init(inst, def);
|
|
inst._zod.when = (payload) => {
|
|
const val = payload.value;
|
|
return !nullish(val) && val.length !== void 0;
|
|
};
|
|
inst._zod.onattach.push((inst2) => {
|
|
const bag = inst2._zod.bag;
|
|
bag.minimum = def.length;
|
|
bag.maximum = def.length;
|
|
bag.length = def.length;
|
|
});
|
|
inst._zod.check = (payload) => {
|
|
const input = payload.value;
|
|
const length = input.length;
|
|
if (length === def.length)
|
|
return;
|
|
const origin = getLengthableOrigin(input);
|
|
const tooBig = length > def.length;
|
|
payload.issues.push({
|
|
origin,
|
|
...tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length },
|
|
inclusive: true,
|
|
exact: true,
|
|
input: payload.value,
|
|
inst,
|
|
continue: !def.abort
|
|
});
|
|
};
|
|
});
|
|
var $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => {
|
|
var _a2, _b2;
|
|
var _a, _b;
|
|
$ZodCheck.init(inst, def);
|
|
inst._zod.onattach.push((inst2) => {
|
|
var _a3;
|
|
const bag = inst2._zod.bag;
|
|
bag.format = def.format;
|
|
if (def.pattern) {
|
|
(_a3 = bag.patterns) != null ? _a3 : bag.patterns = /* @__PURE__ */ new Set();
|
|
bag.patterns.add(def.pattern);
|
|
}
|
|
});
|
|
if (def.pattern)
|
|
(_a2 = (_a = inst._zod).check) != null ? _a2 : _a.check = (payload) => {
|
|
def.pattern.lastIndex = 0;
|
|
if (def.pattern.test(payload.value))
|
|
return;
|
|
payload.issues.push({
|
|
origin: "string",
|
|
code: "invalid_format",
|
|
format: def.format,
|
|
input: payload.value,
|
|
...def.pattern ? { pattern: def.pattern.toString() } : {},
|
|
inst,
|
|
continue: !def.abort
|
|
});
|
|
};
|
|
else
|
|
(_b2 = (_b = inst._zod).check) != null ? _b2 : _b.check = () => {
|
|
};
|
|
});
|
|
var $ZodCheckRegex = /* @__PURE__ */ $constructor("$ZodCheckRegex", (inst, def) => {
|
|
$ZodCheckStringFormat.init(inst, def);
|
|
inst._zod.check = (payload) => {
|
|
def.pattern.lastIndex = 0;
|
|
if (def.pattern.test(payload.value))
|
|
return;
|
|
payload.issues.push({
|
|
origin: "string",
|
|
code: "invalid_format",
|
|
format: "regex",
|
|
input: payload.value,
|
|
pattern: def.pattern.toString(),
|
|
inst,
|
|
continue: !def.abort
|
|
});
|
|
};
|
|
});
|
|
var $ZodCheckLowerCase = /* @__PURE__ */ $constructor("$ZodCheckLowerCase", (inst, def) => {
|
|
var _a;
|
|
(_a = def.pattern) != null ? _a : def.pattern = lowercase;
|
|
$ZodCheckStringFormat.init(inst, def);
|
|
});
|
|
var $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (inst, def) => {
|
|
var _a;
|
|
(_a = def.pattern) != null ? _a : def.pattern = uppercase;
|
|
$ZodCheckStringFormat.init(inst, def);
|
|
});
|
|
var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => {
|
|
$ZodCheck.init(inst, def);
|
|
const escapedRegex = escapeRegex(def.includes);
|
|
const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);
|
|
def.pattern = pattern;
|
|
inst._zod.onattach.push((inst2) => {
|
|
var _a;
|
|
const bag = inst2._zod.bag;
|
|
(_a = bag.patterns) != null ? _a : bag.patterns = /* @__PURE__ */ new Set();
|
|
bag.patterns.add(pattern);
|
|
});
|
|
inst._zod.check = (payload) => {
|
|
if (payload.value.includes(def.includes, def.position))
|
|
return;
|
|
payload.issues.push({
|
|
origin: "string",
|
|
code: "invalid_format",
|
|
format: "includes",
|
|
includes: def.includes,
|
|
input: payload.value,
|
|
inst,
|
|
continue: !def.abort
|
|
});
|
|
};
|
|
});
|
|
var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def) => {
|
|
var _a;
|
|
$ZodCheck.init(inst, def);
|
|
const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`);
|
|
(_a = def.pattern) != null ? _a : def.pattern = pattern;
|
|
inst._zod.onattach.push((inst2) => {
|
|
var _a2;
|
|
const bag = inst2._zod.bag;
|
|
(_a2 = bag.patterns) != null ? _a2 : bag.patterns = /* @__PURE__ */ new Set();
|
|
bag.patterns.add(pattern);
|
|
});
|
|
inst._zod.check = (payload) => {
|
|
if (payload.value.startsWith(def.prefix))
|
|
return;
|
|
payload.issues.push({
|
|
origin: "string",
|
|
code: "invalid_format",
|
|
format: "starts_with",
|
|
prefix: def.prefix,
|
|
input: payload.value,
|
|
inst,
|
|
continue: !def.abort
|
|
});
|
|
};
|
|
});
|
|
var $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def) => {
|
|
var _a;
|
|
$ZodCheck.init(inst, def);
|
|
const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`);
|
|
(_a = def.pattern) != null ? _a : def.pattern = pattern;
|
|
inst._zod.onattach.push((inst2) => {
|
|
var _a2;
|
|
const bag = inst2._zod.bag;
|
|
(_a2 = bag.patterns) != null ? _a2 : bag.patterns = /* @__PURE__ */ new Set();
|
|
bag.patterns.add(pattern);
|
|
});
|
|
inst._zod.check = (payload) => {
|
|
if (payload.value.endsWith(def.suffix))
|
|
return;
|
|
payload.issues.push({
|
|
origin: "string",
|
|
code: "invalid_format",
|
|
format: "ends_with",
|
|
suffix: def.suffix,
|
|
input: payload.value,
|
|
inst,
|
|
continue: !def.abort
|
|
});
|
|
};
|
|
});
|
|
var $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def) => {
|
|
$ZodCheck.init(inst, def);
|
|
inst._zod.check = (payload) => {
|
|
payload.value = def.tx(payload.value);
|
|
};
|
|
});
|
|
var Doc = class {
|
|
constructor(args = []) {
|
|
this.content = [];
|
|
this.indent = 0;
|
|
if (this)
|
|
this.args = args;
|
|
}
|
|
indented(fn) {
|
|
this.indent += 1;
|
|
fn(this);
|
|
this.indent -= 1;
|
|
}
|
|
write(arg) {
|
|
if (typeof arg === "function") {
|
|
arg(this, { execution: "sync" });
|
|
arg(this, { execution: "async" });
|
|
return;
|
|
}
|
|
const content = arg;
|
|
const lines = content.split(`
|
|
`).filter((x) => x);
|
|
const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));
|
|
const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x);
|
|
for (const line of dedented) {
|
|
this.content.push(line);
|
|
}
|
|
}
|
|
compile() {
|
|
var _a;
|
|
const F = Function;
|
|
const args = this == null ? void 0 : this.args;
|
|
const content = (_a = this == null ? void 0 : this.content) != null ? _a : [``];
|
|
const lines = [...content.map((x) => ` ${x}`)];
|
|
return new F(...args, lines.join(`
|
|
`));
|
|
}
|
|
};
|
|
var version = {
|
|
major: 4,
|
|
minor: 0,
|
|
patch: 0
|
|
};
|
|
var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {
|
|
var _a2, _b, _c;
|
|
var _a;
|
|
inst != null ? inst : inst = {};
|
|
inst._zod.def = def;
|
|
inst._zod.bag = inst._zod.bag || {};
|
|
inst._zod.version = version;
|
|
const checks = [...(_a2 = inst._zod.def.checks) != null ? _a2 : []];
|
|
if (inst._zod.traits.has("$ZodCheck")) {
|
|
checks.unshift(inst);
|
|
}
|
|
for (const ch of checks) {
|
|
for (const fn of ch._zod.onattach) {
|
|
fn(inst);
|
|
}
|
|
}
|
|
if (checks.length === 0) {
|
|
(_b = (_a = inst._zod).deferred) != null ? _b : _a.deferred = [];
|
|
(_c = inst._zod.deferred) == null ? void 0 : _c.push(() => {
|
|
inst._zod.run = inst._zod.parse;
|
|
});
|
|
} else {
|
|
const runChecks = (payload, checks2, ctx) => {
|
|
let isAborted2 = aborted(payload);
|
|
let asyncResult;
|
|
for (const ch of checks2) {
|
|
if (ch._zod.when) {
|
|
const shouldRun = ch._zod.when(payload);
|
|
if (!shouldRun)
|
|
continue;
|
|
} else if (isAborted2) {
|
|
continue;
|
|
}
|
|
const currLen = payload.issues.length;
|
|
const _ = ch._zod.check(payload);
|
|
if (_ instanceof Promise && (ctx == null ? void 0 : ctx.async) === false) {
|
|
throw new $ZodAsyncError();
|
|
}
|
|
if (asyncResult || _ instanceof Promise) {
|
|
asyncResult = (asyncResult != null ? asyncResult : Promise.resolve()).then(async () => {
|
|
await _;
|
|
const nextLen = payload.issues.length;
|
|
if (nextLen === currLen)
|
|
return;
|
|
if (!isAborted2)
|
|
isAborted2 = aborted(payload, currLen);
|
|
});
|
|
} else {
|
|
const nextLen = payload.issues.length;
|
|
if (nextLen === currLen)
|
|
continue;
|
|
if (!isAborted2)
|
|
isAborted2 = aborted(payload, currLen);
|
|
}
|
|
}
|
|
if (asyncResult) {
|
|
return asyncResult.then(() => {
|
|
return payload;
|
|
});
|
|
}
|
|
return payload;
|
|
};
|
|
inst._zod.run = (payload, ctx) => {
|
|
const result = inst._zod.parse(payload, ctx);
|
|
if (result instanceof Promise) {
|
|
if (ctx.async === false)
|
|
throw new $ZodAsyncError();
|
|
return result.then((result2) => runChecks(result2, checks, ctx));
|
|
}
|
|
return runChecks(result, checks, ctx);
|
|
};
|
|
}
|
|
inst["~standard"] = {
|
|
validate: (value) => {
|
|
var _a3;
|
|
try {
|
|
const r = safeParse(inst, value);
|
|
return r.success ? { value: r.data } : { issues: (_a3 = r.error) == null ? void 0 : _a3.issues };
|
|
} catch (_) {
|
|
return safeParseAsync(inst, value).then((r) => {
|
|
var _a4;
|
|
return r.success ? { value: r.data } : { issues: (_a4 = r.error) == null ? void 0 : _a4.issues };
|
|
});
|
|
}
|
|
},
|
|
vendor: "zod",
|
|
version: 1
|
|
};
|
|
});
|
|
var $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => {
|
|
var _a, _b, _c;
|
|
$ZodType.init(inst, def);
|
|
inst._zod.pattern = (_c = [...(_b = (_a = inst == null ? void 0 : inst._zod.bag) == null ? void 0 : _a.patterns) != null ? _b : []].pop()) != null ? _c : string(inst._zod.bag);
|
|
inst._zod.parse = (payload, _) => {
|
|
if (def.coerce)
|
|
try {
|
|
payload.value = String(payload.value);
|
|
} catch (_2) {
|
|
}
|
|
if (typeof payload.value === "string")
|
|
return payload;
|
|
payload.issues.push({
|
|
expected: "string",
|
|
code: "invalid_type",
|
|
input: payload.value,
|
|
inst
|
|
});
|
|
return payload;
|
|
};
|
|
});
|
|
var $ZodStringFormat = /* @__PURE__ */ $constructor("$ZodStringFormat", (inst, def) => {
|
|
$ZodCheckStringFormat.init(inst, def);
|
|
$ZodString.init(inst, def);
|
|
});
|
|
var $ZodGUID = /* @__PURE__ */ $constructor("$ZodGUID", (inst, def) => {
|
|
var _a;
|
|
(_a = def.pattern) != null ? _a : def.pattern = guid;
|
|
$ZodStringFormat.init(inst, def);
|
|
});
|
|
var $ZodUUID = /* @__PURE__ */ $constructor("$ZodUUID", (inst, def) => {
|
|
var _a, _b;
|
|
if (def.version) {
|
|
const versionMap = {
|
|
v1: 1,
|
|
v2: 2,
|
|
v3: 3,
|
|
v4: 4,
|
|
v5: 5,
|
|
v6: 6,
|
|
v7: 7,
|
|
v8: 8
|
|
};
|
|
const v = versionMap[def.version];
|
|
if (v === void 0)
|
|
throw new Error(`Invalid UUID version: "${def.version}"`);
|
|
(_a = def.pattern) != null ? _a : def.pattern = uuid(v);
|
|
} else
|
|
(_b = def.pattern) != null ? _b : def.pattern = uuid();
|
|
$ZodStringFormat.init(inst, def);
|
|
});
|
|
var $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => {
|
|
var _a;
|
|
(_a = def.pattern) != null ? _a : def.pattern = email;
|
|
$ZodStringFormat.init(inst, def);
|
|
});
|
|
var $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => {
|
|
$ZodStringFormat.init(inst, def);
|
|
inst._zod.check = (payload) => {
|
|
try {
|
|
const orig = payload.value;
|
|
const url = new URL(orig);
|
|
const href = url.href;
|
|
if (def.hostname) {
|
|
def.hostname.lastIndex = 0;
|
|
if (!def.hostname.test(url.hostname)) {
|
|
payload.issues.push({
|
|
code: "invalid_format",
|
|
format: "url",
|
|
note: "Invalid hostname",
|
|
pattern: hostname.source,
|
|
input: payload.value,
|
|
inst,
|
|
continue: !def.abort
|
|
});
|
|
}
|
|
}
|
|
if (def.protocol) {
|
|
def.protocol.lastIndex = 0;
|
|
if (!def.protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol)) {
|
|
payload.issues.push({
|
|
code: "invalid_format",
|
|
format: "url",
|
|
note: "Invalid protocol",
|
|
pattern: def.protocol.source,
|
|
input: payload.value,
|
|
inst,
|
|
continue: !def.abort
|
|
});
|
|
}
|
|
}
|
|
if (!orig.endsWith("/") && href.endsWith("/")) {
|
|
payload.value = href.slice(0, -1);
|
|
} else {
|
|
payload.value = href;
|
|
}
|
|
return;
|
|
} catch (_) {
|
|
payload.issues.push({
|
|
code: "invalid_format",
|
|
format: "url",
|
|
input: payload.value,
|
|
inst,
|
|
continue: !def.abort
|
|
});
|
|
}
|
|
};
|
|
});
|
|
var $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => {
|
|
var _a;
|
|
(_a = def.pattern) != null ? _a : def.pattern = emoji();
|
|
$ZodStringFormat.init(inst, def);
|
|
});
|
|
var $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => {
|
|
var _a;
|
|
(_a = def.pattern) != null ? _a : def.pattern = nanoid;
|
|
$ZodStringFormat.init(inst, def);
|
|
});
|
|
var $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => {
|
|
var _a;
|
|
(_a = def.pattern) != null ? _a : def.pattern = cuid;
|
|
$ZodStringFormat.init(inst, def);
|
|
});
|
|
var $ZodCUID2 = /* @__PURE__ */ $constructor("$ZodCUID2", (inst, def) => {
|
|
var _a;
|
|
(_a = def.pattern) != null ? _a : def.pattern = cuid2;
|
|
$ZodStringFormat.init(inst, def);
|
|
});
|
|
var $ZodULID = /* @__PURE__ */ $constructor("$ZodULID", (inst, def) => {
|
|
var _a;
|
|
(_a = def.pattern) != null ? _a : def.pattern = ulid;
|
|
$ZodStringFormat.init(inst, def);
|
|
});
|
|
var $ZodXID = /* @__PURE__ */ $constructor("$ZodXID", (inst, def) => {
|
|
var _a;
|
|
(_a = def.pattern) != null ? _a : def.pattern = xid;
|
|
$ZodStringFormat.init(inst, def);
|
|
});
|
|
var $ZodKSUID = /* @__PURE__ */ $constructor("$ZodKSUID", (inst, def) => {
|
|
var _a;
|
|
(_a = def.pattern) != null ? _a : def.pattern = ksuid;
|
|
$ZodStringFormat.init(inst, def);
|
|
});
|
|
var $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def) => {
|
|
var _a;
|
|
(_a = def.pattern) != null ? _a : def.pattern = datetime(def);
|
|
$ZodStringFormat.init(inst, def);
|
|
});
|
|
var $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def) => {
|
|
var _a;
|
|
(_a = def.pattern) != null ? _a : def.pattern = date;
|
|
$ZodStringFormat.init(inst, def);
|
|
});
|
|
var $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def) => {
|
|
var _a;
|
|
(_a = def.pattern) != null ? _a : def.pattern = time(def);
|
|
$ZodStringFormat.init(inst, def);
|
|
});
|
|
var $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def) => {
|
|
var _a;
|
|
(_a = def.pattern) != null ? _a : def.pattern = duration;
|
|
$ZodStringFormat.init(inst, def);
|
|
});
|
|
var $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => {
|
|
var _a;
|
|
(_a = def.pattern) != null ? _a : def.pattern = ipv4;
|
|
$ZodStringFormat.init(inst, def);
|
|
inst._zod.onattach.push((inst2) => {
|
|
const bag = inst2._zod.bag;
|
|
bag.format = `ipv4`;
|
|
});
|
|
});
|
|
var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => {
|
|
var _a;
|
|
(_a = def.pattern) != null ? _a : def.pattern = ipv6;
|
|
$ZodStringFormat.init(inst, def);
|
|
inst._zod.onattach.push((inst2) => {
|
|
const bag = inst2._zod.bag;
|
|
bag.format = `ipv6`;
|
|
});
|
|
inst._zod.check = (payload) => {
|
|
try {
|
|
new URL(`http://[${payload.value}]`);
|
|
} catch (e) {
|
|
payload.issues.push({
|
|
code: "invalid_format",
|
|
format: "ipv6",
|
|
input: payload.value,
|
|
inst,
|
|
continue: !def.abort
|
|
});
|
|
}
|
|
};
|
|
});
|
|
var $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => {
|
|
var _a;
|
|
(_a = def.pattern) != null ? _a : def.pattern = cidrv4;
|
|
$ZodStringFormat.init(inst, def);
|
|
});
|
|
var $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => {
|
|
var _a;
|
|
(_a = def.pattern) != null ? _a : def.pattern = cidrv6;
|
|
$ZodStringFormat.init(inst, def);
|
|
inst._zod.check = (payload) => {
|
|
const [address, prefix] = payload.value.split("/");
|
|
try {
|
|
if (!prefix)
|
|
throw new Error();
|
|
const prefixNum = Number(prefix);
|
|
if (`${prefixNum}` !== prefix)
|
|
throw new Error();
|
|
if (prefixNum < 0 || prefixNum > 128)
|
|
throw new Error();
|
|
new URL(`http://[${address}]`);
|
|
} catch (e) {
|
|
payload.issues.push({
|
|
code: "invalid_format",
|
|
format: "cidrv6",
|
|
input: payload.value,
|
|
inst,
|
|
continue: !def.abort
|
|
});
|
|
}
|
|
};
|
|
});
|
|
function isValidBase64(data) {
|
|
if (data === "")
|
|
return true;
|
|
if (data.length % 4 !== 0)
|
|
return false;
|
|
try {
|
|
atob(data);
|
|
return true;
|
|
} catch (e) {
|
|
return false;
|
|
}
|
|
}
|
|
var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => {
|
|
var _a;
|
|
(_a = def.pattern) != null ? _a : def.pattern = base64;
|
|
$ZodStringFormat.init(inst, def);
|
|
inst._zod.onattach.push((inst2) => {
|
|
inst2._zod.bag.contentEncoding = "base64";
|
|
});
|
|
inst._zod.check = (payload) => {
|
|
if (isValidBase64(payload.value))
|
|
return;
|
|
payload.issues.push({
|
|
code: "invalid_format",
|
|
format: "base64",
|
|
input: payload.value,
|
|
inst,
|
|
continue: !def.abort
|
|
});
|
|
};
|
|
});
|
|
function isValidBase64URL(data) {
|
|
if (!base64url.test(data))
|
|
return false;
|
|
const base642 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
|
|
const padded = base642.padEnd(Math.ceil(base642.length / 4) * 4, "=");
|
|
return isValidBase64(padded);
|
|
}
|
|
var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => {
|
|
var _a;
|
|
(_a = def.pattern) != null ? _a : def.pattern = base64url;
|
|
$ZodStringFormat.init(inst, def);
|
|
inst._zod.onattach.push((inst2) => {
|
|
inst2._zod.bag.contentEncoding = "base64url";
|
|
});
|
|
inst._zod.check = (payload) => {
|
|
if (isValidBase64URL(payload.value))
|
|
return;
|
|
payload.issues.push({
|
|
code: "invalid_format",
|
|
format: "base64url",
|
|
input: payload.value,
|
|
inst,
|
|
continue: !def.abort
|
|
});
|
|
};
|
|
});
|
|
var $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => {
|
|
var _a;
|
|
(_a = def.pattern) != null ? _a : def.pattern = e164;
|
|
$ZodStringFormat.init(inst, def);
|
|
});
|
|
function isValidJWT2(token, algorithm = null) {
|
|
try {
|
|
const tokensParts = token.split(".");
|
|
if (tokensParts.length !== 3)
|
|
return false;
|
|
const [header] = tokensParts;
|
|
if (!header)
|
|
return false;
|
|
const parsedHeader = JSON.parse(atob(header));
|
|
if ("typ" in parsedHeader && (parsedHeader == null ? void 0 : parsedHeader.typ) !== "JWT")
|
|
return false;
|
|
if (!parsedHeader.alg)
|
|
return false;
|
|
if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm))
|
|
return false;
|
|
return true;
|
|
} catch (e) {
|
|
return false;
|
|
}
|
|
}
|
|
var $ZodJWT = /* @__PURE__ */ $constructor("$ZodJWT", (inst, def) => {
|
|
$ZodStringFormat.init(inst, def);
|
|
inst._zod.check = (payload) => {
|
|
if (isValidJWT2(payload.value, def.alg))
|
|
return;
|
|
payload.issues.push({
|
|
code: "invalid_format",
|
|
format: "jwt",
|
|
input: payload.value,
|
|
inst,
|
|
continue: !def.abort
|
|
});
|
|
};
|
|
});
|
|
var $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => {
|
|
var _a;
|
|
$ZodType.init(inst, def);
|
|
inst._zod.pattern = (_a = inst._zod.bag.pattern) != null ? _a : number;
|
|
inst._zod.parse = (payload, _ctx) => {
|
|
if (def.coerce)
|
|
try {
|
|
payload.value = Number(payload.value);
|
|
} catch (_) {
|
|
}
|
|
const input = payload.value;
|
|
if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) {
|
|
return payload;
|
|
}
|
|
const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0;
|
|
payload.issues.push({
|
|
expected: "number",
|
|
code: "invalid_type",
|
|
input,
|
|
inst,
|
|
...received ? { received } : {}
|
|
});
|
|
return payload;
|
|
};
|
|
});
|
|
var $ZodNumberFormat = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => {
|
|
$ZodCheckNumberFormat.init(inst, def);
|
|
$ZodNumber.init(inst, def);
|
|
});
|
|
var $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => {
|
|
$ZodType.init(inst, def);
|
|
inst._zod.pattern = boolean;
|
|
inst._zod.parse = (payload, _ctx) => {
|
|
if (def.coerce)
|
|
try {
|
|
payload.value = Boolean(payload.value);
|
|
} catch (_) {
|
|
}
|
|
const input = payload.value;
|
|
if (typeof input === "boolean")
|
|
return payload;
|
|
payload.issues.push({
|
|
expected: "boolean",
|
|
code: "invalid_type",
|
|
input,
|
|
inst
|
|
});
|
|
return payload;
|
|
};
|
|
});
|
|
var $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => {
|
|
$ZodType.init(inst, def);
|
|
inst._zod.pattern = _null;
|
|
inst._zod.values = /* @__PURE__ */ new Set([null]);
|
|
inst._zod.parse = (payload, _ctx) => {
|
|
const input = payload.value;
|
|
if (input === null)
|
|
return payload;
|
|
payload.issues.push({
|
|
expected: "null",
|
|
code: "invalid_type",
|
|
input,
|
|
inst
|
|
});
|
|
return payload;
|
|
};
|
|
});
|
|
var $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def) => {
|
|
$ZodType.init(inst, def);
|
|
inst._zod.parse = (payload) => payload;
|
|
});
|
|
var $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => {
|
|
$ZodType.init(inst, def);
|
|
inst._zod.parse = (payload, _ctx) => {
|
|
payload.issues.push({
|
|
expected: "never",
|
|
code: "invalid_type",
|
|
input: payload.value,
|
|
inst
|
|
});
|
|
return payload;
|
|
};
|
|
});
|
|
function handleArrayResult(result, final, index) {
|
|
if (result.issues.length) {
|
|
final.issues.push(...prefixIssues(index, result.issues));
|
|
}
|
|
final.value[index] = result.value;
|
|
}
|
|
var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {
|
|
$ZodType.init(inst, def);
|
|
inst._zod.parse = (payload, ctx) => {
|
|
const input = payload.value;
|
|
if (!Array.isArray(input)) {
|
|
payload.issues.push({
|
|
expected: "array",
|
|
code: "invalid_type",
|
|
input,
|
|
inst
|
|
});
|
|
return payload;
|
|
}
|
|
payload.value = Array(input.length);
|
|
const proms = [];
|
|
for (let i = 0; i < input.length; i++) {
|
|
const item = input[i];
|
|
const result = def.element._zod.run({
|
|
value: item,
|
|
issues: []
|
|
}, ctx);
|
|
if (result instanceof Promise) {
|
|
proms.push(result.then((result2) => handleArrayResult(result2, payload, i)));
|
|
} else {
|
|
handleArrayResult(result, payload, i);
|
|
}
|
|
}
|
|
if (proms.length) {
|
|
return Promise.all(proms).then(() => payload);
|
|
}
|
|
return payload;
|
|
};
|
|
});
|
|
function handleObjectResult(result, final, key) {
|
|
if (result.issues.length) {
|
|
final.issues.push(...prefixIssues(key, result.issues));
|
|
}
|
|
final.value[key] = result.value;
|
|
}
|
|
function handleOptionalObjectResult(result, final, key, input) {
|
|
if (result.issues.length) {
|
|
if (input[key] === void 0) {
|
|
if (key in input) {
|
|
final.value[key] = void 0;
|
|
} else {
|
|
final.value[key] = result.value;
|
|
}
|
|
} else {
|
|
final.issues.push(...prefixIssues(key, result.issues));
|
|
}
|
|
} else if (result.value === void 0) {
|
|
if (key in input)
|
|
final.value[key] = void 0;
|
|
} else {
|
|
final.value[key] = result.value;
|
|
}
|
|
}
|
|
var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
|
|
$ZodType.init(inst, def);
|
|
const _normalized = cached(() => {
|
|
const keys = Object.keys(def.shape);
|
|
for (const k of keys) {
|
|
if (!(def.shape[k] instanceof $ZodType)) {
|
|
throw new Error(`Invalid element at key "${k}": expected a Zod schema`);
|
|
}
|
|
}
|
|
const okeys = optionalKeys(def.shape);
|
|
return {
|
|
shape: def.shape,
|
|
keys,
|
|
keySet: new Set(keys),
|
|
numKeys: keys.length,
|
|
optionalKeys: new Set(okeys)
|
|
};
|
|
});
|
|
defineLazy(inst._zod, "propValues", () => {
|
|
var _a;
|
|
const shape = def.shape;
|
|
const propValues = {};
|
|
for (const key in shape) {
|
|
const field = shape[key]._zod;
|
|
if (field.values) {
|
|
(_a = propValues[key]) != null ? _a : propValues[key] = /* @__PURE__ */ new Set();
|
|
for (const v of field.values)
|
|
propValues[key].add(v);
|
|
}
|
|
}
|
|
return propValues;
|
|
});
|
|
const generateFastpass = (shape) => {
|
|
const doc = new Doc(["shape", "payload", "ctx"]);
|
|
const normalized = _normalized.value;
|
|
const parseStr = (key) => {
|
|
const k = esc(key);
|
|
return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;
|
|
};
|
|
doc.write(`const input = payload.value;`);
|
|
const ids = /* @__PURE__ */ Object.create(null);
|
|
let counter = 0;
|
|
for (const key of normalized.keys) {
|
|
ids[key] = `key_${counter++}`;
|
|
}
|
|
doc.write(`const newResult = {}`);
|
|
for (const key of normalized.keys) {
|
|
if (normalized.optionalKeys.has(key)) {
|
|
const id = ids[key];
|
|
doc.write(`const ${id} = ${parseStr(key)};`);
|
|
const k = esc(key);
|
|
doc.write(`
|
|
if (${id}.issues.length) {
|
|
if (input[${k}] === undefined) {
|
|
if (${k} in input) {
|
|
newResult[${k}] = undefined;
|
|
}
|
|
} else {
|
|
payload.issues = payload.issues.concat(
|
|
${id}.issues.map((iss) => ({
|
|
...iss,
|
|
path: iss.path ? [${k}, ...iss.path] : [${k}],
|
|
}))
|
|
);
|
|
}
|
|
} else if (${id}.value === undefined) {
|
|
if (${k} in input) newResult[${k}] = undefined;
|
|
} else {
|
|
newResult[${k}] = ${id}.value;
|
|
}
|
|
`);
|
|
} else {
|
|
const id = ids[key];
|
|
doc.write(`const ${id} = ${parseStr(key)};`);
|
|
doc.write(`
|
|
if (${id}.issues.length) payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
|
|
...iss,
|
|
path: iss.path ? [${esc(key)}, ...iss.path] : [${esc(key)}]
|
|
})));`);
|
|
doc.write(`newResult[${esc(key)}] = ${id}.value`);
|
|
}
|
|
}
|
|
doc.write(`payload.value = newResult;`);
|
|
doc.write(`return payload;`);
|
|
const fn = doc.compile();
|
|
return (payload, ctx) => fn(shape, payload, ctx);
|
|
};
|
|
let fastpass;
|
|
const isObject3 = isObject2;
|
|
const jit = !globalConfig.jitless;
|
|
const allowsEval2 = allowsEval;
|
|
const fastEnabled = jit && allowsEval2.value;
|
|
const catchall = def.catchall;
|
|
let value;
|
|
inst._zod.parse = (payload, ctx) => {
|
|
value != null ? value : value = _normalized.value;
|
|
const input = payload.value;
|
|
if (!isObject3(input)) {
|
|
payload.issues.push({
|
|
expected: "object",
|
|
code: "invalid_type",
|
|
input,
|
|
inst
|
|
});
|
|
return payload;
|
|
}
|
|
const proms = [];
|
|
if (jit && fastEnabled && (ctx == null ? void 0 : ctx.async) === false && ctx.jitless !== true) {
|
|
if (!fastpass)
|
|
fastpass = generateFastpass(def.shape);
|
|
payload = fastpass(payload, ctx);
|
|
} else {
|
|
payload.value = {};
|
|
const shape = value.shape;
|
|
for (const key of value.keys) {
|
|
const el = shape[key];
|
|
const r = el._zod.run({ value: input[key], issues: [] }, ctx);
|
|
const isOptional = el._zod.optin === "optional" && el._zod.optout === "optional";
|
|
if (r instanceof Promise) {
|
|
proms.push(r.then((r2) => isOptional ? handleOptionalObjectResult(r2, payload, key, input) : handleObjectResult(r2, payload, key)));
|
|
} else if (isOptional) {
|
|
handleOptionalObjectResult(r, payload, key, input);
|
|
} else {
|
|
handleObjectResult(r, payload, key);
|
|
}
|
|
}
|
|
}
|
|
if (!catchall) {
|
|
return proms.length ? Promise.all(proms).then(() => payload) : payload;
|
|
}
|
|
const unrecognized = [];
|
|
const keySet = value.keySet;
|
|
const _catchall = catchall._zod;
|
|
const t = _catchall.def.type;
|
|
for (const key of Object.keys(input)) {
|
|
if (keySet.has(key))
|
|
continue;
|
|
if (t === "never") {
|
|
unrecognized.push(key);
|
|
continue;
|
|
}
|
|
const r = _catchall.run({ value: input[key], issues: [] }, ctx);
|
|
if (r instanceof Promise) {
|
|
proms.push(r.then((r2) => handleObjectResult(r2, payload, key)));
|
|
} else {
|
|
handleObjectResult(r, payload, key);
|
|
}
|
|
}
|
|
if (unrecognized.length) {
|
|
payload.issues.push({
|
|
code: "unrecognized_keys",
|
|
keys: unrecognized,
|
|
input,
|
|
inst
|
|
});
|
|
}
|
|
if (!proms.length)
|
|
return payload;
|
|
return Promise.all(proms).then(() => {
|
|
return payload;
|
|
});
|
|
};
|
|
});
|
|
function handleUnionResults(results, final, inst, ctx) {
|
|
for (const result of results) {
|
|
if (result.issues.length === 0) {
|
|
final.value = result.value;
|
|
return final;
|
|
}
|
|
}
|
|
final.issues.push({
|
|
code: "invalid_union",
|
|
input: final.value,
|
|
inst,
|
|
errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
|
|
});
|
|
return final;
|
|
}
|
|
var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => {
|
|
$ZodType.init(inst, def);
|
|
defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0);
|
|
defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0);
|
|
defineLazy(inst._zod, "values", () => {
|
|
if (def.options.every((o) => o._zod.values)) {
|
|
return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));
|
|
}
|
|
return;
|
|
});
|
|
defineLazy(inst._zod, "pattern", () => {
|
|
if (def.options.every((o) => o._zod.pattern)) {
|
|
const patterns = def.options.map((o) => o._zod.pattern);
|
|
return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`);
|
|
}
|
|
return;
|
|
});
|
|
inst._zod.parse = (payload, ctx) => {
|
|
let async = false;
|
|
const results = [];
|
|
for (const option of def.options) {
|
|
const result = option._zod.run({
|
|
value: payload.value,
|
|
issues: []
|
|
}, ctx);
|
|
if (result instanceof Promise) {
|
|
results.push(result);
|
|
async = true;
|
|
} else {
|
|
if (result.issues.length === 0)
|
|
return result;
|
|
results.push(result);
|
|
}
|
|
}
|
|
if (!async)
|
|
return handleUnionResults(results, payload, inst, ctx);
|
|
return Promise.all(results).then((results2) => {
|
|
return handleUnionResults(results2, payload, inst, ctx);
|
|
});
|
|
};
|
|
});
|
|
var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def) => {
|
|
$ZodUnion.init(inst, def);
|
|
const _super = inst._zod.parse;
|
|
defineLazy(inst._zod, "propValues", () => {
|
|
const propValues = {};
|
|
for (const option of def.options) {
|
|
const pv = option._zod.propValues;
|
|
if (!pv || Object.keys(pv).length === 0)
|
|
throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);
|
|
for (const [k, v] of Object.entries(pv)) {
|
|
if (!propValues[k])
|
|
propValues[k] = /* @__PURE__ */ new Set();
|
|
for (const val of v) {
|
|
propValues[k].add(val);
|
|
}
|
|
}
|
|
}
|
|
return propValues;
|
|
});
|
|
const disc = cached(() => {
|
|
const opts = def.options;
|
|
const map = /* @__PURE__ */ new Map();
|
|
for (const o of opts) {
|
|
const values = o._zod.propValues[def.discriminator];
|
|
if (!values || values.size === 0)
|
|
throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`);
|
|
for (const v of values) {
|
|
if (map.has(v)) {
|
|
throw new Error(`Duplicate discriminator value "${String(v)}"`);
|
|
}
|
|
map.set(v, o);
|
|
}
|
|
}
|
|
return map;
|
|
});
|
|
inst._zod.parse = (payload, ctx) => {
|
|
const input = payload.value;
|
|
if (!isObject2(input)) {
|
|
payload.issues.push({
|
|
code: "invalid_type",
|
|
expected: "object",
|
|
input,
|
|
inst
|
|
});
|
|
return payload;
|
|
}
|
|
const opt = disc.value.get(input == null ? void 0 : input[def.discriminator]);
|
|
if (opt) {
|
|
return opt._zod.run(payload, ctx);
|
|
}
|
|
if (def.unionFallback) {
|
|
return _super(payload, ctx);
|
|
}
|
|
payload.issues.push({
|
|
code: "invalid_union",
|
|
errors: [],
|
|
note: "No matching discriminator",
|
|
input,
|
|
path: [def.discriminator],
|
|
inst
|
|
});
|
|
return payload;
|
|
};
|
|
});
|
|
var $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def) => {
|
|
$ZodType.init(inst, def);
|
|
inst._zod.parse = (payload, ctx) => {
|
|
const input = payload.value;
|
|
const left = def.left._zod.run({ value: input, issues: [] }, ctx);
|
|
const right = def.right._zod.run({ value: input, issues: [] }, ctx);
|
|
const async = left instanceof Promise || right instanceof Promise;
|
|
if (async) {
|
|
return Promise.all([left, right]).then(([left2, right2]) => {
|
|
return handleIntersectionResults(payload, left2, right2);
|
|
});
|
|
}
|
|
return handleIntersectionResults(payload, left, right);
|
|
};
|
|
});
|
|
function mergeValues2(a, b) {
|
|
if (a === b) {
|
|
return { valid: true, data: a };
|
|
}
|
|
if (a instanceof Date && b instanceof Date && +a === +b) {
|
|
return { valid: true, data: a };
|
|
}
|
|
if (isPlainObject(a) && isPlainObject(b)) {
|
|
const bKeys = Object.keys(b);
|
|
const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
|
|
const newObj = { ...a, ...b };
|
|
for (const key of sharedKeys) {
|
|
const sharedValue = mergeValues2(a[key], b[key]);
|
|
if (!sharedValue.valid) {
|
|
return {
|
|
valid: false,
|
|
mergeErrorPath: [key, ...sharedValue.mergeErrorPath]
|
|
};
|
|
}
|
|
newObj[key] = sharedValue.data;
|
|
}
|
|
return { valid: true, data: newObj };
|
|
}
|
|
if (Array.isArray(a) && Array.isArray(b)) {
|
|
if (a.length !== b.length) {
|
|
return { valid: false, mergeErrorPath: [] };
|
|
}
|
|
const newArray = [];
|
|
for (let index = 0; index < a.length; index++) {
|
|
const itemA = a[index];
|
|
const itemB = b[index];
|
|
const sharedValue = mergeValues2(itemA, itemB);
|
|
if (!sharedValue.valid) {
|
|
return {
|
|
valid: false,
|
|
mergeErrorPath: [index, ...sharedValue.mergeErrorPath]
|
|
};
|
|
}
|
|
newArray.push(sharedValue.data);
|
|
}
|
|
return { valid: true, data: newArray };
|
|
}
|
|
return { valid: false, mergeErrorPath: [] };
|
|
}
|
|
function handleIntersectionResults(result, left, right) {
|
|
if (left.issues.length) {
|
|
result.issues.push(...left.issues);
|
|
}
|
|
if (right.issues.length) {
|
|
result.issues.push(...right.issues);
|
|
}
|
|
if (aborted(result))
|
|
return result;
|
|
const merged = mergeValues2(left.value, right.value);
|
|
if (!merged.valid) {
|
|
throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`);
|
|
}
|
|
result.value = merged.data;
|
|
return result;
|
|
}
|
|
var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
|
|
$ZodType.init(inst, def);
|
|
inst._zod.parse = (payload, ctx) => {
|
|
const input = payload.value;
|
|
if (!isPlainObject(input)) {
|
|
payload.issues.push({
|
|
expected: "record",
|
|
code: "invalid_type",
|
|
input,
|
|
inst
|
|
});
|
|
return payload;
|
|
}
|
|
const proms = [];
|
|
if (def.keyType._zod.values) {
|
|
const values = def.keyType._zod.values;
|
|
payload.value = {};
|
|
for (const key of values) {
|
|
if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") {
|
|
const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
|
|
if (result instanceof Promise) {
|
|
proms.push(result.then((result2) => {
|
|
if (result2.issues.length) {
|
|
payload.issues.push(...prefixIssues(key, result2.issues));
|
|
}
|
|
payload.value[key] = result2.value;
|
|
}));
|
|
} else {
|
|
if (result.issues.length) {
|
|
payload.issues.push(...prefixIssues(key, result.issues));
|
|
}
|
|
payload.value[key] = result.value;
|
|
}
|
|
}
|
|
}
|
|
let unrecognized;
|
|
for (const key in input) {
|
|
if (!values.has(key)) {
|
|
unrecognized = unrecognized != null ? unrecognized : [];
|
|
unrecognized.push(key);
|
|
}
|
|
}
|
|
if (unrecognized && unrecognized.length > 0) {
|
|
payload.issues.push({
|
|
code: "unrecognized_keys",
|
|
input,
|
|
inst,
|
|
keys: unrecognized
|
|
});
|
|
}
|
|
} else {
|
|
payload.value = {};
|
|
for (const key of Reflect.ownKeys(input)) {
|
|
if (key === "__proto__")
|
|
continue;
|
|
const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
|
|
if (keyResult instanceof Promise) {
|
|
throw new Error("Async schemas not supported in object keys currently");
|
|
}
|
|
if (keyResult.issues.length) {
|
|
payload.issues.push({
|
|
origin: "record",
|
|
code: "invalid_key",
|
|
issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),
|
|
input: key,
|
|
path: [key],
|
|
inst
|
|
});
|
|
payload.value[keyResult.value] = keyResult.value;
|
|
continue;
|
|
}
|
|
const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
|
|
if (result instanceof Promise) {
|
|
proms.push(result.then((result2) => {
|
|
if (result2.issues.length) {
|
|
payload.issues.push(...prefixIssues(key, result2.issues));
|
|
}
|
|
payload.value[keyResult.value] = result2.value;
|
|
}));
|
|
} else {
|
|
if (result.issues.length) {
|
|
payload.issues.push(...prefixIssues(key, result.issues));
|
|
}
|
|
payload.value[keyResult.value] = result.value;
|
|
}
|
|
}
|
|
}
|
|
if (proms.length) {
|
|
return Promise.all(proms).then(() => payload);
|
|
}
|
|
return payload;
|
|
};
|
|
});
|
|
var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => {
|
|
$ZodType.init(inst, def);
|
|
const values = getEnumValues(def.entries);
|
|
inst._zod.values = new Set(values);
|
|
inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`);
|
|
inst._zod.parse = (payload, _ctx) => {
|
|
const input = payload.value;
|
|
if (inst._zod.values.has(input)) {
|
|
return payload;
|
|
}
|
|
payload.issues.push({
|
|
code: "invalid_value",
|
|
values,
|
|
input,
|
|
inst
|
|
});
|
|
return payload;
|
|
};
|
|
});
|
|
var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => {
|
|
$ZodType.init(inst, def);
|
|
inst._zod.values = new Set(def.values);
|
|
inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? o.toString() : String(o)).join("|")})$`);
|
|
inst._zod.parse = (payload, _ctx) => {
|
|
const input = payload.value;
|
|
if (inst._zod.values.has(input)) {
|
|
return payload;
|
|
}
|
|
payload.issues.push({
|
|
code: "invalid_value",
|
|
values: def.values,
|
|
input,
|
|
inst
|
|
});
|
|
return payload;
|
|
};
|
|
});
|
|
var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => {
|
|
$ZodType.init(inst, def);
|
|
inst._zod.parse = (payload, _ctx) => {
|
|
const _out = def.transform(payload.value, payload);
|
|
if (_ctx.async) {
|
|
const output = _out instanceof Promise ? _out : Promise.resolve(_out);
|
|
return output.then((output2) => {
|
|
payload.value = output2;
|
|
return payload;
|
|
});
|
|
}
|
|
if (_out instanceof Promise) {
|
|
throw new $ZodAsyncError();
|
|
}
|
|
payload.value = _out;
|
|
return payload;
|
|
};
|
|
});
|
|
var $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => {
|
|
$ZodType.init(inst, def);
|
|
inst._zod.optin = "optional";
|
|
inst._zod.optout = "optional";
|
|
defineLazy(inst._zod, "values", () => {
|
|
return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0;
|
|
});
|
|
defineLazy(inst._zod, "pattern", () => {
|
|
const pattern = def.innerType._zod.pattern;
|
|
return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0;
|
|
});
|
|
inst._zod.parse = (payload, ctx) => {
|
|
if (def.innerType._zod.optin === "optional") {
|
|
return def.innerType._zod.run(payload, ctx);
|
|
}
|
|
if (payload.value === void 0) {
|
|
return payload;
|
|
}
|
|
return def.innerType._zod.run(payload, ctx);
|
|
};
|
|
});
|
|
var $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => {
|
|
$ZodType.init(inst, def);
|
|
defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
|
|
defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
|
|
defineLazy(inst._zod, "pattern", () => {
|
|
const pattern = def.innerType._zod.pattern;
|
|
return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0;
|
|
});
|
|
defineLazy(inst._zod, "values", () => {
|
|
return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0;
|
|
});
|
|
inst._zod.parse = (payload, ctx) => {
|
|
if (payload.value === null)
|
|
return payload;
|
|
return def.innerType._zod.run(payload, ctx);
|
|
};
|
|
});
|
|
var $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => {
|
|
$ZodType.init(inst, def);
|
|
inst._zod.optin = "optional";
|
|
defineLazy(inst._zod, "values", () => def.innerType._zod.values);
|
|
inst._zod.parse = (payload, ctx) => {
|
|
if (payload.value === void 0) {
|
|
payload.value = def.defaultValue;
|
|
return payload;
|
|
}
|
|
const result = def.innerType._zod.run(payload, ctx);
|
|
if (result instanceof Promise) {
|
|
return result.then((result2) => handleDefaultResult(result2, def));
|
|
}
|
|
return handleDefaultResult(result, def);
|
|
};
|
|
});
|
|
function handleDefaultResult(payload, def) {
|
|
if (payload.value === void 0) {
|
|
payload.value = def.defaultValue;
|
|
}
|
|
return payload;
|
|
}
|
|
var $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => {
|
|
$ZodType.init(inst, def);
|
|
inst._zod.optin = "optional";
|
|
defineLazy(inst._zod, "values", () => def.innerType._zod.values);
|
|
inst._zod.parse = (payload, ctx) => {
|
|
if (payload.value === void 0) {
|
|
payload.value = def.defaultValue;
|
|
}
|
|
return def.innerType._zod.run(payload, ctx);
|
|
};
|
|
});
|
|
var $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => {
|
|
$ZodType.init(inst, def);
|
|
defineLazy(inst._zod, "values", () => {
|
|
const v = def.innerType._zod.values;
|
|
return v ? new Set([...v].filter((x) => x !== void 0)) : void 0;
|
|
});
|
|
inst._zod.parse = (payload, ctx) => {
|
|
const result = def.innerType._zod.run(payload, ctx);
|
|
if (result instanceof Promise) {
|
|
return result.then((result2) => handleNonOptionalResult(result2, inst));
|
|
}
|
|
return handleNonOptionalResult(result, inst);
|
|
};
|
|
});
|
|
function handleNonOptionalResult(payload, inst) {
|
|
if (!payload.issues.length && payload.value === void 0) {
|
|
payload.issues.push({
|
|
code: "invalid_type",
|
|
expected: "nonoptional",
|
|
input: payload.value,
|
|
inst
|
|
});
|
|
}
|
|
return payload;
|
|
}
|
|
var $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => {
|
|
$ZodType.init(inst, def);
|
|
inst._zod.optin = "optional";
|
|
defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
|
|
defineLazy(inst._zod, "values", () => def.innerType._zod.values);
|
|
inst._zod.parse = (payload, ctx) => {
|
|
const result = def.innerType._zod.run(payload, ctx);
|
|
if (result instanceof Promise) {
|
|
return result.then((result2) => {
|
|
payload.value = result2.value;
|
|
if (result2.issues.length) {
|
|
payload.value = def.catchValue({
|
|
...payload,
|
|
error: {
|
|
issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config()))
|
|
},
|
|
input: payload.value
|
|
});
|
|
payload.issues = [];
|
|
}
|
|
return payload;
|
|
});
|
|
}
|
|
payload.value = result.value;
|
|
if (result.issues.length) {
|
|
payload.value = def.catchValue({
|
|
...payload,
|
|
error: {
|
|
issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config()))
|
|
},
|
|
input: payload.value
|
|
});
|
|
payload.issues = [];
|
|
}
|
|
return payload;
|
|
};
|
|
});
|
|
var $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => {
|
|
$ZodType.init(inst, def);
|
|
defineLazy(inst._zod, "values", () => def.in._zod.values);
|
|
defineLazy(inst._zod, "optin", () => def.in._zod.optin);
|
|
defineLazy(inst._zod, "optout", () => def.out._zod.optout);
|
|
inst._zod.parse = (payload, ctx) => {
|
|
const left = def.in._zod.run(payload, ctx);
|
|
if (left instanceof Promise) {
|
|
return left.then((left2) => handlePipeResult(left2, def, ctx));
|
|
}
|
|
return handlePipeResult(left, def, ctx);
|
|
};
|
|
});
|
|
function handlePipeResult(left, def, ctx) {
|
|
if (aborted(left)) {
|
|
return left;
|
|
}
|
|
return def.out._zod.run({ value: left.value, issues: left.issues }, ctx);
|
|
}
|
|
var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => {
|
|
$ZodType.init(inst, def);
|
|
defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues);
|
|
defineLazy(inst._zod, "values", () => def.innerType._zod.values);
|
|
defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
|
|
defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
|
|
inst._zod.parse = (payload, ctx) => {
|
|
const result = def.innerType._zod.run(payload, ctx);
|
|
if (result instanceof Promise) {
|
|
return result.then(handleReadonlyResult);
|
|
}
|
|
return handleReadonlyResult(result);
|
|
};
|
|
});
|
|
function handleReadonlyResult(payload) {
|
|
payload.value = Object.freeze(payload.value);
|
|
return payload;
|
|
}
|
|
var $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => {
|
|
$ZodCheck.init(inst, def);
|
|
$ZodType.init(inst, def);
|
|
inst._zod.parse = (payload, _) => {
|
|
return payload;
|
|
};
|
|
inst._zod.check = (payload) => {
|
|
const input = payload.value;
|
|
const r = def.fn(input);
|
|
if (r instanceof Promise) {
|
|
return r.then((r2) => handleRefineResult(r2, payload, input, inst));
|
|
}
|
|
handleRefineResult(r, payload, input, inst);
|
|
return;
|
|
};
|
|
});
|
|
function handleRefineResult(result, payload, input, inst) {
|
|
var _a;
|
|
if (!result) {
|
|
const _iss = {
|
|
code: "custom",
|
|
input,
|
|
inst,
|
|
path: [...(_a = inst._zod.def.path) != null ? _a : []],
|
|
continue: !inst._zod.def.abort
|
|
};
|
|
if (inst._zod.def.params)
|
|
_iss.params = inst._zod.def.params;
|
|
payload.issues.push(issue(_iss));
|
|
}
|
|
}
|
|
var parsedType = (data) => {
|
|
const t = typeof data;
|
|
switch (t) {
|
|
case "number": {
|
|
return Number.isNaN(data) ? "NaN" : "number";
|
|
}
|
|
case "object": {
|
|
if (Array.isArray(data)) {
|
|
return "array";
|
|
}
|
|
if (data === null) {
|
|
return "null";
|
|
}
|
|
if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
|
|
return data.constructor.name;
|
|
}
|
|
}
|
|
}
|
|
return t;
|
|
};
|
|
var error = () => {
|
|
const Sizable = {
|
|
string: { unit: "characters", verb: "to have" },
|
|
file: { unit: "bytes", verb: "to have" },
|
|
array: { unit: "items", verb: "to have" },
|
|
set: { unit: "items", verb: "to have" }
|
|
};
|
|
function getSizing(origin) {
|
|
var _a;
|
|
return (_a = Sizable[origin]) != null ? _a : null;
|
|
}
|
|
const Nouns = {
|
|
regex: "input",
|
|
email: "email address",
|
|
url: "URL",
|
|
emoji: "emoji",
|
|
uuid: "UUID",
|
|
uuidv4: "UUIDv4",
|
|
uuidv6: "UUIDv6",
|
|
nanoid: "nanoid",
|
|
guid: "GUID",
|
|
cuid: "cuid",
|
|
cuid2: "cuid2",
|
|
ulid: "ULID",
|
|
xid: "XID",
|
|
ksuid: "KSUID",
|
|
datetime: "ISO datetime",
|
|
date: "ISO date",
|
|
time: "ISO time",
|
|
duration: "ISO duration",
|
|
ipv4: "IPv4 address",
|
|
ipv6: "IPv6 address",
|
|
cidrv4: "IPv4 range",
|
|
cidrv6: "IPv6 range",
|
|
base64: "base64-encoded string",
|
|
base64url: "base64url-encoded string",
|
|
json_string: "JSON string",
|
|
e164: "E.164 number",
|
|
jwt: "JWT",
|
|
template_literal: "input"
|
|
};
|
|
return (issue2) => {
|
|
var _a, _b, _c, _d;
|
|
switch (issue2.code) {
|
|
case "invalid_type":
|
|
return `Invalid input: expected ${issue2.expected}, received ${parsedType(issue2.input)}`;
|
|
case "invalid_value":
|
|
if (issue2.values.length === 1)
|
|
return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`;
|
|
return `Invalid option: expected one of ${joinValues(issue2.values, "|")}`;
|
|
case "too_big": {
|
|
const adj = issue2.inclusive ? "<=" : "<";
|
|
const sizing = getSizing(issue2.origin);
|
|
if (sizing)
|
|
return `Too big: expected ${(_a = issue2.origin) != null ? _a : "value"} to have ${adj}${issue2.maximum.toString()} ${(_b = sizing.unit) != null ? _b : "elements"}`;
|
|
return `Too big: expected ${(_c = issue2.origin) != null ? _c : "value"} to be ${adj}${issue2.maximum.toString()}`;
|
|
}
|
|
case "too_small": {
|
|
const adj = issue2.inclusive ? ">=" : ">";
|
|
const sizing = getSizing(issue2.origin);
|
|
if (sizing) {
|
|
return `Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
|
|
}
|
|
return `Too small: expected ${issue2.origin} to be ${adj}${issue2.minimum.toString()}`;
|
|
}
|
|
case "invalid_format": {
|
|
const _issue = issue2;
|
|
if (_issue.format === "starts_with") {
|
|
return `Invalid string: must start with "${_issue.prefix}"`;
|
|
}
|
|
if (_issue.format === "ends_with")
|
|
return `Invalid string: must end with "${_issue.suffix}"`;
|
|
if (_issue.format === "includes")
|
|
return `Invalid string: must include "${_issue.includes}"`;
|
|
if (_issue.format === "regex")
|
|
return `Invalid string: must match pattern ${_issue.pattern}`;
|
|
return `Invalid ${(_d = Nouns[_issue.format]) != null ? _d : issue2.format}`;
|
|
}
|
|
case "not_multiple_of":
|
|
return `Invalid number: must be a multiple of ${issue2.divisor}`;
|
|
case "unrecognized_keys":
|
|
return `Unrecognized key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
|
|
case "invalid_key":
|
|
return `Invalid key in ${issue2.origin}`;
|
|
case "invalid_union":
|
|
return "Invalid input";
|
|
case "invalid_element":
|
|
return `Invalid value in ${issue2.origin}`;
|
|
default:
|
|
return `Invalid input`;
|
|
}
|
|
};
|
|
};
|
|
function en_default2() {
|
|
return {
|
|
localeError: error()
|
|
};
|
|
}
|
|
var $ZodRegistry = class {
|
|
constructor() {
|
|
this._map = /* @__PURE__ */ new WeakMap();
|
|
this._idmap = /* @__PURE__ */ new Map();
|
|
}
|
|
add(schema, ..._meta) {
|
|
const meta = _meta[0];
|
|
this._map.set(schema, meta);
|
|
if (meta && typeof meta === "object" && "id" in meta) {
|
|
if (this._idmap.has(meta.id)) {
|
|
throw new Error(`ID ${meta.id} already exists in the registry`);
|
|
}
|
|
this._idmap.set(meta.id, schema);
|
|
}
|
|
return this;
|
|
}
|
|
remove(schema) {
|
|
this._map.delete(schema);
|
|
return this;
|
|
}
|
|
get(schema) {
|
|
var _a;
|
|
const p = schema._zod.parent;
|
|
if (p) {
|
|
const pm = { ...(_a = this.get(p)) != null ? _a : {} };
|
|
delete pm.id;
|
|
return { ...pm, ...this._map.get(schema) };
|
|
}
|
|
return this._map.get(schema);
|
|
}
|
|
has(schema) {
|
|
return this._map.has(schema);
|
|
}
|
|
};
|
|
function registry() {
|
|
return new $ZodRegistry();
|
|
}
|
|
var globalRegistry = /* @__PURE__ */ registry();
|
|
function _string(Class2, params) {
|
|
return new Class2({
|
|
type: "string",
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _email(Class2, params) {
|
|
return new Class2({
|
|
type: "string",
|
|
format: "email",
|
|
check: "string_format",
|
|
abort: false,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _guid(Class2, params) {
|
|
return new Class2({
|
|
type: "string",
|
|
format: "guid",
|
|
check: "string_format",
|
|
abort: false,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _uuid(Class2, params) {
|
|
return new Class2({
|
|
type: "string",
|
|
format: "uuid",
|
|
check: "string_format",
|
|
abort: false,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _uuidv4(Class2, params) {
|
|
return new Class2({
|
|
type: "string",
|
|
format: "uuid",
|
|
check: "string_format",
|
|
abort: false,
|
|
version: "v4",
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _uuidv6(Class2, params) {
|
|
return new Class2({
|
|
type: "string",
|
|
format: "uuid",
|
|
check: "string_format",
|
|
abort: false,
|
|
version: "v6",
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _uuidv7(Class2, params) {
|
|
return new Class2({
|
|
type: "string",
|
|
format: "uuid",
|
|
check: "string_format",
|
|
abort: false,
|
|
version: "v7",
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _url(Class2, params) {
|
|
return new Class2({
|
|
type: "string",
|
|
format: "url",
|
|
check: "string_format",
|
|
abort: false,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _emoji2(Class2, params) {
|
|
return new Class2({
|
|
type: "string",
|
|
format: "emoji",
|
|
check: "string_format",
|
|
abort: false,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _nanoid(Class2, params) {
|
|
return new Class2({
|
|
type: "string",
|
|
format: "nanoid",
|
|
check: "string_format",
|
|
abort: false,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _cuid(Class2, params) {
|
|
return new Class2({
|
|
type: "string",
|
|
format: "cuid",
|
|
check: "string_format",
|
|
abort: false,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _cuid2(Class2, params) {
|
|
return new Class2({
|
|
type: "string",
|
|
format: "cuid2",
|
|
check: "string_format",
|
|
abort: false,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _ulid(Class2, params) {
|
|
return new Class2({
|
|
type: "string",
|
|
format: "ulid",
|
|
check: "string_format",
|
|
abort: false,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _xid(Class2, params) {
|
|
return new Class2({
|
|
type: "string",
|
|
format: "xid",
|
|
check: "string_format",
|
|
abort: false,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _ksuid(Class2, params) {
|
|
return new Class2({
|
|
type: "string",
|
|
format: "ksuid",
|
|
check: "string_format",
|
|
abort: false,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _ipv4(Class2, params) {
|
|
return new Class2({
|
|
type: "string",
|
|
format: "ipv4",
|
|
check: "string_format",
|
|
abort: false,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _ipv6(Class2, params) {
|
|
return new Class2({
|
|
type: "string",
|
|
format: "ipv6",
|
|
check: "string_format",
|
|
abort: false,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _cidrv4(Class2, params) {
|
|
return new Class2({
|
|
type: "string",
|
|
format: "cidrv4",
|
|
check: "string_format",
|
|
abort: false,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _cidrv6(Class2, params) {
|
|
return new Class2({
|
|
type: "string",
|
|
format: "cidrv6",
|
|
check: "string_format",
|
|
abort: false,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _base64(Class2, params) {
|
|
return new Class2({
|
|
type: "string",
|
|
format: "base64",
|
|
check: "string_format",
|
|
abort: false,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _base64url(Class2, params) {
|
|
return new Class2({
|
|
type: "string",
|
|
format: "base64url",
|
|
check: "string_format",
|
|
abort: false,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _e164(Class2, params) {
|
|
return new Class2({
|
|
type: "string",
|
|
format: "e164",
|
|
check: "string_format",
|
|
abort: false,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _jwt(Class2, params) {
|
|
return new Class2({
|
|
type: "string",
|
|
format: "jwt",
|
|
check: "string_format",
|
|
abort: false,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _isoDateTime(Class2, params) {
|
|
return new Class2({
|
|
type: "string",
|
|
format: "datetime",
|
|
check: "string_format",
|
|
offset: false,
|
|
local: false,
|
|
precision: null,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _isoDate(Class2, params) {
|
|
return new Class2({
|
|
type: "string",
|
|
format: "date",
|
|
check: "string_format",
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _isoTime(Class2, params) {
|
|
return new Class2({
|
|
type: "string",
|
|
format: "time",
|
|
check: "string_format",
|
|
precision: null,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _isoDuration(Class2, params) {
|
|
return new Class2({
|
|
type: "string",
|
|
format: "duration",
|
|
check: "string_format",
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _number(Class2, params) {
|
|
return new Class2({
|
|
type: "number",
|
|
checks: [],
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _int(Class2, params) {
|
|
return new Class2({
|
|
type: "number",
|
|
check: "number_format",
|
|
abort: false,
|
|
format: "safeint",
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _boolean(Class2, params) {
|
|
return new Class2({
|
|
type: "boolean",
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _null2(Class2, params) {
|
|
return new Class2({
|
|
type: "null",
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _unknown(Class2) {
|
|
return new Class2({
|
|
type: "unknown"
|
|
});
|
|
}
|
|
function _never(Class2, params) {
|
|
return new Class2({
|
|
type: "never",
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _lt(value, params) {
|
|
return new $ZodCheckLessThan({
|
|
check: "less_than",
|
|
...normalizeParams(params),
|
|
value,
|
|
inclusive: false
|
|
});
|
|
}
|
|
function _lte(value, params) {
|
|
return new $ZodCheckLessThan({
|
|
check: "less_than",
|
|
...normalizeParams(params),
|
|
value,
|
|
inclusive: true
|
|
});
|
|
}
|
|
function _gt(value, params) {
|
|
return new $ZodCheckGreaterThan({
|
|
check: "greater_than",
|
|
...normalizeParams(params),
|
|
value,
|
|
inclusive: false
|
|
});
|
|
}
|
|
function _gte(value, params) {
|
|
return new $ZodCheckGreaterThan({
|
|
check: "greater_than",
|
|
...normalizeParams(params),
|
|
value,
|
|
inclusive: true
|
|
});
|
|
}
|
|
function _multipleOf(value, params) {
|
|
return new $ZodCheckMultipleOf({
|
|
check: "multiple_of",
|
|
...normalizeParams(params),
|
|
value
|
|
});
|
|
}
|
|
function _maxLength(maximum, params) {
|
|
const ch = new $ZodCheckMaxLength({
|
|
check: "max_length",
|
|
...normalizeParams(params),
|
|
maximum
|
|
});
|
|
return ch;
|
|
}
|
|
function _minLength(minimum, params) {
|
|
return new $ZodCheckMinLength({
|
|
check: "min_length",
|
|
...normalizeParams(params),
|
|
minimum
|
|
});
|
|
}
|
|
function _length(length, params) {
|
|
return new $ZodCheckLengthEquals({
|
|
check: "length_equals",
|
|
...normalizeParams(params),
|
|
length
|
|
});
|
|
}
|
|
function _regex(pattern, params) {
|
|
return new $ZodCheckRegex({
|
|
check: "string_format",
|
|
format: "regex",
|
|
...normalizeParams(params),
|
|
pattern
|
|
});
|
|
}
|
|
function _lowercase(params) {
|
|
return new $ZodCheckLowerCase({
|
|
check: "string_format",
|
|
format: "lowercase",
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _uppercase(params) {
|
|
return new $ZodCheckUpperCase({
|
|
check: "string_format",
|
|
format: "uppercase",
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _includes(includes, params) {
|
|
return new $ZodCheckIncludes({
|
|
check: "string_format",
|
|
format: "includes",
|
|
...normalizeParams(params),
|
|
includes
|
|
});
|
|
}
|
|
function _startsWith(prefix, params) {
|
|
return new $ZodCheckStartsWith({
|
|
check: "string_format",
|
|
format: "starts_with",
|
|
...normalizeParams(params),
|
|
prefix
|
|
});
|
|
}
|
|
function _endsWith(suffix, params) {
|
|
return new $ZodCheckEndsWith({
|
|
check: "string_format",
|
|
format: "ends_with",
|
|
...normalizeParams(params),
|
|
suffix
|
|
});
|
|
}
|
|
function _overwrite(tx) {
|
|
return new $ZodCheckOverwrite({
|
|
check: "overwrite",
|
|
tx
|
|
});
|
|
}
|
|
function _normalize(form) {
|
|
return _overwrite((input) => input.normalize(form));
|
|
}
|
|
function _trim() {
|
|
return _overwrite((input) => input.trim());
|
|
}
|
|
function _toLowerCase() {
|
|
return _overwrite((input) => input.toLowerCase());
|
|
}
|
|
function _toUpperCase() {
|
|
return _overwrite((input) => input.toUpperCase());
|
|
}
|
|
function _array(Class2, element, params) {
|
|
return new Class2({
|
|
type: "array",
|
|
element,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _custom(Class2, fn, _params) {
|
|
var _a;
|
|
const norm = normalizeParams(_params);
|
|
(_a = norm.abort) != null ? _a : norm.abort = true;
|
|
const schema = new Class2({
|
|
type: "custom",
|
|
check: "custom",
|
|
fn,
|
|
...norm
|
|
});
|
|
return schema;
|
|
}
|
|
function _refine(Class2, fn, _params) {
|
|
const schema = new Class2({
|
|
type: "custom",
|
|
check: "custom",
|
|
fn,
|
|
...normalizeParams(_params)
|
|
});
|
|
return schema;
|
|
}
|
|
var exports_iso2 = {};
|
|
__export2(exports_iso2, {
|
|
time: () => time2,
|
|
duration: () => duration2,
|
|
datetime: () => datetime2,
|
|
date: () => date2,
|
|
ZodISOTime: () => ZodISOTime,
|
|
ZodISODuration: () => ZodISODuration,
|
|
ZodISODateTime: () => ZodISODateTime,
|
|
ZodISODate: () => ZodISODate
|
|
});
|
|
var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => {
|
|
$ZodISODateTime.init(inst, def);
|
|
ZodStringFormat.init(inst, def);
|
|
});
|
|
function datetime2(params) {
|
|
return _isoDateTime(ZodISODateTime, params);
|
|
}
|
|
var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => {
|
|
$ZodISODate.init(inst, def);
|
|
ZodStringFormat.init(inst, def);
|
|
});
|
|
function date2(params) {
|
|
return _isoDate(ZodISODate, params);
|
|
}
|
|
var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => {
|
|
$ZodISOTime.init(inst, def);
|
|
ZodStringFormat.init(inst, def);
|
|
});
|
|
function time2(params) {
|
|
return _isoTime(ZodISOTime, params);
|
|
}
|
|
var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => {
|
|
$ZodISODuration.init(inst, def);
|
|
ZodStringFormat.init(inst, def);
|
|
});
|
|
function duration2(params) {
|
|
return _isoDuration(ZodISODuration, params);
|
|
}
|
|
var initializer2 = (inst, issues) => {
|
|
$ZodError.init(inst, issues);
|
|
inst.name = "ZodError";
|
|
Object.defineProperties(inst, {
|
|
format: {
|
|
value: (mapper) => formatError(inst, mapper)
|
|
},
|
|
flatten: {
|
|
value: (mapper) => flattenError(inst, mapper)
|
|
},
|
|
addIssue: {
|
|
value: (issue2) => inst.issues.push(issue2)
|
|
},
|
|
addIssues: {
|
|
value: (issues2) => inst.issues.push(...issues2)
|
|
},
|
|
isEmpty: {
|
|
get() {
|
|
return inst.issues.length === 0;
|
|
}
|
|
}
|
|
});
|
|
};
|
|
var ZodError2 = $constructor("ZodError", initializer2);
|
|
var ZodRealError = $constructor("ZodError", initializer2, {
|
|
Parent: Error
|
|
});
|
|
var parse4 = /* @__PURE__ */ _parse(ZodRealError);
|
|
var parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError);
|
|
var safeParse3 = /* @__PURE__ */ _safeParse(ZodRealError);
|
|
var safeParseAsync3 = /* @__PURE__ */ _safeParseAsync(ZodRealError);
|
|
var ZodType2 = /* @__PURE__ */ $constructor("ZodType", (inst, def) => {
|
|
$ZodType.init(inst, def);
|
|
inst.def = def;
|
|
Object.defineProperty(inst, "_def", { value: def });
|
|
inst.check = (...checks3) => {
|
|
var _a;
|
|
return inst.clone({
|
|
...def,
|
|
checks: [
|
|
...(_a = def.checks) != null ? _a : [],
|
|
...checks3.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch)
|
|
]
|
|
});
|
|
};
|
|
inst.clone = (def2, params) => clone(inst, def2, params);
|
|
inst.brand = () => inst;
|
|
inst.register = (reg, meta) => {
|
|
reg.add(inst, meta);
|
|
return inst;
|
|
};
|
|
inst.parse = (data, params) => parse4(inst, data, params, { callee: inst.parse });
|
|
inst.safeParse = (data, params) => safeParse3(inst, data, params);
|
|
inst.parseAsync = async (data, params) => parseAsync2(inst, data, params, { callee: inst.parseAsync });
|
|
inst.safeParseAsync = async (data, params) => safeParseAsync3(inst, data, params);
|
|
inst.spa = inst.safeParseAsync;
|
|
inst.refine = (check2, params) => inst.check(refine(check2, params));
|
|
inst.superRefine = (refinement) => inst.check(superRefine(refinement));
|
|
inst.overwrite = (fn) => inst.check(_overwrite(fn));
|
|
inst.optional = () => optional(inst);
|
|
inst.nullable = () => nullable(inst);
|
|
inst.nullish = () => optional(nullable(inst));
|
|
inst.nonoptional = (params) => nonoptional(inst, params);
|
|
inst.array = () => array(inst);
|
|
inst.or = (arg) => union([inst, arg]);
|
|
inst.and = (arg) => intersection(inst, arg);
|
|
inst.transform = (tx) => pipe(inst, transform(tx));
|
|
inst.default = (def2) => _default(inst, def2);
|
|
inst.prefault = (def2) => prefault(inst, def2);
|
|
inst.catch = (params) => _catch(inst, params);
|
|
inst.pipe = (target) => pipe(inst, target);
|
|
inst.readonly = () => readonly(inst);
|
|
inst.describe = (description) => {
|
|
const cl = inst.clone();
|
|
globalRegistry.add(cl, { description });
|
|
return cl;
|
|
};
|
|
Object.defineProperty(inst, "description", {
|
|
get() {
|
|
var _a;
|
|
return (_a = globalRegistry.get(inst)) == null ? void 0 : _a.description;
|
|
},
|
|
configurable: true
|
|
});
|
|
inst.meta = (...args) => {
|
|
if (args.length === 0) {
|
|
return globalRegistry.get(inst);
|
|
}
|
|
const cl = inst.clone();
|
|
globalRegistry.add(cl, args[0]);
|
|
return cl;
|
|
};
|
|
inst.isOptional = () => inst.safeParse(void 0).success;
|
|
inst.isNullable = () => inst.safeParse(null).success;
|
|
return inst;
|
|
});
|
|
var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => {
|
|
var _a, _b, _c;
|
|
$ZodString.init(inst, def);
|
|
ZodType2.init(inst, def);
|
|
const bag = inst._zod.bag;
|
|
inst.format = (_a = bag.format) != null ? _a : null;
|
|
inst.minLength = (_b = bag.minimum) != null ? _b : null;
|
|
inst.maxLength = (_c = bag.maximum) != null ? _c : null;
|
|
inst.regex = (...args) => inst.check(_regex(...args));
|
|
inst.includes = (...args) => inst.check(_includes(...args));
|
|
inst.startsWith = (...args) => inst.check(_startsWith(...args));
|
|
inst.endsWith = (...args) => inst.check(_endsWith(...args));
|
|
inst.min = (...args) => inst.check(_minLength(...args));
|
|
inst.max = (...args) => inst.check(_maxLength(...args));
|
|
inst.length = (...args) => inst.check(_length(...args));
|
|
inst.nonempty = (...args) => inst.check(_minLength(1, ...args));
|
|
inst.lowercase = (params) => inst.check(_lowercase(params));
|
|
inst.uppercase = (params) => inst.check(_uppercase(params));
|
|
inst.trim = () => inst.check(_trim());
|
|
inst.normalize = (...args) => inst.check(_normalize(...args));
|
|
inst.toLowerCase = () => inst.check(_toLowerCase());
|
|
inst.toUpperCase = () => inst.check(_toUpperCase());
|
|
});
|
|
var ZodString2 = /* @__PURE__ */ $constructor("ZodString", (inst, def) => {
|
|
$ZodString.init(inst, def);
|
|
_ZodString.init(inst, def);
|
|
inst.email = (params) => inst.check(_email(ZodEmail, params));
|
|
inst.url = (params) => inst.check(_url(ZodURL, params));
|
|
inst.jwt = (params) => inst.check(_jwt(ZodJWT, params));
|
|
inst.emoji = (params) => inst.check(_emoji2(ZodEmoji, params));
|
|
inst.guid = (params) => inst.check(_guid(ZodGUID, params));
|
|
inst.uuid = (params) => inst.check(_uuid(ZodUUID, params));
|
|
inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params));
|
|
inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params));
|
|
inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params));
|
|
inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params));
|
|
inst.guid = (params) => inst.check(_guid(ZodGUID, params));
|
|
inst.cuid = (params) => inst.check(_cuid(ZodCUID, params));
|
|
inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params));
|
|
inst.ulid = (params) => inst.check(_ulid(ZodULID, params));
|
|
inst.base64 = (params) => inst.check(_base64(ZodBase64, params));
|
|
inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params));
|
|
inst.xid = (params) => inst.check(_xid(ZodXID, params));
|
|
inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params));
|
|
inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params));
|
|
inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params));
|
|
inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params));
|
|
inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params));
|
|
inst.e164 = (params) => inst.check(_e164(ZodE164, params));
|
|
inst.datetime = (params) => inst.check(datetime2(params));
|
|
inst.date = (params) => inst.check(date2(params));
|
|
inst.time = (params) => inst.check(time2(params));
|
|
inst.duration = (params) => inst.check(duration2(params));
|
|
});
|
|
function string2(params) {
|
|
return _string(ZodString2, params);
|
|
}
|
|
var ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def) => {
|
|
$ZodStringFormat.init(inst, def);
|
|
_ZodString.init(inst, def);
|
|
});
|
|
var ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => {
|
|
$ZodEmail.init(inst, def);
|
|
ZodStringFormat.init(inst, def);
|
|
});
|
|
var ZodGUID = /* @__PURE__ */ $constructor("ZodGUID", (inst, def) => {
|
|
$ZodGUID.init(inst, def);
|
|
ZodStringFormat.init(inst, def);
|
|
});
|
|
var ZodUUID = /* @__PURE__ */ $constructor("ZodUUID", (inst, def) => {
|
|
$ZodUUID.init(inst, def);
|
|
ZodStringFormat.init(inst, def);
|
|
});
|
|
var ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def) => {
|
|
$ZodURL.init(inst, def);
|
|
ZodStringFormat.init(inst, def);
|
|
});
|
|
var ZodEmoji = /* @__PURE__ */ $constructor("ZodEmoji", (inst, def) => {
|
|
$ZodEmoji.init(inst, def);
|
|
ZodStringFormat.init(inst, def);
|
|
});
|
|
var ZodNanoID = /* @__PURE__ */ $constructor("ZodNanoID", (inst, def) => {
|
|
$ZodNanoID.init(inst, def);
|
|
ZodStringFormat.init(inst, def);
|
|
});
|
|
var ZodCUID = /* @__PURE__ */ $constructor("ZodCUID", (inst, def) => {
|
|
$ZodCUID.init(inst, def);
|
|
ZodStringFormat.init(inst, def);
|
|
});
|
|
var ZodCUID2 = /* @__PURE__ */ $constructor("ZodCUID2", (inst, def) => {
|
|
$ZodCUID2.init(inst, def);
|
|
ZodStringFormat.init(inst, def);
|
|
});
|
|
var ZodULID = /* @__PURE__ */ $constructor("ZodULID", (inst, def) => {
|
|
$ZodULID.init(inst, def);
|
|
ZodStringFormat.init(inst, def);
|
|
});
|
|
var ZodXID = /* @__PURE__ */ $constructor("ZodXID", (inst, def) => {
|
|
$ZodXID.init(inst, def);
|
|
ZodStringFormat.init(inst, def);
|
|
});
|
|
var ZodKSUID = /* @__PURE__ */ $constructor("ZodKSUID", (inst, def) => {
|
|
$ZodKSUID.init(inst, def);
|
|
ZodStringFormat.init(inst, def);
|
|
});
|
|
var ZodIPv4 = /* @__PURE__ */ $constructor("ZodIPv4", (inst, def) => {
|
|
$ZodIPv4.init(inst, def);
|
|
ZodStringFormat.init(inst, def);
|
|
});
|
|
var ZodIPv6 = /* @__PURE__ */ $constructor("ZodIPv6", (inst, def) => {
|
|
$ZodIPv6.init(inst, def);
|
|
ZodStringFormat.init(inst, def);
|
|
});
|
|
var ZodCIDRv4 = /* @__PURE__ */ $constructor("ZodCIDRv4", (inst, def) => {
|
|
$ZodCIDRv4.init(inst, def);
|
|
ZodStringFormat.init(inst, def);
|
|
});
|
|
var ZodCIDRv6 = /* @__PURE__ */ $constructor("ZodCIDRv6", (inst, def) => {
|
|
$ZodCIDRv6.init(inst, def);
|
|
ZodStringFormat.init(inst, def);
|
|
});
|
|
var ZodBase64 = /* @__PURE__ */ $constructor("ZodBase64", (inst, def) => {
|
|
$ZodBase64.init(inst, def);
|
|
ZodStringFormat.init(inst, def);
|
|
});
|
|
var ZodBase64URL = /* @__PURE__ */ $constructor("ZodBase64URL", (inst, def) => {
|
|
$ZodBase64URL.init(inst, def);
|
|
ZodStringFormat.init(inst, def);
|
|
});
|
|
var ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => {
|
|
$ZodE164.init(inst, def);
|
|
ZodStringFormat.init(inst, def);
|
|
});
|
|
var ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => {
|
|
$ZodJWT.init(inst, def);
|
|
ZodStringFormat.init(inst, def);
|
|
});
|
|
var ZodNumber2 = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => {
|
|
var _a, _b, _c, _d, _e, _f, _g, _h, _i;
|
|
$ZodNumber.init(inst, def);
|
|
ZodType2.init(inst, def);
|
|
inst.gt = (value, params) => inst.check(_gt(value, params));
|
|
inst.gte = (value, params) => inst.check(_gte(value, params));
|
|
inst.min = (value, params) => inst.check(_gte(value, params));
|
|
inst.lt = (value, params) => inst.check(_lt(value, params));
|
|
inst.lte = (value, params) => inst.check(_lte(value, params));
|
|
inst.max = (value, params) => inst.check(_lte(value, params));
|
|
inst.int = (params) => inst.check(int(params));
|
|
inst.safe = (params) => inst.check(int(params));
|
|
inst.positive = (params) => inst.check(_gt(0, params));
|
|
inst.nonnegative = (params) => inst.check(_gte(0, params));
|
|
inst.negative = (params) => inst.check(_lt(0, params));
|
|
inst.nonpositive = (params) => inst.check(_lte(0, params));
|
|
inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params));
|
|
inst.step = (value, params) => inst.check(_multipleOf(value, params));
|
|
inst.finite = () => inst;
|
|
const bag = inst._zod.bag;
|
|
inst.minValue = (_c = Math.max((_a = bag.minimum) != null ? _a : Number.NEGATIVE_INFINITY, (_b = bag.exclusiveMinimum) != null ? _b : Number.NEGATIVE_INFINITY)) != null ? _c : null;
|
|
inst.maxValue = (_f = Math.min((_d = bag.maximum) != null ? _d : Number.POSITIVE_INFINITY, (_e = bag.exclusiveMaximum) != null ? _e : Number.POSITIVE_INFINITY)) != null ? _f : null;
|
|
inst.isInt = ((_g = bag.format) != null ? _g : "").includes("int") || Number.isSafeInteger((_h = bag.multipleOf) != null ? _h : 0.5);
|
|
inst.isFinite = true;
|
|
inst.format = (_i = bag.format) != null ? _i : null;
|
|
});
|
|
function number2(params) {
|
|
return _number(ZodNumber2, params);
|
|
}
|
|
var ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def) => {
|
|
$ZodNumberFormat.init(inst, def);
|
|
ZodNumber2.init(inst, def);
|
|
});
|
|
function int(params) {
|
|
return _int(ZodNumberFormat, params);
|
|
}
|
|
var ZodBoolean2 = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => {
|
|
$ZodBoolean.init(inst, def);
|
|
ZodType2.init(inst, def);
|
|
});
|
|
function boolean2(params) {
|
|
return _boolean(ZodBoolean2, params);
|
|
}
|
|
var ZodNull2 = /* @__PURE__ */ $constructor("ZodNull", (inst, def) => {
|
|
$ZodNull.init(inst, def);
|
|
ZodType2.init(inst, def);
|
|
});
|
|
function _null3(params) {
|
|
return _null2(ZodNull2, params);
|
|
}
|
|
var ZodUnknown2 = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => {
|
|
$ZodUnknown.init(inst, def);
|
|
ZodType2.init(inst, def);
|
|
});
|
|
function unknown() {
|
|
return _unknown(ZodUnknown2);
|
|
}
|
|
var ZodNever2 = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => {
|
|
$ZodNever.init(inst, def);
|
|
ZodType2.init(inst, def);
|
|
});
|
|
function never(params) {
|
|
return _never(ZodNever2, params);
|
|
}
|
|
var ZodArray2 = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => {
|
|
$ZodArray.init(inst, def);
|
|
ZodType2.init(inst, def);
|
|
inst.element = def.element;
|
|
inst.min = (minLength, params) => inst.check(_minLength(minLength, params));
|
|
inst.nonempty = (params) => inst.check(_minLength(1, params));
|
|
inst.max = (maxLength, params) => inst.check(_maxLength(maxLength, params));
|
|
inst.length = (len, params) => inst.check(_length(len, params));
|
|
inst.unwrap = () => inst.element;
|
|
});
|
|
function array(element, params) {
|
|
return _array(ZodArray2, element, params);
|
|
}
|
|
var ZodObject2 = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => {
|
|
$ZodObject.init(inst, def);
|
|
ZodType2.init(inst, def);
|
|
exports_util.defineLazy(inst, "shape", () => def.shape);
|
|
inst.keyof = () => _enum(Object.keys(inst._zod.def.shape));
|
|
inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall });
|
|
inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() });
|
|
inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() });
|
|
inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never() });
|
|
inst.strip = () => inst.clone({ ...inst._zod.def, catchall: void 0 });
|
|
inst.extend = (incoming) => {
|
|
return exports_util.extend(inst, incoming);
|
|
};
|
|
inst.merge = (other) => exports_util.merge(inst, other);
|
|
inst.pick = (mask) => exports_util.pick(inst, mask);
|
|
inst.omit = (mask) => exports_util.omit(inst, mask);
|
|
inst.partial = (...args) => exports_util.partial(ZodOptional2, inst, args[0]);
|
|
inst.required = (...args) => exports_util.required(ZodNonOptional, inst, args[0]);
|
|
});
|
|
function object2(shape, params) {
|
|
const def = {
|
|
type: "object",
|
|
get shape() {
|
|
exports_util.assignProp(this, "shape", { ...shape });
|
|
return this.shape;
|
|
},
|
|
...exports_util.normalizeParams(params)
|
|
};
|
|
return new ZodObject2(def);
|
|
}
|
|
function looseObject(shape, params) {
|
|
return new ZodObject2({
|
|
type: "object",
|
|
get shape() {
|
|
exports_util.assignProp(this, "shape", { ...shape });
|
|
return this.shape;
|
|
},
|
|
catchall: unknown(),
|
|
...exports_util.normalizeParams(params)
|
|
});
|
|
}
|
|
var ZodUnion2 = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => {
|
|
$ZodUnion.init(inst, def);
|
|
ZodType2.init(inst, def);
|
|
inst.options = def.options;
|
|
});
|
|
function union(options, params) {
|
|
return new ZodUnion2({
|
|
type: "union",
|
|
options,
|
|
...exports_util.normalizeParams(params)
|
|
});
|
|
}
|
|
var ZodDiscriminatedUnion2 = /* @__PURE__ */ $constructor("ZodDiscriminatedUnion", (inst, def) => {
|
|
ZodUnion2.init(inst, def);
|
|
$ZodDiscriminatedUnion.init(inst, def);
|
|
});
|
|
function discriminatedUnion(discriminator, options, params) {
|
|
return new ZodDiscriminatedUnion2({
|
|
type: "union",
|
|
options,
|
|
discriminator,
|
|
...exports_util.normalizeParams(params)
|
|
});
|
|
}
|
|
var ZodIntersection2 = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def) => {
|
|
$ZodIntersection.init(inst, def);
|
|
ZodType2.init(inst, def);
|
|
});
|
|
function intersection(left, right) {
|
|
return new ZodIntersection2({
|
|
type: "intersection",
|
|
left,
|
|
right
|
|
});
|
|
}
|
|
var ZodRecord2 = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => {
|
|
$ZodRecord.init(inst, def);
|
|
ZodType2.init(inst, def);
|
|
inst.keyType = def.keyType;
|
|
inst.valueType = def.valueType;
|
|
});
|
|
function record(keyType, valueType, params) {
|
|
return new ZodRecord2({
|
|
type: "record",
|
|
keyType,
|
|
valueType,
|
|
...exports_util.normalizeParams(params)
|
|
});
|
|
}
|
|
var ZodEnum2 = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => {
|
|
$ZodEnum.init(inst, def);
|
|
ZodType2.init(inst, def);
|
|
inst.enum = def.entries;
|
|
inst.options = Object.values(def.entries);
|
|
const keys = new Set(Object.keys(def.entries));
|
|
inst.extract = (values, params) => {
|
|
const newEntries = {};
|
|
for (const value of values) {
|
|
if (keys.has(value)) {
|
|
newEntries[value] = def.entries[value];
|
|
} else
|
|
throw new Error(`Key ${value} not found in enum`);
|
|
}
|
|
return new ZodEnum2({
|
|
...def,
|
|
checks: [],
|
|
...exports_util.normalizeParams(params),
|
|
entries: newEntries
|
|
});
|
|
};
|
|
inst.exclude = (values, params) => {
|
|
const newEntries = { ...def.entries };
|
|
for (const value of values) {
|
|
if (keys.has(value)) {
|
|
delete newEntries[value];
|
|
} else
|
|
throw new Error(`Key ${value} not found in enum`);
|
|
}
|
|
return new ZodEnum2({
|
|
...def,
|
|
checks: [],
|
|
...exports_util.normalizeParams(params),
|
|
entries: newEntries
|
|
});
|
|
};
|
|
});
|
|
function _enum(values, params) {
|
|
const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;
|
|
return new ZodEnum2({
|
|
type: "enum",
|
|
entries,
|
|
...exports_util.normalizeParams(params)
|
|
});
|
|
}
|
|
var ZodLiteral2 = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def) => {
|
|
$ZodLiteral.init(inst, def);
|
|
ZodType2.init(inst, def);
|
|
inst.values = new Set(def.values);
|
|
Object.defineProperty(inst, "value", {
|
|
get() {
|
|
if (def.values.length > 1) {
|
|
throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");
|
|
}
|
|
return def.values[0];
|
|
}
|
|
});
|
|
});
|
|
function literal(value, params) {
|
|
return new ZodLiteral2({
|
|
type: "literal",
|
|
values: Array.isArray(value) ? value : [value],
|
|
...exports_util.normalizeParams(params)
|
|
});
|
|
}
|
|
var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => {
|
|
$ZodTransform.init(inst, def);
|
|
ZodType2.init(inst, def);
|
|
inst._zod.parse = (payload, _ctx) => {
|
|
payload.addIssue = (issue2) => {
|
|
var _a, _b, _c, _d;
|
|
if (typeof issue2 === "string") {
|
|
payload.issues.push(exports_util.issue(issue2, payload.value, def));
|
|
} else {
|
|
const _issue = issue2;
|
|
if (_issue.fatal)
|
|
_issue.continue = false;
|
|
(_a = _issue.code) != null ? _a : _issue.code = "custom";
|
|
(_b = _issue.input) != null ? _b : _issue.input = payload.value;
|
|
(_c = _issue.inst) != null ? _c : _issue.inst = inst;
|
|
(_d = _issue.continue) != null ? _d : _issue.continue = true;
|
|
payload.issues.push(exports_util.issue(_issue));
|
|
}
|
|
};
|
|
const output = def.transform(payload.value, payload);
|
|
if (output instanceof Promise) {
|
|
return output.then((output2) => {
|
|
payload.value = output2;
|
|
return payload;
|
|
});
|
|
}
|
|
payload.value = output;
|
|
return payload;
|
|
};
|
|
});
|
|
function transform(fn) {
|
|
return new ZodTransform({
|
|
type: "transform",
|
|
transform: fn
|
|
});
|
|
}
|
|
var ZodOptional2 = /* @__PURE__ */ $constructor("ZodOptional", (inst, def) => {
|
|
$ZodOptional.init(inst, def);
|
|
ZodType2.init(inst, def);
|
|
inst.unwrap = () => inst._zod.def.innerType;
|
|
});
|
|
function optional(innerType) {
|
|
return new ZodOptional2({
|
|
type: "optional",
|
|
innerType
|
|
});
|
|
}
|
|
var ZodNullable2 = /* @__PURE__ */ $constructor("ZodNullable", (inst, def) => {
|
|
$ZodNullable.init(inst, def);
|
|
ZodType2.init(inst, def);
|
|
inst.unwrap = () => inst._zod.def.innerType;
|
|
});
|
|
function nullable(innerType) {
|
|
return new ZodNullable2({
|
|
type: "nullable",
|
|
innerType
|
|
});
|
|
}
|
|
var ZodDefault2 = /* @__PURE__ */ $constructor("ZodDefault", (inst, def) => {
|
|
$ZodDefault.init(inst, def);
|
|
ZodType2.init(inst, def);
|
|
inst.unwrap = () => inst._zod.def.innerType;
|
|
inst.removeDefault = inst.unwrap;
|
|
});
|
|
function _default(innerType, defaultValue) {
|
|
return new ZodDefault2({
|
|
type: "default",
|
|
innerType,
|
|
get defaultValue() {
|
|
return typeof defaultValue === "function" ? defaultValue() : defaultValue;
|
|
}
|
|
});
|
|
}
|
|
var ZodPrefault = /* @__PURE__ */ $constructor("ZodPrefault", (inst, def) => {
|
|
$ZodPrefault.init(inst, def);
|
|
ZodType2.init(inst, def);
|
|
inst.unwrap = () => inst._zod.def.innerType;
|
|
});
|
|
function prefault(innerType, defaultValue) {
|
|
return new ZodPrefault({
|
|
type: "prefault",
|
|
innerType,
|
|
get defaultValue() {
|
|
return typeof defaultValue === "function" ? defaultValue() : defaultValue;
|
|
}
|
|
});
|
|
}
|
|
var ZodNonOptional = /* @__PURE__ */ $constructor("ZodNonOptional", (inst, def) => {
|
|
$ZodNonOptional.init(inst, def);
|
|
ZodType2.init(inst, def);
|
|
inst.unwrap = () => inst._zod.def.innerType;
|
|
});
|
|
function nonoptional(innerType, params) {
|
|
return new ZodNonOptional({
|
|
type: "nonoptional",
|
|
innerType,
|
|
...exports_util.normalizeParams(params)
|
|
});
|
|
}
|
|
var ZodCatch2 = /* @__PURE__ */ $constructor("ZodCatch", (inst, def) => {
|
|
$ZodCatch.init(inst, def);
|
|
ZodType2.init(inst, def);
|
|
inst.unwrap = () => inst._zod.def.innerType;
|
|
inst.removeCatch = inst.unwrap;
|
|
});
|
|
function _catch(innerType, catchValue) {
|
|
return new ZodCatch2({
|
|
type: "catch",
|
|
innerType,
|
|
catchValue: typeof catchValue === "function" ? catchValue : () => catchValue
|
|
});
|
|
}
|
|
var ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def) => {
|
|
$ZodPipe.init(inst, def);
|
|
ZodType2.init(inst, def);
|
|
inst.in = def.in;
|
|
inst.out = def.out;
|
|
});
|
|
function pipe(in_, out) {
|
|
return new ZodPipe({
|
|
type: "pipe",
|
|
in: in_,
|
|
out
|
|
});
|
|
}
|
|
var ZodReadonly2 = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def) => {
|
|
$ZodReadonly.init(inst, def);
|
|
ZodType2.init(inst, def);
|
|
});
|
|
function readonly(innerType) {
|
|
return new ZodReadonly2({
|
|
type: "readonly",
|
|
innerType
|
|
});
|
|
}
|
|
var ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def) => {
|
|
$ZodCustom.init(inst, def);
|
|
ZodType2.init(inst, def);
|
|
});
|
|
function check(fn, params) {
|
|
const ch = new $ZodCheck({
|
|
check: "custom",
|
|
...exports_util.normalizeParams(params)
|
|
});
|
|
ch._zod.check = fn;
|
|
return ch;
|
|
}
|
|
function custom(fn, _params) {
|
|
return _custom(ZodCustom, fn != null ? fn : (() => true), _params);
|
|
}
|
|
function refine(fn, _params = {}) {
|
|
return _refine(ZodCustom, fn, _params);
|
|
}
|
|
function superRefine(fn, params) {
|
|
const ch = check((payload) => {
|
|
payload.addIssue = (issue2) => {
|
|
var _a, _b, _c, _d;
|
|
if (typeof issue2 === "string") {
|
|
payload.issues.push(exports_util.issue(issue2, payload.value, ch._zod.def));
|
|
} else {
|
|
const _issue = issue2;
|
|
if (_issue.fatal)
|
|
_issue.continue = false;
|
|
(_a = _issue.code) != null ? _a : _issue.code = "custom";
|
|
(_b = _issue.input) != null ? _b : _issue.input = payload.value;
|
|
(_c = _issue.inst) != null ? _c : _issue.inst = ch;
|
|
(_d = _issue.continue) != null ? _d : _issue.continue = !ch._zod.def.abort;
|
|
payload.issues.push(exports_util.issue(_issue));
|
|
}
|
|
};
|
|
return fn(payload.value, payload);
|
|
}, params);
|
|
return ch;
|
|
}
|
|
function preprocess(fn, schema) {
|
|
return pipe(transform(fn), schema);
|
|
}
|
|
config(en_default2());
|
|
var RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task";
|
|
var JSONRPC_VERSION = "2.0";
|
|
var AssertObjectSchema = custom((v) => v !== null && (typeof v === "object" || typeof v === "function"));
|
|
var ProgressTokenSchema = union([string2(), number2().int()]);
|
|
var CursorSchema = string2();
|
|
var TaskCreationParamsSchema = looseObject({
|
|
ttl: union([number2(), _null3()]).optional(),
|
|
pollInterval: number2().optional()
|
|
});
|
|
var RelatedTaskMetadataSchema = looseObject({
|
|
taskId: string2()
|
|
});
|
|
var RequestMetaSchema = looseObject({
|
|
progressToken: ProgressTokenSchema.optional(),
|
|
[RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional()
|
|
});
|
|
var BaseRequestParamsSchema = looseObject({
|
|
task: TaskCreationParamsSchema.optional(),
|
|
_meta: RequestMetaSchema.optional()
|
|
});
|
|
var RequestSchema = object2({
|
|
method: string2(),
|
|
params: BaseRequestParamsSchema.optional()
|
|
});
|
|
var NotificationsParamsSchema = looseObject({
|
|
_meta: object2({
|
|
[RELATED_TASK_META_KEY]: optional(RelatedTaskMetadataSchema)
|
|
}).passthrough().optional()
|
|
});
|
|
var NotificationSchema = object2({
|
|
method: string2(),
|
|
params: NotificationsParamsSchema.optional()
|
|
});
|
|
var ResultSchema = looseObject({
|
|
_meta: looseObject({
|
|
[RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional()
|
|
}).optional()
|
|
});
|
|
var RequestIdSchema = union([string2(), number2().int()]);
|
|
var JSONRPCRequestSchema = object2({
|
|
jsonrpc: literal(JSONRPC_VERSION),
|
|
id: RequestIdSchema,
|
|
...RequestSchema.shape
|
|
}).strict();
|
|
var JSONRPCNotificationSchema = object2({
|
|
jsonrpc: literal(JSONRPC_VERSION),
|
|
...NotificationSchema.shape
|
|
}).strict();
|
|
var JSONRPCResponseSchema = object2({
|
|
jsonrpc: literal(JSONRPC_VERSION),
|
|
id: RequestIdSchema,
|
|
result: ResultSchema
|
|
}).strict();
|
|
var ErrorCode;
|
|
(function(ErrorCode2) {
|
|
ErrorCode2[ErrorCode2["ConnectionClosed"] = -32e3] = "ConnectionClosed";
|
|
ErrorCode2[ErrorCode2["RequestTimeout"] = -32001] = "RequestTimeout";
|
|
ErrorCode2[ErrorCode2["ParseError"] = -32700] = "ParseError";
|
|
ErrorCode2[ErrorCode2["InvalidRequest"] = -32600] = "InvalidRequest";
|
|
ErrorCode2[ErrorCode2["MethodNotFound"] = -32601] = "MethodNotFound";
|
|
ErrorCode2[ErrorCode2["InvalidParams"] = -32602] = "InvalidParams";
|
|
ErrorCode2[ErrorCode2["InternalError"] = -32603] = "InternalError";
|
|
ErrorCode2[ErrorCode2["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired";
|
|
})(ErrorCode || (ErrorCode = {}));
|
|
var JSONRPCErrorSchema = object2({
|
|
jsonrpc: literal(JSONRPC_VERSION),
|
|
id: RequestIdSchema,
|
|
error: object2({
|
|
code: number2().int(),
|
|
message: string2(),
|
|
data: optional(unknown())
|
|
})
|
|
}).strict();
|
|
var JSONRPCMessageSchema = union([JSONRPCRequestSchema, JSONRPCNotificationSchema, JSONRPCResponseSchema, JSONRPCErrorSchema]);
|
|
var EmptyResultSchema = ResultSchema.strict();
|
|
var CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({
|
|
requestId: RequestIdSchema,
|
|
reason: string2().optional()
|
|
});
|
|
var CancelledNotificationSchema = NotificationSchema.extend({
|
|
method: literal("notifications/cancelled"),
|
|
params: CancelledNotificationParamsSchema
|
|
});
|
|
var IconSchema = object2({
|
|
src: string2(),
|
|
mimeType: string2().optional(),
|
|
sizes: array(string2()).optional()
|
|
});
|
|
var IconsSchema = object2({
|
|
icons: array(IconSchema).optional()
|
|
});
|
|
var BaseMetadataSchema = object2({
|
|
name: string2(),
|
|
title: string2().optional()
|
|
});
|
|
var ImplementationSchema = BaseMetadataSchema.extend({
|
|
...BaseMetadataSchema.shape,
|
|
...IconsSchema.shape,
|
|
version: string2(),
|
|
websiteUrl: string2().optional()
|
|
});
|
|
var FormElicitationCapabilitySchema = intersection(object2({
|
|
applyDefaults: boolean2().optional()
|
|
}), record(string2(), unknown()));
|
|
var ElicitationCapabilitySchema = preprocess((value) => {
|
|
if (value && typeof value === "object" && !Array.isArray(value)) {
|
|
if (Object.keys(value).length === 0) {
|
|
return { form: {} };
|
|
}
|
|
}
|
|
return value;
|
|
}, intersection(object2({
|
|
form: FormElicitationCapabilitySchema.optional(),
|
|
url: AssertObjectSchema.optional()
|
|
}), record(string2(), unknown()).optional()));
|
|
var ClientTasksCapabilitySchema = object2({
|
|
list: optional(object2({}).passthrough()),
|
|
cancel: optional(object2({}).passthrough()),
|
|
requests: optional(object2({
|
|
sampling: optional(object2({
|
|
createMessage: optional(object2({}).passthrough())
|
|
}).passthrough()),
|
|
elicitation: optional(object2({
|
|
create: optional(object2({}).passthrough())
|
|
}).passthrough())
|
|
}).passthrough())
|
|
}).passthrough();
|
|
var ServerTasksCapabilitySchema = object2({
|
|
list: optional(object2({}).passthrough()),
|
|
cancel: optional(object2({}).passthrough()),
|
|
requests: optional(object2({
|
|
tools: optional(object2({
|
|
call: optional(object2({}).passthrough())
|
|
}).passthrough())
|
|
}).passthrough())
|
|
}).passthrough();
|
|
var ClientCapabilitiesSchema = object2({
|
|
experimental: record(string2(), AssertObjectSchema).optional(),
|
|
sampling: object2({
|
|
context: AssertObjectSchema.optional(),
|
|
tools: AssertObjectSchema.optional()
|
|
}).optional(),
|
|
elicitation: ElicitationCapabilitySchema.optional(),
|
|
roots: object2({
|
|
listChanged: boolean2().optional()
|
|
}).optional(),
|
|
tasks: optional(ClientTasksCapabilitySchema)
|
|
});
|
|
var InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({
|
|
protocolVersion: string2(),
|
|
capabilities: ClientCapabilitiesSchema,
|
|
clientInfo: ImplementationSchema
|
|
});
|
|
var InitializeRequestSchema = RequestSchema.extend({
|
|
method: literal("initialize"),
|
|
params: InitializeRequestParamsSchema
|
|
});
|
|
var ServerCapabilitiesSchema = object2({
|
|
experimental: record(string2(), AssertObjectSchema).optional(),
|
|
logging: AssertObjectSchema.optional(),
|
|
completions: AssertObjectSchema.optional(),
|
|
prompts: optional(object2({
|
|
listChanged: optional(boolean2())
|
|
})),
|
|
resources: object2({
|
|
subscribe: boolean2().optional(),
|
|
listChanged: boolean2().optional()
|
|
}).optional(),
|
|
tools: object2({
|
|
listChanged: boolean2().optional()
|
|
}).optional(),
|
|
tasks: optional(ServerTasksCapabilitySchema)
|
|
}).passthrough();
|
|
var InitializeResultSchema = ResultSchema.extend({
|
|
protocolVersion: string2(),
|
|
capabilities: ServerCapabilitiesSchema,
|
|
serverInfo: ImplementationSchema,
|
|
instructions: string2().optional()
|
|
});
|
|
var InitializedNotificationSchema = NotificationSchema.extend({
|
|
method: literal("notifications/initialized")
|
|
});
|
|
var PingRequestSchema = RequestSchema.extend({
|
|
method: literal("ping")
|
|
});
|
|
var ProgressSchema = object2({
|
|
progress: number2(),
|
|
total: optional(number2()),
|
|
message: optional(string2())
|
|
});
|
|
var ProgressNotificationParamsSchema = object2({
|
|
...NotificationsParamsSchema.shape,
|
|
...ProgressSchema.shape,
|
|
progressToken: ProgressTokenSchema
|
|
});
|
|
var ProgressNotificationSchema = NotificationSchema.extend({
|
|
method: literal("notifications/progress"),
|
|
params: ProgressNotificationParamsSchema
|
|
});
|
|
var PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({
|
|
cursor: CursorSchema.optional()
|
|
});
|
|
var PaginatedRequestSchema = RequestSchema.extend({
|
|
params: PaginatedRequestParamsSchema.optional()
|
|
});
|
|
var PaginatedResultSchema = ResultSchema.extend({
|
|
nextCursor: optional(CursorSchema)
|
|
});
|
|
var TaskSchema = object2({
|
|
taskId: string2(),
|
|
status: _enum(["working", "input_required", "completed", "failed", "cancelled"]),
|
|
ttl: union([number2(), _null3()]),
|
|
createdAt: string2(),
|
|
lastUpdatedAt: string2(),
|
|
pollInterval: optional(number2()),
|
|
statusMessage: optional(string2())
|
|
});
|
|
var CreateTaskResultSchema = ResultSchema.extend({
|
|
task: TaskSchema
|
|
});
|
|
var TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema);
|
|
var TaskStatusNotificationSchema = NotificationSchema.extend({
|
|
method: literal("notifications/tasks/status"),
|
|
params: TaskStatusNotificationParamsSchema
|
|
});
|
|
var GetTaskRequestSchema = RequestSchema.extend({
|
|
method: literal("tasks/get"),
|
|
params: BaseRequestParamsSchema.extend({
|
|
taskId: string2()
|
|
})
|
|
});
|
|
var GetTaskResultSchema = ResultSchema.merge(TaskSchema);
|
|
var GetTaskPayloadRequestSchema = RequestSchema.extend({
|
|
method: literal("tasks/result"),
|
|
params: BaseRequestParamsSchema.extend({
|
|
taskId: string2()
|
|
})
|
|
});
|
|
var ListTasksRequestSchema = PaginatedRequestSchema.extend({
|
|
method: literal("tasks/list")
|
|
});
|
|
var ListTasksResultSchema = PaginatedResultSchema.extend({
|
|
tasks: array(TaskSchema)
|
|
});
|
|
var CancelTaskRequestSchema = RequestSchema.extend({
|
|
method: literal("tasks/cancel"),
|
|
params: BaseRequestParamsSchema.extend({
|
|
taskId: string2()
|
|
})
|
|
});
|
|
var CancelTaskResultSchema = ResultSchema.merge(TaskSchema);
|
|
var ResourceContentsSchema = object2({
|
|
uri: string2(),
|
|
mimeType: optional(string2()),
|
|
_meta: record(string2(), unknown()).optional()
|
|
});
|
|
var TextResourceContentsSchema = ResourceContentsSchema.extend({
|
|
text: string2()
|
|
});
|
|
var Base64Schema = string2().refine((val) => {
|
|
try {
|
|
atob(val);
|
|
return true;
|
|
} catch (_a) {
|
|
return false;
|
|
}
|
|
}, { message: "Invalid Base64 string" });
|
|
var BlobResourceContentsSchema = ResourceContentsSchema.extend({
|
|
blob: Base64Schema
|
|
});
|
|
var AnnotationsSchema = object2({
|
|
audience: array(_enum(["user", "assistant"])).optional(),
|
|
priority: number2().min(0).max(1).optional(),
|
|
lastModified: exports_iso2.datetime({ offset: true }).optional()
|
|
});
|
|
var ResourceSchema = object2({
|
|
...BaseMetadataSchema.shape,
|
|
...IconsSchema.shape,
|
|
uri: string2(),
|
|
description: optional(string2()),
|
|
mimeType: optional(string2()),
|
|
annotations: AnnotationsSchema.optional(),
|
|
_meta: optional(looseObject({}))
|
|
});
|
|
var ResourceTemplateSchema = object2({
|
|
...BaseMetadataSchema.shape,
|
|
...IconsSchema.shape,
|
|
uriTemplate: string2(),
|
|
description: optional(string2()),
|
|
mimeType: optional(string2()),
|
|
annotations: AnnotationsSchema.optional(),
|
|
_meta: optional(looseObject({}))
|
|
});
|
|
var ListResourcesRequestSchema = PaginatedRequestSchema.extend({
|
|
method: literal("resources/list")
|
|
});
|
|
var ListResourcesResultSchema = PaginatedResultSchema.extend({
|
|
resources: array(ResourceSchema)
|
|
});
|
|
var ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({
|
|
method: literal("resources/templates/list")
|
|
});
|
|
var ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({
|
|
resourceTemplates: array(ResourceTemplateSchema)
|
|
});
|
|
var ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({
|
|
uri: string2()
|
|
});
|
|
var ReadResourceRequestParamsSchema = ResourceRequestParamsSchema;
|
|
var ReadResourceRequestSchema = RequestSchema.extend({
|
|
method: literal("resources/read"),
|
|
params: ReadResourceRequestParamsSchema
|
|
});
|
|
var ReadResourceResultSchema = ResultSchema.extend({
|
|
contents: array(union([TextResourceContentsSchema, BlobResourceContentsSchema]))
|
|
});
|
|
var ResourceListChangedNotificationSchema = NotificationSchema.extend({
|
|
method: literal("notifications/resources/list_changed")
|
|
});
|
|
var SubscribeRequestParamsSchema = ResourceRequestParamsSchema;
|
|
var SubscribeRequestSchema = RequestSchema.extend({
|
|
method: literal("resources/subscribe"),
|
|
params: SubscribeRequestParamsSchema
|
|
});
|
|
var UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema;
|
|
var UnsubscribeRequestSchema = RequestSchema.extend({
|
|
method: literal("resources/unsubscribe"),
|
|
params: UnsubscribeRequestParamsSchema
|
|
});
|
|
var ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({
|
|
uri: string2()
|
|
});
|
|
var ResourceUpdatedNotificationSchema = NotificationSchema.extend({
|
|
method: literal("notifications/resources/updated"),
|
|
params: ResourceUpdatedNotificationParamsSchema
|
|
});
|
|
var PromptArgumentSchema = object2({
|
|
name: string2(),
|
|
description: optional(string2()),
|
|
required: optional(boolean2())
|
|
});
|
|
var PromptSchema = object2({
|
|
...BaseMetadataSchema.shape,
|
|
...IconsSchema.shape,
|
|
description: optional(string2()),
|
|
arguments: optional(array(PromptArgumentSchema)),
|
|
_meta: optional(looseObject({}))
|
|
});
|
|
var ListPromptsRequestSchema = PaginatedRequestSchema.extend({
|
|
method: literal("prompts/list")
|
|
});
|
|
var ListPromptsResultSchema = PaginatedResultSchema.extend({
|
|
prompts: array(PromptSchema)
|
|
});
|
|
var GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({
|
|
name: string2(),
|
|
arguments: record(string2(), string2()).optional()
|
|
});
|
|
var GetPromptRequestSchema = RequestSchema.extend({
|
|
method: literal("prompts/get"),
|
|
params: GetPromptRequestParamsSchema
|
|
});
|
|
var TextContentSchema = object2({
|
|
type: literal("text"),
|
|
text: string2(),
|
|
annotations: AnnotationsSchema.optional(),
|
|
_meta: record(string2(), unknown()).optional()
|
|
});
|
|
var ImageContentSchema = object2({
|
|
type: literal("image"),
|
|
data: Base64Schema,
|
|
mimeType: string2(),
|
|
annotations: AnnotationsSchema.optional(),
|
|
_meta: record(string2(), unknown()).optional()
|
|
});
|
|
var AudioContentSchema = object2({
|
|
type: literal("audio"),
|
|
data: Base64Schema,
|
|
mimeType: string2(),
|
|
annotations: AnnotationsSchema.optional(),
|
|
_meta: record(string2(), unknown()).optional()
|
|
});
|
|
var ToolUseContentSchema = object2({
|
|
type: literal("tool_use"),
|
|
name: string2(),
|
|
id: string2(),
|
|
input: object2({}).passthrough(),
|
|
_meta: optional(object2({}).passthrough())
|
|
}).passthrough();
|
|
var EmbeddedResourceSchema = object2({
|
|
type: literal("resource"),
|
|
resource: union([TextResourceContentsSchema, BlobResourceContentsSchema]),
|
|
annotations: AnnotationsSchema.optional(),
|
|
_meta: record(string2(), unknown()).optional()
|
|
});
|
|
var ResourceLinkSchema = ResourceSchema.extend({
|
|
type: literal("resource_link")
|
|
});
|
|
var ContentBlockSchema = union([
|
|
TextContentSchema,
|
|
ImageContentSchema,
|
|
AudioContentSchema,
|
|
ResourceLinkSchema,
|
|
EmbeddedResourceSchema
|
|
]);
|
|
var PromptMessageSchema = object2({
|
|
role: _enum(["user", "assistant"]),
|
|
content: ContentBlockSchema
|
|
});
|
|
var GetPromptResultSchema = ResultSchema.extend({
|
|
description: optional(string2()),
|
|
messages: array(PromptMessageSchema)
|
|
});
|
|
var PromptListChangedNotificationSchema = NotificationSchema.extend({
|
|
method: literal("notifications/prompts/list_changed")
|
|
});
|
|
var ToolAnnotationsSchema = object2({
|
|
title: string2().optional(),
|
|
readOnlyHint: boolean2().optional(),
|
|
destructiveHint: boolean2().optional(),
|
|
idempotentHint: boolean2().optional(),
|
|
openWorldHint: boolean2().optional()
|
|
});
|
|
var ToolExecutionSchema = object2({
|
|
taskSupport: _enum(["required", "optional", "forbidden"]).optional()
|
|
});
|
|
var ToolSchema = object2({
|
|
...BaseMetadataSchema.shape,
|
|
...IconsSchema.shape,
|
|
description: string2().optional(),
|
|
inputSchema: object2({
|
|
type: literal("object"),
|
|
properties: record(string2(), AssertObjectSchema).optional(),
|
|
required: array(string2()).optional()
|
|
}).catchall(unknown()),
|
|
outputSchema: object2({
|
|
type: literal("object"),
|
|
properties: record(string2(), AssertObjectSchema).optional(),
|
|
required: array(string2()).optional()
|
|
}).catchall(unknown()).optional(),
|
|
annotations: optional(ToolAnnotationsSchema),
|
|
execution: optional(ToolExecutionSchema),
|
|
_meta: record(string2(), unknown()).optional()
|
|
});
|
|
var ListToolsRequestSchema = PaginatedRequestSchema.extend({
|
|
method: literal("tools/list")
|
|
});
|
|
var ListToolsResultSchema = PaginatedResultSchema.extend({
|
|
tools: array(ToolSchema)
|
|
});
|
|
var CallToolResultSchema = ResultSchema.extend({
|
|
content: array(ContentBlockSchema).default([]),
|
|
structuredContent: record(string2(), unknown()).optional(),
|
|
isError: optional(boolean2())
|
|
});
|
|
var CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({
|
|
toolResult: unknown()
|
|
}));
|
|
var CallToolRequestParamsSchema = BaseRequestParamsSchema.extend({
|
|
name: string2(),
|
|
arguments: optional(record(string2(), unknown()))
|
|
});
|
|
var CallToolRequestSchema = RequestSchema.extend({
|
|
method: literal("tools/call"),
|
|
params: CallToolRequestParamsSchema
|
|
});
|
|
var ToolListChangedNotificationSchema = NotificationSchema.extend({
|
|
method: literal("notifications/tools/list_changed")
|
|
});
|
|
var LoggingLevelSchema = _enum(["debug", "info", "notice", "warning", "error", "critical", "alert", "emergency"]);
|
|
var SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({
|
|
level: LoggingLevelSchema
|
|
});
|
|
var SetLevelRequestSchema = RequestSchema.extend({
|
|
method: literal("logging/setLevel"),
|
|
params: SetLevelRequestParamsSchema
|
|
});
|
|
var LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({
|
|
level: LoggingLevelSchema,
|
|
logger: string2().optional(),
|
|
data: unknown()
|
|
});
|
|
var LoggingMessageNotificationSchema = NotificationSchema.extend({
|
|
method: literal("notifications/message"),
|
|
params: LoggingMessageNotificationParamsSchema
|
|
});
|
|
var ModelHintSchema = object2({
|
|
name: string2().optional()
|
|
});
|
|
var ModelPreferencesSchema = object2({
|
|
hints: optional(array(ModelHintSchema)),
|
|
costPriority: optional(number2().min(0).max(1)),
|
|
speedPriority: optional(number2().min(0).max(1)),
|
|
intelligencePriority: optional(number2().min(0).max(1))
|
|
});
|
|
var ToolChoiceSchema = object2({
|
|
mode: optional(_enum(["auto", "required", "none"]))
|
|
});
|
|
var ToolResultContentSchema = object2({
|
|
type: literal("tool_result"),
|
|
toolUseId: string2().describe("The unique identifier for the corresponding tool call."),
|
|
content: array(ContentBlockSchema).default([]),
|
|
structuredContent: object2({}).passthrough().optional(),
|
|
isError: optional(boolean2()),
|
|
_meta: optional(object2({}).passthrough())
|
|
}).passthrough();
|
|
var SamplingContentSchema = discriminatedUnion("type", [TextContentSchema, ImageContentSchema, AudioContentSchema]);
|
|
var SamplingMessageContentBlockSchema = discriminatedUnion("type", [
|
|
TextContentSchema,
|
|
ImageContentSchema,
|
|
AudioContentSchema,
|
|
ToolUseContentSchema,
|
|
ToolResultContentSchema
|
|
]);
|
|
var SamplingMessageSchema = object2({
|
|
role: _enum(["user", "assistant"]),
|
|
content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]),
|
|
_meta: optional(object2({}).passthrough())
|
|
}).passthrough();
|
|
var CreateMessageRequestParamsSchema = BaseRequestParamsSchema.extend({
|
|
messages: array(SamplingMessageSchema),
|
|
modelPreferences: ModelPreferencesSchema.optional(),
|
|
systemPrompt: string2().optional(),
|
|
includeContext: _enum(["none", "thisServer", "allServers"]).optional(),
|
|
temperature: number2().optional(),
|
|
maxTokens: number2().int(),
|
|
stopSequences: array(string2()).optional(),
|
|
metadata: AssertObjectSchema.optional(),
|
|
tools: optional(array(ToolSchema)),
|
|
toolChoice: optional(ToolChoiceSchema)
|
|
});
|
|
var CreateMessageRequestSchema = RequestSchema.extend({
|
|
method: literal("sampling/createMessage"),
|
|
params: CreateMessageRequestParamsSchema
|
|
});
|
|
var CreateMessageResultSchema = ResultSchema.extend({
|
|
model: string2(),
|
|
stopReason: optional(_enum(["endTurn", "stopSequence", "maxTokens"]).or(string2())),
|
|
role: _enum(["user", "assistant"]),
|
|
content: SamplingContentSchema
|
|
});
|
|
var CreateMessageResultWithToolsSchema = ResultSchema.extend({
|
|
model: string2(),
|
|
stopReason: optional(_enum(["endTurn", "stopSequence", "maxTokens", "toolUse"]).or(string2())),
|
|
role: _enum(["user", "assistant"]),
|
|
content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)])
|
|
});
|
|
var BooleanSchemaSchema = object2({
|
|
type: literal("boolean"),
|
|
title: string2().optional(),
|
|
description: string2().optional(),
|
|
default: boolean2().optional()
|
|
});
|
|
var StringSchemaSchema = object2({
|
|
type: literal("string"),
|
|
title: string2().optional(),
|
|
description: string2().optional(),
|
|
minLength: number2().optional(),
|
|
maxLength: number2().optional(),
|
|
format: _enum(["email", "uri", "date", "date-time"]).optional(),
|
|
default: string2().optional()
|
|
});
|
|
var NumberSchemaSchema = object2({
|
|
type: _enum(["number", "integer"]),
|
|
title: string2().optional(),
|
|
description: string2().optional(),
|
|
minimum: number2().optional(),
|
|
maximum: number2().optional(),
|
|
default: number2().optional()
|
|
});
|
|
var UntitledSingleSelectEnumSchemaSchema = object2({
|
|
type: literal("string"),
|
|
title: string2().optional(),
|
|
description: string2().optional(),
|
|
enum: array(string2()),
|
|
default: string2().optional()
|
|
});
|
|
var TitledSingleSelectEnumSchemaSchema = object2({
|
|
type: literal("string"),
|
|
title: string2().optional(),
|
|
description: string2().optional(),
|
|
oneOf: array(object2({
|
|
const: string2(),
|
|
title: string2()
|
|
})),
|
|
default: string2().optional()
|
|
});
|
|
var LegacyTitledEnumSchemaSchema = object2({
|
|
type: literal("string"),
|
|
title: string2().optional(),
|
|
description: string2().optional(),
|
|
enum: array(string2()),
|
|
enumNames: array(string2()).optional(),
|
|
default: string2().optional()
|
|
});
|
|
var SingleSelectEnumSchemaSchema = union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]);
|
|
var UntitledMultiSelectEnumSchemaSchema = object2({
|
|
type: literal("array"),
|
|
title: string2().optional(),
|
|
description: string2().optional(),
|
|
minItems: number2().optional(),
|
|
maxItems: number2().optional(),
|
|
items: object2({
|
|
type: literal("string"),
|
|
enum: array(string2())
|
|
}),
|
|
default: array(string2()).optional()
|
|
});
|
|
var TitledMultiSelectEnumSchemaSchema = object2({
|
|
type: literal("array"),
|
|
title: string2().optional(),
|
|
description: string2().optional(),
|
|
minItems: number2().optional(),
|
|
maxItems: number2().optional(),
|
|
items: object2({
|
|
anyOf: array(object2({
|
|
const: string2(),
|
|
title: string2()
|
|
}))
|
|
}),
|
|
default: array(string2()).optional()
|
|
});
|
|
var MultiSelectEnumSchemaSchema = union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]);
|
|
var EnumSchemaSchema = union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]);
|
|
var PrimitiveSchemaDefinitionSchema = union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]);
|
|
var ElicitRequestFormParamsSchema = BaseRequestParamsSchema.extend({
|
|
mode: literal("form").optional(),
|
|
message: string2(),
|
|
requestedSchema: object2({
|
|
type: literal("object"),
|
|
properties: record(string2(), PrimitiveSchemaDefinitionSchema),
|
|
required: array(string2()).optional()
|
|
})
|
|
});
|
|
var ElicitRequestURLParamsSchema = BaseRequestParamsSchema.extend({
|
|
mode: literal("url"),
|
|
message: string2(),
|
|
elicitationId: string2(),
|
|
url: string2().url()
|
|
});
|
|
var ElicitRequestParamsSchema = union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]);
|
|
var ElicitRequestSchema = RequestSchema.extend({
|
|
method: literal("elicitation/create"),
|
|
params: ElicitRequestParamsSchema
|
|
});
|
|
var ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({
|
|
elicitationId: string2()
|
|
});
|
|
var ElicitationCompleteNotificationSchema = NotificationSchema.extend({
|
|
method: literal("notifications/elicitation/complete"),
|
|
params: ElicitationCompleteNotificationParamsSchema
|
|
});
|
|
var ElicitResultSchema = ResultSchema.extend({
|
|
action: _enum(["accept", "decline", "cancel"]),
|
|
content: preprocess((val) => val === null ? void 0 : val, record(string2(), union([string2(), number2(), boolean2(), array(string2())])).optional())
|
|
});
|
|
var ResourceTemplateReferenceSchema = object2({
|
|
type: literal("ref/resource"),
|
|
uri: string2()
|
|
});
|
|
var PromptReferenceSchema = object2({
|
|
type: literal("ref/prompt"),
|
|
name: string2()
|
|
});
|
|
var CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({
|
|
ref: union([PromptReferenceSchema, ResourceTemplateReferenceSchema]),
|
|
argument: object2({
|
|
name: string2(),
|
|
value: string2()
|
|
}),
|
|
context: object2({
|
|
arguments: record(string2(), string2()).optional()
|
|
}).optional()
|
|
});
|
|
var CompleteRequestSchema = RequestSchema.extend({
|
|
method: literal("completion/complete"),
|
|
params: CompleteRequestParamsSchema
|
|
});
|
|
var CompleteResultSchema = ResultSchema.extend({
|
|
completion: looseObject({
|
|
values: array(string2()).max(100),
|
|
total: optional(number2().int()),
|
|
hasMore: optional(boolean2())
|
|
})
|
|
});
|
|
var RootSchema = object2({
|
|
uri: string2().startsWith("file://"),
|
|
name: string2().optional(),
|
|
_meta: record(string2(), unknown()).optional()
|
|
});
|
|
var ListRootsRequestSchema = RequestSchema.extend({
|
|
method: literal("roots/list")
|
|
});
|
|
var ListRootsResultSchema = ResultSchema.extend({
|
|
roots: array(RootSchema)
|
|
});
|
|
var RootsListChangedNotificationSchema = NotificationSchema.extend({
|
|
method: literal("notifications/roots/list_changed")
|
|
});
|
|
var ClientRequestSchema = union([
|
|
PingRequestSchema,
|
|
InitializeRequestSchema,
|
|
CompleteRequestSchema,
|
|
SetLevelRequestSchema,
|
|
GetPromptRequestSchema,
|
|
ListPromptsRequestSchema,
|
|
ListResourcesRequestSchema,
|
|
ListResourceTemplatesRequestSchema,
|
|
ReadResourceRequestSchema,
|
|
SubscribeRequestSchema,
|
|
UnsubscribeRequestSchema,
|
|
CallToolRequestSchema,
|
|
ListToolsRequestSchema,
|
|
GetTaskRequestSchema,
|
|
GetTaskPayloadRequestSchema,
|
|
ListTasksRequestSchema
|
|
]);
|
|
var ClientNotificationSchema = union([
|
|
CancelledNotificationSchema,
|
|
ProgressNotificationSchema,
|
|
InitializedNotificationSchema,
|
|
RootsListChangedNotificationSchema,
|
|
TaskStatusNotificationSchema
|
|
]);
|
|
var ClientResultSchema = union([
|
|
EmptyResultSchema,
|
|
CreateMessageResultSchema,
|
|
CreateMessageResultWithToolsSchema,
|
|
ElicitResultSchema,
|
|
ListRootsResultSchema,
|
|
GetTaskResultSchema,
|
|
ListTasksResultSchema,
|
|
CreateTaskResultSchema
|
|
]);
|
|
var ServerRequestSchema = union([
|
|
PingRequestSchema,
|
|
CreateMessageRequestSchema,
|
|
ElicitRequestSchema,
|
|
ListRootsRequestSchema,
|
|
GetTaskRequestSchema,
|
|
GetTaskPayloadRequestSchema,
|
|
ListTasksRequestSchema
|
|
]);
|
|
var ServerNotificationSchema = union([
|
|
CancelledNotificationSchema,
|
|
ProgressNotificationSchema,
|
|
LoggingMessageNotificationSchema,
|
|
ResourceUpdatedNotificationSchema,
|
|
ResourceListChangedNotificationSchema,
|
|
ToolListChangedNotificationSchema,
|
|
PromptListChangedNotificationSchema,
|
|
TaskStatusNotificationSchema,
|
|
ElicitationCompleteNotificationSchema
|
|
]);
|
|
var ServerResultSchema = union([
|
|
EmptyResultSchema,
|
|
InitializeResultSchema,
|
|
CompleteResultSchema,
|
|
GetPromptResultSchema,
|
|
ListPromptsResultSchema,
|
|
ListResourcesResultSchema,
|
|
ListResourceTemplatesResultSchema,
|
|
ReadResourceResultSchema,
|
|
CallToolResultSchema,
|
|
ListToolsResultSchema,
|
|
GetTaskResultSchema,
|
|
ListTasksResultSchema,
|
|
CreateTaskResultSchema
|
|
]);
|
|
var ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
|
|
var import_ajv = __toESM2(require_ajv(), 1);
|
|
var import_ajv_formats = __toESM2(require_dist(), 1);
|
|
var McpZodTypeKind;
|
|
(function(McpZodTypeKind2) {
|
|
McpZodTypeKind2["Completable"] = "McpCompletable";
|
|
})(McpZodTypeKind || (McpZodTypeKind = {}));
|
|
function query({
|
|
prompt,
|
|
options
|
|
}) {
|
|
const { systemPrompt, settingSources, sandbox, ...rest } = options != null ? options : {};
|
|
let customSystemPrompt;
|
|
let appendSystemPrompt;
|
|
if (systemPrompt === void 0) {
|
|
customSystemPrompt = "";
|
|
} else if (typeof systemPrompt === "string") {
|
|
customSystemPrompt = systemPrompt;
|
|
} else if (systemPrompt.type === "preset") {
|
|
appendSystemPrompt = systemPrompt.append;
|
|
}
|
|
let pathToClaudeCodeExecutable = rest.pathToClaudeCodeExecutable;
|
|
if (!pathToClaudeCodeExecutable) {
|
|
const filename = (0, import_url.fileURLToPath)(import_meta.url);
|
|
const dirname22 = (0, import_path.join)(filename, "..");
|
|
pathToClaudeCodeExecutable = (0, import_path.join)(dirname22, "cli.js");
|
|
}
|
|
process.env.CLAUDE_AGENT_SDK_VERSION = "0.1.76";
|
|
const {
|
|
abortController = createAbortController(),
|
|
additionalDirectories = [],
|
|
agents,
|
|
allowedTools = [],
|
|
betas,
|
|
canUseTool,
|
|
continue: continueConversation,
|
|
cwd: cwd2,
|
|
disallowedTools = [],
|
|
tools,
|
|
env,
|
|
executable = isRunningWithBun() ? "bun" : "node",
|
|
executableArgs = [],
|
|
extraArgs = {},
|
|
fallbackModel,
|
|
enableFileCheckpointing,
|
|
forkSession,
|
|
hooks,
|
|
includePartialMessages,
|
|
persistSession,
|
|
maxThinkingTokens,
|
|
maxTurns,
|
|
maxBudgetUsd,
|
|
mcpServers,
|
|
model,
|
|
outputFormat,
|
|
permissionMode = "default",
|
|
allowDangerouslySkipPermissions = false,
|
|
permissionPromptToolName,
|
|
plugins,
|
|
resume,
|
|
resumeSessionAt,
|
|
stderr,
|
|
strictMcpConfig
|
|
} = rest;
|
|
const jsonSchema = (outputFormat == null ? void 0 : outputFormat.type) === "json_schema" ? outputFormat.schema : void 0;
|
|
let processEnv = env;
|
|
if (!processEnv) {
|
|
processEnv = { ...process.env };
|
|
}
|
|
if (!processEnv.CLAUDE_CODE_ENTRYPOINT) {
|
|
processEnv.CLAUDE_CODE_ENTRYPOINT = "sdk-ts";
|
|
}
|
|
if (enableFileCheckpointing) {
|
|
processEnv.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING = "true";
|
|
}
|
|
if (!pathToClaudeCodeExecutable) {
|
|
throw new Error("pathToClaudeCodeExecutable is required");
|
|
}
|
|
const allMcpServers = {};
|
|
const sdkMcpServers = /* @__PURE__ */ new Map();
|
|
if (mcpServers) {
|
|
for (const [name, config2] of Object.entries(mcpServers)) {
|
|
if (config2.type === "sdk" && "instance" in config2) {
|
|
sdkMcpServers.set(name, config2.instance);
|
|
allMcpServers[name] = {
|
|
type: "sdk",
|
|
name
|
|
};
|
|
} else {
|
|
allMcpServers[name] = config2;
|
|
}
|
|
}
|
|
}
|
|
const isSingleUserTurn = typeof prompt === "string";
|
|
const transport = new ProcessTransport({
|
|
abortController,
|
|
additionalDirectories,
|
|
betas,
|
|
cwd: cwd2,
|
|
executable,
|
|
executableArgs,
|
|
extraArgs,
|
|
pathToClaudeCodeExecutable,
|
|
env: processEnv,
|
|
forkSession,
|
|
stderr,
|
|
maxThinkingTokens,
|
|
maxTurns,
|
|
maxBudgetUsd,
|
|
model,
|
|
fallbackModel,
|
|
jsonSchema,
|
|
permissionMode,
|
|
allowDangerouslySkipPermissions,
|
|
permissionPromptToolName,
|
|
continueConversation,
|
|
resume,
|
|
resumeSessionAt,
|
|
settingSources: settingSources != null ? settingSources : [],
|
|
allowedTools,
|
|
disallowedTools,
|
|
tools,
|
|
mcpServers: allMcpServers,
|
|
strictMcpConfig,
|
|
canUseTool: !!canUseTool,
|
|
hooks: !!hooks,
|
|
includePartialMessages,
|
|
persistSession,
|
|
plugins,
|
|
sandbox,
|
|
spawnClaudeCodeProcess: rest.spawnClaudeCodeProcess
|
|
});
|
|
const initConfig = {
|
|
systemPrompt: customSystemPrompt,
|
|
appendSystemPrompt,
|
|
agents
|
|
};
|
|
const queryInstance = new Query(transport, isSingleUserTurn, canUseTool, hooks, abortController, sdkMcpServers, jsonSchema, initConfig);
|
|
if (typeof prompt === "string") {
|
|
transport.write(JSON.stringify({
|
|
type: "user",
|
|
session_id: "",
|
|
message: {
|
|
role: "user",
|
|
content: [{ type: "text", text: prompt }]
|
|
},
|
|
parent_tool_use_id: null
|
|
}) + `
|
|
`);
|
|
} else {
|
|
queryInstance.streamInput(prompt);
|
|
}
|
|
return queryInstance;
|
|
}
|
|
|
|
// src/core/agent/ClaudianService.ts
|
|
var fs6 = __toESM(require("fs"));
|
|
var os2 = __toESM(require("os"));
|
|
var path7 = __toESM(require("path"));
|
|
|
|
// src/utils/context.ts
|
|
var CURRENT_NOTE_PREFIX_REGEX = /^<current_note>\n[\s\S]*?<\/current_note>\n\n/;
|
|
function formatCurrentNote(notePath) {
|
|
return `<current_note>
|
|
${notePath}
|
|
</current_note>`;
|
|
}
|
|
function prependCurrentNote(prompt, notePath) {
|
|
return `${formatCurrentNote(notePath)}
|
|
|
|
${prompt}`;
|
|
}
|
|
function stripCurrentNotePrefix(prompt) {
|
|
return prompt.replace(CURRENT_NOTE_PREFIX_REGEX, "");
|
|
}
|
|
function formatContextFilesLine(files) {
|
|
return `<context_files>
|
|
${files.join(", ")}
|
|
</context_files>`;
|
|
}
|
|
function prependContextFiles(prompt, files) {
|
|
return `${formatContextFilesLine(files)}
|
|
|
|
${prompt}`;
|
|
}
|
|
|
|
// src/utils/env.ts
|
|
var path = __toESM(require("path"));
|
|
var isWindows = process.platform === "win32";
|
|
var PATH_SEPARATOR = isWindows ? ";" : ":";
|
|
function getHomeDir() {
|
|
return process.env.HOME || process.env.USERPROFILE || "";
|
|
}
|
|
function getExtraBinaryPaths() {
|
|
const home = getHomeDir();
|
|
if (isWindows) {
|
|
const paths = [];
|
|
const localAppData = process.env.LOCALAPPDATA;
|
|
const appData = process.env.APPDATA;
|
|
const programFiles = process.env.ProgramFiles || "C:\\Program Files";
|
|
const programFilesX86 = process.env["ProgramFiles(x86)"] || "C:\\Program Files (x86)";
|
|
if (appData) {
|
|
paths.push(path.join(appData, "npm"));
|
|
paths.push(path.join(appData, "nvm"));
|
|
}
|
|
if (localAppData) {
|
|
paths.push(path.join(localAppData, "Programs", "node"));
|
|
}
|
|
paths.push(path.join(programFiles, "nodejs"));
|
|
paths.push(path.join(programFilesX86, "nodejs"));
|
|
paths.push(path.join(programFiles, "Docker", "Docker", "resources", "bin"));
|
|
if (home) {
|
|
paths.push(path.join(home, ".local", "bin"));
|
|
}
|
|
return paths;
|
|
} else {
|
|
const paths = [
|
|
"/usr/local/bin",
|
|
"/opt/homebrew/bin",
|
|
// macOS ARM Homebrew
|
|
"/usr/bin",
|
|
"/bin"
|
|
];
|
|
if (home) {
|
|
paths.push(path.join(home, ".local", "bin"));
|
|
paths.push(path.join(home, ".docker", "bin"));
|
|
const nvmBin = process.env.NVM_BIN;
|
|
if (nvmBin) {
|
|
paths.push(nvmBin);
|
|
}
|
|
}
|
|
return paths;
|
|
}
|
|
}
|
|
function getEnhancedPath(additionalPaths) {
|
|
const extraPaths = getExtraBinaryPaths().filter((p) => p);
|
|
const currentPath = process.env.PATH || "";
|
|
const segments = [];
|
|
if (additionalPaths) {
|
|
segments.push(...additionalPaths.split(PATH_SEPARATOR).filter((p) => p));
|
|
}
|
|
segments.push(...extraPaths);
|
|
if (currentPath) {
|
|
segments.push(...currentPath.split(PATH_SEPARATOR).filter((p) => p));
|
|
}
|
|
const seen = /* @__PURE__ */ new Set();
|
|
const unique = segments.filter((p) => {
|
|
const normalized = isWindows ? p.toLowerCase() : p;
|
|
if (seen.has(normalized)) return false;
|
|
seen.add(normalized);
|
|
return true;
|
|
});
|
|
return unique.join(PATH_SEPARATOR);
|
|
}
|
|
function parseEnvironmentVariables(input) {
|
|
const result = {};
|
|
for (const line of input.split(/\r?\n/)) {
|
|
const trimmed = line.trim();
|
|
if (!trimmed || trimmed.startsWith("#")) continue;
|
|
const eqIndex = trimmed.indexOf("=");
|
|
if (eqIndex > 0) {
|
|
const key = trimmed.substring(0, eqIndex).trim();
|
|
let value = trimmed.substring(eqIndex + 1).trim();
|
|
if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
|
|
value = value.slice(1, -1);
|
|
}
|
|
if (key) {
|
|
result[key] = value;
|
|
}
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
function getModelsFromEnvironment(envVars) {
|
|
const modelMap = /* @__PURE__ */ new Map();
|
|
const modelEnvEntries = [
|
|
{ type: "model", envKey: "ANTHROPIC_MODEL" },
|
|
{ type: "opus", envKey: "ANTHROPIC_DEFAULT_OPUS_MODEL" },
|
|
{ type: "sonnet", envKey: "ANTHROPIC_DEFAULT_SONNET_MODEL" },
|
|
{ type: "haiku", envKey: "ANTHROPIC_DEFAULT_HAIKU_MODEL" }
|
|
];
|
|
for (const { type, envKey } of modelEnvEntries) {
|
|
const modelValue = envVars[envKey];
|
|
if (modelValue) {
|
|
const label = modelValue.includes("/") ? modelValue.split("/").pop() || modelValue : modelValue.replace(/-/g, " ").replace(/\b\w/g, (l) => l.toUpperCase());
|
|
if (!modelMap.has(modelValue)) {
|
|
modelMap.set(modelValue, { types: [type], label });
|
|
} else {
|
|
modelMap.get(modelValue).types.push(type);
|
|
}
|
|
}
|
|
}
|
|
const models = [];
|
|
const typePriority = { "model": 4, "haiku": 3, "sonnet": 2, "opus": 1 };
|
|
const sortedEntries = Array.from(modelMap.entries()).sort(([, aInfo], [, bInfo]) => {
|
|
const aPriority = Math.max(...aInfo.types.map((t) => typePriority[t] || 0));
|
|
const bPriority = Math.max(...bInfo.types.map((t) => typePriority[t] || 0));
|
|
return bPriority - aPriority;
|
|
});
|
|
for (const [modelValue, info] of sortedEntries) {
|
|
const sortedTypes = info.types.sort(
|
|
(a, b) => (typePriority[b] || 0) - (typePriority[a] || 0)
|
|
);
|
|
models.push({
|
|
value: modelValue,
|
|
label: info.label,
|
|
description: `Custom model (${sortedTypes.join(", ")})`
|
|
});
|
|
}
|
|
return models;
|
|
}
|
|
function getCurrentModelFromEnvironment(envVars) {
|
|
if (envVars.ANTHROPIC_MODEL) {
|
|
return envVars.ANTHROPIC_MODEL;
|
|
}
|
|
if (envVars.ANTHROPIC_DEFAULT_HAIKU_MODEL) {
|
|
return envVars.ANTHROPIC_DEFAULT_HAIKU_MODEL;
|
|
}
|
|
if (envVars.ANTHROPIC_DEFAULT_SONNET_MODEL) {
|
|
return envVars.ANTHROPIC_DEFAULT_SONNET_MODEL;
|
|
}
|
|
if (envVars.ANTHROPIC_DEFAULT_OPUS_MODEL) {
|
|
return envVars.ANTHROPIC_DEFAULT_OPUS_MODEL;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
// src/utils/path.ts
|
|
var fs2 = __toESM(require("fs"));
|
|
var os = __toESM(require("os"));
|
|
var path2 = __toESM(require("path"));
|
|
function getVaultPath(app) {
|
|
const adapter = app.vault.adapter;
|
|
if ("basePath" in adapter) {
|
|
return adapter.basePath;
|
|
}
|
|
return null;
|
|
}
|
|
function getEnvValue(key) {
|
|
const hasKey = (name) => Object.prototype.hasOwnProperty.call(process.env, name);
|
|
if (hasKey(key)) {
|
|
return process.env[key];
|
|
}
|
|
if (process.platform !== "win32") {
|
|
return void 0;
|
|
}
|
|
const upper = key.toUpperCase();
|
|
if (hasKey(upper)) {
|
|
return process.env[upper];
|
|
}
|
|
const lower = key.toLowerCase();
|
|
if (hasKey(lower)) {
|
|
return process.env[lower];
|
|
}
|
|
const matchKey = Object.keys(process.env).find((name) => name.toLowerCase() === key.toLowerCase());
|
|
return matchKey ? process.env[matchKey] : void 0;
|
|
}
|
|
function expandEnvironmentVariables(value) {
|
|
if (!value.includes("%") && !value.includes("$") && !value.includes("!")) {
|
|
return value;
|
|
}
|
|
const isWindows2 = process.platform === "win32";
|
|
let expanded = value;
|
|
expanded = expanded.replace(/%([A-Za-z_][A-Za-z0-9_]*(?:\([A-Za-z0-9_]+\))?[A-Za-z0-9_]*)%/g, (match, name) => {
|
|
const envValue = getEnvValue(name);
|
|
return envValue !== void 0 ? envValue : match;
|
|
});
|
|
if (isWindows2) {
|
|
expanded = expanded.replace(/!([A-Za-z_][A-Za-z0-9_]*)!/g, (match, name) => {
|
|
const envValue = getEnvValue(name);
|
|
return envValue !== void 0 ? envValue : match;
|
|
});
|
|
expanded = expanded.replace(/\$env:([A-Za-z_][A-Za-z0-9_]*)/gi, (match, name) => {
|
|
const envValue = getEnvValue(name);
|
|
return envValue !== void 0 ? envValue : match;
|
|
});
|
|
}
|
|
expanded = expanded.replace(/\$([A-Za-z_][A-Za-z0-9_]*)|\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (match, name1, name2) => {
|
|
const key = name1 != null ? name1 : name2;
|
|
if (!key) return match;
|
|
const envValue = getEnvValue(key);
|
|
return envValue !== void 0 ? envValue : match;
|
|
});
|
|
return expanded;
|
|
}
|
|
function expandHomePath(p) {
|
|
const expanded = expandEnvironmentVariables(p);
|
|
if (expanded === "~") {
|
|
return os.homedir();
|
|
}
|
|
if (expanded.startsWith("~/")) {
|
|
return path2.join(os.homedir(), expanded.slice(2));
|
|
}
|
|
if (expanded.startsWith("~\\")) {
|
|
return path2.join(os.homedir(), expanded.slice(2));
|
|
}
|
|
return expanded;
|
|
}
|
|
function getNpmGlobalPrefix() {
|
|
if (process.env.npm_config_prefix) {
|
|
return process.env.npm_config_prefix;
|
|
}
|
|
if (process.platform === "win32") {
|
|
const appDataNpm = process.env.APPDATA ? path2.join(process.env.APPDATA, "npm") : null;
|
|
if (appDataNpm && fs2.existsSync(appDataNpm)) {
|
|
return appDataNpm;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
function getNpmCliJsPaths() {
|
|
const homeDir = os.homedir();
|
|
const isWindows2 = process.platform === "win32";
|
|
const cliJsPaths = [];
|
|
if (isWindows2) {
|
|
cliJsPaths.push(
|
|
path2.join(homeDir, "AppData", "Roaming", "npm", "node_modules", "@anthropic-ai", "claude-code", "cli.js")
|
|
);
|
|
const npmPrefix = getNpmGlobalPrefix();
|
|
if (npmPrefix) {
|
|
cliJsPaths.push(
|
|
path2.join(npmPrefix, "node_modules", "@anthropic-ai", "claude-code", "cli.js")
|
|
);
|
|
}
|
|
const programFiles = process.env.ProgramFiles || "C:\\Program Files";
|
|
const programFilesX86 = process.env["ProgramFiles(x86)"] || "C:\\Program Files (x86)";
|
|
cliJsPaths.push(
|
|
path2.join(programFiles, "nodejs", "node_global", "node_modules", "@anthropic-ai", "claude-code", "cli.js"),
|
|
path2.join(programFilesX86, "nodejs", "node_global", "node_modules", "@anthropic-ai", "claude-code", "cli.js")
|
|
);
|
|
cliJsPaths.push(
|
|
path2.join("D:", "Program Files", "nodejs", "node_global", "node_modules", "@anthropic-ai", "claude-code", "cli.js")
|
|
);
|
|
} else {
|
|
cliJsPaths.push(
|
|
path2.join(homeDir, ".npm-global", "lib", "node_modules", "@anthropic-ai", "claude-code", "cli.js"),
|
|
"/usr/local/lib/node_modules/@anthropic-ai/claude-code/cli.js",
|
|
"/usr/lib/node_modules/@anthropic-ai/claude-code/cli.js"
|
|
);
|
|
if (process.env.npm_config_prefix) {
|
|
cliJsPaths.push(
|
|
path2.join(process.env.npm_config_prefix, "lib", "node_modules", "@anthropic-ai", "claude-code", "cli.js")
|
|
);
|
|
}
|
|
}
|
|
return cliJsPaths;
|
|
}
|
|
function findClaudeCLIPath() {
|
|
const homeDir = os.homedir();
|
|
const isWindows2 = process.platform === "win32";
|
|
if (isWindows2) {
|
|
const exePaths = [
|
|
path2.join(homeDir, ".claude", "local", "claude.exe"),
|
|
path2.join(homeDir, "AppData", "Local", "Claude", "claude.exe"),
|
|
path2.join(process.env.ProgramFiles || "C:\\Program Files", "Claude", "claude.exe"),
|
|
path2.join(process.env["ProgramFiles(x86)"] || "C:\\Program Files (x86)", "Claude", "claude.exe"),
|
|
path2.join(homeDir, ".local", "bin", "claude.exe"),
|
|
path2.join(homeDir, ".bun", "bin", "claude.exe"),
|
|
];
|
|
for (const p of exePaths) {
|
|
if (fs2.existsSync(p)) {
|
|
return p;
|
|
}
|
|
}
|
|
const cliJsPaths = getNpmCliJsPaths();
|
|
for (const p of cliJsPaths) {
|
|
if (fs2.existsSync(p)) {
|
|
return p;
|
|
}
|
|
}
|
|
const cmdPaths = [
|
|
path2.join(homeDir, "AppData", "Roaming", "npm", "claude.cmd")
|
|
];
|
|
for (const p of cmdPaths) {
|
|
if (fs2.existsSync(p)) {
|
|
return p;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
const commonPaths = [
|
|
// Native binary paths (preferred)
|
|
path2.join(homeDir, ".claude", "local", "claude"),
|
|
path2.join(homeDir, ".local", "bin", "claude"),
|
|
"/usr/local/bin/claude",
|
|
"/opt/homebrew/bin/claude",
|
|
path2.join(homeDir, "bin", "claude"),
|
|
// npm global bin symlinks (created by npm install -g)
|
|
path2.join(homeDir, ".npm-global", "bin", "claude")
|
|
];
|
|
const npmPrefix = getNpmGlobalPrefix();
|
|
if (npmPrefix) {
|
|
commonPaths.push(path2.join(npmPrefix, "bin", "claude"));
|
|
}
|
|
for (const p of commonPaths) {
|
|
if (fs2.existsSync(p)) {
|
|
return p;
|
|
}
|
|
}
|
|
if (!isWindows2) {
|
|
const cliJsPaths = getNpmCliJsPaths();
|
|
for (const p of cliJsPaths) {
|
|
if (fs2.existsSync(p)) {
|
|
return p;
|
|
}
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
function resolveRealPath(p) {
|
|
var _a;
|
|
const realpathFn = (_a = fs2.realpathSync.native) != null ? _a : fs2.realpathSync;
|
|
try {
|
|
return realpathFn(p);
|
|
} catch (e) {
|
|
const absolute = path2.resolve(p);
|
|
let current = absolute;
|
|
const suffix = [];
|
|
while (true) {
|
|
try {
|
|
if (fs2.existsSync(current)) {
|
|
const resolvedExisting = realpathFn(current);
|
|
return suffix.length > 0 ? path2.join(resolvedExisting, ...suffix.reverse()) : resolvedExisting;
|
|
}
|
|
} catch (e2) {
|
|
}
|
|
const parent = path2.dirname(current);
|
|
if (parent === current) {
|
|
return absolute;
|
|
}
|
|
suffix.push(path2.basename(current));
|
|
current = parent;
|
|
}
|
|
}
|
|
}
|
|
function translateMsysPath(value) {
|
|
var _a;
|
|
if (process.platform !== "win32") {
|
|
return value;
|
|
}
|
|
const msysMatch = value.match(/^\/([a-zA-Z])(\/.*)?$/);
|
|
if (msysMatch) {
|
|
const driveLetter = msysMatch[1].toUpperCase();
|
|
const restOfPath = (_a = msysMatch[2]) != null ? _a : "";
|
|
return `${driveLetter}:${restOfPath.replace(/\//g, "\\")}`;
|
|
}
|
|
return value;
|
|
}
|
|
function normalizePathBeforeResolution(p) {
|
|
const expanded = expandHomePath(p);
|
|
return translateMsysPath(expanded);
|
|
}
|
|
function normalizeWindowsPathPrefix(value) {
|
|
if (process.platform !== "win32") {
|
|
return value;
|
|
}
|
|
const normalized = translateMsysPath(value);
|
|
if (normalized.startsWith("\\\\?\\UNC\\")) {
|
|
return `\\\\${normalized.slice("\\\\?\\UNC\\".length)}`;
|
|
}
|
|
if (normalized.startsWith("\\\\?\\")) {
|
|
return normalized.slice("\\\\?\\".length);
|
|
}
|
|
return normalized;
|
|
}
|
|
function normalizePathForFilesystem(value) {
|
|
if (!value || typeof value !== "string") {
|
|
return "";
|
|
}
|
|
const expanded = normalizePathBeforeResolution(value);
|
|
let normalized = expanded;
|
|
try {
|
|
normalized = process.platform === "win32" ? path2.win32.normalize(expanded) : path2.normalize(expanded);
|
|
} catch (e) {
|
|
normalized = expanded;
|
|
}
|
|
return normalizeWindowsPathPrefix(normalized);
|
|
}
|
|
function normalizePathForComparison(value) {
|
|
if (!value || typeof value !== "string") {
|
|
return "";
|
|
}
|
|
const expanded = normalizePathBeforeResolution(value);
|
|
let normalized = expanded;
|
|
try {
|
|
normalized = process.platform === "win32" ? path2.win32.normalize(expanded) : path2.normalize(expanded);
|
|
} catch (e) {
|
|
normalized = expanded;
|
|
}
|
|
normalized = normalizeWindowsPathPrefix(normalized);
|
|
normalized = normalized.replace(/\\/g, "/").replace(/\/+$/, "");
|
|
return process.platform === "win32" ? normalized.toLowerCase() : normalized;
|
|
}
|
|
function isPathWithinVault(candidatePath, vaultPath) {
|
|
const vaultReal = normalizePathForComparison(resolveRealPath(vaultPath));
|
|
const normalizedPath = normalizePathBeforeResolution(candidatePath);
|
|
const absCandidate = path2.isAbsolute(normalizedPath) ? normalizedPath : path2.resolve(vaultPath, normalizedPath);
|
|
const resolvedCandidate = normalizePathForComparison(resolveRealPath(absCandidate));
|
|
return resolvedCandidate === vaultReal || resolvedCandidate.startsWith(vaultReal + "/");
|
|
}
|
|
function getPathAccessType(candidatePath, allowedContextPaths, allowedExportPaths, vaultPath) {
|
|
if (!candidatePath) return "none";
|
|
const vaultReal = normalizePathForComparison(resolveRealPath(vaultPath));
|
|
const normalizedCandidate = normalizePathBeforeResolution(candidatePath);
|
|
const absCandidate = path2.isAbsolute(normalizedCandidate) ? normalizedCandidate : path2.resolve(vaultPath, normalizedCandidate);
|
|
const resolvedCandidate = normalizePathForComparison(resolveRealPath(absCandidate));
|
|
if (resolvedCandidate === vaultReal || resolvedCandidate.startsWith(vaultReal + "/")) {
|
|
return "vault";
|
|
}
|
|
const claudeDir = normalizePathForComparison(resolveRealPath(path2.join(os.homedir(), ".claude")));
|
|
if (resolvedCandidate === claudeDir || resolvedCandidate.startsWith(claudeDir + "/")) {
|
|
return "vault";
|
|
}
|
|
const roots = /* @__PURE__ */ new Map();
|
|
const addRoot = (rawPath, kind) => {
|
|
var _a;
|
|
const trimmed = rawPath.trim();
|
|
if (!trimmed) return;
|
|
const normalized = normalizePathBeforeResolution(trimmed);
|
|
const resolved = normalizePathForComparison(resolveRealPath(normalized));
|
|
const existing = (_a = roots.get(resolved)) != null ? _a : { context: false, export: false };
|
|
existing[kind] = true;
|
|
roots.set(resolved, existing);
|
|
};
|
|
for (const contextPath of allowedContextPaths != null ? allowedContextPaths : []) {
|
|
addRoot(contextPath, "context");
|
|
}
|
|
for (const exportPath of allowedExportPaths != null ? allowedExportPaths : []) {
|
|
addRoot(exportPath, "export");
|
|
}
|
|
let bestRoot = null;
|
|
let bestFlags = null;
|
|
for (const [root2, flags] of roots) {
|
|
if (resolvedCandidate === root2 || resolvedCandidate.startsWith(root2 + "/")) {
|
|
if (!bestRoot || root2.length > bestRoot.length) {
|
|
bestRoot = root2;
|
|
bestFlags = flags;
|
|
}
|
|
}
|
|
}
|
|
if (!bestRoot || !bestFlags) return "none";
|
|
if (bestFlags.context && bestFlags.export) return "readwrite";
|
|
if (bestFlags.context) return "context";
|
|
if (bestFlags.export) return "export";
|
|
return "none";
|
|
}
|
|
|
|
// src/utils/session.ts
|
|
var SESSION_ERROR_PATTERNS = [
|
|
"session expired",
|
|
"session not found",
|
|
"invalid session",
|
|
"session invalid",
|
|
"process exited with code"
|
|
];
|
|
var SESSION_ERROR_COMPOUND_PATTERNS = [
|
|
{ includes: ["session", "expired"] },
|
|
{ includes: ["resume", "failed"] },
|
|
{ includes: ["resume", "error"] }
|
|
];
|
|
function isSessionExpiredError(error2) {
|
|
const msg = error2 instanceof Error ? error2.message.toLowerCase() : "";
|
|
for (const pattern of SESSION_ERROR_PATTERNS) {
|
|
if (msg.includes(pattern)) {
|
|
return true;
|
|
}
|
|
}
|
|
for (const { includes } of SESSION_ERROR_COMPOUND_PATTERNS) {
|
|
if (includes.every((part) => msg.includes(part))) {
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
function formatToolCallForContext(toolCall, maxResultLength = 800) {
|
|
var _a;
|
|
const status = (_a = toolCall.status) != null ? _a : "completed";
|
|
const base = `[Tool ${toolCall.name} status=${status}]`;
|
|
const hasResult = typeof toolCall.result === "string" && toolCall.result.trim().length > 0;
|
|
if (!hasResult) {
|
|
return base;
|
|
}
|
|
const result = truncateToolResult(toolCall.result, maxResultLength);
|
|
return `${base} result: ${result}`;
|
|
}
|
|
function truncateToolResult(result, maxLength = 800) {
|
|
if (result.length > maxLength) {
|
|
return `${result.slice(0, maxLength)}... (truncated)`;
|
|
}
|
|
return result;
|
|
}
|
|
function formatContextLine(message) {
|
|
if (!message.currentNote) {
|
|
return null;
|
|
}
|
|
return formatCurrentNote(message.currentNote);
|
|
}
|
|
function buildContextFromHistory(messages) {
|
|
var _a, _b, _c;
|
|
const parts = [];
|
|
for (const message of messages) {
|
|
if (message.role !== "user" && message.role !== "assistant") {
|
|
continue;
|
|
}
|
|
if (message.role === "assistant") {
|
|
const hasContent = message.content && message.content.trim().length > 0;
|
|
const hasToolResult = (_a = message.toolCalls) == null ? void 0 : _a.some(
|
|
(tc) => tc.result && tc.result.trim().length > 0
|
|
);
|
|
if (!hasContent && !hasToolResult) {
|
|
continue;
|
|
}
|
|
}
|
|
const role = message.role === "user" ? "User" : "Assistant";
|
|
const lines = [];
|
|
const content = (_b = message.content) == null ? void 0 : _b.trim();
|
|
const contextLine = formatContextLine(message);
|
|
const userPayload = contextLine ? content ? `${contextLine}
|
|
|
|
${content}` : contextLine : content;
|
|
lines.push(userPayload ? `${role}: ${userPayload}` : `${role}:`);
|
|
if (message.role === "assistant" && ((_c = message.toolCalls) == null ? void 0 : _c.length)) {
|
|
const toolLines = message.toolCalls.map((tc) => formatToolCallForContext(tc)).filter(Boolean);
|
|
if (toolLines.length > 0) {
|
|
lines.push(...toolLines);
|
|
}
|
|
}
|
|
parts.push(lines.join("\n"));
|
|
}
|
|
return parts.join("\n\n");
|
|
}
|
|
function getLastUserMessage(messages) {
|
|
for (let i = messages.length - 1; i >= 0; i--) {
|
|
if (messages[i].role === "user") {
|
|
return messages[i];
|
|
}
|
|
}
|
|
return void 0;
|
|
}
|
|
|
|
// src/core/hooks/DiffTrackingHooks.ts
|
|
var fs3 = __toESM(require("fs"));
|
|
var path3 = __toESM(require("path"));
|
|
|
|
// src/core/tools/toolNames.ts
|
|
var TOOL_AGENT_OUTPUT = "AgentOutputTool";
|
|
var TOOL_ASK_USER_QUESTION = "AskUserQuestion";
|
|
var TOOL_BASH = "Bash";
|
|
var TOOL_BASH_OUTPUT = "BashOutput";
|
|
var TOOL_EDIT = "Edit";
|
|
var TOOL_GLOB = "Glob";
|
|
var TOOL_GREP = "Grep";
|
|
var TOOL_KILL_SHELL = "KillShell";
|
|
var TOOL_LS = "LS";
|
|
var TOOL_LIST_MCP_RESOURCES = "ListMcpResources";
|
|
var TOOL_MCP = "Mcp";
|
|
var TOOL_NOTEBOOK_EDIT = "NotebookEdit";
|
|
var TOOL_READ = "Read";
|
|
var TOOL_READ_MCP_RESOURCE = "ReadMcpResource";
|
|
var TOOL_SKILL = "Skill";
|
|
var TOOL_TASK = "Task";
|
|
var TOOL_TODO_WRITE = "TodoWrite";
|
|
var TOOL_WEB_FETCH = "WebFetch";
|
|
var TOOL_WEB_SEARCH = "WebSearch";
|
|
var TOOL_WRITE = "Write";
|
|
var TOOL_ENTER_PLAN_MODE = "EnterPlanMode";
|
|
var TOOL_EXIT_PLAN_MODE = "ExitPlanMode";
|
|
var PLAN_MODE_TOOLS = [TOOL_ENTER_PLAN_MODE, TOOL_EXIT_PLAN_MODE];
|
|
function isPlanModeTool(toolName) {
|
|
return PLAN_MODE_TOOLS.includes(toolName);
|
|
}
|
|
var EDIT_TOOLS = [TOOL_WRITE, TOOL_EDIT, TOOL_NOTEBOOK_EDIT];
|
|
var WRITE_EDIT_TOOLS = [TOOL_WRITE, TOOL_EDIT];
|
|
var FILE_TOOLS = [
|
|
TOOL_READ,
|
|
TOOL_WRITE,
|
|
TOOL_EDIT,
|
|
TOOL_GLOB,
|
|
TOOL_GREP,
|
|
TOOL_LS,
|
|
TOOL_NOTEBOOK_EDIT,
|
|
TOOL_BASH
|
|
];
|
|
var READ_ONLY_TOOLS = [
|
|
TOOL_READ,
|
|
TOOL_GREP,
|
|
TOOL_GLOB,
|
|
TOOL_LS,
|
|
TOOL_WEB_SEARCH,
|
|
TOOL_WEB_FETCH
|
|
];
|
|
function isEditTool(toolName) {
|
|
return EDIT_TOOLS.includes(toolName);
|
|
}
|
|
function isWriteEditTool(toolName) {
|
|
return WRITE_EDIT_TOOLS.includes(toolName);
|
|
}
|
|
function isFileTool(toolName) {
|
|
return FILE_TOOLS.includes(toolName);
|
|
}
|
|
function isReadOnlyTool(toolName) {
|
|
return READ_ONLY_TOOLS.includes(toolName);
|
|
}
|
|
|
|
// src/core/hooks/DiffTrackingHooks.ts
|
|
var MAX_DIFF_SIZE = 100 * 1024;
|
|
function createFileHashPreHook(vaultPath, originalContents) {
|
|
return {
|
|
matcher: "Write|Edit|NotebookEdit",
|
|
hooks: [
|
|
async (hookInput, toolUseId, _options) => {
|
|
const input = hookInput;
|
|
if (input.tool_name === TOOL_WRITE || input.tool_name === TOOL_EDIT) {
|
|
const rawPath = input.tool_input.file_path;
|
|
const filePath = typeof rawPath === "string" && rawPath ? rawPath : void 0;
|
|
if (filePath && vaultPath && toolUseId) {
|
|
const normalizedPath = normalizePathForFilesystem(filePath);
|
|
const fullPath = path3.isAbsolute(normalizedPath) ? normalizedPath : path3.join(vaultPath, normalizedPath);
|
|
try {
|
|
if (fs3.existsSync(fullPath)) {
|
|
const stats = fs3.statSync(fullPath);
|
|
if (stats.size <= MAX_DIFF_SIZE) {
|
|
const content = fs3.readFileSync(fullPath, "utf-8");
|
|
originalContents.set(toolUseId, { filePath, content });
|
|
} else {
|
|
originalContents.set(toolUseId, { filePath, content: null, skippedReason: "too_large" });
|
|
}
|
|
} else {
|
|
originalContents.set(toolUseId, { filePath, content: "" });
|
|
}
|
|
} catch (error2) {
|
|
console.warn("Failed to capture original file contents:", fullPath, error2);
|
|
originalContents.set(toolUseId, { filePath, content: null, skippedReason: "unavailable" });
|
|
}
|
|
}
|
|
}
|
|
return { continue: true };
|
|
}
|
|
]
|
|
};
|
|
}
|
|
function createFileHashPostHook(vaultPath, originalContents, pendingDiffData, postCallback) {
|
|
return {
|
|
matcher: "Write|Edit|NotebookEdit",
|
|
hooks: [
|
|
async (hookInput, toolUseId, _options) => {
|
|
var _a, _b, _c;
|
|
const input = hookInput;
|
|
const isError = (_b = (_a = input.tool_result) == null ? void 0 : _a.is_error) != null ? _b : false;
|
|
if ((input.tool_name === TOOL_WRITE || input.tool_name === TOOL_EDIT) && toolUseId) {
|
|
const originalEntry = originalContents.get(toolUseId);
|
|
const rawPath = input.tool_input.file_path;
|
|
const filePath = typeof rawPath === "string" && rawPath ? rawPath : originalEntry == null ? void 0 : originalEntry.filePath;
|
|
if (!isError && filePath && vaultPath) {
|
|
const normalizedPath = normalizePathForFilesystem(filePath);
|
|
const fullPath = path3.isAbsolute(normalizedPath) ? normalizedPath : path3.join(vaultPath, normalizedPath);
|
|
let diffData;
|
|
if ((originalEntry == null ? void 0 : originalEntry.content) === null) {
|
|
diffData = { filePath, skippedReason: (_c = originalEntry.skippedReason) != null ? _c : "unavailable" };
|
|
} else {
|
|
try {
|
|
if (fs3.existsSync(fullPath)) {
|
|
const stats = fs3.statSync(fullPath);
|
|
if (stats.size <= MAX_DIFF_SIZE) {
|
|
const newContent = fs3.readFileSync(fullPath, "utf-8");
|
|
if (originalEntry && originalEntry.content !== void 0) {
|
|
diffData = {
|
|
filePath,
|
|
originalContent: originalEntry.content,
|
|
newContent
|
|
};
|
|
} else {
|
|
diffData = { filePath, skippedReason: "unavailable" };
|
|
}
|
|
} else {
|
|
diffData = { filePath, skippedReason: "too_large" };
|
|
}
|
|
} else {
|
|
diffData = { filePath, skippedReason: "unavailable" };
|
|
}
|
|
} catch (error2) {
|
|
console.warn("Failed to capture updated file contents:", fullPath, error2);
|
|
diffData = { filePath, skippedReason: "unavailable" };
|
|
}
|
|
}
|
|
if (diffData) {
|
|
pendingDiffData.set(toolUseId, diffData);
|
|
}
|
|
}
|
|
originalContents.delete(toolUseId);
|
|
}
|
|
await (postCallback == null ? void 0 : postCallback.trackEditedFile(input.tool_name, input.tool_input, isError));
|
|
return { continue: true };
|
|
}
|
|
]
|
|
};
|
|
}
|
|
|
|
// src/core/security/BashPathValidator.ts
|
|
var path4 = __toESM(require("path"));
|
|
function tokenizeBashCommand(command) {
|
|
var _a;
|
|
const tokens = [];
|
|
const tokenRegex = /(['"`])(.*?)\1|[^\s]+/g;
|
|
let match;
|
|
while ((match = tokenRegex.exec(command)) !== null) {
|
|
const token = (_a = match[2]) != null ? _a : match[0];
|
|
const cleaned = token.trim();
|
|
if (!cleaned) continue;
|
|
tokens.push(cleaned);
|
|
}
|
|
return tokens;
|
|
}
|
|
function splitBashTokensIntoSegments(tokens) {
|
|
const separators = /* @__PURE__ */ new Set(["&&", "||", ";", "|"]);
|
|
const segments = [];
|
|
let current = [];
|
|
for (const token of tokens) {
|
|
if (separators.has(token)) {
|
|
if (current.length > 0) {
|
|
segments.push(current);
|
|
current = [];
|
|
}
|
|
continue;
|
|
}
|
|
current.push(token);
|
|
}
|
|
if (current.length > 0) {
|
|
segments.push(current);
|
|
}
|
|
return segments;
|
|
}
|
|
function getBashSegmentCommandName(segment) {
|
|
const wrappers = /* @__PURE__ */ new Set(["command", "env", "sudo"]);
|
|
let cmdIndex = 0;
|
|
while (cmdIndex < segment.length && wrappers.has(segment[cmdIndex])) {
|
|
cmdIndex += 1;
|
|
}
|
|
const rawCmd = segment[cmdIndex] || "";
|
|
const cmdName = path4.basename(rawCmd);
|
|
return { cmdName, cmdIndex };
|
|
}
|
|
function isBashOutputRedirectOperator(token) {
|
|
return token === ">" || token === ">>" || token === "1>" || token === "1>>" || token === "2>" || token === "2>>" || token === "&>" || token === "&>>" || token === ">|";
|
|
}
|
|
function isBashInputRedirectOperator(token) {
|
|
return token === "<" || token === "<<" || token === "0<" || token === "0<<";
|
|
}
|
|
function isBashOutputOptionExpectingValue(token) {
|
|
return token === "-o" || token === "--output" || token === "--out" || token === "--outfile" || token === "--output-file";
|
|
}
|
|
function cleanPathToken(raw) {
|
|
let token = raw.trim();
|
|
if (!token) return null;
|
|
if (token.startsWith('"') && token.endsWith('"') || token.startsWith("'") && token.endsWith("'") || token.startsWith("`") && token.endsWith("`")) {
|
|
token = token.slice(1, -1).trim();
|
|
}
|
|
while (token.startsWith("(") || token.startsWith("[") || token.startsWith("{")) {
|
|
token = token.slice(1).trim();
|
|
}
|
|
while (token.endsWith(")") || token.endsWith("]") || token.endsWith("}") || token.endsWith(";") || token.endsWith(",")) {
|
|
token = token.slice(0, -1).trim();
|
|
}
|
|
if (!token) return null;
|
|
if (token === "." || token === "/" || token === "\\") return null;
|
|
return token;
|
|
}
|
|
function isPathLikeToken(token) {
|
|
const cleaned = token.trim();
|
|
if (!cleaned) return false;
|
|
if (cleaned === "." || cleaned === "/" || cleaned === "\\" || cleaned === "--") return false;
|
|
const isWindows2 = process.platform === "win32";
|
|
return (
|
|
// Home directory paths (Unix and Windows style)
|
|
cleaned === "~" || cleaned.startsWith("~/") || isWindows2 && cleaned.startsWith("~\\") || // Relative paths
|
|
cleaned.startsWith("./") || cleaned.startsWith("../") || cleaned === ".." || isWindows2 && (cleaned.startsWith(".\\") || cleaned.startsWith("..\\")) || // Absolute paths (Unix)
|
|
cleaned.startsWith("/") || // Absolute paths (Windows drive letters)
|
|
isWindows2 && /^[A-Za-z]:[\\/]/.test(cleaned) || // Absolute paths (Windows UNC)
|
|
isWindows2 && (cleaned.startsWith("\\\\") || cleaned.startsWith("//")) || // Contains path separators
|
|
cleaned.includes("/") || isWindows2 && cleaned.includes("\\")
|
|
);
|
|
}
|
|
function checkBashPathAccess(candidate, access, context) {
|
|
const cleaned = cleanPathToken(candidate);
|
|
if (!cleaned) return null;
|
|
const accessType = context.getPathAccessType(cleaned);
|
|
if (accessType === "vault" || accessType === "readwrite") {
|
|
return null;
|
|
}
|
|
if (accessType === "context") {
|
|
return access === "read" ? null : { type: "context_path_write", path: cleaned };
|
|
}
|
|
if (accessType === "export") {
|
|
return access === "write" ? null : { type: "export_path_read", path: cleaned };
|
|
}
|
|
return { type: "outside_vault", path: cleaned };
|
|
}
|
|
function findBashPathViolationInSegment(segment, context) {
|
|
if (segment.length === 0) return null;
|
|
const { cmdName, cmdIndex } = getBashSegmentCommandName(segment);
|
|
const destinationCommands = /* @__PURE__ */ new Set(["cp", "mv", "rsync"]);
|
|
let destinationTokenIndex = null;
|
|
if (destinationCommands.has(cmdName)) {
|
|
const pathArgIndices = [];
|
|
let seenDoubleDash = false;
|
|
for (let i = cmdIndex + 1; i < segment.length; i += 1) {
|
|
const token = segment[i];
|
|
if (!seenDoubleDash && token === "--") {
|
|
seenDoubleDash = true;
|
|
continue;
|
|
}
|
|
if (!seenDoubleDash && token.startsWith("-")) {
|
|
continue;
|
|
}
|
|
if (isPathLikeToken(token)) {
|
|
pathArgIndices.push(i);
|
|
}
|
|
}
|
|
if (pathArgIndices.length > 0) {
|
|
destinationTokenIndex = pathArgIndices[pathArgIndices.length - 1];
|
|
}
|
|
}
|
|
let expectWriteNext = false;
|
|
for (let i = 0; i < segment.length; i += 1) {
|
|
const token = segment[i];
|
|
if (isBashOutputRedirectOperator(token)) {
|
|
expectWriteNext = true;
|
|
continue;
|
|
}
|
|
if (isBashInputRedirectOperator(token)) {
|
|
expectWriteNext = false;
|
|
continue;
|
|
}
|
|
if (isBashOutputOptionExpectingValue(token)) {
|
|
expectWriteNext = true;
|
|
continue;
|
|
}
|
|
const embeddedOutputRedirect = token.match(/^(?:&>>|&>|\d*>>|\d*>\||\d*>|>>|>\||>)(.+)$/);
|
|
if (embeddedOutputRedirect) {
|
|
const violation2 = checkBashPathAccess(embeddedOutputRedirect[1], "write", context);
|
|
if (violation2) return violation2;
|
|
continue;
|
|
}
|
|
const embeddedInputRedirect = token.match(/^(?:\d*<<|\d*<|<<|<)(.+)$/);
|
|
if (embeddedInputRedirect) {
|
|
const violation2 = checkBashPathAccess(embeddedInputRedirect[1], "read", context);
|
|
if (violation2) return violation2;
|
|
continue;
|
|
}
|
|
const embeddedLongOutput = token.match(/^--(?:output|out|outfile|output-file)=(.+)$/);
|
|
if (embeddedLongOutput) {
|
|
const violation2 = checkBashPathAccess(embeddedLongOutput[1], "write", context);
|
|
if (violation2) return violation2;
|
|
continue;
|
|
}
|
|
const embeddedShortOutput = token.match(/^-o(.+)$/);
|
|
if (embeddedShortOutput) {
|
|
const violation2 = checkBashPathAccess(embeddedShortOutput[1], "write", context);
|
|
if (violation2) return violation2;
|
|
continue;
|
|
}
|
|
const eqIndex = token.indexOf("=");
|
|
if (eqIndex > 0) {
|
|
const key = token.slice(0, eqIndex);
|
|
const value = token.slice(eqIndex + 1);
|
|
if (key.startsWith("-") && isPathLikeToken(value)) {
|
|
const violation2 = checkBashPathAccess(value, "read", context);
|
|
if (violation2) return violation2;
|
|
}
|
|
}
|
|
if (!isPathLikeToken(token)) {
|
|
expectWriteNext = false;
|
|
continue;
|
|
}
|
|
const access = i === destinationTokenIndex || expectWriteNext ? "write" : "read";
|
|
const violation = checkBashPathAccess(token, access, context);
|
|
if (violation) return violation;
|
|
expectWriteNext = false;
|
|
}
|
|
return null;
|
|
}
|
|
function findBashCommandPathViolation(command, context) {
|
|
if (!command) return null;
|
|
const tokens = tokenizeBashCommand(command);
|
|
const segments = splitBashTokensIntoSegments(tokens);
|
|
for (const segment of segments) {
|
|
const violation = findBashPathViolationInSegment(segment, context);
|
|
if (violation) {
|
|
return violation;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
// src/core/security/BlocklistChecker.ts
|
|
function isCommandBlocked(command, patterns, enableBlocklist) {
|
|
if (!enableBlocklist) {
|
|
return false;
|
|
}
|
|
return patterns.some((pattern) => {
|
|
try {
|
|
return new RegExp(pattern, "i").test(command);
|
|
} catch (e) {
|
|
return command.toLowerCase().includes(pattern.toLowerCase());
|
|
}
|
|
});
|
|
}
|
|
|
|
// src/core/tools/toolInput.ts
|
|
function getPathFromToolInput(toolName, toolInput) {
|
|
switch (toolName) {
|
|
case TOOL_READ:
|
|
case TOOL_WRITE:
|
|
case TOOL_EDIT:
|
|
case TOOL_NOTEBOOK_EDIT:
|
|
return toolInput.file_path || toolInput.notebook_path || null;
|
|
case TOOL_GLOB:
|
|
return toolInput.path || toolInput.pattern || null;
|
|
case TOOL_GREP:
|
|
return toolInput.path || null;
|
|
case TOOL_LS:
|
|
return toolInput.path || null;
|
|
default:
|
|
return null;
|
|
}
|
|
}
|
|
|
|
// src/core/types/chat.ts
|
|
var VIEW_TYPE_CLAUDIAN = "claudian-view";
|
|
|
|
// src/core/types/models.ts
|
|
var DEFAULT_CLAUDE_MODELS = [
|
|
{ value: "haiku", label: "Haiku", description: "Fast and efficient" },
|
|
{ value: "sonnet", label: "Sonnet", description: "Balanced performance" },
|
|
{ value: "opus", label: "Opus", description: "Most capable" }
|
|
];
|
|
var THINKING_BUDGETS = [
|
|
{ value: "off", label: "Off", tokens: 0 },
|
|
{ value: "low", label: "Low", tokens: 4e3 },
|
|
{ value: "medium", label: "Med", tokens: 8e3 },
|
|
{ value: "high", label: "High", tokens: 16e3 },
|
|
{ value: "xhigh", label: "Ultra", tokens: 32e3 }
|
|
];
|
|
var DEFAULT_THINKING_BUDGET = {
|
|
"haiku": "off",
|
|
"sonnet": "low",
|
|
"opus": "medium"
|
|
};
|
|
|
|
// src/core/types/settings.ts
|
|
var UNIX_BLOCKED_COMMANDS = [
|
|
"rm -rf",
|
|
"chmod 777",
|
|
"chmod -R 777"
|
|
];
|
|
var WINDOWS_BLOCKED_COMMANDS = [
|
|
// CMD commands
|
|
"del /s /q",
|
|
"rd /s /q",
|
|
"rmdir /s /q",
|
|
"format",
|
|
"diskpart",
|
|
// PowerShell Remove-Item variants (full and abbreviated flags)
|
|
"Remove-Item -Recurse -Force",
|
|
"Remove-Item -Force -Recurse",
|
|
"Remove-Item -r -fo",
|
|
"Remove-Item -fo -r",
|
|
"Remove-Item -Recurse",
|
|
"Remove-Item -r",
|
|
// PowerShell aliases for Remove-Item
|
|
"ri -Recurse",
|
|
"ri -r",
|
|
"ri -Force",
|
|
"ri -fo",
|
|
"rm -r -fo",
|
|
"rm -Recurse",
|
|
"rm -Force",
|
|
"del -Recurse",
|
|
"del -Force",
|
|
"erase -Recurse",
|
|
"erase -Force",
|
|
// PowerShell directory removal aliases
|
|
"rd -Recurse",
|
|
"rmdir -Recurse",
|
|
// Dangerous disk/volume commands
|
|
"Format-Volume",
|
|
"Clear-Disk",
|
|
"Initialize-Disk",
|
|
"Remove-Partition"
|
|
];
|
|
function getDefaultBlockedCommands() {
|
|
return {
|
|
unix: [...UNIX_BLOCKED_COMMANDS],
|
|
windows: [...WINDOWS_BLOCKED_COMMANDS]
|
|
};
|
|
}
|
|
function getCurrentPlatformKey() {
|
|
return process.platform === "win32" ? "windows" : "unix";
|
|
}
|
|
function getCurrentPlatformBlockedCommands(commands) {
|
|
return commands[getCurrentPlatformKey()];
|
|
}
|
|
function getBashToolBlockedCommands(commands) {
|
|
if (process.platform === "win32") {
|
|
return Array.from(/* @__PURE__ */ new Set([...commands.unix, ...commands.windows]));
|
|
}
|
|
return getCurrentPlatformBlockedCommands(commands);
|
|
}
|
|
var DEFAULT_SETTINGS = {
|
|
userName: "",
|
|
enableBlocklist: true,
|
|
blockedCommands: getDefaultBlockedCommands(),
|
|
model: "haiku",
|
|
enableAutoTitleGeneration: true,
|
|
titleGenerationModel: "",
|
|
// Empty = auto (ANTHROPIC_DEFAULT_HAIKU_MODEL or claude-haiku-4-5)
|
|
lastClaudeModel: "haiku",
|
|
lastCustomModel: "",
|
|
lastEnvHash: "",
|
|
thinkingBudget: "off",
|
|
permissionMode: "yolo",
|
|
lastNonPlanPermissionMode: "yolo",
|
|
permissions: [],
|
|
excludedTags: [],
|
|
mediaFolder: "",
|
|
environmentVariables: "",
|
|
envSnippets: [],
|
|
systemPrompt: "",
|
|
allowedExportPaths: ["~/Desktop", "~/Downloads"],
|
|
allowedContextPaths: [],
|
|
slashCommands: [],
|
|
keyboardNavigation: {
|
|
scrollUpKey: "w",
|
|
scrollDownKey: "s",
|
|
focusInputKey: "i"
|
|
},
|
|
claudeCliPath: ""
|
|
// Empty = auto-detect
|
|
};
|
|
|
|
// src/core/types/mcp.ts
|
|
function getMcpServerType(config2) {
|
|
if (config2.type === "sse") return "sse";
|
|
if (config2.type === "http") return "http";
|
|
if ("url" in config2) return "http";
|
|
return "stdio";
|
|
}
|
|
function isValidMcpServerConfig(obj) {
|
|
if (!obj || typeof obj !== "object") return false;
|
|
const config2 = obj;
|
|
if (config2.command && typeof config2.command === "string") return true;
|
|
if (config2.url && typeof config2.url === "string") return true;
|
|
return false;
|
|
}
|
|
var DEFAULT_MCP_SERVER = {
|
|
enabled: true,
|
|
contextSaving: true
|
|
};
|
|
|
|
// src/core/hooks/SecurityHooks.ts
|
|
function createBlocklistHook(getContext) {
|
|
return {
|
|
matcher: TOOL_BASH,
|
|
hooks: [
|
|
async (hookInput) => {
|
|
var _a;
|
|
const input = hookInput;
|
|
const command = ((_a = input.tool_input) == null ? void 0 : _a.command) || "";
|
|
const context = getContext();
|
|
const bashToolCommands = getBashToolBlockedCommands(context.blockedCommands);
|
|
if (isCommandBlocked(command, bashToolCommands, context.enableBlocklist)) {
|
|
return {
|
|
continue: false,
|
|
hookSpecificOutput: {
|
|
hookEventName: "PreToolUse",
|
|
permissionDecision: "deny",
|
|
permissionDecisionReason: `Command blocked by blocklist: ${command}`
|
|
}
|
|
};
|
|
}
|
|
return { continue: true };
|
|
}
|
|
]
|
|
};
|
|
}
|
|
function createVaultRestrictionHook(context) {
|
|
return {
|
|
hooks: [
|
|
async (hookInput) => {
|
|
var _a;
|
|
const input = hookInput;
|
|
const toolName = input.tool_name;
|
|
if (toolName === TOOL_BASH) {
|
|
const command = ((_a = input.tool_input) == null ? void 0 : _a.command) || "";
|
|
const pathCheckContext = {
|
|
getPathAccessType: (p) => context.getPathAccessType(p)
|
|
};
|
|
const violation = findBashCommandPathViolation(command, pathCheckContext);
|
|
if (violation) {
|
|
const reason = violation.type === "export_path_read" ? `Access denied: Command path "${violation.path}" is in an allowed export directory, but export paths are write-only.` : violation.type === "context_path_write" ? `Access denied: Command path "${violation.path}" is in an allowed context directory, but context paths are read-only.` : `Access denied: Command path "${violation.path}" is outside the vault. Agent is restricted to vault directory only.`;
|
|
return {
|
|
continue: false,
|
|
hookSpecificOutput: {
|
|
hookEventName: "PreToolUse",
|
|
permissionDecision: "deny",
|
|
permissionDecisionReason: reason
|
|
}
|
|
};
|
|
}
|
|
return { continue: true };
|
|
}
|
|
if (!isFileTool(toolName)) {
|
|
return { continue: true };
|
|
}
|
|
const filePath = getPathFromToolInput(toolName, input.tool_input);
|
|
if (filePath) {
|
|
const accessType = context.getPathAccessType(filePath);
|
|
if (accessType === "vault" || accessType === "readwrite") {
|
|
return { continue: true };
|
|
}
|
|
if (!isEditTool(toolName) && accessType === "context") {
|
|
return { continue: true };
|
|
}
|
|
if (isEditTool(toolName)) {
|
|
if (accessType === "export") {
|
|
return { continue: true };
|
|
}
|
|
if (accessType === "context") {
|
|
return {
|
|
continue: false,
|
|
hookSpecificOutput: {
|
|
hookEventName: "PreToolUse",
|
|
permissionDecision: "deny",
|
|
permissionDecisionReason: `Access denied: Path "${filePath}" is in an allowed context directory, but context paths are read-only.`
|
|
}
|
|
};
|
|
}
|
|
}
|
|
if (!isEditTool(toolName) && accessType === "export") {
|
|
return {
|
|
continue: false,
|
|
hookSpecificOutput: {
|
|
hookEventName: "PreToolUse",
|
|
permissionDecision: "deny",
|
|
permissionDecisionReason: `Access denied: Path "${filePath}" is in an allowed export directory, but export paths are write-only.`
|
|
}
|
|
};
|
|
}
|
|
return {
|
|
continue: false,
|
|
hookSpecificOutput: {
|
|
hookEventName: "PreToolUse",
|
|
permissionDecision: "deny",
|
|
permissionDecisionReason: `Access denied: Path "${filePath}" is outside the vault. Agent is restricted to vault directory only.`
|
|
}
|
|
};
|
|
}
|
|
return { continue: true };
|
|
}
|
|
]
|
|
};
|
|
}
|
|
|
|
// src/core/images/imageLoader.ts
|
|
var fs5 = __toESM(require("fs"));
|
|
var path6 = __toESM(require("path"));
|
|
|
|
// src/core/images/imageCache.ts
|
|
var import_crypto4 = require("crypto");
|
|
var fs4 = __toESM(require("fs"));
|
|
var path5 = __toESM(require("path"));
|
|
var IMAGE_CACHE_DIR = ".claudian-cache/images";
|
|
function ensureImageCacheDir(app) {
|
|
const vaultPath = getVaultPath(app);
|
|
if (!vaultPath) return null;
|
|
const cacheDir = path5.join(vaultPath, IMAGE_CACHE_DIR);
|
|
fs4.mkdirSync(cacheDir, { recursive: true });
|
|
return cacheDir;
|
|
}
|
|
function saveImageToCache(app, buffer, mediaType, preferredName) {
|
|
const cacheDir = ensureImageCacheDir(app);
|
|
if (!cacheDir) return null;
|
|
const hash = (0, import_crypto4.createHash)("sha256").update(buffer).digest("hex");
|
|
const ext = getExtension(mediaType, preferredName);
|
|
const filename = `${hash}${ext}`;
|
|
const relPath = path5.posix.join(IMAGE_CACHE_DIR, filename);
|
|
const absPath = path5.join(cacheDir, filename);
|
|
if (!fs4.existsSync(absPath)) {
|
|
fs4.writeFileSync(absPath, buffer);
|
|
}
|
|
return { relPath, absPath };
|
|
}
|
|
function readCachedImageBase64(app, relPath) {
|
|
const absPath = getCacheAbsolutePath(app, relPath);
|
|
if (!absPath) return null;
|
|
try {
|
|
const buffer = fs4.readFileSync(absPath);
|
|
return buffer.toString("base64");
|
|
} catch (e) {
|
|
return null;
|
|
}
|
|
}
|
|
function deleteCachedImages(app, relPaths) {
|
|
const seen = /* @__PURE__ */ new Set();
|
|
for (const relPath of relPaths) {
|
|
const normalized = normalizeCacheRelPath(relPath);
|
|
if (!normalized || seen.has(normalized)) continue;
|
|
seen.add(normalized);
|
|
const absPath = getCacheAbsolutePath(app, normalized);
|
|
if (absPath && fs4.existsSync(absPath)) {
|
|
try {
|
|
fs4.unlinkSync(absPath);
|
|
} catch (e) {
|
|
}
|
|
}
|
|
}
|
|
}
|
|
function getCacheAbsolutePath(app, relPath) {
|
|
const vaultPath = getVaultPath(app);
|
|
if (!vaultPath) return null;
|
|
const normalizedRel = normalizeCacheRelPath(relPath);
|
|
if (!normalizedRel) return null;
|
|
const absPath = path5.resolve(vaultPath, normalizedRel);
|
|
const cacheRoot = path5.resolve(vaultPath, IMAGE_CACHE_DIR);
|
|
if (!absPath.startsWith(cacheRoot)) {
|
|
return null;
|
|
}
|
|
return absPath;
|
|
}
|
|
function normalizeCacheRelPath(relPath) {
|
|
if (!relPath) return null;
|
|
const normalized = relPath.replace(/\\/g, "/");
|
|
if (path5.isAbsolute(normalized)) return null;
|
|
if (!normalized.startsWith(IMAGE_CACHE_DIR)) return null;
|
|
return normalized;
|
|
}
|
|
function getExtension(mediaType, preferredName) {
|
|
if (preferredName) {
|
|
const ext = path5.extname(preferredName);
|
|
if (ext) return ext;
|
|
}
|
|
const subtype = mediaType.split("/")[1] || "png";
|
|
return `.${subtype === "jpeg" ? "jpg" : subtype}`;
|
|
}
|
|
|
|
// src/core/images/imageLoader.ts
|
|
function resolveImageFilePath(filePath, vaultPath) {
|
|
const normalized = normalizePathForFilesystem(filePath);
|
|
if (path6.isAbsolute(normalized)) {
|
|
return normalized;
|
|
}
|
|
if (vaultPath) {
|
|
return path6.join(vaultPath, normalized);
|
|
}
|
|
return null;
|
|
}
|
|
function readFileBase64(absPath) {
|
|
try {
|
|
const buffer = fs5.readFileSync(absPath);
|
|
return buffer.toString("base64");
|
|
} catch (error2) {
|
|
console.warn("Failed to read image file:", absPath, error2);
|
|
return null;
|
|
}
|
|
}
|
|
function readImageAttachmentBase64(app, image, vaultPath) {
|
|
if (image.cachePath) {
|
|
const cached2 = readCachedImageBase64(app, image.cachePath);
|
|
if (cached2) return cached2;
|
|
}
|
|
if (image.filePath) {
|
|
const vault = vaultPath != null ? vaultPath : getVaultPath(app);
|
|
const absPath = resolveImageFilePath(image.filePath, vault);
|
|
if (absPath && fs5.existsSync(absPath)) {
|
|
return readFileBase64(absPath);
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
function ensureImageAttachmentBase64(app, image, vaultPath) {
|
|
if (image.data) return image.data;
|
|
const base642 = readImageAttachmentBase64(app, image, vaultPath);
|
|
if (base642) {
|
|
image.data = base642;
|
|
}
|
|
return base642;
|
|
}
|
|
function toImageDataUri(mediaType, base642) {
|
|
return `data:${mediaType};base64,${base642}`;
|
|
}
|
|
function getImageAttachmentDataUri(app, image, vaultPath) {
|
|
const base642 = ensureImageAttachmentBase64(app, image, vaultPath);
|
|
if (!base642) return null;
|
|
return toImageDataUri(image.mediaType, base642);
|
|
}
|
|
async function hydrateImagesData(app, images, vaultPath) {
|
|
if (!images || images.length === 0) return void 0;
|
|
const hydrated = [];
|
|
for (const image of images) {
|
|
if (image.data) {
|
|
hydrated.push(image);
|
|
continue;
|
|
}
|
|
const base642 = readImageAttachmentBase64(app, image, vaultPath);
|
|
if (base642) {
|
|
hydrated.push({ ...image, data: base642 });
|
|
}
|
|
}
|
|
return hydrated.length > 0 ? hydrated : void 0;
|
|
}
|
|
|
|
// src/utils/date.ts
|
|
function getTodayDate() {
|
|
const now = /* @__PURE__ */ new Date();
|
|
const readable = now.toLocaleDateString("en-US", {
|
|
weekday: "long",
|
|
year: "numeric",
|
|
month: "long",
|
|
day: "numeric"
|
|
});
|
|
const iso = now.toISOString().split("T")[0];
|
|
return `${readable} (${iso})`;
|
|
}
|
|
|
|
// src/core/prompts/mainAgent.ts
|
|
function getBaseSystemPrompt(vaultPath) {
|
|
const vaultInfo = vaultPath ? `
|
|
|
|
Vault absolute path: ${vaultPath}` : "";
|
|
return `## Time Context
|
|
|
|
- **Current Date**: ${getTodayDate()}
|
|
- **Knowledge Status**: You possess extensive internal knowledge up to your training cutoff. You do not know the exact date of your cutoff, but you must assume that your internal weights are static and "past," while the Current Date is "present."
|
|
|
|
## Identity & Role
|
|
|
|
You are **Claudian**, an expert AI assistant specialized in Obsidian vault management, knowledge organization, and code analysis. You operate directly inside the user's Obsidian vault.
|
|
|
|
**Core Principles:**
|
|
1. **Obsidian Native**: You understand Markdown, YAML frontmatter, Wiki-links, and the "second brain" philosophy.
|
|
2. **Safety First**: You never overwrite data without understanding context. You always use relative paths.
|
|
3. **Proactive Thinking**: You do not just execute; you *plan* and *verify*. You anticipate potential issues (like broken links or missing files).
|
|
4. **Clarity**: Your changes are precise, minimizing "noise" in the user's notes or code.
|
|
|
|
The current working directory is the user's vault root.${vaultInfo}
|
|
|
|
## Critical Path Rules (MUST FOLLOW)
|
|
|
|
**ALL file operations** (Read, Write, Edit, Glob, Grep, LS) require RELATIVE paths from vault root:
|
|
- \u2713 Correct: "notes/my-note.md", "my-note.md", "folder/subfolder/file.md", "."
|
|
- \u2717 WRONG: "/notes/my-note.md", "/my-note.md", "${vaultPath || "/absolute/path"}/file.md"
|
|
|
|
A leading slash ("/") or absolute path will FAIL. Always use paths relative to the vault root.
|
|
|
|
**Export Exception**: You may write files outside the vault ONLY to configured export paths (write-only). Export destinations may use ~ or absolute paths.
|
|
|
|
## User Message Format
|
|
|
|
User messages use XML tags for structured context:
|
|
|
|
\`\`\`xml
|
|
<current_note>
|
|
path/to/note.md
|
|
</current_note>
|
|
|
|
<query>
|
|
User's question or request here
|
|
</query>
|
|
\`\`\`
|
|
|
|
- \`<current_note>\`: The note the user is currently viewing/focused on. Read this to understand context. Only appears when the focused note changes.
|
|
- \`<query>\`: The user's actual question or request.
|
|
- \`@filename.md\`: Files mentioned with @ in the query. Read these files when referenced.
|
|
|
|
## Obsidian Context
|
|
|
|
- **Structure**: Files are Markdown (.md). Folders organize content.
|
|
- **Frontmatter**: YAML at the top of files (metadata). Respect existing fields.
|
|
- **Links**: Internal Wiki-links \`[[note-name]]\` or \`[[folder/note-name]]\`. External links \`[text](url)\`.
|
|
- **Tags**: #tag-name for categorization.
|
|
- **Dataview**: You may encounter Dataview queries (in \`\`\`dataview\`\`\` blocks). Do not break them unless asked.
|
|
- **Vault Config**: \`.obsidian/\` contains internal config. Touch only if you know what you are doing.
|
|
|
|
## Tool Usage Guidelines
|
|
|
|
Standard tools (Read, Write, Edit, Glob, Grep, LS, Bash, WebSearch, WebFetch, Skills, AskUserQuestion) work as expected.
|
|
|
|
**Thinking Process:**
|
|
Before taking action, explicitly THINK about:
|
|
1. **Context**: Do I have enough information? (Use Read/Search if not).
|
|
2. **Impact**: What will this change affect? (Links, other files).
|
|
3. **Plan**: What are the steps? (Use TodoWrite for >2 steps).
|
|
|
|
**Tool-Specific Rules:**
|
|
- **Read**:
|
|
- Always Read a file before Editing it.
|
|
- Read can view images (PNG, JPG, GIF, WebP) for visual analysis.
|
|
- **Edit**:
|
|
- Requires **EXACT** \`old_string\` match including whitespace/indentation.
|
|
- If Edit fails, Read the file again to check the current content.
|
|
- **Bash**:
|
|
- Runs with vault as working directory.
|
|
- **Prefer** Read/Write/Edit over shell commands for file operations (safer).
|
|
- Use BashOutput/KillShell to manage background processes.
|
|
- **LS**: Uses "." for vault root.
|
|
- **WebFetch**: For text/HTML/PDF only. Avoid binaries.
|
|
|
|
### WebSearch
|
|
|
|
Use WebSearch strictly according to the following logic:
|
|
|
|
1. **Static/Historical**: Rely on internal knowledge for established facts, history, or older code libraries.
|
|
2. **Dynamic/Recent**: **MUST** search for:
|
|
- "Latest" news, versions, docs.
|
|
- Events in the current/previous year.
|
|
- Volatile data (prices, weather).
|
|
3. **Date Awareness**: If user says "yesterday", calculate the date relative to **Current Date**.
|
|
4. **Ambiguity**: If unsure if knowledge is outdated, SEARCH.
|
|
|
|
### Task (Subagents)
|
|
|
|
Spawn subagents for complex multi-step tasks. Parameters: \`prompt\`, \`description\`, \`subagent_type\`, \`run_in_background\`.
|
|
|
|
**CRITICAL - Subagent Path Rules:**
|
|
- Subagents inherit the vault as their working directory.
|
|
- Reference files using **RELATIVE** paths.
|
|
- NEVER use absolute paths in subagent prompts.
|
|
|
|
**When to use:**
|
|
- Parallelizable work (main + subagent or multiple subagents)
|
|
- Preserve main context budget for sub-tasks
|
|
- Offload contained tasks while continuing other work
|
|
|
|
**Sync Mode (Default - \`run_in_background=false\`)**:
|
|
- Runs inline, result returned directly.
|
|
- **DEFAULT** to this unless explicitly asked or the task is very long-running.
|
|
|
|
**Async Mode (\`run_in_background=true\`)**:
|
|
- Use ONLY when explicitly requested or task is clearly long-running.
|
|
- Returns \`agent_id\` immediately.
|
|
- **Must retrieve result** with \`AgentOutputTool\` (poll with block=false, then block=true).
|
|
- Never end response without retrieving async results.
|
|
|
|
**Async workflow:**
|
|
1. Launch: \`Task prompt="..." run_in_background=true\` \u2192 get \`agent_id\`
|
|
2. Check immediately: \`AgentOutputTool agentId="..." block=false\`
|
|
3. Poll while working: \`AgentOutputTool agentId="..." block=false\`
|
|
4. When idle: \`AgentOutputTool agentId="..." block=true\` (wait for completion)
|
|
5. Report result to user
|
|
|
|
**Critical:** Never end response without retrieving async task results.
|
|
|
|
### TodoWrite
|
|
|
|
Track task progress. Parameter: \`todos\` (array of {content, status, activeForm}).
|
|
- Statuses: \`pending\`, \`in_progress\`, \`completed\`
|
|
- \`content\`: imperative ("Fix the bug")
|
|
- \`activeForm\`: present continuous ("Fixing the bug")
|
|
|
|
**Use for:** Tasks with 3+ steps, multi-file changes, complex operations.
|
|
Use proactively for any task meeting these criteria to keep progress visible.
|
|
|
|
**Workflow:**
|
|
1. **Plan**: Create the todo list at the start.
|
|
2. **Execute**: Mark \`in_progress\` -> do work -> Mark \`completed\`.
|
|
3. **Update**: If new tasks arise, add them.
|
|
|
|
**Example:** User asks "refactor auth and add tests"
|
|
\`\`\`
|
|
[
|
|
{content: "Analyze auth module", status: "in_progress", activeForm: "Analyzing auth module"},
|
|
{content: "Refactor auth code", status: "pending", activeForm: "Refactoring auth code"},
|
|
{content: "Add unit tests", status: "pending", activeForm: "Adding unit tests"}
|
|
]
|
|
\`\`\`
|
|
|
|
### Skills
|
|
|
|
Reusable capability modules. Use the \`Skill\` tool to invoke them when their description matches the user's need.`;
|
|
}
|
|
function getImageInstructions(mediaFolder) {
|
|
const folder = mediaFolder.trim();
|
|
const mediaPath = folder ? "./" + folder : ".";
|
|
const examplePath = folder ? folder + "/" : "";
|
|
return `
|
|
|
|
## Embedded Images in Notes
|
|
|
|
**Proactive image reading**: When reading a note with embedded images, read them alongside text for full context. Images often contain critical information (diagrams, screenshots, charts).
|
|
|
|
**Local images** (\`![[image.jpg]]\`):
|
|
- Located in media folder: \`${mediaPath}\`
|
|
- Read with: \`Read file_path="${examplePath}image.jpg"\`
|
|
- Formats: PNG, JPG/JPEG, GIF, WebP
|
|
|
|
**External images** (\`\`):
|
|
- WebFetch does NOT support images
|
|
- Download to media folder \u2192 Read \u2192 Replace URL with wiki-link:
|
|
|
|
\`\`\`bash
|
|
# Download to media folder with descriptive name
|
|
mkdir -p ${mediaPath}
|
|
img_name="downloaded_\\$(date +%s).png"
|
|
curl -sfo "${examplePath}$img_name" 'URL'
|
|
\`\`\`
|
|
|
|
Then read with \`Read file_path="${examplePath}$img_name"\`, and replace the markdown link \`\` with \`![[${examplePath}$img_name]]\` in the note.
|
|
|
|
**Benefits**: Image becomes a permanent vault asset, works offline, and uses Obsidian's native embed syntax.`;
|
|
}
|
|
function getExportInstructions(allowedExportPaths) {
|
|
if (!allowedExportPaths || allowedExportPaths.length === 0) {
|
|
return "";
|
|
}
|
|
const uniquePaths = Array.from(new Set(allowedExportPaths.map((p) => p.trim()).filter(Boolean)));
|
|
if (uniquePaths.length === 0) {
|
|
return "";
|
|
}
|
|
const formattedPaths = uniquePaths.map((p) => `- ${p}`).join("\n");
|
|
return `
|
|
|
|
## Allowed Export Paths
|
|
|
|
You are restricted to the vault by default. You may write exported files outside the vault ONLY to the following allowed export paths:
|
|
|
|
${formattedPaths}
|
|
|
|
Rules:
|
|
- Treat export paths as write-only (do not read/list files from them)
|
|
- If a path appears in both export and context lists, it is read-write for that root
|
|
- For vault files, always use relative paths
|
|
- For export destinations, you may use ~ or absolute paths
|
|
|
|
Examples:
|
|
|
|
\`\`\`bash
|
|
pandoc ./note.md -o ~/Desktop/note.docx
|
|
cp ./note.md ~/Desktop/note.md
|
|
cat ./note.md > ~/Desktop/note.md
|
|
\`\`\``;
|
|
}
|
|
function getContextPathInstructions(allowedContextPaths) {
|
|
if (!allowedContextPaths || allowedContextPaths.length === 0) {
|
|
return "";
|
|
}
|
|
const uniquePaths = Array.from(new Set(allowedContextPaths.map((p) => p.trim()).filter(Boolean)));
|
|
if (uniquePaths.length === 0) {
|
|
return "";
|
|
}
|
|
const formattedPaths = uniquePaths.map((p) => {
|
|
const normalized = p.replace(/\\/g, "/").replace(/\/+$/, "");
|
|
const segments = normalized.split("/");
|
|
const folderName = segments[segments.length - 1] || p;
|
|
return `- \`${folderName}\` \u2192 ${p}`;
|
|
}).join("\n");
|
|
return `
|
|
|
|
## Extra Context Paths
|
|
|
|
The user has selected these directories as relevant to their tasks. Proactively read from them when helpful:
|
|
|
|
${formattedPaths}
|
|
|
|
Rules:
|
|
- These paths are READ-ONLY (do not write, edit, or create files in them)
|
|
- If a path is in both context and export lists, it is read-write
|
|
- When user refers to a folder by name (e.g., "check Workspace"), use the corresponding path`;
|
|
}
|
|
function getEditorContextInstructions() {
|
|
return `
|
|
|
|
## Editor Selection
|
|
|
|
User messages may include an \`<editor_selection>\` tag showing text the user selected:
|
|
|
|
\`\`\`xml
|
|
<editor_selection path="path/to/file.md">
|
|
selected text here
|
|
possibly multiple lines
|
|
</editor_selection>
|
|
\`\`\`
|
|
|
|
**When present:** The user selected this text before sending their message. Use this context to understand what they're referring to.`;
|
|
}
|
|
function getPlanModeInstructions() {
|
|
return `
|
|
|
|
### Plan Mode (EnterPlanMode / ExitPlanMode)
|
|
|
|
You are in **plan mode** - a read-only exploration phase before implementation.
|
|
|
|
**Available tools:**
|
|
- Read, Grep, Glob, LS (file exploration)
|
|
- WebSearch, WebFetch (research)
|
|
- TodoWrite (organize findings)
|
|
|
|
**Disabled tools:** Write, Edit, Bash, NotebookEdit - you cannot modify files during planning.
|
|
|
|
**Workflow:**
|
|
1. Call \`EnterPlanMode\` to begin (already done if you see this)
|
|
2. Explore the codebase to understand the task
|
|
3. Create a detailed implementation plan
|
|
4. Call \`ExitPlanMode\` when ready for user approval
|
|
|
|
**Plan structure guidelines:**
|
|
- Start with a brief summary of the task
|
|
- List files to create/modify with specific changes
|
|
- Note dependencies and order of operations
|
|
- Identify potential risks or edge cases
|
|
- Keep it actionable - each step should be concrete
|
|
|
|
**After approval:** The plan is appended to your system prompt and you gain full tool access for implementation.`;
|
|
}
|
|
function buildSystemPrompt(settings = {}) {
|
|
var _a, _b;
|
|
let prompt = getBaseSystemPrompt(settings.vaultPath);
|
|
prompt += getImageInstructions(settings.mediaFolder || "");
|
|
prompt += getExportInstructions(settings.allowedExportPaths || []);
|
|
prompt += getContextPathInstructions(settings.allowedContextPaths || []);
|
|
if ((_a = settings.customPrompt) == null ? void 0 : _a.trim()) {
|
|
prompt += "\n\n## Custom Instructions\n\n" + settings.customPrompt.trim();
|
|
}
|
|
if (settings.hasEditorContext) {
|
|
prompt += getEditorContextInstructions();
|
|
}
|
|
if (settings.planMode) {
|
|
prompt += getPlanModeInstructions();
|
|
}
|
|
if ((_b = settings.appendedPlan) == null ? void 0 : _b.trim()) {
|
|
prompt += "\n\n## Approved Implementation Plan\n\n<plan>\n" + settings.appendedPlan.trim() + "\n</plan>";
|
|
prompt += "\n\n**IMPORTANT:** Follow this plan exactly. The user has approved this implementation. Execute the steps in order.";
|
|
}
|
|
return prompt;
|
|
}
|
|
|
|
// src/core/sdk/selectModelUsage.ts
|
|
function selectModelUsage(usageByModel, messageModel, intendedModel) {
|
|
var _a, _b, _c;
|
|
const entries = Object.entries(usageByModel);
|
|
if (entries.length === 0) return null;
|
|
if (messageModel && usageByModel[messageModel]) {
|
|
return { modelName: messageModel, usage: usageByModel[messageModel] };
|
|
}
|
|
if (intendedModel && usageByModel[intendedModel]) {
|
|
return { modelName: intendedModel, usage: usageByModel[intendedModel] };
|
|
}
|
|
let bestEntry = null;
|
|
let maxTokens = -1;
|
|
for (const [modelName, usage] of entries) {
|
|
const contextTokens = ((_a = usage.inputTokens) != null ? _a : 0) + ((_b = usage.cacheCreationInputTokens) != null ? _b : 0) + ((_c = usage.cacheReadInputTokens) != null ? _c : 0);
|
|
if (contextTokens > maxTokens) {
|
|
maxTokens = contextTokens;
|
|
bestEntry = { modelName, usage };
|
|
}
|
|
}
|
|
return bestEntry;
|
|
}
|
|
|
|
// src/core/sdk/transformSDKMessage.ts
|
|
function* transformSDKMessage(message, options) {
|
|
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
|
|
const parentToolUseId = (_a = message.parent_tool_use_id) != null ? _a : null;
|
|
switch (message.type) {
|
|
case "system":
|
|
if (message.subtype === "init" && message.session_id) {
|
|
yield { type: "session_init", sessionId: message.session_id };
|
|
}
|
|
break;
|
|
case "assistant":
|
|
if (((_b = message.message) == null ? void 0 : _b.content) && Array.isArray(message.message.content)) {
|
|
for (const block of message.message.content) {
|
|
if (block.type === "thinking" && block.thinking) {
|
|
yield { type: "thinking", content: block.thinking, parentToolUseId };
|
|
} else if (block.type === "text" && block.text) {
|
|
yield { type: "text", content: block.text, parentToolUseId };
|
|
} else if (block.type === "tool_use") {
|
|
yield {
|
|
type: "tool_use",
|
|
id: block.id || `tool-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`,
|
|
name: block.name || "unknown",
|
|
input: block.input || {},
|
|
parentToolUseId
|
|
};
|
|
}
|
|
}
|
|
}
|
|
break;
|
|
case "user":
|
|
if (message._blocked && message._blockReason) {
|
|
yield {
|
|
type: "blocked",
|
|
content: message._blockReason
|
|
};
|
|
break;
|
|
}
|
|
if (message.tool_use_result !== void 0 && message.parent_tool_use_id) {
|
|
yield {
|
|
type: "tool_result",
|
|
id: message.parent_tool_use_id,
|
|
content: typeof message.tool_use_result === "string" ? message.tool_use_result : JSON.stringify(message.tool_use_result, null, 2),
|
|
isError: false,
|
|
parentToolUseId
|
|
};
|
|
}
|
|
if (((_c = message.message) == null ? void 0 : _c.content) && Array.isArray(message.message.content)) {
|
|
for (const block of message.message.content) {
|
|
if (block.type === "tool_result") {
|
|
yield {
|
|
type: "tool_result",
|
|
id: block.tool_use_id || message.parent_tool_use_id || "",
|
|
content: typeof block.content === "string" ? block.content : JSON.stringify(block.content, null, 2),
|
|
isError: block.is_error || false,
|
|
parentToolUseId
|
|
};
|
|
}
|
|
}
|
|
}
|
|
break;
|
|
case "stream_event": {
|
|
const event = message.event;
|
|
if ((event == null ? void 0 : event.type) === "content_block_start" && ((_d = event.content_block) == null ? void 0 : _d.type) === "tool_use") {
|
|
yield {
|
|
type: "tool_use",
|
|
id: event.content_block.id || `tool-${Date.now()}`,
|
|
name: event.content_block.name || "unknown",
|
|
input: event.content_block.input || {},
|
|
parentToolUseId
|
|
};
|
|
} else if ((event == null ? void 0 : event.type) === "content_block_start" && ((_e = event.content_block) == null ? void 0 : _e.type) === "thinking") {
|
|
if (event.content_block.thinking) {
|
|
yield { type: "thinking", content: event.content_block.thinking, parentToolUseId };
|
|
}
|
|
} else if ((event == null ? void 0 : event.type) === "content_block_start" && ((_f = event.content_block) == null ? void 0 : _f.type) === "text") {
|
|
if (event.content_block.text) {
|
|
yield { type: "text", content: event.content_block.text, parentToolUseId };
|
|
}
|
|
} else if ((event == null ? void 0 : event.type) === "content_block_delta") {
|
|
if (((_g = event.delta) == null ? void 0 : _g.type) === "thinking_delta" && event.delta.thinking) {
|
|
yield { type: "thinking", content: event.delta.thinking, parentToolUseId };
|
|
} else if (((_h = event.delta) == null ? void 0 : _h.type) === "text_delta" && event.delta.text) {
|
|
yield { type: "text", content: event.delta.text, parentToolUseId };
|
|
}
|
|
}
|
|
break;
|
|
}
|
|
case "result": {
|
|
if (parentToolUseId) {
|
|
break;
|
|
}
|
|
const usageByModel = message.modelUsage;
|
|
if (usageByModel) {
|
|
const selected = selectModelUsage(usageByModel, message.model, options == null ? void 0 : options.intendedModel);
|
|
if (selected && selected.usage.contextWindow && selected.usage.contextWindow > 0) {
|
|
const { modelName, usage } = selected;
|
|
const inputTokens = (_i = usage.inputTokens) != null ? _i : 0;
|
|
const cacheCreationInputTokens = (_j = usage.cacheCreationInputTokens) != null ? _j : 0;
|
|
const cacheReadInputTokens = (_k = usage.cacheReadInputTokens) != null ? _k : 0;
|
|
const contextTokens = inputTokens + cacheCreationInputTokens + cacheReadInputTokens;
|
|
const percentage = Math.min(100, Math.max(0, Math.round(contextTokens / usage.contextWindow * 100)));
|
|
const usageInfo = {
|
|
model: modelName,
|
|
inputTokens,
|
|
cacheCreationInputTokens,
|
|
cacheReadInputTokens,
|
|
contextWindow: usage.contextWindow,
|
|
contextTokens,
|
|
percentage
|
|
};
|
|
yield { type: "usage", usage: usageInfo };
|
|
}
|
|
}
|
|
break;
|
|
}
|
|
case "error":
|
|
if (message.error) {
|
|
yield { type: "error", content: message.error };
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
|
|
// src/core/sdk/typeGuards.ts
|
|
function isSessionInitEvent(event) {
|
|
return event.type === "session_init";
|
|
}
|
|
function isStreamChunk(event) {
|
|
return event.type !== "session_init";
|
|
}
|
|
|
|
// src/core/security/ApprovalManager.ts
|
|
function getActionPattern(toolName, input) {
|
|
switch (toolName) {
|
|
case TOOL_BASH:
|
|
return typeof input.command === "string" ? input.command.trim() : "";
|
|
case TOOL_READ:
|
|
case TOOL_WRITE:
|
|
case TOOL_EDIT:
|
|
return input.file_path || "*";
|
|
case TOOL_NOTEBOOK_EDIT:
|
|
return input.notebook_path || input.file_path || "*";
|
|
case TOOL_GLOB:
|
|
return input.pattern || "*";
|
|
case TOOL_GREP:
|
|
return input.pattern || "*";
|
|
default:
|
|
return JSON.stringify(input);
|
|
}
|
|
}
|
|
function getActionDescription(toolName, input) {
|
|
switch (toolName) {
|
|
case TOOL_BASH:
|
|
return `Run command: ${input.command}`;
|
|
case TOOL_READ:
|
|
return `Read file: ${input.file_path}`;
|
|
case TOOL_WRITE:
|
|
return `Write to file: ${input.file_path}`;
|
|
case TOOL_EDIT:
|
|
return `Edit file: ${input.file_path}`;
|
|
case TOOL_GLOB:
|
|
return `Search files matching: ${input.pattern}`;
|
|
case TOOL_GREP:
|
|
return `Search content matching: ${input.pattern}`;
|
|
default:
|
|
return `${toolName}: ${JSON.stringify(input)}`;
|
|
}
|
|
}
|
|
function matchesPattern(toolName, actionPattern, approvedPattern) {
|
|
if (toolName === TOOL_BASH) {
|
|
return actionPattern === approvedPattern;
|
|
}
|
|
const normalizedAction = normalizeMatchPattern(actionPattern);
|
|
const normalizedApproved = normalizeMatchPattern(approvedPattern);
|
|
if (normalizedApproved === "*") return true;
|
|
if (normalizedAction === normalizedApproved) return true;
|
|
if (toolName === TOOL_READ || toolName === TOOL_WRITE || toolName === TOOL_EDIT || toolName === TOOL_NOTEBOOK_EDIT) {
|
|
return isPathPrefixMatch(normalizedAction, normalizedApproved);
|
|
}
|
|
if (normalizedAction.startsWith(normalizedApproved)) return true;
|
|
return false;
|
|
}
|
|
function normalizeMatchPattern(value) {
|
|
return value.replace(/\\/g, "/");
|
|
}
|
|
function isPathPrefixMatch(actionPath, approvedPath) {
|
|
if (!actionPath.startsWith(approvedPath)) {
|
|
return false;
|
|
}
|
|
if (approvedPath.endsWith("/")) {
|
|
return true;
|
|
}
|
|
if (actionPath.length === approvedPath.length) {
|
|
return true;
|
|
}
|
|
return actionPath.charAt(approvedPath.length) === "/";
|
|
}
|
|
var ApprovalManager = class {
|
|
constructor(getPermanentApprovals) {
|
|
this.sessionApprovedActions = [];
|
|
this.persistCallback = null;
|
|
this.getPermanentApprovals = getPermanentApprovals;
|
|
}
|
|
/**
|
|
* Set callback for persisting permanent approvals.
|
|
*/
|
|
setPersistCallback(callback) {
|
|
this.persistCallback = callback;
|
|
}
|
|
/**
|
|
* Check if an action is pre-approved (either session or permanent).
|
|
*/
|
|
isActionApproved(toolName, input) {
|
|
const pattern = getActionPattern(toolName, input);
|
|
const sessionApproved = this.sessionApprovedActions.some(
|
|
(action) => action.toolName === toolName && matchesPattern(toolName, pattern, action.pattern)
|
|
);
|
|
if (sessionApproved) return true;
|
|
const permanentApprovals = this.getPermanentApprovals();
|
|
const permanentApproved = permanentApprovals.some(
|
|
(action) => action.toolName === toolName && matchesPattern(toolName, pattern, action.pattern)
|
|
);
|
|
return permanentApproved;
|
|
}
|
|
/**
|
|
* Add an action to the approved list.
|
|
*/
|
|
async approveAction(toolName, input, scope) {
|
|
const pattern = getActionPattern(toolName, input);
|
|
const action = {
|
|
toolName,
|
|
pattern,
|
|
approvedAt: Date.now(),
|
|
scope
|
|
};
|
|
if (scope === "session") {
|
|
this.sessionApprovedActions.push(action);
|
|
} else {
|
|
if (this.persistCallback) {
|
|
await this.persistCallback(action);
|
|
}
|
|
}
|
|
}
|
|
/**
|
|
* Clear session-scoped approvals.
|
|
*/
|
|
clearSessionApprovals() {
|
|
this.sessionApprovedActions = [];
|
|
}
|
|
/**
|
|
* Get session-scoped approvals (for testing/debugging).
|
|
*/
|
|
getSessionApprovals() {
|
|
return [...this.sessionApprovedActions];
|
|
}
|
|
};
|
|
|
|
// src/core/agent/ClaudianService.ts
|
|
var SessionManager = class {
|
|
constructor() {
|
|
this.state = {
|
|
sessionId: null,
|
|
sessionModel: null,
|
|
pendingSessionModel: null,
|
|
wasInterrupted: false
|
|
};
|
|
}
|
|
getSessionId() {
|
|
return this.state.sessionId;
|
|
}
|
|
setSessionId(id, defaultModel) {
|
|
this.state.sessionId = id;
|
|
this.state.sessionModel = id ? defaultModel != null ? defaultModel : null : null;
|
|
}
|
|
wasInterrupted() {
|
|
return this.state.wasInterrupted;
|
|
}
|
|
markInterrupted() {
|
|
this.state.wasInterrupted = true;
|
|
}
|
|
clearInterrupted() {
|
|
this.state.wasInterrupted = false;
|
|
}
|
|
setPendingModel(model) {
|
|
this.state.pendingSessionModel = model;
|
|
}
|
|
clearPendingModel() {
|
|
this.state.pendingSessionModel = null;
|
|
}
|
|
captureSession(sessionId) {
|
|
this.state.sessionId = sessionId;
|
|
this.state.sessionModel = this.state.pendingSessionModel;
|
|
this.state.pendingSessionModel = null;
|
|
}
|
|
invalidateSession() {
|
|
this.state.sessionId = null;
|
|
this.state.sessionModel = null;
|
|
}
|
|
reset() {
|
|
this.state = {
|
|
sessionId: null,
|
|
sessionModel: null,
|
|
pendingSessionModel: null,
|
|
wasInterrupted: false
|
|
};
|
|
}
|
|
};
|
|
var DiffStore = class {
|
|
constructor() {
|
|
this.originalContents = /* @__PURE__ */ new Map();
|
|
this.pendingDiffData = /* @__PURE__ */ new Map();
|
|
}
|
|
getOriginalContents() {
|
|
return this.originalContents;
|
|
}
|
|
getPendingDiffData() {
|
|
return this.pendingDiffData;
|
|
}
|
|
getDiffData(toolUseId) {
|
|
const data = this.pendingDiffData.get(toolUseId);
|
|
if (data) {
|
|
this.pendingDiffData.delete(toolUseId);
|
|
}
|
|
return data;
|
|
}
|
|
clear() {
|
|
this.originalContents.clear();
|
|
this.pendingDiffData.clear();
|
|
}
|
|
};
|
|
var ClaudianService = class {
|
|
constructor(plugin, mcpManager) {
|
|
this.abortController = null;
|
|
this.resolvedClaudePath = null;
|
|
this.approvalCallback = null;
|
|
this.askUserQuestionCallback = null;
|
|
this.exitPlanModeCallback = null;
|
|
this.enterPlanModeCallback = null;
|
|
this.currentPlanFilePath = null;
|
|
this.approvedPlanContent = null;
|
|
this.vaultPath = null;
|
|
// Modular components
|
|
this.sessionManager = new SessionManager();
|
|
this.diffStore = new DiffStore();
|
|
// Store AskUserQuestion answers by tool_use_id
|
|
this.askUserQuestionAnswers = /* @__PURE__ */ new Map();
|
|
this.plugin = plugin;
|
|
this.mcpManager = mcpManager;
|
|
this.approvalManager = new ApprovalManager(
|
|
() => this.plugin.settings.permissions
|
|
);
|
|
this.approvalManager.setPersistCallback(async (action) => {
|
|
this.plugin.settings.permissions.push(action);
|
|
await this.plugin.saveSettings();
|
|
});
|
|
}
|
|
/** Load MCP server configurations from storage. */
|
|
async loadMcpServers() {
|
|
await this.mcpManager.loadServers();
|
|
}
|
|
/** Reload MCP server configurations (call after settings change). */
|
|
async reloadMcpServers() {
|
|
await this.mcpManager.loadServers();
|
|
}
|
|
findClaudeCLI() {
|
|
var _a;
|
|
const customPath = (_a = this.plugin.settings.claudeCliPath) == null ? void 0 : _a.trim();
|
|
if (customPath) {
|
|
const expandedPath = expandHomePath(customPath);
|
|
if (fs6.existsSync(expandedPath)) {
|
|
try {
|
|
const stat = fs6.statSync(expandedPath);
|
|
if (stat.isFile()) {
|
|
return expandedPath;
|
|
}
|
|
console.warn(`Claudian: Custom CLI path is a directory, not a file: ${expandedPath}`);
|
|
} catch (error2) {
|
|
const message = error2 instanceof Error ? error2.message : String(error2);
|
|
console.warn(`Claudian: Custom CLI path not accessible: ${expandedPath} (${message})`);
|
|
}
|
|
} else {
|
|
console.warn(`Claudian: Custom CLI path not found: ${expandedPath}`);
|
|
}
|
|
}
|
|
return findClaudeCLIPath();
|
|
}
|
|
/** Sends a query to Claude and streams the response. */
|
|
async *query(prompt, images, conversationHistory, queryOptions) {
|
|
const vaultPath = getVaultPath(this.plugin.app);
|
|
if (!vaultPath) {
|
|
yield { type: "error", content: "Could not determine vault path" };
|
|
return;
|
|
}
|
|
if (!this.resolvedClaudePath) {
|
|
this.resolvedClaudePath = this.findClaudeCLI();
|
|
}
|
|
if (!this.resolvedClaudePath) {
|
|
yield { type: "error", content: "Claude CLI not found. Please install Claude Code CLI." };
|
|
return;
|
|
}
|
|
this.abortController = new AbortController();
|
|
const hydratedImages = await hydrateImagesData(this.plugin.app, images, vaultPath);
|
|
let queryPrompt = prompt;
|
|
if (this.sessionManager.wasInterrupted() && conversationHistory && conversationHistory.length > 0) {
|
|
const historyContext = buildContextFromHistory(conversationHistory);
|
|
if (historyContext) {
|
|
queryPrompt = `${historyContext}
|
|
|
|
User: ${prompt}`;
|
|
}
|
|
this.sessionManager.invalidateSession();
|
|
this.sessionManager.clearInterrupted();
|
|
}
|
|
const noSessionButHasHistory = !this.sessionManager.getSessionId() && conversationHistory && conversationHistory.length > 0;
|
|
if (noSessionButHasHistory) {
|
|
if (conversationHistory && conversationHistory.length > 0) {
|
|
const historyContext = buildContextFromHistory(conversationHistory);
|
|
const lastUserMessage = getLastUserMessage(conversationHistory);
|
|
const actualPrompt = stripCurrentNotePrefix(prompt);
|
|
const shouldAppendPrompt = !lastUserMessage || lastUserMessage.content.trim() !== actualPrompt.trim();
|
|
queryPrompt = historyContext ? shouldAppendPrompt ? `${historyContext}
|
|
|
|
User: ${prompt}` : historyContext : prompt;
|
|
}
|
|
this.sessionManager.invalidateSession();
|
|
}
|
|
try {
|
|
yield* this.queryViaSDK(queryPrompt, vaultPath, hydratedImages, queryOptions);
|
|
} catch (error2) {
|
|
if (isSessionExpiredError(error2) && conversationHistory && conversationHistory.length > 0) {
|
|
this.sessionManager.invalidateSession();
|
|
const historyContext = buildContextFromHistory(conversationHistory);
|
|
const lastUserMessage = getLastUserMessage(conversationHistory);
|
|
const actualPrompt = stripCurrentNotePrefix(prompt);
|
|
const shouldAppendPrompt = !lastUserMessage || lastUserMessage.content.trim() !== actualPrompt.trim();
|
|
const fullPrompt = historyContext ? shouldAppendPrompt ? `${historyContext}
|
|
|
|
User: ${prompt}` : historyContext : prompt;
|
|
const retryImages = await hydrateImagesData(this.plugin.app, lastUserMessage == null ? void 0 : lastUserMessage.images, vaultPath);
|
|
try {
|
|
yield* this.queryViaSDK(fullPrompt, vaultPath, retryImages, queryOptions);
|
|
} catch (retryError) {
|
|
const msg2 = retryError instanceof Error ? retryError.message : "Unknown error";
|
|
yield { type: "error", content: msg2 };
|
|
}
|
|
return;
|
|
}
|
|
const msg = error2 instanceof Error ? error2.message : "Unknown error";
|
|
yield { type: "error", content: msg };
|
|
} finally {
|
|
this.abortController = null;
|
|
}
|
|
}
|
|
/**
|
|
* Build a prompt with images as content blocks
|
|
*/
|
|
buildPromptWithImages(prompt, images) {
|
|
const validImages = (images || []).filter((img) => !!img.data);
|
|
if (validImages.length === 0) {
|
|
return prompt;
|
|
}
|
|
const content = [];
|
|
for (const image of validImages) {
|
|
content.push({
|
|
type: "image",
|
|
source: {
|
|
type: "base64",
|
|
media_type: image.mediaType,
|
|
data: image.data
|
|
}
|
|
});
|
|
}
|
|
if (prompt.trim()) {
|
|
content.push({
|
|
type: "text",
|
|
text: prompt
|
|
});
|
|
}
|
|
async function* messageGenerator() {
|
|
yield {
|
|
type: "user",
|
|
message: {
|
|
role: "user",
|
|
content
|
|
}
|
|
};
|
|
}
|
|
return messageGenerator();
|
|
}
|
|
async *queryViaSDK(prompt, cwd2, images, queryOptions) {
|
|
var _a, _b, _c;
|
|
const selectedModel = (queryOptions == null ? void 0 : queryOptions.model) || this.plugin.settings.model;
|
|
const permissionMode = this.plugin.settings.permissionMode;
|
|
this.sessionManager.setPendingModel(selectedModel);
|
|
this.vaultPath = cwd2;
|
|
const customEnv = parseEnvironmentVariables(this.plugin.getActiveEnvironmentVariables());
|
|
const enhancedPath = getEnhancedPath(customEnv.PATH);
|
|
const queryPrompt = this.buildPromptWithImages(prompt, images);
|
|
const hasEditorContext = prompt.includes("<editor_selection");
|
|
const systemPrompt = buildSystemPrompt({
|
|
mediaFolder: this.plugin.settings.mediaFolder,
|
|
customPrompt: this.plugin.settings.systemPrompt,
|
|
allowedExportPaths: this.plugin.settings.allowedExportPaths,
|
|
allowedContextPaths: this.plugin.settings.allowedContextPaths,
|
|
vaultPath: cwd2,
|
|
hasEditorContext,
|
|
planMode: queryOptions == null ? void 0 : queryOptions.planMode,
|
|
appendedPlan: (_a = this.approvedPlanContent) != null ? _a : void 0
|
|
});
|
|
const options = {
|
|
cwd: cwd2,
|
|
systemPrompt,
|
|
model: selectedModel,
|
|
abortController: (_b = this.abortController) != null ? _b : void 0,
|
|
pathToClaudeCodeExecutable: this.resolvedClaudePath,
|
|
settingSources: ["user", "project"],
|
|
env: {
|
|
...process.env,
|
|
...customEnv,
|
|
PATH: enhancedPath
|
|
}
|
|
};
|
|
const mcpMentions = (queryOptions == null ? void 0 : queryOptions.mcpMentions) || /* @__PURE__ */ new Set();
|
|
const uiEnabledServers = (queryOptions == null ? void 0 : queryOptions.enabledMcpServers) || /* @__PURE__ */ new Set();
|
|
const combinedMentions = /* @__PURE__ */ new Set([...mcpMentions, ...uiEnabledServers]);
|
|
const mcpServers = this.mcpManager.getActiveServers(combinedMentions);
|
|
if (Object.keys(mcpServers).length > 0) {
|
|
options.mcpServers = mcpServers;
|
|
}
|
|
const disallowedMcpTools = this.mcpManager.getDisallowedMcpTools(combinedMentions);
|
|
if (disallowedMcpTools.length > 0) {
|
|
options.disallowedTools = disallowedMcpTools;
|
|
}
|
|
const blocklistHook = createBlocklistHook(() => ({
|
|
blockedCommands: this.plugin.settings.blockedCommands,
|
|
enableBlocklist: this.plugin.settings.enableBlocklist
|
|
}));
|
|
const vaultRestrictionHook = createVaultRestrictionHook({
|
|
getPathAccessType: (p) => this.getPathAccessType(p)
|
|
});
|
|
const postCallback = {
|
|
trackEditedFile: async (name, input, isError) => {
|
|
if (name === "Write" && !isError) {
|
|
const filePath = input == null ? void 0 : input.file_path;
|
|
if (typeof filePath === "string" && this.isPlanFilePath(filePath)) {
|
|
this.currentPlanFilePath = this.resolvePlanPath(filePath);
|
|
}
|
|
}
|
|
}
|
|
};
|
|
const fileHashPreHook = createFileHashPreHook(
|
|
this.vaultPath,
|
|
this.diffStore.getOriginalContents()
|
|
);
|
|
const fileHashPostHook = createFileHashPostHook(
|
|
this.vaultPath,
|
|
this.diffStore.getOriginalContents(),
|
|
this.diffStore.getPendingDiffData(),
|
|
postCallback
|
|
);
|
|
options.canUseTool = this.createUnifiedToolCallback(permissionMode);
|
|
options.hooks = {
|
|
PreToolUse: [blocklistHook, vaultRestrictionHook, fileHashPreHook],
|
|
PostToolUse: [fileHashPostHook]
|
|
};
|
|
if (queryOptions == null ? void 0 : queryOptions.planMode) {
|
|
options.permissionMode = "plan";
|
|
} else if (permissionMode === "yolo") {
|
|
options.permissionMode = "bypassPermissions";
|
|
options.allowDangerouslySkipPermissions = true;
|
|
} else {
|
|
options.permissionMode = "default";
|
|
}
|
|
const budgetSetting = this.plugin.settings.thinkingBudget;
|
|
const budgetConfig = THINKING_BUDGETS.find((b) => b.value === budgetSetting);
|
|
if (budgetConfig && budgetConfig.tokens > 0) {
|
|
options.maxThinkingTokens = budgetConfig.tokens;
|
|
}
|
|
if ((queryOptions == null ? void 0 : queryOptions.allowedTools) && queryOptions.allowedTools.length > 0) {
|
|
options.allowedTools = [...queryOptions.allowedTools, "Skill"];
|
|
}
|
|
const sessionId = this.sessionManager.getSessionId();
|
|
if (sessionId) {
|
|
options.resume = sessionId;
|
|
}
|
|
try {
|
|
const response = query({ prompt: queryPrompt, options });
|
|
let streamSessionId = this.sessionManager.getSessionId();
|
|
for await (const message of response) {
|
|
if ((_c = this.abortController) == null ? void 0 : _c.signal.aborted) {
|
|
await response.interrupt();
|
|
break;
|
|
}
|
|
for (const event of transformSDKMessage(message, { intendedModel: selectedModel })) {
|
|
if (isSessionInitEvent(event)) {
|
|
this.sessionManager.captureSession(event.sessionId);
|
|
streamSessionId = event.sessionId;
|
|
} else if (isStreamChunk(event)) {
|
|
if (event.type === "usage") {
|
|
yield { ...event, sessionId: streamSessionId };
|
|
} else {
|
|
yield event;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
} catch (error2) {
|
|
const msg = error2 instanceof Error ? error2.message : "Unknown error";
|
|
yield { type: "error", content: msg };
|
|
} finally {
|
|
this.sessionManager.clearPendingModel();
|
|
}
|
|
yield { type: "done" };
|
|
}
|
|
/** Cancel the current query. */
|
|
cancel() {
|
|
if (this.abortController) {
|
|
this.abortController.abort();
|
|
this.sessionManager.markInterrupted();
|
|
}
|
|
}
|
|
/** Reset the conversation session. */
|
|
resetSession() {
|
|
this.sessionManager.reset();
|
|
this.approvalManager.clearSessionApprovals();
|
|
this.diffStore.clear();
|
|
this.approvedPlanContent = null;
|
|
this.currentPlanFilePath = null;
|
|
}
|
|
/** Get the current session ID. */
|
|
getSessionId() {
|
|
return this.sessionManager.getSessionId();
|
|
}
|
|
/** Set the session ID (for restoring from saved conversation). */
|
|
setSessionId(id) {
|
|
this.sessionManager.setSessionId(id, this.plugin.settings.model);
|
|
}
|
|
/** Cleanup resources. */
|
|
cleanup() {
|
|
this.cancel();
|
|
this.resetSession();
|
|
this.resolvedClaudePath = null;
|
|
}
|
|
/** Sets the approval callback for UI prompts. */
|
|
setApprovalCallback(callback) {
|
|
this.approvalCallback = callback;
|
|
}
|
|
/** Sets the AskUserQuestion callback for interactive questions. */
|
|
setAskUserQuestionCallback(callback) {
|
|
this.askUserQuestionCallback = callback;
|
|
}
|
|
/** Sets the ExitPlanMode callback for plan approval. */
|
|
setExitPlanModeCallback(callback) {
|
|
this.exitPlanModeCallback = callback;
|
|
}
|
|
/** Sets the EnterPlanMode callback for plan mode initiation. */
|
|
setEnterPlanModeCallback(callback) {
|
|
this.enterPlanModeCallback = callback;
|
|
}
|
|
/** Sets the current plan file path (for ExitPlanMode handling). */
|
|
setCurrentPlanFilePath(path12) {
|
|
this.currentPlanFilePath = path12;
|
|
}
|
|
/** Gets the current plan file path. */
|
|
getCurrentPlanFilePath() {
|
|
return this.currentPlanFilePath;
|
|
}
|
|
/** Sets the approved plan content to be included in future system prompts. */
|
|
setApprovedPlanContent(content) {
|
|
this.approvedPlanContent = content;
|
|
}
|
|
/** Gets the approved plan content. */
|
|
getApprovedPlanContent() {
|
|
return this.approvedPlanContent;
|
|
}
|
|
/** Clears the approved plan content. */
|
|
clearApprovedPlanContent() {
|
|
this.approvedPlanContent = null;
|
|
}
|
|
/** Get pending diff data for a tool_use_id (and remove it from pending). */
|
|
getDiffData(toolUseId) {
|
|
return this.diffStore.getDiffData(toolUseId);
|
|
}
|
|
/** Clear all diff-related state. */
|
|
clearDiffState() {
|
|
this.diffStore.clear();
|
|
}
|
|
getPathAccessType(filePath) {
|
|
if (!this.vaultPath) return "vault";
|
|
return getPathAccessType(
|
|
filePath,
|
|
this.plugin.settings.allowedContextPaths,
|
|
this.plugin.settings.allowedExportPaths,
|
|
this.vaultPath
|
|
);
|
|
}
|
|
resolvePlanPath(filePath) {
|
|
const normalized = normalizePathForFilesystem(filePath);
|
|
return path7.resolve(normalized);
|
|
}
|
|
isPlanFilePath(filePath) {
|
|
const plansDir = path7.resolve(os2.homedir(), ".claude", "plans");
|
|
const resolved = this.resolvePlanPath(filePath);
|
|
const normalizedPlans = process.platform === "win32" ? plansDir.toLowerCase() : plansDir;
|
|
const normalizedResolved = process.platform === "win32" ? resolved.toLowerCase() : resolved;
|
|
return normalizedResolved === normalizedPlans || normalizedResolved.startsWith(normalizedPlans + path7.sep);
|
|
}
|
|
/**
|
|
* Create unified callback that handles both YOLO and normal modes.
|
|
* AskUserQuestion, EnterPlanMode, and ExitPlanMode have special handling regardless of mode.
|
|
*/
|
|
createUnifiedToolCallback(mode) {
|
|
return async (toolName, input, context) => {
|
|
if (toolName === TOOL_ASK_USER_QUESTION) {
|
|
return this.handleAskUserQuestionTool(input, context == null ? void 0 : context.toolUseID);
|
|
}
|
|
if (toolName === TOOL_ENTER_PLAN_MODE) {
|
|
return this.handleEnterPlanModeTool();
|
|
}
|
|
if (toolName === TOOL_EXIT_PLAN_MODE) {
|
|
return this.handleExitPlanModeTool(input, context == null ? void 0 : context.toolUseID);
|
|
}
|
|
if (mode === "yolo") {
|
|
return { behavior: "allow", updatedInput: input };
|
|
}
|
|
return this.handleNormalModeApproval(toolName, input);
|
|
};
|
|
}
|
|
/**
|
|
* Handle AskUserQuestion tool - shows panel and returns answers.
|
|
*/
|
|
async handleAskUserQuestionTool(input, toolUseId) {
|
|
if (!this.askUserQuestionCallback) {
|
|
return {
|
|
behavior: "deny",
|
|
message: "No question handler available."
|
|
};
|
|
}
|
|
try {
|
|
const answers = await this.askUserQuestionCallback(input);
|
|
if (answers === null) {
|
|
return {
|
|
behavior: "deny",
|
|
message: "User interrupted.",
|
|
interrupt: true
|
|
};
|
|
}
|
|
if (toolUseId) {
|
|
this.askUserQuestionAnswers.set(toolUseId, answers);
|
|
}
|
|
return {
|
|
behavior: "allow",
|
|
updatedInput: { ...input, answers }
|
|
};
|
|
} catch (e) {
|
|
return {
|
|
behavior: "deny",
|
|
message: "Failed to get user response.",
|
|
interrupt: true
|
|
};
|
|
}
|
|
}
|
|
/** Get stored AskUserQuestion answers for a tool_use_id. */
|
|
getAskUserQuestionAnswers(toolUseId) {
|
|
const answers = this.askUserQuestionAnswers.get(toolUseId);
|
|
if (answers) {
|
|
this.askUserQuestionAnswers.delete(toolUseId);
|
|
}
|
|
return answers;
|
|
}
|
|
/**
|
|
* Handle EnterPlanMode tool - notifies UI to activate plan mode after the reply ends.
|
|
*/
|
|
async handleEnterPlanModeTool() {
|
|
if (!this.enterPlanModeCallback) {
|
|
return { behavior: "allow", updatedInput: {} };
|
|
}
|
|
try {
|
|
await this.enterPlanModeCallback();
|
|
} catch (e) {
|
|
}
|
|
return { behavior: "allow", updatedInput: {} };
|
|
}
|
|
/**
|
|
* Handle ExitPlanMode tool - shows plan approval UI and handles decision.
|
|
* Reads plan content from the persisted file in ~/.claude/plans/.
|
|
*/
|
|
async handleExitPlanModeTool(input, toolUseId) {
|
|
if (!this.exitPlanModeCallback) {
|
|
return {
|
|
behavior: "deny",
|
|
message: "No plan mode handler available."
|
|
};
|
|
}
|
|
let planContent = null;
|
|
if (this.currentPlanFilePath && this.isPlanFilePath(this.currentPlanFilePath)) {
|
|
const planPath = this.resolvePlanPath(this.currentPlanFilePath);
|
|
try {
|
|
const fs10 = await import("fs");
|
|
if (fs10.existsSync(planPath)) {
|
|
planContent = fs10.readFileSync(planPath, "utf-8");
|
|
}
|
|
} catch (e) {
|
|
}
|
|
}
|
|
if (!planContent) {
|
|
planContent = typeof input.plan === "string" ? input.plan : null;
|
|
}
|
|
if (!planContent) {
|
|
return {
|
|
behavior: "deny",
|
|
message: "No plan content available."
|
|
};
|
|
}
|
|
try {
|
|
const decision = await this.exitPlanModeCallback(planContent);
|
|
switch (decision.decision) {
|
|
case "approve":
|
|
return {
|
|
behavior: "deny",
|
|
message: "PLAN APPROVED. Plan mode has ended. The user has approved your plan and it has been saved. Implementation will begin with a new query that has full tool access.",
|
|
interrupt: true
|
|
};
|
|
case "approve_new_session":
|
|
return {
|
|
behavior: "deny",
|
|
message: "PLAN APPROVED WITH NEW SESSION. Plan mode has ended. Implementation will begin with a fresh session that has full tool access.",
|
|
interrupt: true
|
|
};
|
|
case "revise": {
|
|
const feedback = decision.feedback.trim();
|
|
const feedbackSection = feedback ? `
|
|
|
|
User feedback:
|
|
${feedback}` : "";
|
|
return {
|
|
behavior: "deny",
|
|
message: `Please revise the plan based on user feedback and call ExitPlanMode again when ready.${feedbackSection}`,
|
|
interrupt: false
|
|
};
|
|
}
|
|
case "cancel":
|
|
return {
|
|
behavior: "deny",
|
|
message: "Plan cancelled by user.",
|
|
interrupt: true
|
|
};
|
|
default:
|
|
return {
|
|
behavior: "deny",
|
|
message: "Unknown decision.",
|
|
interrupt: true
|
|
};
|
|
}
|
|
} catch (e) {
|
|
return {
|
|
behavior: "deny",
|
|
message: "Failed to get plan approval.",
|
|
interrupt: true
|
|
};
|
|
}
|
|
}
|
|
/**
|
|
* Handle normal mode approval - check approved actions, then prompt user.
|
|
*/
|
|
async handleNormalModeApproval(toolName, input) {
|
|
if (this.approvalManager.isActionApproved(toolName, input)) {
|
|
return { behavior: "allow", updatedInput: input };
|
|
}
|
|
if (!this.approvalCallback) {
|
|
return {
|
|
behavior: "deny",
|
|
message: "No approval handler available. Please enable YOLO mode or configure permissions."
|
|
};
|
|
}
|
|
const description = getActionDescription(toolName, input);
|
|
try {
|
|
const decision = await this.approvalCallback(toolName, input, description);
|
|
if (decision === "cancel") {
|
|
return {
|
|
behavior: "deny",
|
|
message: "User interrupted.",
|
|
interrupt: true
|
|
};
|
|
}
|
|
if (decision === "deny") {
|
|
return {
|
|
behavior: "deny",
|
|
message: "User denied this action.",
|
|
interrupt: false
|
|
};
|
|
}
|
|
if (decision === "allow-always") {
|
|
await this.approvalManager.approveAction(toolName, input, "always");
|
|
} else if (decision === "allow") {
|
|
await this.approvalManager.approveAction(toolName, input, "session");
|
|
}
|
|
return { behavior: "allow", updatedInput: input };
|
|
} catch (e) {
|
|
return {
|
|
behavior: "deny",
|
|
message: "Approval request failed.",
|
|
interrupt: true
|
|
};
|
|
}
|
|
}
|
|
};
|
|
|
|
// src/core/storage/McpStorage.ts
|
|
var MCP_CONFIG_PATH = ".claude/mcp.json";
|
|
var McpStorage = class _McpStorage {
|
|
constructor(adapter) {
|
|
this.adapter = adapter;
|
|
}
|
|
/** Load MCP servers from .claude/mcp.json. */
|
|
async load() {
|
|
var _a, _b, _c, _d, _e;
|
|
try {
|
|
if (!await this.adapter.exists(MCP_CONFIG_PATH)) {
|
|
return [];
|
|
}
|
|
const content = await this.adapter.read(MCP_CONFIG_PATH);
|
|
const file = JSON.parse(content);
|
|
if (!file.mcpServers || typeof file.mcpServers !== "object") {
|
|
return [];
|
|
}
|
|
const claudianMeta = (_b = (_a = file._claudian) == null ? void 0 : _a.servers) != null ? _b : {};
|
|
const servers = [];
|
|
for (const [name, config2] of Object.entries(file.mcpServers)) {
|
|
if (!isValidMcpServerConfig(config2)) {
|
|
console.warn(`[Claudian] Invalid MCP server config for "${name}", skipping`);
|
|
continue;
|
|
}
|
|
const meta = (_c = claudianMeta[name]) != null ? _c : {};
|
|
const disabledTools = Array.isArray(meta.disabledTools) ? meta.disabledTools.filter((tool) => typeof tool === "string") : void 0;
|
|
const normalizedDisabledTools = disabledTools && disabledTools.length > 0 ? disabledTools : void 0;
|
|
servers.push({
|
|
name,
|
|
config: config2,
|
|
enabled: (_d = meta.enabled) != null ? _d : DEFAULT_MCP_SERVER.enabled,
|
|
contextSaving: (_e = meta.contextSaving) != null ? _e : DEFAULT_MCP_SERVER.contextSaving,
|
|
disabledTools: normalizedDisabledTools,
|
|
description: meta.description
|
|
});
|
|
}
|
|
return servers;
|
|
} catch (error2) {
|
|
console.error("[Claudian] Failed to load MCP config:", error2);
|
|
return [];
|
|
}
|
|
}
|
|
/** Save MCP servers to .claude/mcp.json. */
|
|
async save(servers) {
|
|
var _a;
|
|
try {
|
|
const mcpServers = {};
|
|
const claudianServers = {};
|
|
for (const server of servers) {
|
|
mcpServers[server.name] = server.config;
|
|
const meta = {};
|
|
if (server.enabled !== DEFAULT_MCP_SERVER.enabled) {
|
|
meta.enabled = server.enabled;
|
|
}
|
|
if (server.contextSaving !== DEFAULT_MCP_SERVER.contextSaving) {
|
|
meta.contextSaving = server.contextSaving;
|
|
}
|
|
const normalizedDisabledTools = (_a = server.disabledTools) == null ? void 0 : _a.map((tool) => tool.trim()).filter((tool) => tool.length > 0);
|
|
if (normalizedDisabledTools && normalizedDisabledTools.length > 0) {
|
|
meta.disabledTools = normalizedDisabledTools;
|
|
}
|
|
if (server.description) {
|
|
meta.description = server.description;
|
|
}
|
|
if (Object.keys(meta).length > 0) {
|
|
claudianServers[server.name] = meta;
|
|
}
|
|
}
|
|
let existing = null;
|
|
if (await this.adapter.exists(MCP_CONFIG_PATH)) {
|
|
try {
|
|
const raw = await this.adapter.read(MCP_CONFIG_PATH);
|
|
const parsed = JSON.parse(raw);
|
|
if (parsed && typeof parsed === "object") {
|
|
existing = parsed;
|
|
}
|
|
} catch (e) {
|
|
existing = null;
|
|
}
|
|
}
|
|
const file = existing ? { ...existing } : {};
|
|
file.mcpServers = mcpServers;
|
|
const existingClaudian = existing && typeof existing._claudian === "object" ? existing._claudian : null;
|
|
if (Object.keys(claudianServers).length > 0) {
|
|
file._claudian = { ...existingClaudian != null ? existingClaudian : {}, servers: claudianServers };
|
|
} else if (existingClaudian) {
|
|
const { servers: _servers, ...rest } = existingClaudian;
|
|
if (Object.keys(rest).length > 0) {
|
|
file._claudian = rest;
|
|
} else {
|
|
delete file._claudian;
|
|
}
|
|
} else {
|
|
delete file._claudian;
|
|
}
|
|
const content = JSON.stringify(file, null, 2);
|
|
await this.adapter.write(MCP_CONFIG_PATH, content);
|
|
} catch (error2) {
|
|
console.error("[Claudian] Failed to save MCP config:", error2);
|
|
throw error2;
|
|
}
|
|
}
|
|
/** Check if config file exists. */
|
|
async exists() {
|
|
return this.adapter.exists(MCP_CONFIG_PATH);
|
|
}
|
|
/**
|
|
* Parse pasted JSON (supports multiple formats).
|
|
*
|
|
* Formats supported:
|
|
* 1. Full Claude Code format: { "mcpServers": { "name": {...} } }
|
|
* 2. Single server with name: { "name": { "command": "..." } }
|
|
* 3. Single server without name: { "command": "..." }
|
|
*/
|
|
static parseClipboardConfig(json) {
|
|
try {
|
|
const parsed = JSON.parse(json);
|
|
if (!parsed || typeof parsed !== "object") {
|
|
throw new Error("Invalid JSON object");
|
|
}
|
|
if (parsed.mcpServers && typeof parsed.mcpServers === "object") {
|
|
const servers2 = [];
|
|
for (const [name, config2] of Object.entries(parsed.mcpServers)) {
|
|
if (isValidMcpServerConfig(config2)) {
|
|
servers2.push({ name, config: config2 });
|
|
}
|
|
}
|
|
if (servers2.length === 0) {
|
|
throw new Error("No valid server configs found in mcpServers");
|
|
}
|
|
return { servers: servers2, needsName: false };
|
|
}
|
|
if (isValidMcpServerConfig(parsed)) {
|
|
return {
|
|
servers: [{ name: "", config: parsed }],
|
|
needsName: true
|
|
};
|
|
}
|
|
const entries = Object.entries(parsed);
|
|
if (entries.length === 1) {
|
|
const [name, config2] = entries[0];
|
|
if (isValidMcpServerConfig(config2)) {
|
|
return {
|
|
servers: [{ name, config: config2 }],
|
|
needsName: false
|
|
};
|
|
}
|
|
}
|
|
const servers = [];
|
|
for (const [name, config2] of entries) {
|
|
if (isValidMcpServerConfig(config2)) {
|
|
servers.push({ name, config: config2 });
|
|
}
|
|
}
|
|
if (servers.length > 0) {
|
|
return { servers, needsName: false };
|
|
}
|
|
throw new Error("Invalid MCP configuration format");
|
|
} catch (error2) {
|
|
if (error2 instanceof SyntaxError) {
|
|
throw new Error("Invalid JSON");
|
|
}
|
|
throw error2;
|
|
}
|
|
}
|
|
/**
|
|
* Try to parse clipboard content as MCP config.
|
|
* Returns null if not valid MCP config.
|
|
*/
|
|
static tryParseClipboardConfig(text) {
|
|
const trimmed = text.trim();
|
|
if (!trimmed.startsWith("{")) {
|
|
return null;
|
|
}
|
|
try {
|
|
return _McpStorage.parseClipboardConfig(trimmed);
|
|
} catch (e) {
|
|
return null;
|
|
}
|
|
}
|
|
};
|
|
|
|
// src/core/storage/SessionStorage.ts
|
|
var SESSIONS_PATH = ".claude/sessions";
|
|
var SessionStorage = class {
|
|
constructor(adapter) {
|
|
this.adapter = adapter;
|
|
}
|
|
/** Load a conversation from its JSONL file. */
|
|
async loadConversation(id) {
|
|
const filePath = this.getFilePath(id);
|
|
try {
|
|
if (!await this.adapter.exists(filePath)) {
|
|
return null;
|
|
}
|
|
const content = await this.adapter.read(filePath);
|
|
return this.parseJSONL(content);
|
|
} catch (error2) {
|
|
console.error(`[Claudian] Failed to load conversation ${id}:`, error2);
|
|
return null;
|
|
}
|
|
}
|
|
/** Save a conversation to its JSONL file. */
|
|
async saveConversation(conversation) {
|
|
const filePath = this.getFilePath(conversation.id);
|
|
const content = this.serializeToJSONL(conversation);
|
|
await this.adapter.write(filePath, content);
|
|
}
|
|
/** Delete a conversation's JSONL file. */
|
|
async deleteConversation(id) {
|
|
const filePath = this.getFilePath(id);
|
|
await this.adapter.delete(filePath);
|
|
}
|
|
/** List all conversation metadata (without loading full messages). */
|
|
async listConversations() {
|
|
const metas = [];
|
|
try {
|
|
const files = await this.adapter.listFiles(SESSIONS_PATH);
|
|
for (const filePath of files) {
|
|
if (!filePath.endsWith(".jsonl")) continue;
|
|
try {
|
|
const meta = await this.loadMetaOnly(filePath);
|
|
if (meta) {
|
|
metas.push(meta);
|
|
}
|
|
} catch (error2) {
|
|
console.error(`[Claudian] Failed to load meta from ${filePath}:`, error2);
|
|
}
|
|
}
|
|
metas.sort((a, b) => b.updatedAt - a.updatedAt);
|
|
} catch (error2) {
|
|
console.error("[Claudian] Failed to list sessions:", error2);
|
|
}
|
|
return metas;
|
|
}
|
|
/** Load all conversations (full data). */
|
|
async loadAllConversations() {
|
|
const conversations = [];
|
|
try {
|
|
const files = await this.adapter.listFiles(SESSIONS_PATH);
|
|
for (const filePath of files) {
|
|
if (!filePath.endsWith(".jsonl")) continue;
|
|
try {
|
|
const content = await this.adapter.read(filePath);
|
|
const conversation = this.parseJSONL(content);
|
|
if (conversation) {
|
|
conversations.push(conversation);
|
|
}
|
|
} catch (error2) {
|
|
console.error(`[Claudian] Failed to load conversation from ${filePath}:`, error2);
|
|
}
|
|
}
|
|
conversations.sort((a, b) => b.updatedAt - a.updatedAt);
|
|
} catch (error2) {
|
|
console.error("[Claudian] Failed to load all conversations:", error2);
|
|
}
|
|
return conversations;
|
|
}
|
|
/** Check if any sessions exist. */
|
|
async hasSessions() {
|
|
const files = await this.adapter.listFiles(SESSIONS_PATH);
|
|
return files.some((f) => f.endsWith(".jsonl"));
|
|
}
|
|
/** Get the file path for a conversation. */
|
|
getFilePath(id) {
|
|
return `${SESSIONS_PATH}/${id}.jsonl`;
|
|
}
|
|
/** Load only metadata from a session file (first line). */
|
|
async loadMetaOnly(filePath) {
|
|
const content = await this.adapter.read(filePath);
|
|
const firstLine = content.split(/\r?\n/)[0];
|
|
if (!firstLine) return null;
|
|
try {
|
|
const record2 = JSON.parse(firstLine);
|
|
if (record2.type !== "meta") return null;
|
|
const lines = content.split(/\r?\n/).filter((l) => l.trim());
|
|
const messageCount = lines.length - 1;
|
|
let preview = "New conversation";
|
|
for (let i = 1; i < lines.length; i++) {
|
|
try {
|
|
const msgRecord = JSON.parse(lines[i]);
|
|
if (msgRecord.type === "message" && msgRecord.message.role === "user") {
|
|
const content2 = msgRecord.message.content;
|
|
preview = content2.substring(0, 50) + (content2.length > 50 ? "..." : "");
|
|
break;
|
|
}
|
|
} catch (e) {
|
|
continue;
|
|
}
|
|
}
|
|
return {
|
|
id: record2.id,
|
|
title: record2.title,
|
|
createdAt: record2.createdAt,
|
|
updatedAt: record2.updatedAt,
|
|
lastResponseAt: record2.lastResponseAt,
|
|
messageCount,
|
|
preview,
|
|
titleGenerationStatus: record2.titleGenerationStatus
|
|
};
|
|
} catch (e) {
|
|
return null;
|
|
}
|
|
}
|
|
/** Parse JSONL content into a Conversation object. */
|
|
parseJSONL(content) {
|
|
const lines = content.split(/\r?\n/).filter((l) => l.trim());
|
|
if (lines.length === 0) return null;
|
|
let meta = null;
|
|
const messages = [];
|
|
for (const line of lines) {
|
|
try {
|
|
const record2 = JSON.parse(line);
|
|
if (record2.type === "meta") {
|
|
meta = record2;
|
|
} else if (record2.type === "message") {
|
|
messages.push(record2.message);
|
|
}
|
|
} catch (error2) {
|
|
console.warn("[Claudian] Failed to parse JSONL line:", error2);
|
|
}
|
|
}
|
|
if (!meta) return null;
|
|
return {
|
|
id: meta.id,
|
|
title: meta.title,
|
|
createdAt: meta.createdAt,
|
|
updatedAt: meta.updatedAt,
|
|
lastResponseAt: meta.lastResponseAt,
|
|
sessionId: meta.sessionId,
|
|
messages,
|
|
currentNote: meta.currentNote,
|
|
usage: meta.usage,
|
|
approvedPlan: meta.approvedPlan,
|
|
pendingPlanContent: meta.pendingPlanContent,
|
|
isInPlanMode: meta.isInPlanMode,
|
|
titleGenerationStatus: meta.titleGenerationStatus
|
|
};
|
|
}
|
|
/** Serialize a Conversation to JSONL format. */
|
|
serializeToJSONL(conversation) {
|
|
const lines = [];
|
|
const meta = {
|
|
type: "meta",
|
|
id: conversation.id,
|
|
title: conversation.title,
|
|
createdAt: conversation.createdAt,
|
|
updatedAt: conversation.updatedAt,
|
|
lastResponseAt: conversation.lastResponseAt,
|
|
sessionId: conversation.sessionId,
|
|
currentNote: conversation.currentNote,
|
|
usage: conversation.usage,
|
|
approvedPlan: conversation.approvedPlan,
|
|
pendingPlanContent: conversation.pendingPlanContent,
|
|
isInPlanMode: conversation.isInPlanMode,
|
|
titleGenerationStatus: conversation.titleGenerationStatus
|
|
};
|
|
lines.push(JSON.stringify(meta));
|
|
for (const message of conversation.messages) {
|
|
const storedMessage = this.prepareMessageForStorage(message);
|
|
const record2 = {
|
|
type: "message",
|
|
message: storedMessage
|
|
};
|
|
lines.push(JSON.stringify(record2));
|
|
}
|
|
return lines.join("\n");
|
|
}
|
|
/** Prepare a message for storage (strip image data). */
|
|
prepareMessageForStorage(message) {
|
|
if (!message.images || message.images.length === 0) {
|
|
return message;
|
|
}
|
|
const strippedImages = message.images.map((img) => {
|
|
if (!img.cachePath && !img.filePath) {
|
|
return img;
|
|
}
|
|
const { data: _, ...rest } = img;
|
|
return rest;
|
|
});
|
|
return {
|
|
...message,
|
|
images: strippedImages
|
|
};
|
|
}
|
|
};
|
|
|
|
// src/core/storage/SettingsStorage.ts
|
|
var SETTINGS_PATH = ".claude/settings.json";
|
|
function normalizeCommandList(value, fallback) {
|
|
if (!Array.isArray(value)) {
|
|
return [...fallback];
|
|
}
|
|
return value.filter((item) => typeof item === "string").map((item) => item.trim()).filter((item) => item.length > 0);
|
|
}
|
|
function normalizeBlockedCommands(value) {
|
|
const defaults = getDefaultBlockedCommands();
|
|
if (Array.isArray(value)) {
|
|
return {
|
|
unix: normalizeCommandList(value, defaults.unix),
|
|
windows: [...defaults.windows]
|
|
};
|
|
}
|
|
if (!value || typeof value !== "object") {
|
|
return defaults;
|
|
}
|
|
const candidate = value;
|
|
return {
|
|
unix: normalizeCommandList(candidate.unix, defaults.unix),
|
|
windows: normalizeCommandList(candidate.windows, defaults.windows)
|
|
};
|
|
}
|
|
var SettingsStorage = class {
|
|
constructor(adapter) {
|
|
this.adapter = adapter;
|
|
}
|
|
/** Load settings from .claude/settings.json, merging with defaults. */
|
|
async load() {
|
|
try {
|
|
if (!await this.adapter.exists(SETTINGS_PATH)) {
|
|
return this.getDefaults();
|
|
}
|
|
const content = await this.adapter.read(SETTINGS_PATH);
|
|
const stored = JSON.parse(content);
|
|
const blockedCommands = normalizeBlockedCommands(stored.blockedCommands);
|
|
return {
|
|
...this.getDefaults(),
|
|
...stored,
|
|
blockedCommands
|
|
};
|
|
} catch (error2) {
|
|
console.error("[Claudian] Failed to load settings:", error2);
|
|
return this.getDefaults();
|
|
}
|
|
}
|
|
/** Save settings to .claude/settings.json. */
|
|
async save(settings) {
|
|
try {
|
|
const content = JSON.stringify(settings, null, 2);
|
|
await this.adapter.write(SETTINGS_PATH, content);
|
|
} catch (error2) {
|
|
console.error("[Claudian] Failed to save settings:", error2);
|
|
throw error2;
|
|
}
|
|
}
|
|
/** Check if settings file exists. */
|
|
async exists() {
|
|
return this.adapter.exists(SETTINGS_PATH);
|
|
}
|
|
/** Get default settings (excluding state fields). */
|
|
getDefaults() {
|
|
const {
|
|
slashCommands: _,
|
|
lastEnvHash: __,
|
|
lastClaudeModel: ___,
|
|
lastCustomModel: ____,
|
|
...defaults
|
|
} = DEFAULT_SETTINGS;
|
|
return defaults;
|
|
}
|
|
};
|
|
|
|
// src/utils/slashCommand.ts
|
|
function formatSlashCommandWarnings(errors) {
|
|
const maxItems = 3;
|
|
const head = errors.slice(0, maxItems);
|
|
const more = errors.length > maxItems ? `
|
|
...and ${errors.length - maxItems} more` : "";
|
|
return `Slash command expansion warnings:
|
|
- ${head.join("\n- ")}${more}`;
|
|
}
|
|
function parseSlashCommandContent(content) {
|
|
const frontmatterPattern = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/;
|
|
const match = content.match(frontmatterPattern);
|
|
if (!match) {
|
|
return { promptContent: content };
|
|
}
|
|
const yamlContent = match[1];
|
|
const promptContent = match[2];
|
|
const result = { promptContent };
|
|
const lines = yamlContent.split(/\r?\n/);
|
|
let arrayKey = null;
|
|
let arrayItems = [];
|
|
const flushArray = () => {
|
|
if (arrayKey === "allowed-tools") {
|
|
result.allowedTools = arrayItems;
|
|
}
|
|
arrayKey = null;
|
|
arrayItems = [];
|
|
};
|
|
for (const line of lines) {
|
|
const trimmedLine = line.trim();
|
|
if (arrayKey) {
|
|
if (trimmedLine.startsWith("- ")) {
|
|
arrayItems.push(unquoteYamlString(trimmedLine.slice(2).trim()));
|
|
continue;
|
|
}
|
|
if (trimmedLine === "") {
|
|
continue;
|
|
}
|
|
flushArray();
|
|
}
|
|
const colonIndex = line.indexOf(":");
|
|
if (colonIndex <= 0) {
|
|
continue;
|
|
}
|
|
const key = line.slice(0, colonIndex).trim();
|
|
const value = line.slice(colonIndex + 1).trim();
|
|
switch (key) {
|
|
case "description":
|
|
result.description = unquoteYamlString(value);
|
|
break;
|
|
case "argument-hint":
|
|
result.argumentHint = unquoteYamlString(value);
|
|
break;
|
|
case "model":
|
|
result.model = unquoteYamlString(value);
|
|
break;
|
|
case "allowed-tools":
|
|
if (!value) {
|
|
arrayKey = key;
|
|
arrayItems = [];
|
|
break;
|
|
}
|
|
if (value.startsWith("[") && value.endsWith("]")) {
|
|
result.allowedTools = value.slice(1, -1).split(",").map((s) => unquoteYamlString(s.trim())).filter(Boolean);
|
|
break;
|
|
}
|
|
result.allowedTools = [unquoteYamlString(value)].filter(Boolean);
|
|
break;
|
|
}
|
|
}
|
|
if (arrayKey) {
|
|
flushArray();
|
|
}
|
|
return result;
|
|
}
|
|
function unquoteYamlString(value) {
|
|
if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
|
|
return value.slice(1, -1);
|
|
}
|
|
return value;
|
|
}
|
|
|
|
// src/core/storage/SlashCommandStorage.ts
|
|
var COMMANDS_PATH = ".claude/commands";
|
|
var SlashCommandStorage = class {
|
|
constructor(adapter) {
|
|
this.adapter = adapter;
|
|
}
|
|
/** Load all commands from .claude/commands/ recursively. */
|
|
async loadAll() {
|
|
const commands = [];
|
|
try {
|
|
const files = await this.adapter.listFilesRecursive(COMMANDS_PATH);
|
|
for (const filePath of files) {
|
|
if (!filePath.endsWith(".md")) continue;
|
|
try {
|
|
const command = await this.loadFromFile(filePath);
|
|
if (command) {
|
|
commands.push(command);
|
|
}
|
|
} catch (error2) {
|
|
console.error(`[Claudian] Failed to load command from ${filePath}:`, error2);
|
|
}
|
|
}
|
|
} catch (error2) {
|
|
console.error("[Claudian] Failed to list command files:", error2);
|
|
}
|
|
return commands;
|
|
}
|
|
/** Load a single command from a file path. */
|
|
async loadFromFile(filePath) {
|
|
try {
|
|
const content = await this.adapter.read(filePath);
|
|
return this.parseFile(content, filePath);
|
|
} catch (error2) {
|
|
console.error(`[Claudian] Failed to read command file ${filePath}:`, error2);
|
|
return null;
|
|
}
|
|
}
|
|
/** Save a command to its file. */
|
|
async save(command) {
|
|
const filePath = this.getFilePath(command);
|
|
const content = this.serializeCommand(command);
|
|
await this.adapter.write(filePath, content);
|
|
}
|
|
/** Delete a command file by ID. */
|
|
async delete(commandId) {
|
|
const files = await this.adapter.listFilesRecursive(COMMANDS_PATH);
|
|
for (const filePath of files) {
|
|
if (!filePath.endsWith(".md")) continue;
|
|
const id = this.filePathToId(filePath);
|
|
if (id === commandId) {
|
|
await this.adapter.delete(filePath);
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
/** Check if any commands exist. */
|
|
async hasCommands() {
|
|
const files = await this.adapter.listFilesRecursive(COMMANDS_PATH);
|
|
return files.some((f) => f.endsWith(".md"));
|
|
}
|
|
/** Get the file path for a command. */
|
|
getFilePath(command) {
|
|
const safeName = command.name.replace(/[^a-zA-Z0-9_/-]/g, "-");
|
|
return `${COMMANDS_PATH}/${safeName}.md`;
|
|
}
|
|
/** Parse a command file into a SlashCommand object. */
|
|
parseFile(content, filePath) {
|
|
const parsed = parseSlashCommandContent(content);
|
|
const id = this.filePathToId(filePath);
|
|
const name = this.filePathToName(filePath);
|
|
return {
|
|
id,
|
|
name,
|
|
description: parsed.description,
|
|
argumentHint: parsed.argumentHint,
|
|
allowedTools: parsed.allowedTools,
|
|
model: parsed.model,
|
|
content: parsed.promptContent
|
|
};
|
|
}
|
|
/** Convert a file path to a command ID (reversible encoding). */
|
|
filePathToId(filePath) {
|
|
const relativePath = filePath.replace(`${COMMANDS_PATH}/`, "").replace(/\.md$/, "");
|
|
const escaped = relativePath.replace(/-/g, "-_").replace(/\//g, "--");
|
|
return `cmd-${escaped}`;
|
|
}
|
|
/** Convert a file path to a command name. */
|
|
filePathToName(filePath) {
|
|
return filePath.replace(`${COMMANDS_PATH}/`, "").replace(/\.md$/, "");
|
|
}
|
|
/** Serialize a command to Markdown with YAML frontmatter. */
|
|
serializeCommand(command) {
|
|
const lines = ["---"];
|
|
if (command.description) {
|
|
lines.push(`description: ${this.yamlString(command.description)}`);
|
|
}
|
|
if (command.argumentHint) {
|
|
lines.push(`argument-hint: ${this.yamlString(command.argumentHint)}`);
|
|
}
|
|
if (command.allowedTools && command.allowedTools.length > 0) {
|
|
lines.push("allowed-tools:");
|
|
for (const tool of command.allowedTools) {
|
|
lines.push(` - ${tool}`);
|
|
}
|
|
}
|
|
if (command.model) {
|
|
lines.push(`model: ${command.model}`);
|
|
}
|
|
lines.push("---");
|
|
const parsed = parseSlashCommandContent(command.content);
|
|
lines.push(parsed.promptContent);
|
|
return lines.join("\n");
|
|
}
|
|
/** Quote a YAML string if needed. */
|
|
yamlString(value) {
|
|
if (value.includes(":") || value.includes("#") || value.includes("\n") || value.startsWith(" ") || value.endsWith(" ")) {
|
|
return `"${value.replace(/"/g, '\\"')}"`;
|
|
}
|
|
return value;
|
|
}
|
|
};
|
|
|
|
// src/core/storage/VaultFileAdapter.ts
|
|
var VaultFileAdapter = class {
|
|
constructor(app) {
|
|
this.app = app;
|
|
}
|
|
/** Check if a file or folder exists. */
|
|
async exists(path12) {
|
|
return this.app.vault.adapter.exists(path12);
|
|
}
|
|
/** Read file contents as string. */
|
|
async read(path12) {
|
|
return this.app.vault.adapter.read(path12);
|
|
}
|
|
/** Write content to a file, creating parent directories if needed. */
|
|
async write(path12, content) {
|
|
const folder = path12.substring(0, path12.lastIndexOf("/"));
|
|
if (folder && !await this.exists(folder)) {
|
|
await this.ensureFolder(folder);
|
|
}
|
|
await this.app.vault.adapter.write(path12, content);
|
|
}
|
|
/** Append content to a file. Creates the file if it doesn't exist. */
|
|
async append(path12, content) {
|
|
const folder = path12.substring(0, path12.lastIndexOf("/"));
|
|
if (folder && !await this.exists(folder)) {
|
|
await this.ensureFolder(folder);
|
|
}
|
|
if (await this.exists(path12)) {
|
|
const existing = await this.read(path12);
|
|
await this.app.vault.adapter.write(path12, existing + content);
|
|
} else {
|
|
await this.app.vault.adapter.write(path12, content);
|
|
}
|
|
}
|
|
/** Delete a file if it exists. */
|
|
async delete(path12) {
|
|
if (await this.exists(path12)) {
|
|
await this.app.vault.adapter.remove(path12);
|
|
}
|
|
}
|
|
/** List files in a folder. Returns relative paths from the folder. */
|
|
async listFiles(folder) {
|
|
if (!await this.exists(folder)) {
|
|
return [];
|
|
}
|
|
const listing = await this.app.vault.adapter.list(folder);
|
|
return listing.files;
|
|
}
|
|
/** List subfolders in a folder. Returns relative paths from the folder. */
|
|
async listFolders(folder) {
|
|
if (!await this.exists(folder)) {
|
|
return [];
|
|
}
|
|
const listing = await this.app.vault.adapter.list(folder);
|
|
return listing.folders;
|
|
}
|
|
/** Recursively list all files in a folder and subfolders. */
|
|
async listFilesRecursive(folder) {
|
|
const allFiles = [];
|
|
const processFolder = async (currentFolder) => {
|
|
if (!await this.exists(currentFolder)) return;
|
|
const listing = await this.app.vault.adapter.list(currentFolder);
|
|
allFiles.push(...listing.files);
|
|
for (const subfolder of listing.folders) {
|
|
await processFolder(subfolder);
|
|
}
|
|
};
|
|
await processFolder(folder);
|
|
return allFiles;
|
|
}
|
|
/** Ensure a folder exists, creating it and parent folders if needed. */
|
|
async ensureFolder(path12) {
|
|
if (await this.exists(path12)) return;
|
|
const parts = path12.split("/").filter(Boolean);
|
|
let current = "";
|
|
for (const part of parts) {
|
|
current = current ? `${current}/${part}` : part;
|
|
if (!await this.exists(current)) {
|
|
await this.app.vault.adapter.mkdir(current);
|
|
}
|
|
}
|
|
}
|
|
/** Rename/move a file. */
|
|
async rename(oldPath, newPath) {
|
|
await this.app.vault.adapter.rename(oldPath, newPath);
|
|
}
|
|
/** Get file stats (mtime, size). */
|
|
async stat(path12) {
|
|
try {
|
|
const stat = await this.app.vault.adapter.stat(path12);
|
|
if (!stat) return null;
|
|
return { mtime: stat.mtime, size: stat.size };
|
|
} catch (e) {
|
|
return null;
|
|
}
|
|
}
|
|
};
|
|
|
|
// src/core/storage/StorageService.ts
|
|
var CLAUDE_PATH = ".claude";
|
|
var DEFAULT_STATE = {
|
|
activeConversationId: null,
|
|
lastEnvHash: "",
|
|
lastClaudeModel: "haiku",
|
|
lastCustomModel: ""
|
|
};
|
|
var StorageService = class {
|
|
constructor(plugin) {
|
|
this.plugin = plugin;
|
|
this.app = plugin.app;
|
|
this.adapter = new VaultFileAdapter(this.app);
|
|
this.settings = new SettingsStorage(this.adapter);
|
|
this.commands = new SlashCommandStorage(this.adapter);
|
|
this.sessions = new SessionStorage(this.adapter);
|
|
this.mcp = new McpStorage(this.adapter);
|
|
}
|
|
/** Initialize storage, running migration if needed. */
|
|
async initialize() {
|
|
await this.ensureDirectories();
|
|
const settingsExist = await this.settings.exists();
|
|
const legacyData = await this.loadLegacyData();
|
|
if (legacyData && this.needsMigration(legacyData)) {
|
|
console.log("[Claudian] Migrating from legacy data.json to distributed storage...");
|
|
const migrated = await this.runMigration(legacyData, { migrateSettings: !settingsExist });
|
|
if (migrated) {
|
|
console.log("[Claudian] Migration complete.");
|
|
} else {
|
|
console.warn("[Claudian] Migration incomplete; will retry on next launch.");
|
|
}
|
|
}
|
|
const settings = await this.settings.load();
|
|
const state = await this.loadState();
|
|
return { settings, state };
|
|
}
|
|
/** Check if migration is needed. */
|
|
needsMigration(legacyData) {
|
|
if (!legacyData) return false;
|
|
const hasConversations = legacyData.conversations && legacyData.conversations.length > 0;
|
|
const hasSlashCommands = legacyData.slashCommands && legacyData.slashCommands.length > 0;
|
|
const stateKeys = /* @__PURE__ */ new Set([
|
|
"conversations",
|
|
"slashCommands",
|
|
"activeConversationId",
|
|
"lastEnvHash",
|
|
"lastClaudeModel",
|
|
"lastCustomModel",
|
|
"migrationVersion"
|
|
]);
|
|
const hasSettings = Object.keys(legacyData).some((key) => !stateKeys.has(key));
|
|
return hasConversations || hasSlashCommands || hasSettings;
|
|
}
|
|
/** Run migration from legacy data.json to distributed storage. */
|
|
async runMigration(legacyData, options = { migrateSettings: true }) {
|
|
let hadErrors = false;
|
|
if (options.migrateSettings) {
|
|
try {
|
|
await this.migrateSettings(legacyData);
|
|
} catch (error2) {
|
|
hadErrors = true;
|
|
console.error("[Claudian] Failed to migrate settings:", error2);
|
|
}
|
|
}
|
|
if (await this.migrateSlashCommands(legacyData.slashCommands || [])) {
|
|
hadErrors = true;
|
|
}
|
|
if (await this.migrateConversations(legacyData.conversations || [])) {
|
|
hadErrors = true;
|
|
}
|
|
if (hadErrors) {
|
|
return false;
|
|
}
|
|
await this.saveState({
|
|
activeConversationId: legacyData.activeConversationId || null,
|
|
lastEnvHash: legacyData.lastEnvHash || "",
|
|
lastClaudeModel: legacyData.lastClaudeModel || "haiku",
|
|
lastCustomModel: legacyData.lastCustomModel || ""
|
|
});
|
|
return true;
|
|
}
|
|
/** Load legacy data from Obsidian's data.json. */
|
|
async loadLegacyData() {
|
|
try {
|
|
const data = await this.plugin.loadData();
|
|
return data || null;
|
|
} catch (e) {
|
|
return null;
|
|
}
|
|
}
|
|
/** Load plugin state from data.json. */
|
|
async loadState() {
|
|
var _a, _b, _c, _d;
|
|
try {
|
|
const data = await this.plugin.loadData();
|
|
return {
|
|
activeConversationId: (_a = data == null ? void 0 : data.activeConversationId) != null ? _a : DEFAULT_STATE.activeConversationId,
|
|
lastEnvHash: (_b = data == null ? void 0 : data.lastEnvHash) != null ? _b : DEFAULT_STATE.lastEnvHash,
|
|
lastClaudeModel: (_c = data == null ? void 0 : data.lastClaudeModel) != null ? _c : DEFAULT_STATE.lastClaudeModel,
|
|
lastCustomModel: (_d = data == null ? void 0 : data.lastCustomModel) != null ? _d : DEFAULT_STATE.lastCustomModel
|
|
};
|
|
} catch (e) {
|
|
return { ...DEFAULT_STATE };
|
|
}
|
|
}
|
|
/** Save plugin state to data.json. */
|
|
async saveState(state) {
|
|
await this.plugin.saveData(state);
|
|
}
|
|
/** Update specific state fields in data.json. */
|
|
async updateState(updates) {
|
|
const current = await this.loadState();
|
|
await this.saveState({ ...current, ...updates });
|
|
}
|
|
/** Ensure all required directories exist. */
|
|
async ensureDirectories() {
|
|
await this.adapter.ensureFolder(CLAUDE_PATH);
|
|
await this.adapter.ensureFolder(COMMANDS_PATH);
|
|
await this.adapter.ensureFolder(SESSIONS_PATH);
|
|
}
|
|
/** Migrate settings from legacy format. */
|
|
async migrateSettings(legacyData) {
|
|
const {
|
|
slashCommands: _,
|
|
conversations: __,
|
|
activeConversationId: ___,
|
|
lastEnvHash: ____,
|
|
lastClaudeModel: _____,
|
|
lastCustomModel: ______,
|
|
migrationVersion: _______,
|
|
...settingsFields
|
|
} = legacyData;
|
|
const settings = {
|
|
...this.getDefaultSettings(),
|
|
...settingsFields
|
|
};
|
|
await this.settings.save(settings);
|
|
}
|
|
/** Migrate slash commands to individual files. */
|
|
async migrateSlashCommands(commands) {
|
|
let hadErrors = false;
|
|
for (const command of commands) {
|
|
try {
|
|
const filePath = this.commands.getFilePath(command);
|
|
if (await this.adapter.exists(filePath)) {
|
|
continue;
|
|
}
|
|
await this.commands.save(command);
|
|
} catch (error2) {
|
|
hadErrors = true;
|
|
console.error(`[Claudian] Failed to migrate command ${command.name}:`, error2);
|
|
}
|
|
}
|
|
return hadErrors;
|
|
}
|
|
/** Migrate conversations to individual JSONL files. */
|
|
async migrateConversations(conversations) {
|
|
let hadErrors = false;
|
|
for (const conversation of conversations) {
|
|
try {
|
|
const filePath = this.sessions.getFilePath(conversation.id);
|
|
if (await this.adapter.exists(filePath)) {
|
|
continue;
|
|
}
|
|
await this.sessions.saveConversation(conversation);
|
|
} catch (error2) {
|
|
hadErrors = true;
|
|
console.error(`[Claudian] Failed to migrate conversation ${conversation.id}:`, error2);
|
|
}
|
|
}
|
|
return hadErrors;
|
|
}
|
|
/** Get default settings (excluding state fields and slashCommands). */
|
|
getDefaultSettings() {
|
|
const {
|
|
slashCommands: _,
|
|
lastEnvHash: __,
|
|
lastClaudeModel: ___,
|
|
lastCustomModel: ____,
|
|
...defaults
|
|
} = DEFAULT_SETTINGS;
|
|
return defaults;
|
|
}
|
|
/** Get the vault file adapter for direct file operations. */
|
|
getAdapter() {
|
|
return this.adapter;
|
|
}
|
|
};
|
|
|
|
// src/features/chat/ClaudianView.ts
|
|
var import_obsidian25 = require("obsidian");
|
|
|
|
// src/core/commands/SlashCommandManager.ts
|
|
var import_child_process2 = require("child_process");
|
|
var import_obsidian = require("obsidian");
|
|
var SlashCommandManager = class {
|
|
constructor(app, vaultPath, options = {}) {
|
|
this.commands = /* @__PURE__ */ new Map();
|
|
var _a;
|
|
this.app = app;
|
|
this.vaultPath = vaultPath;
|
|
this.bashRunner = (_a = options.bashRunner) != null ? _a : defaultBashRunner;
|
|
}
|
|
/** Registers commands from settings. */
|
|
setCommands(commands) {
|
|
this.commands.clear();
|
|
for (const cmd of commands) {
|
|
this.commands.set(cmd.name.toLowerCase(), cmd);
|
|
}
|
|
}
|
|
/** Gets all registered commands. */
|
|
getCommands() {
|
|
return Array.from(this.commands.values());
|
|
}
|
|
/** Gets a command by name. */
|
|
getCommand(name) {
|
|
return this.commands.get(name.toLowerCase());
|
|
}
|
|
/** Gets filtered commands matching a prefix. */
|
|
getMatchingCommands(prefix) {
|
|
const prefixLower = prefix.toLowerCase();
|
|
return this.getCommands().filter(
|
|
(cmd) => {
|
|
var _a;
|
|
return cmd.name.toLowerCase().includes(prefixLower) || ((_a = cmd.description) == null ? void 0 : _a.toLowerCase().includes(prefixLower));
|
|
}
|
|
).slice(0, 10);
|
|
}
|
|
/**
|
|
* Detects if input starts with a slash command.
|
|
* Returns the command name and arguments if found.
|
|
*/
|
|
detectCommand(input) {
|
|
const trimmed = input.trimStart();
|
|
if (!trimmed.startsWith("/")) return null;
|
|
const match = trimmed.match(/^\/([a-zA-Z0-9_/-]+)(?:\s+([\s\S]*))?$/);
|
|
if (!match) return null;
|
|
const commandName = match[1];
|
|
const args = (match[2] || "").trim();
|
|
if (!this.commands.has(commandName.toLowerCase())) {
|
|
return null;
|
|
}
|
|
return { commandName, args };
|
|
}
|
|
/**
|
|
* Expands a command with arguments.
|
|
* Processes frontmatter, placeholders, file references, and bash execution.
|
|
*/
|
|
async expandCommand(command, args, options = {}) {
|
|
const errors = [];
|
|
const parsed = parseSlashCommandContent(command.content);
|
|
let result = parsed.promptContent;
|
|
result = this.replaceArgumentPlaceholders(result, args);
|
|
try {
|
|
const bashResult = await this.executeInlineBash(result, options.bash);
|
|
result = bashResult.content;
|
|
errors.push(...bashResult.errors);
|
|
} catch (error2) {
|
|
errors.push(`Bash execution error: ${error2 instanceof Error ? error2.message : "Unknown error"}`);
|
|
}
|
|
try {
|
|
const fileResult = await this.resolveFileReferences(result);
|
|
result = fileResult.content;
|
|
errors.push(...fileResult.errors);
|
|
} catch (error2) {
|
|
errors.push(`File reference error: ${error2 instanceof Error ? error2.message : "Unknown error"}`);
|
|
}
|
|
return {
|
|
expandedPrompt: result.trim(),
|
|
allowedTools: command.allowedTools || parsed.allowedTools,
|
|
model: command.model || parsed.model,
|
|
errors
|
|
};
|
|
}
|
|
/**
|
|
* Replaces argument placeholders in content.
|
|
* Handles $ARGUMENTS (all args) and $1, $2, etc. (positional).
|
|
*/
|
|
replaceArgumentPlaceholders(content, args) {
|
|
const argParts = this.parseArguments(args);
|
|
let result = content.replace(/\$ARGUMENTS/g, args);
|
|
for (let i = 0; i < argParts.length; i++) {
|
|
const pattern = new RegExp(`\\$${i + 1}(?![0-9])`, "g");
|
|
result = result.replace(pattern, argParts[i]);
|
|
}
|
|
result = result.replace(/\$\d+/g, "");
|
|
return result;
|
|
}
|
|
/**
|
|
* Parses arguments respecting quoted strings.
|
|
* "arg with spaces" and 'single quotes' are treated as single args.
|
|
*/
|
|
parseArguments(args) {
|
|
var _a, _b;
|
|
if (!args.trim()) return [];
|
|
const parts = [];
|
|
const regex = /[^\s"']+|"([^"]*)"|'([^']*)'/g;
|
|
let match;
|
|
while ((match = regex.exec(args)) !== null) {
|
|
parts.push((_b = (_a = match[1]) != null ? _a : match[2]) != null ? _b : match[0]);
|
|
}
|
|
return parts;
|
|
}
|
|
/**
|
|
* Resolves @file references in content.
|
|
* Replaces @path/to/file.md with file contents.
|
|
*/
|
|
async resolveFileReferences(content) {
|
|
var _a;
|
|
const pattern = /(^|[^\w])@(?:"([^"]+)"|'([^']+)'|([^\s]+\.\w+))/g;
|
|
const errors = [];
|
|
const matches = [];
|
|
let match;
|
|
while ((match = pattern.exec(content)) !== null) {
|
|
const prefix = (_a = match[1]) != null ? _a : "";
|
|
const filePath = match[2] || match[3] || match[4];
|
|
matches.push({ full: match[0], prefix, path: filePath, index: match.index });
|
|
}
|
|
let result = content;
|
|
for (let i = matches.length - 1; i >= 0; i--) {
|
|
const m = matches[i];
|
|
try {
|
|
const normalizedPath = m.path.replace(/\\/g, "/");
|
|
const file = this.app.vault.getAbstractFileByPath(normalizedPath);
|
|
if (file instanceof import_obsidian.TFile) {
|
|
const fileContent = await this.app.vault.read(file);
|
|
result = result.slice(0, m.index) + m.prefix + fileContent + result.slice(m.index + m.full.length);
|
|
} else {
|
|
errors.push(`File reference not found: ${normalizedPath}`);
|
|
}
|
|
} catch (error2) {
|
|
errors.push(
|
|
`File reference failed: ${m.path} (${error2 instanceof Error ? error2.message : "Unknown error"})`
|
|
);
|
|
}
|
|
}
|
|
return { content: result, errors };
|
|
}
|
|
/**
|
|
* Executes inline bash commands.
|
|
* Replaces !`command` with command output.
|
|
*/
|
|
async executeInlineBash(content, bashOptions) {
|
|
var _a;
|
|
const pattern = /!`([^`]+)`/g;
|
|
const errors = [];
|
|
const matches = [];
|
|
let match;
|
|
while ((match = pattern.exec(content)) !== null) {
|
|
matches.push({ full: match[0], command: match[1], index: match.index });
|
|
}
|
|
let result = content;
|
|
for (let i = matches.length - 1; i >= 0; i--) {
|
|
const m = matches[i];
|
|
try {
|
|
if (!(bashOptions == null ? void 0 : bashOptions.enabled)) {
|
|
errors.push(`Inline bash is disabled: ${m.command}`);
|
|
result = result.slice(0, m.index) + `[Inline bash disabled]` + result.slice(m.index + m.full.length);
|
|
continue;
|
|
}
|
|
if ((_a = bashOptions.shouldBlockCommand) == null ? void 0 : _a.call(bashOptions, m.command)) {
|
|
errors.push(`Inline bash blocked by blocklist: ${m.command}`);
|
|
result = result.slice(0, m.index) + `[Blocked]` + result.slice(m.index + m.full.length);
|
|
continue;
|
|
}
|
|
if (bashOptions.requestApproval) {
|
|
const approved = await bashOptions.requestApproval(m.command);
|
|
if (!approved) {
|
|
errors.push(`Inline bash denied by user: ${m.command}`);
|
|
result = result.slice(0, m.index) + `[Denied]` + result.slice(m.index + m.full.length);
|
|
continue;
|
|
}
|
|
}
|
|
const output = await this.bashRunner(m.command, this.vaultPath);
|
|
result = result.slice(0, m.index) + output.trim() + result.slice(m.index + m.full.length);
|
|
} catch (error2) {
|
|
const errorMsg = `[Error: ${error2 instanceof Error ? error2.message : "Command failed"}]`;
|
|
errors.push(`Inline bash failed: ${m.command}`);
|
|
result = result.slice(0, m.index) + errorMsg + result.slice(m.index + m.full.length);
|
|
}
|
|
}
|
|
return { content: result, errors };
|
|
}
|
|
};
|
|
function defaultBashRunner(command, cwd2) {
|
|
return new Promise((resolve7, reject) => {
|
|
(0, import_child_process2.exec)(
|
|
command,
|
|
{
|
|
cwd: cwd2,
|
|
timeout: 1e4,
|
|
maxBuffer: 1024 * 1024,
|
|
// Enhance PATH for GUI apps (Obsidian has minimal PATH)
|
|
env: { ...process.env, PATH: getEnhancedPath() }
|
|
},
|
|
(error2, stdout, stderr) => {
|
|
if (error2) {
|
|
reject(new Error(stderr || error2.message));
|
|
} else {
|
|
resolve7(stdout);
|
|
}
|
|
}
|
|
);
|
|
});
|
|
}
|
|
|
|
// src/ui/components/AskUserQuestionPanel.ts
|
|
function findInputElements(containerEl) {
|
|
const inputContainer = containerEl.querySelector(".claudian-input-container");
|
|
const inputWrapper = containerEl.querySelector(".claudian-input-wrapper");
|
|
return { inputContainer, inputWrapper };
|
|
}
|
|
var AskUserQuestionPanel = class {
|
|
constructor(app, options) {
|
|
this.answers = /* @__PURE__ */ new Map();
|
|
this.currentTabIndex = 0;
|
|
this.currentOptionIndex = 0;
|
|
this.isDestroyed = false;
|
|
this.documentKeydownHandler = null;
|
|
// DOM references
|
|
this.tabsEl = null;
|
|
this.questionContentEl = null;
|
|
this.otherInputEl = null;
|
|
// Input area references (for hiding/showing)
|
|
this.inputContainer = null;
|
|
this.inputWrapper = null;
|
|
this.app = app;
|
|
this.containerEl = options.containerEl;
|
|
this.questions = options.input.questions;
|
|
this.onSubmit = options.onSubmit;
|
|
this.onCancel = options.onCancel;
|
|
const { inputContainer, inputWrapper } = findInputElements(this.containerEl);
|
|
this.inputContainer = inputContainer;
|
|
this.inputWrapper = inputWrapper;
|
|
if (this.inputWrapper) {
|
|
this.inputWrapper.style.display = "none";
|
|
}
|
|
this.panelEl = this.createPanel();
|
|
if (this.inputContainer) {
|
|
this.inputContainer.appendChild(this.panelEl);
|
|
} else {
|
|
this.containerEl.appendChild(this.panelEl);
|
|
}
|
|
this.panelEl.focus();
|
|
this.attachDocumentHandler();
|
|
}
|
|
/** Create the panel DOM structure. */
|
|
createPanel() {
|
|
const panel = document.createElement("div");
|
|
panel.className = "claudian-ask-panel";
|
|
panel.setAttribute("tabindex", "0");
|
|
panel.setAttribute("role", "dialog");
|
|
panel.setAttribute("aria-label", "Claude is asking a question");
|
|
panel.addEventListener("keydown", this.handleKeyDown.bind(this));
|
|
this.tabsEl = this.createTabs(panel);
|
|
this.questionContentEl = document.createElement("div");
|
|
this.questionContentEl.className = "claudian-ask-panel-content";
|
|
panel.appendChild(this.questionContentEl);
|
|
const hintEl = document.createElement("div");
|
|
hintEl.className = "claudian-ask-panel-hint";
|
|
hintEl.textContent = "Enter to select \xB7 Tab/Arrow keys to navigate \xB7 Esc to cancel";
|
|
panel.appendChild(hintEl);
|
|
this.renderCurrentContent();
|
|
return panel;
|
|
}
|
|
/** Create tab navigation row. */
|
|
createTabs(parent) {
|
|
const tabsContainer = document.createElement("div");
|
|
tabsContainer.className = "claudian-ask-panel-tabs";
|
|
const leftArrow = document.createElement("span");
|
|
leftArrow.className = "claudian-ask-panel-nav";
|
|
leftArrow.textContent = "\u2190";
|
|
leftArrow.addEventListener("click", () => this.navigateTab(-1));
|
|
tabsContainer.appendChild(leftArrow);
|
|
this.questions.forEach((q, index) => {
|
|
const tab = document.createElement("button");
|
|
tab.className = "claudian-ask-panel-tab";
|
|
tab.setAttribute("data-tab-index", String(index));
|
|
const check2 = document.createElement("span");
|
|
check2.className = "claudian-ask-panel-tab-check";
|
|
check2.textContent = "\u25CB";
|
|
tab.appendChild(check2);
|
|
const label = document.createTextNode(` ${q.header || `Q${index + 1}`}`);
|
|
tab.appendChild(label);
|
|
if (index === 0) {
|
|
tab.classList.add("active");
|
|
}
|
|
tab.addEventListener("click", () => this.switchToTab(index));
|
|
tabsContainer.appendChild(tab);
|
|
});
|
|
const submitTab = document.createElement("button");
|
|
submitTab.className = "claudian-ask-panel-tab claudian-ask-panel-submit-tab";
|
|
submitTab.setAttribute("data-tab-index", String(this.questions.length));
|
|
const submitCheck = document.createElement("span");
|
|
submitCheck.className = "claudian-ask-panel-tab-check";
|
|
submitCheck.textContent = "\u2713";
|
|
submitTab.appendChild(submitCheck);
|
|
const submitLabel = document.createTextNode(" Submit");
|
|
submitTab.appendChild(submitLabel);
|
|
submitTab.addEventListener("click", () => this.switchToTab(this.questions.length));
|
|
tabsContainer.appendChild(submitTab);
|
|
const rightArrow = document.createElement("span");
|
|
rightArrow.className = "claudian-ask-panel-nav";
|
|
rightArrow.textContent = "\u2192";
|
|
rightArrow.addEventListener("click", () => this.navigateTab(1));
|
|
tabsContainer.appendChild(rightArrow);
|
|
parent.appendChild(tabsContainer);
|
|
return tabsContainer;
|
|
}
|
|
/** Navigate tabs by direction. */
|
|
navigateTab(direction) {
|
|
const newIndex = this.currentTabIndex + direction;
|
|
if (newIndex >= 0 && newIndex <= this.questions.length) {
|
|
this.switchToTab(newIndex);
|
|
}
|
|
}
|
|
/** Check if currently on Submit tab. */
|
|
isOnSubmitTab() {
|
|
return this.currentTabIndex === this.questions.length;
|
|
}
|
|
/** Switch to a specific tab/question. */
|
|
switchToTab(index) {
|
|
if (index < 0 || index > this.questions.length) return;
|
|
this.currentTabIndex = index;
|
|
this.currentOptionIndex = 0;
|
|
if (this.tabsEl) {
|
|
const tabs = this.tabsEl.querySelectorAll(".claudian-ask-panel-tab");
|
|
tabs.forEach((tab, i) => {
|
|
tab.classList.toggle("active", i === index);
|
|
});
|
|
}
|
|
this.renderCurrentContent();
|
|
}
|
|
/** Render current tab content. */
|
|
renderCurrentContent() {
|
|
if (this.isOnSubmitTab()) {
|
|
this.renderSubmitReview();
|
|
} else {
|
|
this.renderCurrentQuestion();
|
|
}
|
|
}
|
|
/** Render the current question. */
|
|
renderCurrentQuestion() {
|
|
if (!this.questionContentEl) return;
|
|
this.questionContentEl.innerHTML = "";
|
|
const question = this.questions[this.currentTabIndex];
|
|
if (!question) return;
|
|
const questionTextEl = document.createElement("div");
|
|
questionTextEl.className = "claudian-ask-panel-question";
|
|
questionTextEl.textContent = question.question;
|
|
this.questionContentEl.appendChild(questionTextEl);
|
|
const optionsEl = document.createElement("div");
|
|
optionsEl.className = "claudian-ask-panel-options";
|
|
optionsEl.setAttribute("role", question.multiSelect ? "group" : "radiogroup");
|
|
question.options.forEach((option, index) => {
|
|
const optionEl = this.createOptionElement(question, option, index);
|
|
optionsEl.appendChild(optionEl);
|
|
});
|
|
const otherEl = this.createOtherOption(question);
|
|
optionsEl.appendChild(otherEl);
|
|
this.questionContentEl.appendChild(optionsEl);
|
|
this.updateOptionFocus();
|
|
}
|
|
/** Render the Submit review panel. */
|
|
renderSubmitReview() {
|
|
if (!this.questionContentEl) return;
|
|
this.questionContentEl.innerHTML = "";
|
|
const titleEl = document.createElement("div");
|
|
titleEl.className = "claudian-ask-panel-question";
|
|
titleEl.textContent = "Review your answers";
|
|
this.questionContentEl.appendChild(titleEl);
|
|
const summaryEl = document.createElement("div");
|
|
summaryEl.className = "claudian-ask-panel-summary";
|
|
this.questions.forEach((q) => {
|
|
const itemEl = document.createElement("div");
|
|
itemEl.className = "claudian-ask-panel-summary-item";
|
|
const questionEl = document.createElement("div");
|
|
questionEl.className = "claudian-ask-panel-summary-question";
|
|
questionEl.textContent = `\u25CF ${q.question}`;
|
|
itemEl.appendChild(questionEl);
|
|
const answerEl = document.createElement("div");
|
|
answerEl.className = "claudian-ask-panel-summary-answer";
|
|
const answer = this.answers.get(q.question);
|
|
if (answer) {
|
|
const answerText = Array.isArray(answer) ? answer.join(", ") : answer;
|
|
answerEl.textContent = ` \u2192 ${answerText}`;
|
|
} else {
|
|
answerEl.textContent = " \u2192 (not answered)";
|
|
answerEl.classList.add("unanswered");
|
|
}
|
|
itemEl.appendChild(answerEl);
|
|
summaryEl.appendChild(itemEl);
|
|
});
|
|
this.questionContentEl.appendChild(summaryEl);
|
|
const promptEl = document.createElement("div");
|
|
promptEl.className = "claudian-ask-panel-submit-prompt";
|
|
promptEl.textContent = "Ready to submit your answers?";
|
|
this.questionContentEl.appendChild(promptEl);
|
|
const optionsEl = document.createElement("div");
|
|
optionsEl.className = "claudian-ask-panel-options";
|
|
const submitOptionEl = this.createSubmitOption("Submit answers", 0, () => this.submit());
|
|
optionsEl.appendChild(submitOptionEl);
|
|
const cancelOptionEl = this.createSubmitOption("Cancel", 1, () => this.cancel());
|
|
optionsEl.appendChild(cancelOptionEl);
|
|
this.questionContentEl.appendChild(optionsEl);
|
|
this.updateSubmitOptionFocus();
|
|
}
|
|
/** Create an option for the submit review. */
|
|
createSubmitOption(label, index, onClick) {
|
|
const optionEl = document.createElement("div");
|
|
optionEl.className = "claudian-ask-panel-option claudian-ask-panel-submit-option";
|
|
optionEl.setAttribute("data-option-index", String(index));
|
|
const caret = document.createElement("span");
|
|
caret.className = "claudian-ask-panel-caret";
|
|
caret.textContent = " ";
|
|
optionEl.appendChild(caret);
|
|
const indicator = document.createElement("span");
|
|
indicator.className = "claudian-ask-panel-indicator";
|
|
indicator.textContent = `${index + 1}.`;
|
|
optionEl.appendChild(indicator);
|
|
const labelEl = document.createElement("span");
|
|
labelEl.className = "claudian-ask-panel-option-label";
|
|
labelEl.textContent = label;
|
|
optionEl.appendChild(labelEl);
|
|
optionEl.addEventListener("click", () => {
|
|
this.currentOptionIndex = index;
|
|
this.updateSubmitOptionFocus();
|
|
onClick();
|
|
});
|
|
return optionEl;
|
|
}
|
|
/** Update focus for submit options. */
|
|
updateSubmitOptionFocus() {
|
|
if (!this.questionContentEl) return;
|
|
const options = this.questionContentEl.querySelectorAll(".claudian-ask-panel-submit-option");
|
|
options.forEach((opt, i) => {
|
|
const caret = opt.querySelector(".claudian-ask-panel-caret");
|
|
const isFocused = i === this.currentOptionIndex;
|
|
opt.classList.toggle("focused", isFocused);
|
|
if (caret) {
|
|
caret.textContent = isFocused ? ">" : " ";
|
|
}
|
|
});
|
|
}
|
|
/** Create an option element. */
|
|
createOptionElement(question, option, index) {
|
|
const optionEl = document.createElement("div");
|
|
optionEl.className = "claudian-ask-panel-option";
|
|
optionEl.setAttribute("data-option-index", String(index));
|
|
const caret = document.createElement("span");
|
|
caret.className = "claudian-ask-panel-caret";
|
|
caret.textContent = " ";
|
|
optionEl.appendChild(caret);
|
|
const indicator = document.createElement("span");
|
|
indicator.className = "claudian-ask-panel-indicator";
|
|
if (question.multiSelect) {
|
|
indicator.textContent = `${index + 1}. [ ]`;
|
|
} else {
|
|
indicator.textContent = `${index + 1}.`;
|
|
}
|
|
optionEl.appendChild(indicator);
|
|
const textContainer = document.createElement("div");
|
|
textContainer.className = "claudian-ask-panel-option-text";
|
|
const labelRowEl = document.createElement("div");
|
|
labelRowEl.className = "claudian-ask-panel-label-row";
|
|
const labelEl = document.createElement("span");
|
|
labelEl.className = "claudian-ask-panel-option-label";
|
|
labelEl.textContent = option.label;
|
|
labelRowEl.appendChild(labelEl);
|
|
if (!question.multiSelect) {
|
|
const checkmarkEl = document.createElement("span");
|
|
checkmarkEl.className = "claudian-ask-panel-checkmark";
|
|
checkmarkEl.textContent = "";
|
|
labelRowEl.appendChild(checkmarkEl);
|
|
}
|
|
textContainer.appendChild(labelRowEl);
|
|
if (option.description) {
|
|
const descEl = document.createElement("div");
|
|
descEl.className = "claudian-ask-panel-option-desc";
|
|
descEl.textContent = option.description;
|
|
textContainer.appendChild(descEl);
|
|
}
|
|
optionEl.appendChild(textContainer);
|
|
optionEl.addEventListener("click", () => {
|
|
this.currentOptionIndex = index;
|
|
this.selectOption(index);
|
|
});
|
|
return optionEl;
|
|
}
|
|
/** Create the "Other" option with text input. */
|
|
createOtherOption(question) {
|
|
const otherIndex = question.options.length;
|
|
const otherEl = document.createElement("div");
|
|
otherEl.className = "claudian-ask-panel-option claudian-ask-panel-other";
|
|
otherEl.setAttribute("data-option-index", String(otherIndex));
|
|
const caret = document.createElement("span");
|
|
caret.className = "claudian-ask-panel-caret";
|
|
caret.textContent = " ";
|
|
otherEl.appendChild(caret);
|
|
const indicator = document.createElement("span");
|
|
indicator.className = "claudian-ask-panel-indicator";
|
|
if (question.multiSelect) {
|
|
indicator.textContent = `${otherIndex + 1}. [ ]`;
|
|
} else {
|
|
indicator.textContent = `${otherIndex + 1}.`;
|
|
}
|
|
otherEl.appendChild(indicator);
|
|
this.otherInputEl = document.createElement("input");
|
|
this.otherInputEl.type = "text";
|
|
this.otherInputEl.className = "claudian-ask-panel-other-input";
|
|
this.otherInputEl.placeholder = "Type something.";
|
|
this.otherInputEl.addEventListener("keydown", (e) => {
|
|
if (e.key === "ArrowLeft" || e.key === "ArrowRight" || e.key === "ArrowUp" || e.key === "ArrowDown") {
|
|
e.stopPropagation();
|
|
return;
|
|
}
|
|
if (e.key === "Enter") {
|
|
e.preventDefault();
|
|
e.stopPropagation();
|
|
if (this.otherInputEl && this.otherInputEl.value.trim()) {
|
|
this.selectOther(this.otherInputEl.value.trim());
|
|
}
|
|
}
|
|
});
|
|
this.otherInputEl.addEventListener("focus", () => {
|
|
this.currentOptionIndex = otherIndex;
|
|
this.updateOptionFocus();
|
|
});
|
|
otherEl.appendChild(this.otherInputEl);
|
|
otherEl.addEventListener("click", (e) => {
|
|
var _a;
|
|
if (e.target !== this.otherInputEl) {
|
|
this.currentOptionIndex = otherIndex;
|
|
this.updateOptionFocus();
|
|
(_a = this.otherInputEl) == null ? void 0 : _a.focus();
|
|
}
|
|
});
|
|
return otherEl;
|
|
}
|
|
/** Handle keyboard navigation. */
|
|
handleKeyDown(e) {
|
|
var _a;
|
|
if (this.isDestroyed) return;
|
|
if (this.isOnSubmitTab()) {
|
|
this.handleSubmitTabKeyDown(e);
|
|
return;
|
|
}
|
|
const question = this.questions[this.currentTabIndex];
|
|
if (!question) return;
|
|
const totalOptions = question.options.length + 1;
|
|
switch (e.key) {
|
|
case "ArrowUp":
|
|
e.preventDefault();
|
|
this.currentOptionIndex = (this.currentOptionIndex - 1 + totalOptions) % totalOptions;
|
|
this.updateOptionFocus();
|
|
break;
|
|
case "ArrowDown":
|
|
e.preventDefault();
|
|
this.currentOptionIndex = (this.currentOptionIndex + 1) % totalOptions;
|
|
this.updateOptionFocus();
|
|
break;
|
|
case "ArrowLeft":
|
|
e.preventDefault();
|
|
this.navigateTab(-1);
|
|
break;
|
|
case "ArrowRight":
|
|
e.preventDefault();
|
|
this.navigateTab(1);
|
|
break;
|
|
case "Tab":
|
|
e.preventDefault();
|
|
if (e.shiftKey) {
|
|
this.navigateTab(-1);
|
|
} else {
|
|
this.navigateTab(1);
|
|
}
|
|
break;
|
|
case "Enter":
|
|
if (document.activeElement === this.otherInputEl) return;
|
|
e.preventDefault();
|
|
if (this.currentOptionIndex < question.options.length) {
|
|
this.selectOption(this.currentOptionIndex);
|
|
} else if (this.otherInputEl && this.otherInputEl.value.trim()) {
|
|
this.selectOther(this.otherInputEl.value.trim());
|
|
}
|
|
break;
|
|
case "Escape":
|
|
e.preventDefault();
|
|
this.cancel();
|
|
break;
|
|
// Number keys 1-9 for quick selection
|
|
case "1":
|
|
case "2":
|
|
case "3":
|
|
case "4":
|
|
case "5":
|
|
case "6":
|
|
case "7":
|
|
case "8":
|
|
case "9":
|
|
if (document.activeElement !== this.otherInputEl) {
|
|
const num = parseInt(e.key, 10) - 1;
|
|
if (num < question.options.length) {
|
|
e.preventDefault();
|
|
this.currentOptionIndex = num;
|
|
this.selectOption(num);
|
|
} else if (num === question.options.length) {
|
|
e.preventDefault();
|
|
this.currentOptionIndex = num;
|
|
this.updateOptionFocus();
|
|
(_a = this.otherInputEl) == null ? void 0 : _a.focus();
|
|
}
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
/** Handle keyboard navigation for Submit tab. */
|
|
handleSubmitTabKeyDown(e) {
|
|
const totalOptions = 2;
|
|
switch (e.key) {
|
|
case "ArrowUp":
|
|
e.preventDefault();
|
|
this.currentOptionIndex = (this.currentOptionIndex - 1 + totalOptions) % totalOptions;
|
|
this.updateSubmitOptionFocus();
|
|
break;
|
|
case "ArrowDown":
|
|
e.preventDefault();
|
|
this.currentOptionIndex = (this.currentOptionIndex + 1) % totalOptions;
|
|
this.updateSubmitOptionFocus();
|
|
break;
|
|
case "ArrowLeft":
|
|
e.preventDefault();
|
|
this.navigateTab(-1);
|
|
break;
|
|
case "ArrowRight":
|
|
break;
|
|
case "Tab":
|
|
e.preventDefault();
|
|
if (e.shiftKey) {
|
|
this.navigateTab(-1);
|
|
}
|
|
break;
|
|
case "Enter":
|
|
e.preventDefault();
|
|
if (this.currentOptionIndex === 0) {
|
|
this.submit();
|
|
} else {
|
|
this.cancel();
|
|
}
|
|
break;
|
|
case "Escape":
|
|
e.preventDefault();
|
|
this.cancel();
|
|
break;
|
|
case "1":
|
|
e.preventDefault();
|
|
this.currentOptionIndex = 0;
|
|
this.updateSubmitOptionFocus();
|
|
this.submit();
|
|
break;
|
|
case "2":
|
|
e.preventDefault();
|
|
this.currentOptionIndex = 1;
|
|
this.updateSubmitOptionFocus();
|
|
this.cancel();
|
|
break;
|
|
}
|
|
}
|
|
attachDocumentHandler() {
|
|
this.detachDocumentHandler();
|
|
this.documentKeydownHandler = (e) => {
|
|
if (this.isDestroyed) return;
|
|
if (!this.isNavigationKey(e)) return;
|
|
e.preventDefault();
|
|
e.stopPropagation();
|
|
this.handleKeyDown(e);
|
|
};
|
|
document.addEventListener("keydown", this.documentKeydownHandler, true);
|
|
}
|
|
detachDocumentHandler() {
|
|
if (this.documentKeydownHandler) {
|
|
document.removeEventListener("keydown", this.documentKeydownHandler, true);
|
|
this.documentKeydownHandler = null;
|
|
}
|
|
}
|
|
isNavigationKey(e) {
|
|
return e.key === "ArrowUp" || e.key === "ArrowDown" || e.key === "ArrowLeft" || e.key === "ArrowRight" || e.key === "Tab";
|
|
}
|
|
/** Update visual focus indicator. */
|
|
updateOptionFocus() {
|
|
var _a;
|
|
if (!this.questionContentEl) return;
|
|
const question = this.questions[this.currentTabIndex];
|
|
if (!question) return;
|
|
const questionKey = question.question;
|
|
const answer = this.answers.get(questionKey);
|
|
const answerArray = Array.isArray(answer) ? answer : answer ? [answer] : [];
|
|
const options = this.questionContentEl.querySelectorAll(".claudian-ask-panel-option");
|
|
options.forEach((opt, i) => {
|
|
const caret = opt.querySelector(".claudian-ask-panel-caret");
|
|
const indicator = opt.querySelector(".claudian-ask-panel-indicator");
|
|
const isFocused = i === this.currentOptionIndex;
|
|
let isSelected = false;
|
|
if (i < question.options.length) {
|
|
const optionLabel = question.options[i].label;
|
|
isSelected = answerArray.includes(optionLabel);
|
|
} else {
|
|
isSelected = answerArray.some((v) => typeof v === "string" && !question.options.some((o) => o.label === v));
|
|
}
|
|
opt.classList.toggle("focused", isFocused);
|
|
opt.classList.toggle("selected", isSelected);
|
|
if (caret) {
|
|
caret.textContent = isFocused ? ">" : " ";
|
|
}
|
|
if (indicator) {
|
|
if (question.multiSelect) {
|
|
const checkbox = isSelected ? "[\u2713]" : "[ ]";
|
|
indicator.textContent = `${i + 1}. ${checkbox}`;
|
|
} else {
|
|
indicator.textContent = `${i + 1}.`;
|
|
}
|
|
}
|
|
if (!question.multiSelect) {
|
|
const checkmark = opt.querySelector(".claudian-ask-panel-checkmark");
|
|
if (checkmark) {
|
|
checkmark.textContent = isSelected ? " \u2713" : "";
|
|
}
|
|
}
|
|
});
|
|
if (this.currentOptionIndex === question.options.length) {
|
|
(_a = this.otherInputEl) == null ? void 0 : _a.focus();
|
|
} else {
|
|
if (document.activeElement === this.otherInputEl) {
|
|
this.panelEl.focus();
|
|
}
|
|
}
|
|
}
|
|
/** Select an option. */
|
|
selectOption(optionIndex) {
|
|
const question = this.questions[this.currentTabIndex];
|
|
if (!question || optionIndex >= question.options.length) return;
|
|
const option = question.options[optionIndex];
|
|
const questionKey = question.question;
|
|
if (question.multiSelect) {
|
|
const current = this.answers.get(questionKey);
|
|
const currentArray = Array.isArray(current) ? current : [];
|
|
if (currentArray.includes(option.label)) {
|
|
const filtered = currentArray.filter((v) => v !== option.label);
|
|
if (filtered.length > 0) {
|
|
this.answers.set(questionKey, filtered);
|
|
} else {
|
|
this.answers.delete(questionKey);
|
|
}
|
|
} else {
|
|
this.answers.set(questionKey, [...currentArray, option.label]);
|
|
}
|
|
this.updateSelectionUI();
|
|
} else {
|
|
this.answers.set(questionKey, option.label);
|
|
this.updateSelectionUI();
|
|
this.autoAdvance();
|
|
}
|
|
}
|
|
/** Select "Other" with custom text. */
|
|
selectOther(text) {
|
|
const question = this.questions[this.currentTabIndex];
|
|
if (!question) return;
|
|
const questionKey = question.question;
|
|
if (question.multiSelect) {
|
|
const current = this.answers.get(questionKey);
|
|
const currentArray = Array.isArray(current) ? current : [];
|
|
const filtered = currentArray.filter((v) => question.options.some((o) => o.label === v));
|
|
this.answers.set(questionKey, [...filtered, text]);
|
|
this.updateSelectionUI();
|
|
} else {
|
|
this.answers.set(questionKey, text);
|
|
this.updateSelectionUI();
|
|
this.autoAdvance();
|
|
}
|
|
}
|
|
/** Update selection UI indicators. */
|
|
updateSelectionUI() {
|
|
this.updateOptionFocus();
|
|
this.updateTabIndicators();
|
|
}
|
|
/** Update tab checkbox indicators. */
|
|
updateTabIndicators() {
|
|
if (!this.tabsEl) return;
|
|
const tabs = this.tabsEl.querySelectorAll(".claudian-ask-panel-tab");
|
|
this.questions.forEach((q, i) => {
|
|
const hasAnswer = this.answers.has(q.question);
|
|
const tab = tabs[i];
|
|
if (tab) {
|
|
tab.classList.toggle("answered", hasAnswer);
|
|
const check2 = tab.querySelector(".claudian-ask-panel-tab-check");
|
|
if (check2) {
|
|
check2.textContent = hasAnswer ? "\u25CF" : "\u25CB";
|
|
}
|
|
}
|
|
});
|
|
}
|
|
/** Auto-advance to next question or Submit tab. */
|
|
autoAdvance() {
|
|
this.switchToTab(this.currentTabIndex + 1);
|
|
}
|
|
/** Submit all answers. */
|
|
submit() {
|
|
if (this.isDestroyed) return;
|
|
const answersRecord = {};
|
|
this.answers.forEach((value, key) => {
|
|
answersRecord[key] = value;
|
|
});
|
|
this.destroy();
|
|
this.onSubmit(answersRecord);
|
|
}
|
|
/** Cancel and close panel. */
|
|
cancel() {
|
|
if (this.isDestroyed) return;
|
|
this.destroy();
|
|
this.onCancel();
|
|
}
|
|
/** Clean up and remove panel, restore input area. */
|
|
destroy() {
|
|
if (this.isDestroyed) return;
|
|
this.isDestroyed = true;
|
|
this.detachDocumentHandler();
|
|
this.panelEl.remove();
|
|
if (this.inputWrapper) {
|
|
this.inputWrapper.style.display = "";
|
|
}
|
|
}
|
|
};
|
|
function showAskUserQuestionPanel(app, containerEl, input) {
|
|
return new Promise((resolve7) => {
|
|
new AskUserQuestionPanel(app, {
|
|
containerEl,
|
|
input,
|
|
onSubmit: (answers) => resolve7(answers),
|
|
onCancel: () => resolve7(null)
|
|
});
|
|
});
|
|
}
|
|
|
|
// src/ui/components/FileContext.ts
|
|
var import_obsidian4 = require("obsidian");
|
|
var path9 = __toESM(require("path"));
|
|
|
|
// src/ui/components/file-context/mention/MentionDropdownController.ts
|
|
var import_obsidian2 = require("obsidian");
|
|
|
|
// src/features/chat/constants.ts
|
|
var MCP_ICON_SVG = `<svg fill="currentColor" fill-rule="evenodd" height="1em" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>MCP</title><path d="M15.688 2.343a2.588 2.588 0 00-3.61 0l-9.626 9.44a.863.863 0 01-1.203 0 .823.823 0 010-1.18l9.626-9.44a4.313 4.313 0 016.016 0 4.116 4.116 0 011.204 3.54 4.3 4.3 0 013.609 1.18l.05.05a4.115 4.115 0 010 5.9l-8.706 8.537a.274.274 0 000 .393l1.788 1.754a.823.823 0 010 1.18.863.863 0 01-1.203 0l-1.788-1.753a1.92 1.92 0 010-2.754l8.706-8.538a2.47 2.47 0 000-3.54l-.05-.049a2.588 2.588 0 00-3.607-.003l-7.172 7.034-.002.002-.098.097a.863.863 0 01-1.204 0 .823.823 0 010-1.18l7.273-7.133a2.47 2.47 0 00-.003-3.537z"></path><path d="M14.485 4.703a.823.823 0 000-1.18.863.863 0 00-1.204 0l-7.119 6.982a4.115 4.115 0 000 5.9 4.314 4.314 0 006.016 0l7.12-6.982a.823.823 0 000-1.18.863.863 0 00-1.204 0l-7.119 6.982a2.588 2.588 0 01-3.61 0 2.47 2.47 0 010-3.54l7.12-6.982z"></path></svg>`;
|
|
var LOGO_SVG = {
|
|
viewBox: "0 -.01 39.5 39.53",
|
|
width: "18",
|
|
height: "18",
|
|
path: "m7.75 26.27 7.77-4.36.13-.38-.13-.21h-.38l-1.3-.08-4.44-.12-3.85-.16-3.73-.2-.94-.2-.88-1.16.09-.58.79-.53 1.13.1 2.5.17 3.75.26 2.72.16 4.03.42h.64l.09-.26-.22-.16-.17-.16-3.88-2.63-4.2-2.78-2.2-1.6-1.19-.81-.6-.76-.26-1.66 1.08-1.19 1.45.1.37.1 1.47 1.13 3.14 2.43 4.1 3.02.6.5.24-.17.03-.12-.27-.45-2.23-4.03-2.38-4.1-1.06-1.7-.28-1.02c-.1-.42-.17-.77-.17-1.2l1.23-1.67.68-.22 1.64.22.69.6 1.02 2.33 1.65 3.67 2.56 4.99.75 1.48.4 1.37.15.42h.26v-.24l.21-2.81.39-3.45.38-4.44.13-1.25.62-1.5 1.23-.81.96.46.79 1.13-.11.73-.47 3.05-.92 4.78-.6 3.2h.35l.4-.4 1.62-2.15 2.72-3.4 1.2-1.35 1.4-1.49.9-.71h1.7l1.25 1.86-.56 1.92-1.75 2.22-1.45 1.88-2.08 2.8-1.3 2.24.12.18.31-.03 4.7-1 2.54-.46 3.03-.52 1.37.64.15.65-.54 1.33-3.24.8-3.8.76-5.66 1.34-.07.05.08.1 2.55.24 1.09.06h2.67l4.97.37 1.3.86.78 1.05-.13.8-2 1.02-2.7-.64-6.3-1.5-2.16-.54h-.3v.18l1.8 1.76 3.3 2.98 4.13 3.84.21.95-.53.75-.56-.08-3.63-2.73-1.4-1.23-3.17-2.67h-.21v.28l.73 1.07 3.86 5.8.2 1.78-.28.58-1 .35-1.1-.2-2.26-3.17-2.33-3.57-1.88-3.2-.23.13-1.11 11.95-.52.61-1.2.46-1-.76-.53-1.23.53-2.43.64-3.17.52-2.52.47-3.13.28-1.04-.02-.07-.23.03-2.36 3.24-3.59 4.85-2.84 3.04-.68.27-1.18-.61.11-1.09.66-.97 3.93-5 2.37-3.1 1.53-1.79-.01-.26h-.09l-10.44 6.78-1.86.24-.8-.75.1-1.23.38-.4 3.14-2.16z",
|
|
fill: "#d97757"
|
|
};
|
|
var FLAVOR_TEXTS = [
|
|
// Classic
|
|
"Thinking...",
|
|
"Pondering...",
|
|
"Processing...",
|
|
"Analyzing...",
|
|
"Considering...",
|
|
"Working on it...",
|
|
"One moment...",
|
|
"On it...",
|
|
// Thoughtful
|
|
"Ruminating...",
|
|
"Contemplating...",
|
|
"Reflecting...",
|
|
"Mulling it over...",
|
|
"Let me think...",
|
|
"Hmm...",
|
|
"Cogitating...",
|
|
"Deliberating...",
|
|
"Weighing options...",
|
|
"Gathering thoughts...",
|
|
// Playful
|
|
"Brewing ideas...",
|
|
"Connecting dots...",
|
|
"Assembling thoughts...",
|
|
"Spinning up neurons...",
|
|
"Loading brilliance...",
|
|
"Consulting the oracle...",
|
|
"Summoning knowledge...",
|
|
"Crunching thoughts...",
|
|
"Dusting off neurons...",
|
|
"Wrangling ideas...",
|
|
"Herding thoughts...",
|
|
"Juggling concepts...",
|
|
"Untangling this...",
|
|
"Piecing it together...",
|
|
// Cozy
|
|
"Sipping coffee...",
|
|
"Warming up...",
|
|
"Getting cozy with this...",
|
|
"Settling in...",
|
|
"Making tea...",
|
|
"Grabbing a snack...",
|
|
// Technical
|
|
"Parsing...",
|
|
"Compiling thoughts...",
|
|
"Running inference...",
|
|
"Querying the void...",
|
|
"Defragmenting brain...",
|
|
"Allocating memory...",
|
|
"Optimizing...",
|
|
"Indexing...",
|
|
"Syncing neurons...",
|
|
// Zen
|
|
"Breathing...",
|
|
"Finding clarity...",
|
|
"Channeling focus...",
|
|
"Centering...",
|
|
"Aligning chakras...",
|
|
"Meditating on this...",
|
|
// Whimsical
|
|
"Asking the stars...",
|
|
"Reading tea leaves...",
|
|
"Shaking the magic 8-ball...",
|
|
"Consulting ancient scrolls...",
|
|
"Decoding the matrix...",
|
|
"Communing with the ether...",
|
|
"Peering into the abyss...",
|
|
"Channeling the cosmos...",
|
|
// Action
|
|
"Diving in...",
|
|
"Rolling up sleeves...",
|
|
"Getting to work...",
|
|
"Tackling this...",
|
|
"On the case...",
|
|
"Investigating...",
|
|
"Exploring...",
|
|
"Digging deeper...",
|
|
// Casual
|
|
"Bear with me...",
|
|
"Hang tight...",
|
|
"Just a sec...",
|
|
"Working my magic...",
|
|
"Almost there...",
|
|
"Give me a moment..."
|
|
];
|
|
|
|
// src/utils/contextPath.ts
|
|
function normalizePathForComparison2(p) {
|
|
return normalizePathForComparison(p);
|
|
}
|
|
function normalizePathForDisplay(p) {
|
|
if (!p) return "";
|
|
return p.replace(/\\/g, "/").replace(/\/+$/, "");
|
|
}
|
|
function findConflictingPath(newPath, existingPaths) {
|
|
const normalizedNew = normalizePathForComparison2(newPath);
|
|
for (const existing of existingPaths) {
|
|
const normalizedExisting = normalizePathForComparison2(existing);
|
|
if (normalizedNew.startsWith(normalizedExisting + "/")) {
|
|
return { path: existing, type: "parent" };
|
|
}
|
|
if (normalizedExisting.startsWith(normalizedNew + "/")) {
|
|
return { path: existing, type: "child" };
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
function getFolderName(p) {
|
|
const normalized = normalizePathForDisplay(p);
|
|
const segments = normalized.split("/");
|
|
return segments[segments.length - 1] || normalized;
|
|
}
|
|
|
|
// src/utils/contextPathScanner.ts
|
|
var fs7 = __toESM(require("fs"));
|
|
var path8 = __toESM(require("path"));
|
|
var CACHE_TTL_MS = 3e4;
|
|
var MAX_FILES_PER_PATH = 1e3;
|
|
var MAX_DEPTH = 10;
|
|
var SKIP_DIRECTORIES = /* @__PURE__ */ new Set([
|
|
"node_modules",
|
|
"__pycache__",
|
|
"venv",
|
|
".venv",
|
|
".git",
|
|
".svn",
|
|
".hg",
|
|
"dist",
|
|
"build",
|
|
"out",
|
|
".next",
|
|
".nuxt",
|
|
"target",
|
|
"vendor",
|
|
"Pods"
|
|
]);
|
|
var ContextPathScanner = class {
|
|
constructor() {
|
|
this.cache = /* @__PURE__ */ new Map();
|
|
}
|
|
/**
|
|
* Scans all context paths and returns matching files.
|
|
* Uses cached results when available.
|
|
*/
|
|
scanPaths(contextPaths) {
|
|
const allFiles = [];
|
|
const now = Date.now();
|
|
for (const contextPath of contextPaths) {
|
|
const expandedPath = normalizePathForFilesystem(contextPath);
|
|
const cached2 = this.cache.get(expandedPath);
|
|
if (cached2 && now - cached2.timestamp < CACHE_TTL_MS) {
|
|
allFiles.push(...cached2.files);
|
|
continue;
|
|
}
|
|
const files = this.scanDirectory(expandedPath, expandedPath, 0);
|
|
this.cache.set(expandedPath, { files, timestamp: now });
|
|
allFiles.push(...files);
|
|
}
|
|
return allFiles;
|
|
}
|
|
/**
|
|
* Recursively scans a directory for files.
|
|
*/
|
|
scanDirectory(dir, contextRoot, depth) {
|
|
if (depth > MAX_DEPTH) return [];
|
|
const files = [];
|
|
try {
|
|
if (!fs7.existsSync(dir)) return [];
|
|
const stat = fs7.statSync(dir);
|
|
if (!stat.isDirectory()) return [];
|
|
const entries = fs7.readdirSync(dir, { withFileTypes: true });
|
|
for (const entry of entries) {
|
|
if (entry.name.startsWith(".")) continue;
|
|
if (SKIP_DIRECTORIES.has(entry.name)) continue;
|
|
if (entry.isSymbolicLink()) continue;
|
|
const fullPath = path8.join(dir, entry.name);
|
|
if (entry.isDirectory()) {
|
|
const subFiles = this.scanDirectory(fullPath, contextRoot, depth + 1);
|
|
files.push(...subFiles);
|
|
} else if (entry.isFile()) {
|
|
try {
|
|
const fileStat = fs7.statSync(fullPath);
|
|
files.push({
|
|
path: fullPath,
|
|
name: entry.name,
|
|
relativePath: path8.relative(contextRoot, fullPath),
|
|
contextRoot,
|
|
mtime: fileStat.mtimeMs
|
|
});
|
|
} catch (err) {
|
|
console.debug(`Skipped file ${fullPath}: ${err instanceof Error ? err.message : String(err)}`);
|
|
}
|
|
}
|
|
if (files.length >= MAX_FILES_PER_PATH) break;
|
|
}
|
|
} catch (err) {
|
|
console.warn(`Failed to scan context directory ${dir}: ${err instanceof Error ? err.message : String(err)}`);
|
|
}
|
|
return files;
|
|
}
|
|
/** Clears all cached results. */
|
|
invalidateCache() {
|
|
this.cache.clear();
|
|
}
|
|
/** Clears cached results for a specific context path. */
|
|
invalidatePath(contextPath) {
|
|
const expandedPath = normalizePathForFilesystem(contextPath);
|
|
this.cache.delete(expandedPath);
|
|
}
|
|
};
|
|
var contextPathScanner = new ContextPathScanner();
|
|
|
|
// src/utils/mcp.ts
|
|
function extractMcpMentions(text, validNames) {
|
|
const mentions = /* @__PURE__ */ new Set();
|
|
const regex = /@([a-zA-Z0-9._-]+)(?!\/)/g;
|
|
let match;
|
|
while ((match = regex.exec(text)) !== null) {
|
|
const name = match[1];
|
|
if (validNames.has(name)) {
|
|
mentions.add(name);
|
|
}
|
|
}
|
|
return mentions;
|
|
}
|
|
function transformMcpMentions(text, validNames) {
|
|
if (validNames.size === 0) return text;
|
|
const sortedNames = Array.from(validNames).sort((a, b) => b.length - a.length);
|
|
const escapedNames = sortedNames.map(escapeRegExp).join("|");
|
|
const pattern = new RegExp(
|
|
`@(${escapedNames})(?! MCP)(?!/)(?![a-zA-Z0-9_-])(?!\\.[a-zA-Z0-9_-])`,
|
|
"g"
|
|
);
|
|
return text.replace(pattern, "@$1 MCP");
|
|
}
|
|
function escapeRegExp(str) {
|
|
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
}
|
|
function parseCommand(command, providedArgs) {
|
|
if (providedArgs && providedArgs.length > 0) {
|
|
return { cmd: command, args: providedArgs };
|
|
}
|
|
const parts = splitCommandString(command);
|
|
if (parts.length === 0) {
|
|
return { cmd: "", args: [] };
|
|
}
|
|
return { cmd: parts[0], args: parts.slice(1) };
|
|
}
|
|
function splitCommandString(cmdStr) {
|
|
const parts = [];
|
|
let current = "";
|
|
let inQuote = false;
|
|
let quoteChar = "";
|
|
for (let i = 0; i < cmdStr.length; i++) {
|
|
const char = cmdStr[i];
|
|
if ((char === '"' || char === "'") && !inQuote) {
|
|
inQuote = true;
|
|
quoteChar = char;
|
|
continue;
|
|
}
|
|
if (char === quoteChar && inQuote) {
|
|
inQuote = false;
|
|
quoteChar = "";
|
|
continue;
|
|
}
|
|
if (/\s/.test(char) && !inQuote) {
|
|
if (current) {
|
|
parts.push(current);
|
|
current = "";
|
|
}
|
|
continue;
|
|
}
|
|
current += char;
|
|
}
|
|
if (current) {
|
|
parts.push(current);
|
|
}
|
|
return parts;
|
|
}
|
|
function parseSseEvent(raw) {
|
|
const lines = raw.split(/\r?\n/);
|
|
let event;
|
|
const dataLines = [];
|
|
for (const line of lines) {
|
|
if (!line || line.startsWith(":")) continue;
|
|
if (line.startsWith("event:")) {
|
|
event = line.slice("event:".length).trim();
|
|
continue;
|
|
}
|
|
if (line.startsWith("data:")) {
|
|
dataLines.push(line.slice("data:".length).trimStart());
|
|
}
|
|
}
|
|
if (!event && dataLines.length === 0) {
|
|
return null;
|
|
}
|
|
return { event, data: dataLines.join("\n") };
|
|
}
|
|
async function consumeSseStream(body, onEvent) {
|
|
const reader = body.getReader();
|
|
const decoder = new TextDecoder();
|
|
let buffer = "";
|
|
try {
|
|
let done = false;
|
|
while (!done) {
|
|
const result = await reader.read();
|
|
done = result.done;
|
|
const value = result.value;
|
|
if (done) break;
|
|
buffer += decoder.decode(value, { stream: true });
|
|
const parts = buffer.split(/\r?\n\r?\n/);
|
|
buffer = parts.pop() || "";
|
|
for (const part of parts) {
|
|
const event = parseSseEvent(part);
|
|
if (event) {
|
|
onEvent(event);
|
|
}
|
|
}
|
|
}
|
|
} catch (e) {
|
|
} finally {
|
|
reader.releaseLock();
|
|
}
|
|
}
|
|
function parseRpcId(id) {
|
|
if (typeof id === "number" && Number.isFinite(id)) return id;
|
|
if (typeof id === "string" && id.trim()) {
|
|
const asNumber = Number(id);
|
|
if (Number.isFinite(asNumber)) return asNumber;
|
|
}
|
|
return null;
|
|
}
|
|
function tryParseJson(data) {
|
|
if (!data) return null;
|
|
try {
|
|
return JSON.parse(data);
|
|
} catch (e) {
|
|
return null;
|
|
}
|
|
}
|
|
function resolveSseEndpoint(data, baseUrl) {
|
|
const payload = tryParseJson(data);
|
|
if (payload && typeof payload === "object") {
|
|
const record2 = payload;
|
|
const endpoint = typeof record2.endpoint === "string" && record2.endpoint || typeof record2.messageEndpoint === "string" && record2.messageEndpoint || typeof record2.url === "string" && record2.url || typeof record2.messageUrl === "string" && record2.messageUrl;
|
|
if (endpoint) {
|
|
try {
|
|
return new URL(endpoint, baseUrl);
|
|
} catch (e) {
|
|
return null;
|
|
}
|
|
}
|
|
}
|
|
const trimmed = data.trim();
|
|
if (!trimmed) return null;
|
|
try {
|
|
return new URL(trimmed, baseUrl);
|
|
} catch (e) {
|
|
return null;
|
|
}
|
|
}
|
|
function waitForRpcResponse(pending, id, timeoutMs) {
|
|
return new Promise((resolve7, reject) => {
|
|
const timer = setTimeout(() => {
|
|
pending.delete(id);
|
|
reject(new Error(`Response timeout (${timeoutMs}ms)`));
|
|
}, timeoutMs);
|
|
pending.set(id, (msg) => {
|
|
clearTimeout(timer);
|
|
pending.delete(id);
|
|
resolve7(msg);
|
|
});
|
|
});
|
|
}
|
|
async function postJsonRpc(url, headers, payload, options = {}) {
|
|
const requestHeaders = { ...headers };
|
|
if (!requestHeaders["Content-Type"]) {
|
|
requestHeaders["Content-Type"] = "application/json";
|
|
}
|
|
let controller = null;
|
|
let timeoutId = null;
|
|
let signal = options.signal;
|
|
if (options.timeoutMs !== void 0 || options.signal) {
|
|
controller = new AbortController();
|
|
signal = controller.signal;
|
|
}
|
|
const abortHandler = () => controller == null ? void 0 : controller.abort();
|
|
if (controller && options.signal) {
|
|
if (options.signal.aborted) {
|
|
controller.abort();
|
|
} else {
|
|
options.signal.addEventListener("abort", abortHandler, { once: true });
|
|
}
|
|
}
|
|
if (controller && options.timeoutMs !== void 0) {
|
|
timeoutId = setTimeout(() => controller == null ? void 0 : controller.abort(), options.timeoutMs);
|
|
}
|
|
const requestInit = {
|
|
method: "POST",
|
|
headers: requestHeaders,
|
|
body: JSON.stringify(payload)
|
|
};
|
|
if (signal) {
|
|
requestInit.signal = signal;
|
|
}
|
|
try {
|
|
return await fetch(url.toString(), requestInit);
|
|
} finally {
|
|
if (timeoutId !== null) {
|
|
clearTimeout(timeoutId);
|
|
}
|
|
if (controller && options.signal) {
|
|
options.signal.removeEventListener("abort", abortHandler);
|
|
}
|
|
}
|
|
}
|
|
|
|
// src/ui/components/SelectableDropdown.ts
|
|
var SelectableDropdown = class {
|
|
constructor(containerEl, options) {
|
|
this.dropdownEl = null;
|
|
this.items = [];
|
|
this.itemEls = [];
|
|
this.selectedIndex = 0;
|
|
this.containerEl = containerEl;
|
|
this.options = options;
|
|
}
|
|
isVisible() {
|
|
var _a, _b;
|
|
return (_b = (_a = this.dropdownEl) == null ? void 0 : _a.hasClass("visible")) != null ? _b : false;
|
|
}
|
|
getElement() {
|
|
return this.dropdownEl;
|
|
}
|
|
getSelectedIndex() {
|
|
return this.selectedIndex;
|
|
}
|
|
getSelectedItem() {
|
|
var _a;
|
|
return (_a = this.items[this.selectedIndex]) != null ? _a : null;
|
|
}
|
|
getItems() {
|
|
return this.items;
|
|
}
|
|
hide() {
|
|
if (this.dropdownEl) {
|
|
this.dropdownEl.removeClass("visible");
|
|
}
|
|
}
|
|
destroy() {
|
|
if (this.dropdownEl) {
|
|
this.dropdownEl.remove();
|
|
this.dropdownEl = null;
|
|
}
|
|
}
|
|
render(options) {
|
|
var _a;
|
|
this.items = options.items;
|
|
this.selectedIndex = options.selectedIndex;
|
|
if (!this.dropdownEl) {
|
|
this.dropdownEl = this.createDropdownElement();
|
|
}
|
|
this.dropdownEl.empty();
|
|
this.itemEls = [];
|
|
if (options.items.length === 0) {
|
|
const emptyEl = this.dropdownEl.createDiv({ cls: this.options.emptyClassName });
|
|
emptyEl.setText(options.emptyText);
|
|
} else {
|
|
for (let i = 0; i < options.items.length; i++) {
|
|
const item = options.items[i];
|
|
const itemEl = this.dropdownEl.createDiv({ cls: this.options.itemClassName });
|
|
const extraClass = (_a = options.getItemClass) == null ? void 0 : _a.call(options, item);
|
|
if (Array.isArray(extraClass)) {
|
|
extraClass.forEach((cls) => itemEl.addClass(cls));
|
|
} else if (extraClass) {
|
|
itemEl.addClass(extraClass);
|
|
}
|
|
if (i === this.selectedIndex) {
|
|
itemEl.addClass("selected");
|
|
}
|
|
options.renderItem(item, itemEl);
|
|
itemEl.addEventListener("click", () => {
|
|
var _a2;
|
|
this.selectedIndex = i;
|
|
this.updateSelection();
|
|
(_a2 = options.onItemClick) == null ? void 0 : _a2.call(options, item, i);
|
|
});
|
|
itemEl.addEventListener("mouseenter", () => {
|
|
var _a2;
|
|
this.selectedIndex = i;
|
|
this.updateSelection();
|
|
(_a2 = options.onItemHover) == null ? void 0 : _a2.call(options, item, i);
|
|
});
|
|
this.itemEls.push(itemEl);
|
|
}
|
|
}
|
|
this.dropdownEl.addClass("visible");
|
|
}
|
|
updateSelection() {
|
|
this.itemEls.forEach((itemEl, index) => {
|
|
if (index === this.selectedIndex) {
|
|
itemEl.addClass("selected");
|
|
itemEl.scrollIntoView({ block: "nearest" });
|
|
} else {
|
|
itemEl.removeClass("selected");
|
|
}
|
|
});
|
|
}
|
|
moveSelection(delta) {
|
|
const maxIndex = this.items.length - 1;
|
|
this.selectedIndex = Math.max(0, Math.min(maxIndex, this.selectedIndex + delta));
|
|
this.updateSelection();
|
|
}
|
|
createDropdownElement() {
|
|
const className = this.options.fixed && this.options.fixedClassName ? `${this.options.listClassName} ${this.options.fixedClassName}` : this.options.listClassName;
|
|
return this.containerEl.createDiv({ cls: className });
|
|
}
|
|
};
|
|
|
|
// src/ui/components/file-context/mention/types.ts
|
|
function createContextPathEntry(contextRoot, folderName, displayName) {
|
|
return {
|
|
contextRoot,
|
|
folderName,
|
|
displayName,
|
|
displayNameLower: displayName.toLowerCase()
|
|
};
|
|
}
|
|
|
|
// src/ui/components/file-context/mention/MentionDropdownController.ts
|
|
var MentionDropdownController = class {
|
|
constructor(containerEl, inputEl, callbacks, options = {}) {
|
|
this.mentionStartIndex = -1;
|
|
this.selectedMentionIndex = 0;
|
|
this.filteredMentionItems = [];
|
|
this.filteredContextFiles = [];
|
|
this.activeContextFilter = null;
|
|
this.mcpService = null;
|
|
var _a;
|
|
this.containerEl = containerEl;
|
|
this.inputEl = inputEl;
|
|
this.callbacks = callbacks;
|
|
this.fixed = (_a = options.fixed) != null ? _a : false;
|
|
this.dropdown = new SelectableDropdown(this.containerEl, {
|
|
listClassName: "claudian-mention-dropdown",
|
|
itemClassName: "claudian-mention-item",
|
|
emptyClassName: "claudian-mention-empty",
|
|
fixed: this.fixed,
|
|
fixedClassName: "claudian-mention-dropdown-fixed"
|
|
});
|
|
}
|
|
setMcpService(service) {
|
|
this.mcpService = service;
|
|
}
|
|
preScanContextPaths() {
|
|
const contextPaths = this.callbacks.getContextPaths() || [];
|
|
if (contextPaths.length === 0) return;
|
|
setTimeout(() => {
|
|
try {
|
|
contextPathScanner.scanPaths(contextPaths);
|
|
} catch (err) {
|
|
console.warn(
|
|
"Failed to pre-scan context paths:",
|
|
err instanceof Error ? err.message : String(err)
|
|
);
|
|
}
|
|
}, 0);
|
|
}
|
|
isVisible() {
|
|
return this.dropdown.isVisible();
|
|
}
|
|
hide() {
|
|
this.dropdown.hide();
|
|
this.mentionStartIndex = -1;
|
|
}
|
|
containsElement(el) {
|
|
var _a, _b;
|
|
return (_b = (_a = this.dropdown.getElement()) == null ? void 0 : _a.contains(el)) != null ? _b : false;
|
|
}
|
|
destroy() {
|
|
this.dropdown.destroy();
|
|
}
|
|
updateMcpMentionsFromText(text) {
|
|
var _a, _b;
|
|
if (!this.mcpService) return;
|
|
const validNames = new Set(
|
|
this.mcpService.getContextSavingServers().map((s) => s.name)
|
|
);
|
|
const newMentions = extractMcpMentions(text, validNames);
|
|
const changed = this.callbacks.setMentionedMcpServers(newMentions);
|
|
if (changed) {
|
|
(_b = (_a = this.callbacks).onMcpMentionChange) == null ? void 0 : _b.call(_a, newMentions);
|
|
}
|
|
}
|
|
handleInputChange() {
|
|
const text = this.inputEl.value;
|
|
this.updateMcpMentionsFromText(text);
|
|
const cursorPos = this.inputEl.selectionStart || 0;
|
|
const textBeforeCursor = text.substring(0, cursorPos);
|
|
const lastAtIndex = textBeforeCursor.lastIndexOf("@");
|
|
if (lastAtIndex === -1) {
|
|
this.hide();
|
|
return;
|
|
}
|
|
const charBeforeAt = lastAtIndex > 0 ? textBeforeCursor[lastAtIndex - 1] : " ";
|
|
if (!/\s/.test(charBeforeAt) && lastAtIndex !== 0) {
|
|
this.hide();
|
|
return;
|
|
}
|
|
const searchText = textBeforeCursor.substring(lastAtIndex + 1);
|
|
if (/\s/.test(searchText)) {
|
|
this.hide();
|
|
return;
|
|
}
|
|
this.mentionStartIndex = lastAtIndex;
|
|
this.showMentionDropdown(searchText);
|
|
}
|
|
handleKeydown(e) {
|
|
if (!this.dropdown.isVisible()) return false;
|
|
if (e.key === "ArrowDown") {
|
|
e.preventDefault();
|
|
this.dropdown.moveSelection(1);
|
|
this.selectedMentionIndex = this.dropdown.getSelectedIndex();
|
|
return true;
|
|
}
|
|
if (e.key === "ArrowUp") {
|
|
e.preventDefault();
|
|
this.dropdown.moveSelection(-1);
|
|
this.selectedMentionIndex = this.dropdown.getSelectedIndex();
|
|
return true;
|
|
}
|
|
if (e.key === "Enter" || e.key === "Tab") {
|
|
e.preventDefault();
|
|
this.selectMentionItem();
|
|
return true;
|
|
}
|
|
if (e.key === "Escape") {
|
|
e.preventDefault();
|
|
this.hide();
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
buildContextPathEntries(contextPaths) {
|
|
var _a;
|
|
const counts = /* @__PURE__ */ new Map();
|
|
const normalizedPaths = /* @__PURE__ */ new Map();
|
|
for (const contextPath of contextPaths) {
|
|
const normalized = normalizePathForComparison2(contextPath);
|
|
normalizedPaths.set(contextPath, normalized);
|
|
const folderName = getFolderName(normalized);
|
|
counts.set(folderName, ((_a = counts.get(folderName)) != null ? _a : 0) + 1);
|
|
}
|
|
return contextPaths.map((contextRoot) => {
|
|
var _a2, _b;
|
|
const normalized = (_a2 = normalizedPaths.get(contextRoot)) != null ? _a2 : normalizePathForComparison2(contextRoot);
|
|
const folderName = getFolderName(contextRoot);
|
|
const needsDisambiguation = ((_b = counts.get(folderName)) != null ? _b : 0) > 1;
|
|
const displayName = this.getContextDisplayName(normalized, folderName, needsDisambiguation);
|
|
return createContextPathEntry(contextRoot, folderName, displayName);
|
|
});
|
|
}
|
|
getContextDisplayName(normalizedPath, folderName, needsDisambiguation) {
|
|
if (!needsDisambiguation) return folderName;
|
|
const segments = normalizedPath.split("/").filter(Boolean);
|
|
if (segments.length < 2) return folderName;
|
|
const parent = segments[segments.length - 2];
|
|
if (!parent) return folderName;
|
|
return `${parent}/${folderName}`;
|
|
}
|
|
showMentionDropdown(searchText) {
|
|
const searchLower = searchText.toLowerCase();
|
|
this.filteredMentionItems = [];
|
|
this.filteredContextFiles = [];
|
|
const contextPaths = this.callbacks.getContextPaths() || [];
|
|
const contextEntries = this.buildContextPathEntries(contextPaths);
|
|
const isFilterSearch = searchText.includes("/");
|
|
let fileSearchText = searchLower;
|
|
if (isFilterSearch) {
|
|
const matchingContext = contextEntries.filter((entry) => searchLower.startsWith(`${entry.displayNameLower}/`)).sort((a, b) => b.displayNameLower.length - a.displayNameLower.length)[0];
|
|
if (matchingContext) {
|
|
const prefixLength = matchingContext.displayName.length + 1;
|
|
fileSearchText = searchText.substring(prefixLength).toLowerCase();
|
|
this.activeContextFilter = {
|
|
folderName: matchingContext.displayName,
|
|
contextRoot: matchingContext.contextRoot
|
|
};
|
|
} else {
|
|
this.activeContextFilter = null;
|
|
}
|
|
}
|
|
if (this.activeContextFilter && isFilterSearch) {
|
|
const contextFiles = contextPathScanner.scanPaths([this.activeContextFilter.contextRoot]);
|
|
this.filteredContextFiles = contextFiles.filter((file) => {
|
|
const relativePath = file.relativePath.replace(/\\/g, "/");
|
|
const pathLower = relativePath.toLowerCase();
|
|
const nameLower = file.name.toLowerCase();
|
|
return pathLower.includes(fileSearchText) || nameLower.includes(fileSearchText);
|
|
}).sort((a, b) => {
|
|
const aNameMatch = a.name.toLowerCase().startsWith(fileSearchText);
|
|
const bNameMatch = b.name.toLowerCase().startsWith(fileSearchText);
|
|
if (aNameMatch && !bNameMatch) return -1;
|
|
if (!aNameMatch && bNameMatch) return 1;
|
|
return b.mtime - a.mtime;
|
|
}).slice(0, 10);
|
|
for (const file of this.filteredContextFiles) {
|
|
const relativePath = file.relativePath.replace(/\\/g, "/");
|
|
this.filteredMentionItems.push({
|
|
type: "context-file",
|
|
name: relativePath,
|
|
absolutePath: file.path,
|
|
contextRoot: file.contextRoot,
|
|
folderName: this.activeContextFilter.folderName
|
|
});
|
|
}
|
|
this.selectedMentionIndex = 0;
|
|
this.renderMentionDropdown();
|
|
return;
|
|
}
|
|
this.activeContextFilter = null;
|
|
if (this.mcpService) {
|
|
const mcpServers = this.mcpService.getContextSavingServers();
|
|
for (const server of mcpServers) {
|
|
if (server.name.toLowerCase().includes(searchLower)) {
|
|
this.filteredMentionItems.push({
|
|
type: "mcp-server",
|
|
name: server.name
|
|
});
|
|
}
|
|
}
|
|
}
|
|
if (contextEntries.length > 0) {
|
|
const matchingFolders = /* @__PURE__ */ new Set();
|
|
for (const entry of contextEntries) {
|
|
if (entry.displayNameLower.includes(searchLower) && !matchingFolders.has(entry.displayName)) {
|
|
matchingFolders.add(entry.displayName);
|
|
this.filteredMentionItems.push({
|
|
type: "context-folder",
|
|
name: entry.displayName,
|
|
contextRoot: entry.contextRoot,
|
|
folderName: entry.displayName
|
|
});
|
|
}
|
|
}
|
|
}
|
|
const firstVaultFileIndex = this.filteredMentionItems.length;
|
|
const remainingSlots = 10 - this.filteredMentionItems.length;
|
|
let vaultFiles = [];
|
|
if (remainingSlots > 0) {
|
|
const allFiles = this.callbacks.getCachedMarkdownFiles();
|
|
vaultFiles = allFiles.filter((file) => {
|
|
const pathLower = file.path.toLowerCase();
|
|
const nameLower = file.name.toLowerCase();
|
|
return pathLower.includes(searchLower) || nameLower.includes(searchLower);
|
|
}).sort((a, b) => {
|
|
const aNameMatch = a.name.toLowerCase().startsWith(searchLower);
|
|
const bNameMatch = b.name.toLowerCase().startsWith(searchLower);
|
|
if (aNameMatch && !bNameMatch) return -1;
|
|
if (!aNameMatch && bNameMatch) return 1;
|
|
return b.stat.mtime - a.stat.mtime;
|
|
}).slice(0, remainingSlots);
|
|
for (const file of vaultFiles) {
|
|
this.filteredMentionItems.push({
|
|
type: "file",
|
|
name: file.name,
|
|
path: file.path,
|
|
file
|
|
});
|
|
}
|
|
}
|
|
if (vaultFiles.length > 0) {
|
|
this.selectedMentionIndex = firstVaultFileIndex;
|
|
} else {
|
|
this.selectedMentionIndex = 0;
|
|
}
|
|
this.renderMentionDropdown();
|
|
}
|
|
renderMentionDropdown() {
|
|
this.dropdown.render({
|
|
items: this.filteredMentionItems,
|
|
selectedIndex: this.selectedMentionIndex,
|
|
emptyText: "No matches",
|
|
getItemClass: (item) => {
|
|
if (item.type === "mcp-server") return "mcp-server";
|
|
if (item.type === "context-file") return "context-file";
|
|
if (item.type === "context-folder") return "context-folder";
|
|
return void 0;
|
|
},
|
|
renderItem: (item, itemEl) => {
|
|
const iconEl = itemEl.createSpan({ cls: "claudian-mention-icon" });
|
|
if (item.type === "mcp-server") {
|
|
iconEl.innerHTML = MCP_ICON_SVG;
|
|
} else if (item.type === "context-file") {
|
|
(0, import_obsidian2.setIcon)(iconEl, "folder-open");
|
|
} else if (item.type === "context-folder") {
|
|
(0, import_obsidian2.setIcon)(iconEl, "folder");
|
|
} else {
|
|
(0, import_obsidian2.setIcon)(iconEl, "file-text");
|
|
}
|
|
const textEl = itemEl.createSpan({ cls: "claudian-mention-text" });
|
|
if (item.type === "mcp-server") {
|
|
const nameEl = textEl.createSpan({ cls: "claudian-mention-name" });
|
|
nameEl.setText(`@${item.name}`);
|
|
} else if (item.type === "context-folder") {
|
|
const nameEl = textEl.createSpan({
|
|
cls: "claudian-mention-name claudian-mention-name-folder"
|
|
});
|
|
nameEl.setText(`@${item.name}/`);
|
|
} else if (item.type === "context-file") {
|
|
const nameEl = textEl.createSpan({
|
|
cls: "claudian-mention-name claudian-mention-name-context"
|
|
});
|
|
nameEl.setText(item.name);
|
|
} else {
|
|
const pathEl = textEl.createSpan({ cls: "claudian-mention-path" });
|
|
pathEl.setText(item.path || item.name);
|
|
}
|
|
},
|
|
onItemClick: (_item, index) => {
|
|
this.selectedMentionIndex = index;
|
|
this.selectMentionItem();
|
|
},
|
|
onItemHover: (_item, index) => {
|
|
this.selectedMentionIndex = index;
|
|
}
|
|
});
|
|
if (this.fixed) {
|
|
this.positionFixed();
|
|
}
|
|
}
|
|
positionFixed() {
|
|
const dropdownEl = this.dropdown.getElement();
|
|
if (!dropdownEl) return;
|
|
const inputRect = this.inputEl.getBoundingClientRect();
|
|
dropdownEl.style.position = "fixed";
|
|
dropdownEl.style.bottom = `${window.innerHeight - inputRect.top + 4}px`;
|
|
dropdownEl.style.left = `${inputRect.left}px`;
|
|
dropdownEl.style.right = "auto";
|
|
dropdownEl.style.width = `${Math.max(inputRect.width, 280)}px`;
|
|
dropdownEl.style.zIndex = "10001";
|
|
}
|
|
selectMentionItem() {
|
|
var _a, _b;
|
|
if (this.filteredMentionItems.length === 0) return;
|
|
const selectedIndex = this.dropdown.getSelectedIndex();
|
|
this.selectedMentionIndex = selectedIndex;
|
|
const selectedItem = this.filteredMentionItems[selectedIndex];
|
|
if (!selectedItem) return;
|
|
const text = this.inputEl.value;
|
|
const beforeAt = text.substring(0, this.mentionStartIndex);
|
|
const cursorPos = this.inputEl.selectionStart || 0;
|
|
const afterCursor = text.substring(cursorPos);
|
|
if (selectedItem.type === "mcp-server") {
|
|
const replacement = `@${selectedItem.name} `;
|
|
this.inputEl.value = beforeAt + replacement + afterCursor;
|
|
this.inputEl.selectionStart = this.inputEl.selectionEnd = beforeAt.length + replacement.length;
|
|
this.callbacks.addMentionedMcpServer(selectedItem.name);
|
|
(_b = (_a = this.callbacks).onMcpMentionChange) == null ? void 0 : _b.call(_a, this.callbacks.getMentionedMcpServers());
|
|
} else if (selectedItem.type === "context-folder") {
|
|
const replacement = `@${selectedItem.name}/`;
|
|
this.inputEl.value = beforeAt + replacement + afterCursor;
|
|
this.inputEl.selectionStart = this.inputEl.selectionEnd = beforeAt.length + replacement.length;
|
|
this.inputEl.focus();
|
|
this.handleInputChange();
|
|
return;
|
|
} else if (selectedItem.type === "context-file") {
|
|
if (selectedItem.absolutePath) {
|
|
this.callbacks.onAttachFile(selectedItem.absolutePath);
|
|
}
|
|
const displayName = selectedItem.folderName ? `@${selectedItem.folderName}/${selectedItem.name}` : `@${selectedItem.name}`;
|
|
const replacement = `${displayName} `;
|
|
this.inputEl.value = beforeAt + replacement + afterCursor;
|
|
this.inputEl.selectionStart = this.inputEl.selectionEnd = beforeAt.length + replacement.length;
|
|
} else {
|
|
const file = selectedItem.file;
|
|
if (file) {
|
|
const normalizedPath = this.callbacks.normalizePathForVault(file.path);
|
|
if (normalizedPath) {
|
|
this.callbacks.onAttachFile(normalizedPath);
|
|
}
|
|
} else if (selectedItem.path) {
|
|
const normalizedPath = this.callbacks.normalizePathForVault(selectedItem.path);
|
|
if (normalizedPath) {
|
|
this.callbacks.onAttachFile(normalizedPath);
|
|
}
|
|
}
|
|
const replacement = `@${selectedItem.name} `;
|
|
this.inputEl.value = beforeAt + replacement + afterCursor;
|
|
this.inputEl.selectionStart = this.inputEl.selectionEnd = beforeAt.length + replacement.length;
|
|
}
|
|
this.hide();
|
|
this.inputEl.focus();
|
|
}
|
|
};
|
|
|
|
// src/ui/components/file-context/state/FileContextState.ts
|
|
var FileContextState = class {
|
|
constructor() {
|
|
this.attachedFiles = /* @__PURE__ */ new Set();
|
|
this.sessionStarted = false;
|
|
this.mentionedMcpServers = /* @__PURE__ */ new Set();
|
|
this.currentNoteSent = false;
|
|
}
|
|
getAttachedFiles() {
|
|
return new Set(this.attachedFiles);
|
|
}
|
|
hasSentCurrentNote() {
|
|
return this.currentNoteSent;
|
|
}
|
|
markCurrentNoteSent() {
|
|
this.currentNoteSent = true;
|
|
}
|
|
isSessionStarted() {
|
|
return this.sessionStarted;
|
|
}
|
|
startSession() {
|
|
this.sessionStarted = true;
|
|
}
|
|
resetForNewConversation() {
|
|
this.sessionStarted = false;
|
|
this.currentNoteSent = false;
|
|
this.attachedFiles.clear();
|
|
this.clearMcpMentions();
|
|
}
|
|
resetForLoadedConversation(hasMessages) {
|
|
this.currentNoteSent = hasMessages;
|
|
this.attachedFiles.clear();
|
|
this.sessionStarted = hasMessages;
|
|
this.clearMcpMentions();
|
|
}
|
|
setAttachedFiles(files) {
|
|
this.attachedFiles.clear();
|
|
for (const file of files) {
|
|
this.attachedFiles.add(file);
|
|
}
|
|
}
|
|
attachFile(path12) {
|
|
this.attachedFiles.add(path12);
|
|
}
|
|
detachFile(path12) {
|
|
this.attachedFiles.delete(path12);
|
|
}
|
|
clearAttachments() {
|
|
this.attachedFiles.clear();
|
|
}
|
|
getMentionedMcpServers() {
|
|
return new Set(this.mentionedMcpServers);
|
|
}
|
|
clearMcpMentions() {
|
|
this.mentionedMcpServers.clear();
|
|
}
|
|
setMentionedMcpServers(mentions) {
|
|
const changed = mentions.size !== this.mentionedMcpServers.size || [...mentions].some((name) => !this.mentionedMcpServers.has(name));
|
|
if (changed) {
|
|
this.mentionedMcpServers = new Set(mentions);
|
|
}
|
|
return changed;
|
|
}
|
|
addMentionedMcpServer(name) {
|
|
this.mentionedMcpServers.add(name);
|
|
}
|
|
};
|
|
|
|
// src/ui/components/file-context/state/MarkdownFileCache.ts
|
|
var MarkdownFileCache = class {
|
|
constructor(app) {
|
|
this.cachedFiles = [];
|
|
this.dirty = true;
|
|
this.app = app;
|
|
}
|
|
markDirty() {
|
|
this.dirty = true;
|
|
}
|
|
getFiles() {
|
|
if (this.dirty || this.cachedFiles.length === 0) {
|
|
this.cachedFiles = this.app.vault.getMarkdownFiles();
|
|
this.dirty = false;
|
|
}
|
|
return this.cachedFiles;
|
|
}
|
|
};
|
|
|
|
// src/ui/components/file-context/view/FileChipsView.ts
|
|
var import_obsidian3 = require("obsidian");
|
|
var FileChipsView = class {
|
|
constructor(containerEl, callbacks) {
|
|
this.containerEl = containerEl;
|
|
this.callbacks = callbacks;
|
|
const firstChild = this.containerEl.firstChild;
|
|
this.fileIndicatorEl = this.containerEl.createDiv({ cls: "claudian-file-indicator" });
|
|
if (firstChild) {
|
|
this.containerEl.insertBefore(this.fileIndicatorEl, firstChild);
|
|
}
|
|
}
|
|
destroy() {
|
|
this.fileIndicatorEl.remove();
|
|
}
|
|
/** Renders chip for the current/focus note only. */
|
|
renderCurrentNote(filePath) {
|
|
this.fileIndicatorEl.empty();
|
|
if (!filePath) {
|
|
this.fileIndicatorEl.style.display = "none";
|
|
return;
|
|
}
|
|
this.fileIndicatorEl.style.display = "flex";
|
|
this.renderFileChip(filePath, () => {
|
|
this.callbacks.onRemoveAttachment(filePath);
|
|
});
|
|
}
|
|
renderFileChip(filePath, onRemove) {
|
|
const chipEl = this.fileIndicatorEl.createDiv({ cls: "claudian-file-chip" });
|
|
const iconEl = chipEl.createSpan({ cls: "claudian-file-chip-icon" });
|
|
(0, import_obsidian3.setIcon)(iconEl, "file-text");
|
|
const normalizedPath = filePath.replace(/\\/g, "/");
|
|
const filename = normalizedPath.split("/").pop() || filePath;
|
|
const nameEl = chipEl.createSpan({ cls: "claudian-file-chip-name" });
|
|
nameEl.setText(filename);
|
|
nameEl.setAttribute("title", filePath);
|
|
const removeEl = chipEl.createSpan({ cls: "claudian-file-chip-remove" });
|
|
removeEl.setText("\xD7");
|
|
removeEl.setAttribute("aria-label", "Remove");
|
|
chipEl.addEventListener("click", (e) => {
|
|
if (!e.target.closest(".claudian-file-chip-remove")) {
|
|
this.callbacks.onOpenFile(filePath);
|
|
}
|
|
});
|
|
removeEl.addEventListener("click", () => {
|
|
onRemove();
|
|
});
|
|
}
|
|
};
|
|
|
|
// src/ui/components/FileContext.ts
|
|
var FileContextManager = class {
|
|
constructor(app, containerEl, inputEl, callbacks) {
|
|
this.deleteEventRef = null;
|
|
this.renameEventRef = null;
|
|
// Current note (shown as chip)
|
|
this.currentNotePath = null;
|
|
// MCP server support
|
|
this.mcpService = null;
|
|
this.onMcpMentionChange = null;
|
|
this.app = app;
|
|
this.containerEl = containerEl;
|
|
this.inputEl = inputEl;
|
|
this.callbacks = callbacks;
|
|
this.state = new FileContextState();
|
|
this.fileCache = new MarkdownFileCache(this.app);
|
|
this.chipsView = new FileChipsView(this.containerEl, {
|
|
onRemoveAttachment: (filePath) => {
|
|
if (filePath === this.currentNotePath) {
|
|
this.currentNotePath = null;
|
|
this.state.detachFile(filePath);
|
|
this.refreshCurrentNoteChip();
|
|
}
|
|
},
|
|
onOpenFile: async (filePath) => {
|
|
const file = this.app.vault.getAbstractFileByPath(filePath);
|
|
if (!(file instanceof import_obsidian4.TFile)) {
|
|
new import_obsidian4.Notice(`Could not open file: ${filePath}`);
|
|
return;
|
|
}
|
|
try {
|
|
await this.app.workspace.getLeaf().openFile(file);
|
|
} catch (error2) {
|
|
new import_obsidian4.Notice(`Failed to open file: ${error2 instanceof Error ? error2.message : String(error2)}`);
|
|
}
|
|
}
|
|
});
|
|
this.mentionDropdown = new MentionDropdownController(
|
|
this.containerEl,
|
|
this.inputEl,
|
|
{
|
|
onAttachFile: (filePath) => this.state.attachFile(filePath),
|
|
onMcpMentionChange: (servers) => {
|
|
var _a;
|
|
return (_a = this.onMcpMentionChange) == null ? void 0 : _a.call(this, servers);
|
|
},
|
|
getMentionedMcpServers: () => this.state.getMentionedMcpServers(),
|
|
setMentionedMcpServers: (mentions) => this.state.setMentionedMcpServers(mentions),
|
|
addMentionedMcpServer: (name) => this.state.addMentionedMcpServer(name),
|
|
getContextPaths: () => {
|
|
var _a, _b;
|
|
return ((_b = (_a = this.callbacks).getContextPaths) == null ? void 0 : _b.call(_a)) || [];
|
|
},
|
|
getCachedMarkdownFiles: () => this.fileCache.getFiles(),
|
|
normalizePathForVault: (rawPath) => this.normalizePathForVault(rawPath)
|
|
}
|
|
);
|
|
this.deleteEventRef = this.app.vault.on("delete", (file) => {
|
|
if (file instanceof import_obsidian4.TFile) this.handleFileDeleted(file.path);
|
|
});
|
|
this.renameEventRef = this.app.vault.on("rename", (file, oldPath) => {
|
|
if (file instanceof import_obsidian4.TFile) this.handleFileRenamed(oldPath, file.path);
|
|
});
|
|
}
|
|
/** Returns the current note path (shown as chip). */
|
|
getCurrentNotePath() {
|
|
return this.currentNotePath;
|
|
}
|
|
/** Checks whether current note should be sent for this session. */
|
|
shouldSendCurrentNote(notePath) {
|
|
const resolvedPath = notePath != null ? notePath : this.currentNotePath;
|
|
return !!resolvedPath && !this.state.hasSentCurrentNote();
|
|
}
|
|
/** Marks current note as sent (call after sending a message). */
|
|
markCurrentNoteSent() {
|
|
this.state.markCurrentNoteSent();
|
|
}
|
|
isSessionStarted() {
|
|
return this.state.isSessionStarted();
|
|
}
|
|
startSession() {
|
|
this.state.startSession();
|
|
}
|
|
/** Resets state for a new conversation. */
|
|
resetForNewConversation() {
|
|
this.currentNotePath = null;
|
|
this.state.resetForNewConversation();
|
|
this.refreshCurrentNoteChip();
|
|
}
|
|
/** Resets state for loading an existing conversation. */
|
|
resetForLoadedConversation(hasMessages) {
|
|
this.currentNotePath = null;
|
|
this.state.resetForLoadedConversation(hasMessages);
|
|
this.refreshCurrentNoteChip();
|
|
}
|
|
/** Sets current note (for restoring persisted state). */
|
|
setCurrentNote(notePath) {
|
|
this.currentNotePath = notePath;
|
|
if (notePath) {
|
|
this.state.attachFile(notePath);
|
|
}
|
|
this.refreshCurrentNoteChip();
|
|
}
|
|
/** Auto-attaches the currently focused file (for new sessions). */
|
|
autoAttachActiveFile() {
|
|
const activeFile = this.app.workspace.getActiveFile();
|
|
if (activeFile && !this.hasExcludedTag(activeFile)) {
|
|
const normalizedPath = this.normalizePathForVault(activeFile.path);
|
|
if (normalizedPath) {
|
|
this.currentNotePath = normalizedPath;
|
|
this.state.attachFile(normalizedPath);
|
|
this.refreshCurrentNoteChip();
|
|
}
|
|
}
|
|
}
|
|
/** Handles file open event. */
|
|
handleFileOpen(file) {
|
|
const normalizedPath = this.normalizePathForVault(file.path);
|
|
if (!normalizedPath) return;
|
|
if (!this.state.isSessionStarted()) {
|
|
this.state.clearAttachments();
|
|
if (!this.hasExcludedTag(file)) {
|
|
this.currentNotePath = normalizedPath;
|
|
this.state.attachFile(normalizedPath);
|
|
} else {
|
|
this.currentNotePath = null;
|
|
}
|
|
this.refreshCurrentNoteChip();
|
|
}
|
|
}
|
|
markFilesCacheDirty() {
|
|
this.fileCache.markDirty();
|
|
}
|
|
/** Handles input changes to detect @ mentions. */
|
|
handleInputChange() {
|
|
this.mentionDropdown.handleInputChange();
|
|
}
|
|
/** Handles keyboard navigation in mention dropdown. Returns true if handled. */
|
|
handleMentionKeydown(e) {
|
|
return this.mentionDropdown.handleKeydown(e);
|
|
}
|
|
isMentionDropdownVisible() {
|
|
return this.mentionDropdown.isVisible();
|
|
}
|
|
hideMentionDropdown() {
|
|
this.mentionDropdown.hide();
|
|
}
|
|
containsElement(el) {
|
|
return this.mentionDropdown.containsElement(el);
|
|
}
|
|
/** Cleans up event listeners (call on view close). */
|
|
destroy() {
|
|
if (this.deleteEventRef) this.app.vault.offref(this.deleteEventRef);
|
|
if (this.renameEventRef) this.app.vault.offref(this.renameEventRef);
|
|
this.mentionDropdown.destroy();
|
|
this.chipsView.destroy();
|
|
}
|
|
/** Normalizes a file path to be vault-relative with forward slashes. */
|
|
normalizePathForVault(rawPath) {
|
|
if (!rawPath) return null;
|
|
const normalizedRaw = normalizePathForFilesystem(rawPath);
|
|
const vaultPath = getVaultPath(this.app);
|
|
if (vaultPath && isPathWithinVault(normalizedRaw, vaultPath)) {
|
|
const absolute = path9.isAbsolute(normalizedRaw) ? normalizedRaw : path9.resolve(vaultPath, normalizedRaw);
|
|
const relative5 = path9.relative(vaultPath, absolute);
|
|
if (relative5) {
|
|
return relative5.replace(/\\/g, "/");
|
|
}
|
|
return null;
|
|
}
|
|
return normalizedRaw.replace(/\\/g, "/");
|
|
}
|
|
refreshCurrentNoteChip() {
|
|
var _a, _b;
|
|
this.chipsView.renderCurrentNote(this.currentNotePath);
|
|
(_b = (_a = this.callbacks).onChipsChanged) == null ? void 0 : _b.call(_a);
|
|
}
|
|
handleFileRenamed(oldPath, newPath) {
|
|
const normalizedOld = this.normalizePathForVault(oldPath);
|
|
const normalizedNew = this.normalizePathForVault(newPath);
|
|
if (!normalizedOld) return;
|
|
let needsUpdate = false;
|
|
if (this.currentNotePath === normalizedOld) {
|
|
this.currentNotePath = normalizedNew;
|
|
needsUpdate = true;
|
|
}
|
|
if (this.state.getAttachedFiles().has(normalizedOld)) {
|
|
this.state.detachFile(normalizedOld);
|
|
if (normalizedNew) {
|
|
this.state.attachFile(normalizedNew);
|
|
}
|
|
needsUpdate = true;
|
|
}
|
|
if (needsUpdate) {
|
|
this.refreshCurrentNoteChip();
|
|
}
|
|
}
|
|
handleFileDeleted(deletedPath) {
|
|
const normalized = this.normalizePathForVault(deletedPath);
|
|
if (!normalized) return;
|
|
let needsUpdate = false;
|
|
if (this.currentNotePath === normalized) {
|
|
this.currentNotePath = null;
|
|
needsUpdate = true;
|
|
}
|
|
if (this.state.getAttachedFiles().has(normalized)) {
|
|
this.state.detachFile(normalized);
|
|
needsUpdate = true;
|
|
}
|
|
if (needsUpdate) {
|
|
this.refreshCurrentNoteChip();
|
|
}
|
|
}
|
|
// ========================================
|
|
// MCP Server Support
|
|
// ========================================
|
|
/** Set the MCP service for @-mention autocomplete. */
|
|
setMcpService(service) {
|
|
this.mcpService = service;
|
|
this.mentionDropdown.setMcpService(service);
|
|
}
|
|
/** Set callback for when MCP mentions change (for McpServerSelector integration). */
|
|
setOnMcpMentionChange(callback) {
|
|
this.onMcpMentionChange = callback;
|
|
}
|
|
/**
|
|
* Pre-scans context paths in the background to warm the cache.
|
|
* Should be called when context paths are added/changed.
|
|
*/
|
|
preScanContextPaths() {
|
|
this.mentionDropdown.preScanContextPaths();
|
|
}
|
|
/** Get currently @-mentioned MCP servers. */
|
|
getMentionedMcpServers() {
|
|
return this.state.getMentionedMcpServers();
|
|
}
|
|
/** Clear MCP mentions (call on new conversation). */
|
|
clearMcpMentions() {
|
|
this.state.clearMcpMentions();
|
|
}
|
|
/** Update MCP mentions from input text. */
|
|
updateMcpMentionsFromText(text) {
|
|
this.mentionDropdown.updateMcpMentionsFromText(text);
|
|
}
|
|
hasExcludedTag(file) {
|
|
var _a;
|
|
const excludedTags = this.callbacks.getExcludedTags();
|
|
if (excludedTags.length === 0) return false;
|
|
const cache = this.app.metadataCache.getFileCache(file);
|
|
if (!cache) return false;
|
|
const fileTags = [];
|
|
if ((_a = cache.frontmatter) == null ? void 0 : _a.tags) {
|
|
const fmTags = cache.frontmatter.tags;
|
|
if (Array.isArray(fmTags)) {
|
|
fileTags.push(...fmTags.map((t) => t.replace(/^#/, "")));
|
|
} else if (typeof fmTags === "string") {
|
|
fileTags.push(fmTags.replace(/^#/, ""));
|
|
}
|
|
}
|
|
if (cache.tags) {
|
|
fileTags.push(...cache.tags.map((t) => t.tag.replace(/^#/, "")));
|
|
}
|
|
return fileTags.some((tag) => excludedTags.includes(tag));
|
|
}
|
|
};
|
|
|
|
// src/ui/components/ImageContext.ts
|
|
var fs8 = __toESM(require("fs"));
|
|
var import_obsidian5 = require("obsidian");
|
|
var path10 = __toESM(require("path"));
|
|
var MAX_IMAGE_SIZE = 5 * 1024 * 1024;
|
|
var IMAGE_EXTENSIONS = {
|
|
".jpg": "image/jpeg",
|
|
".jpeg": "image/jpeg",
|
|
".png": "image/png",
|
|
".gif": "image/gif",
|
|
".webp": "image/webp"
|
|
};
|
|
var ImageContextManager = class {
|
|
constructor(app, containerEl, inputEl, callbacks) {
|
|
this.dropOverlay = null;
|
|
this.attachedImages = /* @__PURE__ */ new Map();
|
|
this.app = app;
|
|
this.containerEl = containerEl;
|
|
this.inputEl = inputEl;
|
|
this.callbacks = callbacks;
|
|
const fileIndicator = this.containerEl.querySelector(".claudian-file-indicator");
|
|
this.imagePreviewEl = this.containerEl.createDiv({ cls: "claudian-image-preview" });
|
|
if (fileIndicator) {
|
|
this.containerEl.insertBefore(this.imagePreviewEl, fileIndicator);
|
|
}
|
|
this.setupDragAndDrop();
|
|
this.setupPasteHandler();
|
|
}
|
|
getAttachedImages() {
|
|
return Array.from(this.attachedImages.values());
|
|
}
|
|
hasImages() {
|
|
return this.attachedImages.size > 0;
|
|
}
|
|
clearImages() {
|
|
this.attachedImages.clear();
|
|
this.updateImagePreview();
|
|
this.callbacks.onImagesChanged();
|
|
}
|
|
/** Sets images directly (used for queued messages). */
|
|
setImages(images) {
|
|
this.attachedImages.clear();
|
|
for (const image of images) {
|
|
this.attachedImages.set(image.id, image);
|
|
}
|
|
this.updateImagePreview();
|
|
this.callbacks.onImagesChanged();
|
|
}
|
|
/** Adds an image from a file path. Returns true if successful. */
|
|
async addImageFromPath(imagePath) {
|
|
try {
|
|
const result = await this.loadImageFromPath(imagePath);
|
|
if (result) {
|
|
this.attachedImages.set(result.id, result);
|
|
this.updateImagePreview();
|
|
this.callbacks.onImagesChanged();
|
|
return true;
|
|
}
|
|
this.notifyImageError(`Unable to load image from path: ${imagePath}`);
|
|
} catch (error2) {
|
|
this.notifyImageError(`Failed to load image from path: ${imagePath}`, error2);
|
|
}
|
|
return false;
|
|
}
|
|
/** Extracts an image path from text if present. */
|
|
extractImagePath(text) {
|
|
const info = this.extractImagePathInfo(text);
|
|
return info ? info.normalized : null;
|
|
}
|
|
/** Handles potential image path in message text. Returns cleaned text if image was loaded. */
|
|
async handleImagePathInText(text) {
|
|
const info = this.extractImagePathInfo(text);
|
|
if (!info) {
|
|
return { text, imageLoaded: false };
|
|
}
|
|
const loaded = await this.addImageFromPath(info.normalized);
|
|
if (loaded) {
|
|
const cleanedText = text.replace(info.raw, "").replace(info.normalized, "").replace(/["']\s*["']/g, "").trim();
|
|
return { text: cleanedText, imageLoaded: true };
|
|
}
|
|
return { text, imageLoaded: false };
|
|
}
|
|
extractImagePathInfo(text) {
|
|
const markdownMatch = text.match(/!\[[^\]]*]\(([^)]+)\)/);
|
|
if (markdownMatch && markdownMatch[1]) {
|
|
const markdownCandidate = this.extractMarkdownImagePath(text);
|
|
const normalizedMarkdown = this.normalizeCandidatePath(markdownCandidate);
|
|
if (normalizedMarkdown) {
|
|
return { raw: markdownMatch[1], normalized: normalizedMarkdown };
|
|
}
|
|
}
|
|
const htmlCandidate = this.extractHtmlImagePath(text);
|
|
const normalizedHtml = this.normalizeCandidatePath(htmlCandidate);
|
|
if (htmlCandidate && normalizedHtml) {
|
|
return { raw: htmlCandidate, normalized: normalizedHtml };
|
|
}
|
|
const fileUrlPattern = /file:\/\/[^\s"'<>()[\]]+/gi;
|
|
let sanitizedText = text;
|
|
const fileMatches = text.match(fileUrlPattern) || [];
|
|
for (const raw of fileMatches) {
|
|
const normalized = this.normalizeCandidatePath(raw);
|
|
if (normalized) {
|
|
return { raw, normalized };
|
|
}
|
|
sanitizedText = sanitizedText.replace(raw, " ");
|
|
}
|
|
const tokenPattern = /[^\s"'<>()[\]]+?\.(?:jpe?g|png|gif|webp)\b/gi;
|
|
const matches = sanitizedText.match(tokenPattern) || [];
|
|
for (const raw of matches) {
|
|
const normalized = this.normalizeCandidatePath(raw);
|
|
if (normalized) {
|
|
return { raw, normalized };
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
setupDragAndDrop() {
|
|
const inputWrapper = this.containerEl.querySelector(".claudian-input-wrapper");
|
|
if (!inputWrapper) return;
|
|
this.dropOverlay = inputWrapper.createDiv({ cls: "claudian-drop-overlay" });
|
|
const dropContent = this.dropOverlay.createDiv({ cls: "claudian-drop-content" });
|
|
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
|
|
svg.setAttribute("viewBox", "0 0 24 24");
|
|
svg.setAttribute("width", "32");
|
|
svg.setAttribute("height", "32");
|
|
svg.setAttribute("fill", "none");
|
|
svg.setAttribute("stroke", "currentColor");
|
|
svg.setAttribute("stroke-width", "2");
|
|
const pathEl = document.createElementNS("http://www.w3.org/2000/svg", "path");
|
|
pathEl.setAttribute("d", "M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4");
|
|
const polyline = document.createElementNS("http://www.w3.org/2000/svg", "polyline");
|
|
polyline.setAttribute("points", "17 8 12 3 7 8");
|
|
const line = document.createElementNS("http://www.w3.org/2000/svg", "line");
|
|
line.setAttribute("x1", "12");
|
|
line.setAttribute("y1", "3");
|
|
line.setAttribute("x2", "12");
|
|
line.setAttribute("y2", "15");
|
|
svg.appendChild(pathEl);
|
|
svg.appendChild(polyline);
|
|
svg.appendChild(line);
|
|
dropContent.appendChild(svg);
|
|
dropContent.createSpan({ text: "Drop image here" });
|
|
const dropZone = inputWrapper;
|
|
dropZone.addEventListener("dragenter", (e) => this.handleDragEnter(e));
|
|
dropZone.addEventListener("dragover", (e) => this.handleDragOver(e));
|
|
dropZone.addEventListener("dragleave", (e) => this.handleDragLeave(e));
|
|
dropZone.addEventListener("drop", (e) => this.handleDrop(e));
|
|
}
|
|
handleDragEnter(e) {
|
|
var _a, _b;
|
|
e.preventDefault();
|
|
e.stopPropagation();
|
|
if ((_a = e.dataTransfer) == null ? void 0 : _a.types.includes("Files")) {
|
|
(_b = this.dropOverlay) == null ? void 0 : _b.addClass("visible");
|
|
}
|
|
}
|
|
handleDragOver(e) {
|
|
e.preventDefault();
|
|
e.stopPropagation();
|
|
}
|
|
handleDragLeave(e) {
|
|
var _a, _b;
|
|
e.preventDefault();
|
|
e.stopPropagation();
|
|
const inputWrapper = this.containerEl.querySelector(".claudian-input-wrapper");
|
|
if (!inputWrapper) {
|
|
(_a = this.dropOverlay) == null ? void 0 : _a.removeClass("visible");
|
|
return;
|
|
}
|
|
const rect = inputWrapper.getBoundingClientRect();
|
|
if (e.clientX <= rect.left || e.clientX >= rect.right || e.clientY <= rect.top || e.clientY >= rect.bottom) {
|
|
(_b = this.dropOverlay) == null ? void 0 : _b.removeClass("visible");
|
|
}
|
|
}
|
|
async handleDrop(e) {
|
|
var _a, _b;
|
|
e.preventDefault();
|
|
e.stopPropagation();
|
|
(_a = this.dropOverlay) == null ? void 0 : _a.removeClass("visible");
|
|
const files = (_b = e.dataTransfer) == null ? void 0 : _b.files;
|
|
if (!files) return;
|
|
for (let i = 0; i < files.length; i++) {
|
|
const file = files[i];
|
|
if (this.isImageFile(file)) {
|
|
await this.addImageFromFile(file, "drop");
|
|
}
|
|
}
|
|
}
|
|
setupPasteHandler() {
|
|
this.inputEl.addEventListener("paste", async (e) => {
|
|
var _a;
|
|
const items = (_a = e.clipboardData) == null ? void 0 : _a.items;
|
|
if (!items) return;
|
|
for (let i = 0; i < items.length; i++) {
|
|
const item = items[i];
|
|
if (item.type.startsWith("image/")) {
|
|
e.preventDefault();
|
|
const file = item.getAsFile();
|
|
if (file) {
|
|
await this.addImageFromFile(file, "paste");
|
|
}
|
|
return;
|
|
}
|
|
}
|
|
});
|
|
}
|
|
isImageFile(file) {
|
|
return file.type.startsWith("image/") && this.getMediaType(file.name) !== null;
|
|
}
|
|
getMediaType(filename) {
|
|
const ext = path10.extname(filename).toLowerCase();
|
|
return IMAGE_EXTENSIONS[ext] || null;
|
|
}
|
|
async addImageFromFile(file, source) {
|
|
if (file.size > MAX_IMAGE_SIZE) {
|
|
this.notifyImageError(`Image exceeds ${this.formatSize(MAX_IMAGE_SIZE)} limit.`);
|
|
return false;
|
|
}
|
|
const mediaType = this.getMediaType(file.name) || file.type;
|
|
if (!mediaType) {
|
|
this.notifyImageError("Unsupported image type.");
|
|
return false;
|
|
}
|
|
try {
|
|
const { buffer, base64: base642 } = await this.fileToBufferAndBase64(file);
|
|
const cacheEntry = saveImageToCache(this.app, buffer, mediaType, file.name);
|
|
if (!cacheEntry) {
|
|
this.notifyImageError("Failed to save image to cache.");
|
|
return false;
|
|
}
|
|
const attachment = {
|
|
id: this.generateId(),
|
|
name: file.name || `image-${Date.now()}.${mediaType.split("/")[1]}`,
|
|
mediaType,
|
|
data: base642,
|
|
cachePath: cacheEntry.relPath,
|
|
size: file.size,
|
|
source
|
|
};
|
|
this.attachedImages.set(attachment.id, attachment);
|
|
this.updateImagePreview();
|
|
this.callbacks.onImagesChanged();
|
|
return true;
|
|
} catch (error2) {
|
|
this.notifyImageError("Failed to attach image.", error2);
|
|
return false;
|
|
}
|
|
}
|
|
async loadImageFromPath(imagePath) {
|
|
var _a, _b;
|
|
const mediaType = this.getMediaType(imagePath);
|
|
if (!mediaType) {
|
|
return null;
|
|
}
|
|
const normalizedInput = normalizePathForFilesystem(imagePath);
|
|
let fullPath = normalizedInput;
|
|
const vaultPath = getVaultPath(this.app);
|
|
const mediaFolder = this.callbacks.getMediaFolder ? this.callbacks.getMediaFolder().trim() : void 0;
|
|
if (!path10.isAbsolute(normalizedInput)) {
|
|
const candidates = [];
|
|
if (vaultPath) {
|
|
candidates.push(path10.join(vaultPath, normalizedInput));
|
|
if (mediaFolder) {
|
|
candidates.push(path10.join(vaultPath, mediaFolder, normalizedInput));
|
|
}
|
|
}
|
|
const foundPath = candidates.find((p) => fs8.existsSync(p));
|
|
if (foundPath) {
|
|
fullPath = foundPath;
|
|
}
|
|
}
|
|
if (!fs8.existsSync(fullPath)) {
|
|
const normalizedMediaFolder = mediaFolder == null ? void 0 : mediaFolder.replace(/\\/g, "/").replace(/^\/+|\/+$/g, "");
|
|
const vaultRelativePath = normalizedInput.replace(/\\/g, "/");
|
|
const vaultPaths = [
|
|
vaultRelativePath,
|
|
normalizedMediaFolder ? `${normalizedMediaFolder}/${vaultRelativePath}` : null
|
|
].filter(Boolean);
|
|
for (const vaultRelativePath2 of vaultPaths) {
|
|
const file = this.app.vault.getAbstractFileByPath(vaultRelativePath2);
|
|
if (file instanceof import_obsidian5.TFile) {
|
|
const fileSize = (_b = (_a = file.stat) == null ? void 0 : _a.size) != null ? _b : 0;
|
|
if (fileSize > MAX_IMAGE_SIZE) {
|
|
return null;
|
|
}
|
|
const arrayBuffer = await this.app.vault.readBinary(file);
|
|
const base643 = this.arrayBufferToBase64(arrayBuffer);
|
|
return {
|
|
id: this.generateId(),
|
|
name: file.name,
|
|
mediaType,
|
|
data: base643,
|
|
filePath: file.path,
|
|
size: arrayBuffer.byteLength,
|
|
source: "file"
|
|
};
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
const stats = fs8.statSync(fullPath);
|
|
if (stats.size > MAX_IMAGE_SIZE) {
|
|
return null;
|
|
}
|
|
const buffer = fs8.readFileSync(fullPath);
|
|
const base642 = buffer.toString("base64");
|
|
const storedPath = this.getStoredFilePath(fullPath, vaultPath);
|
|
return {
|
|
id: this.generateId(),
|
|
name: path10.basename(fullPath),
|
|
mediaType,
|
|
data: base642,
|
|
filePath: storedPath,
|
|
size: stats.size,
|
|
source: "file"
|
|
};
|
|
}
|
|
async fileToBufferAndBase64(file) {
|
|
const arrayBuffer = await file.arrayBuffer();
|
|
const buffer = Buffer.from(arrayBuffer);
|
|
return {
|
|
buffer,
|
|
base64: buffer.toString("base64")
|
|
};
|
|
}
|
|
arrayBufferToBase64(buffer) {
|
|
const bytes = new Uint8Array(buffer);
|
|
let binary = "";
|
|
for (let i = 0; i < bytes.byteLength; i++) {
|
|
binary += String.fromCharCode(bytes[i]);
|
|
}
|
|
return btoa(binary);
|
|
}
|
|
// ============================================
|
|
// Private: Image Preview
|
|
// ============================================
|
|
updateImagePreview() {
|
|
this.imagePreviewEl.empty();
|
|
if (this.attachedImages.size === 0) {
|
|
this.imagePreviewEl.style.display = "none";
|
|
return;
|
|
}
|
|
this.imagePreviewEl.style.display = "flex";
|
|
for (const [id, image] of this.attachedImages) {
|
|
this.renderImagePreview(id, image);
|
|
}
|
|
}
|
|
renderImagePreview(id, image) {
|
|
const previewEl = this.imagePreviewEl.createDiv({ cls: "claudian-image-chip" });
|
|
const thumbEl = previewEl.createDiv({ cls: "claudian-image-thumb" });
|
|
thumbEl.createEl("img", {
|
|
attr: {
|
|
src: `data:${image.mediaType};base64,${image.data}`,
|
|
alt: image.name
|
|
}
|
|
});
|
|
const infoEl = previewEl.createDiv({ cls: "claudian-image-info" });
|
|
const nameEl = infoEl.createSpan({ cls: "claudian-image-name" });
|
|
nameEl.setText(this.truncateName(image.name, 20));
|
|
nameEl.setAttribute("title", image.name);
|
|
const sizeEl = infoEl.createSpan({ cls: "claudian-image-size" });
|
|
sizeEl.setText(this.formatSize(image.size));
|
|
const removeEl = previewEl.createSpan({ cls: "claudian-image-remove" });
|
|
removeEl.setText("\xD7");
|
|
removeEl.setAttribute("aria-label", "Remove image");
|
|
removeEl.addEventListener("click", (e) => {
|
|
e.stopPropagation();
|
|
this.attachedImages.delete(id);
|
|
this.updateImagePreview();
|
|
this.callbacks.onImagesChanged();
|
|
});
|
|
thumbEl.addEventListener("click", () => {
|
|
this.showFullImage(image);
|
|
});
|
|
}
|
|
showFullImage(image) {
|
|
const overlay = document.body.createDiv({ cls: "claudian-image-modal-overlay" });
|
|
const modal = overlay.createDiv({ cls: "claudian-image-modal" });
|
|
modal.createEl("img", {
|
|
attr: {
|
|
src: `data:${image.mediaType};base64,${image.data}`,
|
|
alt: image.name
|
|
}
|
|
});
|
|
const closeBtn = modal.createDiv({ cls: "claudian-image-modal-close" });
|
|
closeBtn.setText("\xD7");
|
|
const handleEsc = (e) => {
|
|
if (e.key === "Escape") {
|
|
close();
|
|
}
|
|
};
|
|
const close = () => {
|
|
document.removeEventListener("keydown", handleEsc);
|
|
overlay.remove();
|
|
};
|
|
closeBtn.addEventListener("click", close);
|
|
overlay.addEventListener("click", (e) => {
|
|
if (e.target === overlay) close();
|
|
});
|
|
document.addEventListener("keydown", handleEsc);
|
|
}
|
|
generateId() {
|
|
return `img-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;
|
|
}
|
|
truncateName(name, maxLen) {
|
|
if (name.length <= maxLen) return name;
|
|
const ext = path10.extname(name);
|
|
const base = name.slice(0, name.length - ext.length);
|
|
const truncatedBase = base.slice(0, maxLen - ext.length - 3);
|
|
return `${truncatedBase}...${ext}`;
|
|
}
|
|
formatSize(bytes) {
|
|
if (bytes < 1024) return `${bytes} B`;
|
|
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
|
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
|
}
|
|
cleanImagePathToken(token) {
|
|
let cleaned = token.trim();
|
|
cleaned = cleaned.replace(/^["'`]+|["'`]+$/g, "");
|
|
cleaned = cleaned.replace(/^!\[[^\]]*]\(/, "");
|
|
cleaned = cleaned.replace(/^[[(<]+/, "");
|
|
cleaned = cleaned.replace(/[)\],.;>]+$/g, "");
|
|
return cleaned || null;
|
|
}
|
|
normalizeCandidatePath(candidate) {
|
|
if (!candidate) return null;
|
|
const cleaned = this.cleanImagePathToken(candidate);
|
|
if (!cleaned) return null;
|
|
if (/^file:\/\//i.test(cleaned)) {
|
|
return this.parseFileUrlToPath(cleaned);
|
|
}
|
|
if (/^https?:\/\//i.test(cleaned)) {
|
|
return null;
|
|
}
|
|
if (cleaned.includes("../") || cleaned.includes("..\\")) {
|
|
return null;
|
|
}
|
|
return cleaned;
|
|
}
|
|
extractMarkdownImagePath(text) {
|
|
var _a, _b;
|
|
const match = text.match(/!\[[^\]]*]\(([^)]+)\)/);
|
|
if (!match) return null;
|
|
let inside = match[1].trim();
|
|
if (inside.startsWith("<") && inside.endsWith(">")) {
|
|
inside = inside.slice(1, -1).trim();
|
|
}
|
|
const quoted = inside.match(/^"([^"]+)"|^'([^']+)'/);
|
|
if (quoted) {
|
|
inside = (_b = (_a = quoted[1]) != null ? _a : quoted[2]) != null ? _b : inside;
|
|
}
|
|
if (/\s/.test(inside)) {
|
|
inside = inside.split(/\s+/)[0];
|
|
}
|
|
return inside || null;
|
|
}
|
|
extractHtmlImagePath(text) {
|
|
var _a, _b, _c;
|
|
const match = text.match(/<img[^>]+src\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s>]+))/i);
|
|
if (!match) return null;
|
|
return (_c = (_b = (_a = match[1]) != null ? _a : match[2]) != null ? _b : match[3]) != null ? _c : null;
|
|
}
|
|
parseFileUrlToPath(value) {
|
|
try {
|
|
const url = new URL(value);
|
|
if (url.protocol !== "file:") return null;
|
|
const host = url.hostname;
|
|
const hostLower = host.toLowerCase();
|
|
const isLocalHost = hostLower === "" || hostLower === "localhost" || hostLower === "127.0.0.1" || hostLower === "::1";
|
|
let pathname = decodeURIComponent(url.pathname || "");
|
|
if (!pathname) return null;
|
|
if (isLocalHost && /^\/[a-zA-Z]:\//.test(pathname)) {
|
|
pathname = pathname.slice(1);
|
|
return pathname.replace(/\//g, "\\");
|
|
}
|
|
if (/^[a-zA-Z]:$/.test(host)) {
|
|
const combined = `${host}${pathname}`;
|
|
return combined.replace(/\//g, "\\");
|
|
}
|
|
if (!isLocalHost && host) {
|
|
return `\\\\${host}${pathname.replace(/\//g, "\\")}`;
|
|
}
|
|
return pathname;
|
|
} catch (error2) {
|
|
console.warn("Failed to parse file URL:", value, error2);
|
|
return null;
|
|
}
|
|
}
|
|
notifyImageError(message, error2) {
|
|
if (error2) {
|
|
console.error(message, error2);
|
|
} else {
|
|
console.warn(message);
|
|
}
|
|
let userMessage = message;
|
|
if (error2 instanceof Error) {
|
|
if (error2.message.includes("ENOENT") || error2.message.includes("no such file")) {
|
|
userMessage = `${message} (File not found)`;
|
|
} else if (error2.message.includes("EACCES") || error2.message.includes("permission denied")) {
|
|
userMessage = `${message} (Permission denied)`;
|
|
}
|
|
}
|
|
new import_obsidian5.Notice(userMessage);
|
|
}
|
|
getStoredFilePath(fullPath, vaultPath) {
|
|
const normalizedFull = normalizePathForFilesystem(fullPath);
|
|
if (vaultPath && isPathWithinVault(normalizedFull, vaultPath)) {
|
|
const absolute = path10.isAbsolute(normalizedFull) ? normalizedFull : path10.resolve(vaultPath, normalizedFull);
|
|
const relative5 = path10.relative(vaultPath, absolute);
|
|
return relative5.replace(/\\/g, "/");
|
|
}
|
|
return normalizedFull;
|
|
}
|
|
};
|
|
|
|
// src/ui/components/InputToolbar.ts
|
|
var import_obsidian6 = require("obsidian");
|
|
var ModelSelector = class {
|
|
constructor(parentEl, callbacks) {
|
|
this.buttonEl = null;
|
|
this.dropdownEl = null;
|
|
this.callbacks = callbacks;
|
|
this.container = parentEl.createDiv({ cls: "claudian-model-selector" });
|
|
this.render();
|
|
}
|
|
/** Returns available models (custom from env vars, or defaults). */
|
|
getAvailableModels() {
|
|
let models = [];
|
|
if (this.callbacks.getEnvironmentVariables) {
|
|
const envVarsStr = this.callbacks.getEnvironmentVariables();
|
|
const envVars = parseEnvironmentVariables(envVarsStr);
|
|
const customModels = getModelsFromEnvironment(envVars);
|
|
if (customModels.length > 0) {
|
|
models = customModels;
|
|
} else {
|
|
models = [...DEFAULT_CLAUDE_MODELS];
|
|
}
|
|
} else {
|
|
models = [...DEFAULT_CLAUDE_MODELS];
|
|
}
|
|
return models;
|
|
}
|
|
render() {
|
|
this.container.empty();
|
|
this.buttonEl = this.container.createDiv({ cls: "claudian-model-btn" });
|
|
this.updateDisplay();
|
|
this.dropdownEl = this.container.createDiv({ cls: "claudian-model-dropdown" });
|
|
this.renderOptions();
|
|
}
|
|
updateDisplay() {
|
|
if (!this.buttonEl) return;
|
|
const currentModel = this.callbacks.getSettings().model;
|
|
const models = this.getAvailableModels();
|
|
const modelInfo = models.find((m) => m.value === currentModel);
|
|
const displayModel = modelInfo || models[0];
|
|
this.buttonEl.empty();
|
|
const labelEl = this.buttonEl.createSpan({ cls: "claudian-model-label" });
|
|
labelEl.setText((displayModel == null ? void 0 : displayModel.label) || "Unknown");
|
|
}
|
|
renderOptions() {
|
|
if (!this.dropdownEl) return;
|
|
this.dropdownEl.empty();
|
|
const currentModel = this.callbacks.getSettings().model;
|
|
const models = this.getAvailableModels();
|
|
for (const model of [...models].reverse()) {
|
|
const option = this.dropdownEl.createDiv({ cls: "claudian-model-option" });
|
|
if (model.value === currentModel) {
|
|
option.addClass("selected");
|
|
}
|
|
option.createSpan({ text: model.label });
|
|
if (model.description) {
|
|
option.setAttribute("title", model.description);
|
|
}
|
|
option.addEventListener("click", async (e) => {
|
|
e.stopPropagation();
|
|
await this.callbacks.onModelChange(model.value);
|
|
this.updateDisplay();
|
|
this.renderOptions();
|
|
});
|
|
}
|
|
}
|
|
};
|
|
var ThinkingBudgetSelector = class {
|
|
constructor(parentEl, callbacks) {
|
|
this.gearsEl = null;
|
|
this.callbacks = callbacks;
|
|
this.container = parentEl.createDiv({ cls: "claudian-thinking-selector" });
|
|
this.render();
|
|
}
|
|
render() {
|
|
this.container.empty();
|
|
const labelEl = this.container.createSpan({ cls: "claudian-thinking-label-text" });
|
|
labelEl.setText("Thinking:");
|
|
this.gearsEl = this.container.createDiv({ cls: "claudian-thinking-gears" });
|
|
this.renderGears();
|
|
}
|
|
renderGears() {
|
|
if (!this.gearsEl) return;
|
|
this.gearsEl.empty();
|
|
const currentBudget = this.callbacks.getSettings().thinkingBudget;
|
|
const currentBudgetInfo = THINKING_BUDGETS.find((b) => b.value === currentBudget);
|
|
const currentEl = this.gearsEl.createDiv({ cls: "claudian-thinking-current" });
|
|
currentEl.setText((currentBudgetInfo == null ? void 0 : currentBudgetInfo.label) || "Off");
|
|
const optionsEl = this.gearsEl.createDiv({ cls: "claudian-thinking-options" });
|
|
for (const budget of [...THINKING_BUDGETS].reverse()) {
|
|
const gearEl = optionsEl.createDiv({ cls: "claudian-thinking-gear" });
|
|
gearEl.setText(budget.label);
|
|
gearEl.setAttribute("title", budget.tokens > 0 ? `${budget.tokens.toLocaleString()} tokens` : "Disabled");
|
|
if (budget.value === currentBudget) {
|
|
gearEl.addClass("selected");
|
|
}
|
|
gearEl.addEventListener("click", async (e) => {
|
|
e.stopPropagation();
|
|
await this.callbacks.onThinkingBudgetChange(budget.value);
|
|
this.updateDisplay();
|
|
});
|
|
}
|
|
}
|
|
updateDisplay() {
|
|
this.renderGears();
|
|
}
|
|
};
|
|
var PermissionToggle = class {
|
|
constructor(parentEl, callbacks) {
|
|
this.toggleEl = null;
|
|
this.labelEl = null;
|
|
this.onPlanModeToggle = null;
|
|
this.callbacks = callbacks;
|
|
this.container = parentEl.createDiv({ cls: "claudian-permission-toggle" });
|
|
this.render();
|
|
}
|
|
render() {
|
|
this.container.empty();
|
|
this.labelEl = this.container.createSpan({ cls: "claudian-permission-label" });
|
|
this.toggleEl = this.container.createDiv({ cls: "claudian-toggle-switch" });
|
|
this.updateDisplay();
|
|
this.toggleEl.addEventListener("click", () => this.toggle());
|
|
this.container.addEventListener("click", (e) => {
|
|
if (this.isPlanModeLocked() && e.target !== this.toggleEl) {
|
|
new import_obsidian6.Notice("Plan mode is active until the plan is approved.");
|
|
}
|
|
});
|
|
}
|
|
/** Set callback for plan mode toggle. */
|
|
setOnPlanModeToggle(callback) {
|
|
this.onPlanModeToggle = callback;
|
|
}
|
|
/** Set plan mode active state. */
|
|
setPlanModeActive(_active) {
|
|
this.updateDisplay();
|
|
}
|
|
/** Check if plan mode is active. */
|
|
isPlanModeActive() {
|
|
return this.isPlanModeLocked() || this.isPlanModeRequested();
|
|
}
|
|
isPlanModeLocked() {
|
|
return this.callbacks.getSettings().permissionMode === "plan";
|
|
}
|
|
isPlanModeRequested() {
|
|
var _a, _b, _c;
|
|
return (_c = (_b = (_a = this.callbacks).isPlanModeRequested) == null ? void 0 : _b.call(_a)) != null ? _c : false;
|
|
}
|
|
updateDisplay() {
|
|
if (!this.toggleEl || !this.labelEl) return;
|
|
if (this.isPlanModeActive()) {
|
|
this.toggleEl.removeClass("active");
|
|
this.container.addClass("plan-mode");
|
|
this.labelEl.empty();
|
|
const iconEl = this.labelEl.createSpan({ cls: "claudian-plan-mode-icon" });
|
|
iconEl.textContent = "\u258E\u258E";
|
|
iconEl.style.fontSize = "0.8em";
|
|
iconEl.style.letterSpacing = "-4px";
|
|
this.labelEl.createSpan({ text: "Plan Mode" });
|
|
return;
|
|
}
|
|
this.container.removeClass("plan-mode");
|
|
const isYolo = this.callbacks.getSettings().permissionMode === "yolo";
|
|
if (isYolo) {
|
|
this.toggleEl.addClass("active");
|
|
} else {
|
|
this.toggleEl.removeClass("active");
|
|
}
|
|
this.labelEl.setText(isYolo ? "YOLO" : "Safe");
|
|
}
|
|
async toggle() {
|
|
if (this.isPlanModeLocked()) {
|
|
new import_obsidian6.Notice("Plan mode is active until the plan is approved.");
|
|
return;
|
|
}
|
|
const current = this.callbacks.getSettings().permissionMode;
|
|
const newMode = current === "yolo" ? "normal" : "yolo";
|
|
await this.callbacks.onPermissionModeChange(newMode);
|
|
this.updateDisplay();
|
|
}
|
|
/** Toggle plan mode on/off. */
|
|
async togglePlanMode() {
|
|
var _a;
|
|
if (this.isPlanModeLocked()) {
|
|
new import_obsidian6.Notice("Plan mode is active until the plan is approved.");
|
|
return;
|
|
}
|
|
const nextRequested = !this.isPlanModeRequested();
|
|
(_a = this.onPlanModeToggle) == null ? void 0 : _a.call(this, nextRequested);
|
|
this.updateDisplay();
|
|
}
|
|
};
|
|
var ContextPathSelector = class {
|
|
constructor(parentEl, callbacks) {
|
|
this.iconEl = null;
|
|
this.badgeEl = null;
|
|
this.dropdownEl = null;
|
|
/** Session-specific context paths (resets on new conversation). */
|
|
this.sessionContextPaths = [];
|
|
this.onChangeCallback = null;
|
|
this.callbacks = callbacks;
|
|
this.container = parentEl.createDiv({ cls: "claudian-context-path-selector" });
|
|
this.render();
|
|
}
|
|
/** Set callback for when context paths change. */
|
|
setOnChange(callback) {
|
|
this.onChangeCallback = callback;
|
|
}
|
|
/** Get current session context paths. */
|
|
getContextPaths() {
|
|
return [...this.sessionContextPaths];
|
|
}
|
|
/** Set session context paths (for restoring from conversation). */
|
|
setContextPaths(paths) {
|
|
this.sessionContextPaths = [...paths];
|
|
this.updateDisplay();
|
|
this.renderDropdown();
|
|
}
|
|
/** Clear session context paths (call on new conversation). */
|
|
clearContextPaths() {
|
|
this.sessionContextPaths = [];
|
|
this.updateDisplay();
|
|
this.renderDropdown();
|
|
}
|
|
render() {
|
|
this.container.empty();
|
|
const iconWrapper = this.container.createDiv({ cls: "claudian-context-path-icon-wrapper" });
|
|
this.iconEl = iconWrapper.createDiv({ cls: "claudian-context-path-icon" });
|
|
(0, import_obsidian6.setIcon)(this.iconEl, "folder");
|
|
this.badgeEl = iconWrapper.createDiv({ cls: "claudian-context-path-badge" });
|
|
this.updateDisplay();
|
|
iconWrapper.addEventListener("click", (e) => {
|
|
e.stopPropagation();
|
|
this.openFolderPicker();
|
|
});
|
|
this.dropdownEl = this.container.createDiv({ cls: "claudian-context-path-dropdown" });
|
|
this.renderDropdown();
|
|
}
|
|
async openFolderPicker() {
|
|
var _a;
|
|
try {
|
|
const { remote } = require("electron");
|
|
const result = await remote.dialog.showOpenDialog({
|
|
properties: ["openDirectory"],
|
|
title: "Select Context Path (Read-Only)"
|
|
});
|
|
if (!result.canceled && result.filePaths.length > 0) {
|
|
const selectedPath = result.filePaths[0];
|
|
if (this.sessionContextPaths.includes(selectedPath)) {
|
|
return;
|
|
}
|
|
const conflict = findConflictingPath(selectedPath, this.sessionContextPaths);
|
|
if (conflict) {
|
|
this.showConflictNotice(selectedPath, conflict);
|
|
return;
|
|
}
|
|
this.sessionContextPaths = [...this.sessionContextPaths, selectedPath];
|
|
(_a = this.onChangeCallback) == null ? void 0 : _a.call(this, this.sessionContextPaths);
|
|
this.updateDisplay();
|
|
this.renderDropdown();
|
|
}
|
|
} catch (err) {
|
|
console.error("Failed to open folder picker:", err);
|
|
}
|
|
}
|
|
/** Shows a notice when a conflicting path is detected. */
|
|
showConflictNotice(newPath, conflict) {
|
|
const shortNew = this.shortenPath(newPath);
|
|
const shortExisting = this.shortenPath(conflict.path);
|
|
let message;
|
|
if (conflict.type === "parent") {
|
|
message = `Cannot add "${shortNew}" - it's inside existing path "${shortExisting}"`;
|
|
} else {
|
|
message = `Cannot add "${shortNew}" - it contains existing path "${shortExisting}"`;
|
|
}
|
|
new import_obsidian6.Notice(message, 5e3);
|
|
}
|
|
renderDropdown() {
|
|
if (!this.dropdownEl) return;
|
|
this.dropdownEl.empty();
|
|
const headerEl = this.dropdownEl.createDiv({ cls: "claudian-context-path-header" });
|
|
headerEl.setText("Context Paths (Read-Only)");
|
|
const listEl = this.dropdownEl.createDiv({ cls: "claudian-context-path-list" });
|
|
if (this.sessionContextPaths.length === 0) {
|
|
const emptyEl = listEl.createDiv({ cls: "claudian-context-path-empty" });
|
|
emptyEl.setText("Click folder icon to add");
|
|
} else {
|
|
for (const pathStr of this.sessionContextPaths) {
|
|
const itemEl = listEl.createDiv({ cls: "claudian-context-path-item" });
|
|
const pathTextEl = itemEl.createSpan({ cls: "claudian-context-path-text" });
|
|
const displayPath = this.shortenPath(pathStr);
|
|
pathTextEl.setText(displayPath);
|
|
pathTextEl.setAttribute("title", pathStr);
|
|
const removeBtn = itemEl.createSpan({ cls: "claudian-context-path-remove" });
|
|
(0, import_obsidian6.setIcon)(removeBtn, "x");
|
|
removeBtn.setAttribute("title", "Remove path");
|
|
removeBtn.addEventListener("click", (e) => {
|
|
var _a;
|
|
e.stopPropagation();
|
|
this.sessionContextPaths = this.sessionContextPaths.filter((p) => p !== pathStr);
|
|
(_a = this.onChangeCallback) == null ? void 0 : _a.call(this, this.sessionContextPaths);
|
|
this.updateDisplay();
|
|
this.renderDropdown();
|
|
});
|
|
}
|
|
}
|
|
}
|
|
/** Shorten path for display (replace home dir with ~) */
|
|
shortenPath(fullPath) {
|
|
try {
|
|
const os3 = require("os");
|
|
const homeDir = os3.homedir();
|
|
const normalize2 = (value) => value.replace(/\\/g, "/");
|
|
const normalizedFull = normalize2(fullPath);
|
|
const normalizedHome = normalize2(homeDir);
|
|
const compareFull = process.platform === "win32" ? normalizedFull.toLowerCase() : normalizedFull;
|
|
const compareHome = process.platform === "win32" ? normalizedHome.toLowerCase() : normalizedHome;
|
|
if (compareFull.startsWith(compareHome)) {
|
|
return "~" + fullPath.slice(homeDir.length);
|
|
}
|
|
} catch (e) {
|
|
}
|
|
return fullPath;
|
|
}
|
|
updateDisplay() {
|
|
if (!this.iconEl || !this.badgeEl) return;
|
|
const count = this.sessionContextPaths.length;
|
|
if (count > 0) {
|
|
this.iconEl.addClass("active");
|
|
this.iconEl.setAttribute("title", `${count} context path${count > 1 ? "s" : ""} (click to add more)`);
|
|
if (count > 1) {
|
|
this.badgeEl.setText(String(count));
|
|
this.badgeEl.addClass("visible");
|
|
} else {
|
|
this.badgeEl.removeClass("visible");
|
|
}
|
|
} else {
|
|
this.iconEl.removeClass("active");
|
|
this.iconEl.setAttribute("title", "Add context paths (click)");
|
|
this.badgeEl.removeClass("visible");
|
|
}
|
|
}
|
|
};
|
|
var McpServerSelector = class {
|
|
constructor(parentEl) {
|
|
this.iconEl = null;
|
|
this.badgeEl = null;
|
|
this.dropdownEl = null;
|
|
this.mcpService = null;
|
|
this.enabledServers = /* @__PURE__ */ new Set();
|
|
this.onChangeCallback = null;
|
|
this.container = parentEl.createDiv({ cls: "claudian-mcp-selector" });
|
|
this.render();
|
|
}
|
|
/** Set the MCP service for fetching server list. */
|
|
setMcpService(service) {
|
|
this.mcpService = service;
|
|
this.pruneEnabledServers();
|
|
this.updateDisplay();
|
|
this.renderDropdown();
|
|
}
|
|
/** Set callback for when enabled servers change. */
|
|
setOnChange(callback) {
|
|
this.onChangeCallback = callback;
|
|
}
|
|
/** Get currently enabled servers (via click or @-mention). */
|
|
getEnabledServers() {
|
|
return new Set(this.enabledServers);
|
|
}
|
|
/** Add servers from @-mentions. */
|
|
addMentionedServers(names) {
|
|
let changed = false;
|
|
for (const name of names) {
|
|
if (!this.enabledServers.has(name)) {
|
|
this.enabledServers.add(name);
|
|
changed = true;
|
|
}
|
|
}
|
|
if (changed) {
|
|
this.updateDisplay();
|
|
this.renderDropdown();
|
|
}
|
|
}
|
|
/** Clear enabled servers (call on new conversation). */
|
|
clearEnabled() {
|
|
this.enabledServers.clear();
|
|
this.updateDisplay();
|
|
this.renderDropdown();
|
|
}
|
|
pruneEnabledServers() {
|
|
var _a;
|
|
if (!this.mcpService) return;
|
|
const activeNames = new Set(this.mcpService.getServers().filter((s) => s.enabled).map((s) => s.name));
|
|
let changed = false;
|
|
for (const name of this.enabledServers) {
|
|
if (!activeNames.has(name)) {
|
|
this.enabledServers.delete(name);
|
|
changed = true;
|
|
}
|
|
}
|
|
if (changed) {
|
|
(_a = this.onChangeCallback) == null ? void 0 : _a.call(this, this.enabledServers);
|
|
}
|
|
}
|
|
render() {
|
|
this.container.empty();
|
|
const iconWrapper = this.container.createDiv({ cls: "claudian-mcp-selector-icon-wrapper" });
|
|
this.iconEl = iconWrapper.createDiv({ cls: "claudian-mcp-selector-icon" });
|
|
this.iconEl.innerHTML = MCP_ICON_SVG;
|
|
this.badgeEl = iconWrapper.createDiv({ cls: "claudian-mcp-selector-badge" });
|
|
this.updateDisplay();
|
|
this.dropdownEl = this.container.createDiv({ cls: "claudian-mcp-selector-dropdown" });
|
|
this.renderDropdown();
|
|
this.container.addEventListener("mouseenter", () => {
|
|
this.renderDropdown();
|
|
});
|
|
}
|
|
renderDropdown() {
|
|
var _a;
|
|
if (!this.dropdownEl) return;
|
|
this.pruneEnabledServers();
|
|
this.dropdownEl.empty();
|
|
const headerEl = this.dropdownEl.createDiv({ cls: "claudian-mcp-selector-header" });
|
|
headerEl.setText("MCP Servers");
|
|
const listEl = this.dropdownEl.createDiv({ cls: "claudian-mcp-selector-list" });
|
|
const allServers = ((_a = this.mcpService) == null ? void 0 : _a.getServers()) || [];
|
|
const servers = allServers.filter((s) => s.enabled);
|
|
if (servers.length === 0) {
|
|
const emptyEl = listEl.createDiv({ cls: "claudian-mcp-selector-empty" });
|
|
emptyEl.setText(allServers.length === 0 ? "No MCP servers configured" : "All MCP servers disabled");
|
|
return;
|
|
}
|
|
for (const server of servers) {
|
|
this.renderServerItem(listEl, server);
|
|
}
|
|
}
|
|
renderServerItem(listEl, server) {
|
|
const itemEl = listEl.createDiv({ cls: "claudian-mcp-selector-item" });
|
|
itemEl.dataset.serverName = server.name;
|
|
const isEnabled = this.enabledServers.has(server.name);
|
|
if (isEnabled) {
|
|
itemEl.addClass("enabled");
|
|
}
|
|
const checkEl = itemEl.createDiv({ cls: "claudian-mcp-selector-check" });
|
|
if (isEnabled) {
|
|
(0, import_obsidian6.setIcon)(checkEl, "check");
|
|
}
|
|
const infoEl = itemEl.createDiv({ cls: "claudian-mcp-selector-item-info" });
|
|
const nameEl = infoEl.createSpan({ cls: "claudian-mcp-selector-item-name" });
|
|
nameEl.setText(server.name);
|
|
if (server.contextSaving) {
|
|
const csEl = infoEl.createSpan({ cls: "claudian-mcp-selector-cs-badge" });
|
|
csEl.setText("@");
|
|
csEl.setAttribute("title", "Context-saving: can also enable via @" + server.name);
|
|
}
|
|
itemEl.addEventListener("click", (e) => {
|
|
e.stopPropagation();
|
|
this.toggleServer(server.name, itemEl);
|
|
});
|
|
}
|
|
toggleServer(name, itemEl) {
|
|
var _a;
|
|
if (this.enabledServers.has(name)) {
|
|
this.enabledServers.delete(name);
|
|
} else {
|
|
this.enabledServers.add(name);
|
|
}
|
|
if (itemEl) {
|
|
const isEnabled = this.enabledServers.has(name);
|
|
const checkEl = itemEl.querySelector(".claudian-mcp-selector-check");
|
|
if (isEnabled) {
|
|
itemEl.addClass("enabled");
|
|
if (checkEl) (0, import_obsidian6.setIcon)(checkEl, "check");
|
|
} else {
|
|
itemEl.removeClass("enabled");
|
|
if (checkEl) checkEl.empty();
|
|
}
|
|
}
|
|
this.updateDisplay();
|
|
(_a = this.onChangeCallback) == null ? void 0 : _a.call(this, this.enabledServers);
|
|
}
|
|
updateDisplay() {
|
|
var _a;
|
|
this.pruneEnabledServers();
|
|
if (!this.iconEl || !this.badgeEl) return;
|
|
const count = this.enabledServers.size;
|
|
const hasServers = (((_a = this.mcpService) == null ? void 0 : _a.getServers().length) || 0) > 0;
|
|
if (!hasServers) {
|
|
this.container.style.display = "none";
|
|
return;
|
|
}
|
|
this.container.style.display = "";
|
|
if (count > 0) {
|
|
this.iconEl.addClass("active");
|
|
this.iconEl.setAttribute("title", `${count} MCP server${count > 1 ? "s" : ""} enabled (click to manage)`);
|
|
if (count > 1) {
|
|
this.badgeEl.setText(String(count));
|
|
this.badgeEl.addClass("visible");
|
|
} else {
|
|
this.badgeEl.removeClass("visible");
|
|
}
|
|
} else {
|
|
this.iconEl.removeClass("active");
|
|
this.iconEl.setAttribute("title", "MCP servers (click to enable)");
|
|
this.badgeEl.removeClass("visible");
|
|
}
|
|
}
|
|
};
|
|
var ContextUsageMeter = class {
|
|
constructor(parentEl) {
|
|
this.fillPath = null;
|
|
this.percentEl = null;
|
|
this.circumference = 0;
|
|
this.container = parentEl.createDiv({ cls: "claudian-context-meter" });
|
|
this.render();
|
|
this.container.style.display = "none";
|
|
}
|
|
render() {
|
|
const size = 16;
|
|
const strokeWidth = 2;
|
|
const radius = (size - strokeWidth) / 2;
|
|
const cx = size / 2;
|
|
const cy = size / 2;
|
|
const startAngle = 150;
|
|
const endAngle = 390;
|
|
const arcDegrees = endAngle - startAngle;
|
|
const arcRadians = arcDegrees * Math.PI / 180;
|
|
this.circumference = radius * arcRadians;
|
|
const startRad = startAngle * Math.PI / 180;
|
|
const endRad = endAngle * Math.PI / 180;
|
|
const x1 = cx + radius * Math.cos(startRad);
|
|
const y1 = cy + radius * Math.sin(startRad);
|
|
const x2 = cx + radius * Math.cos(endRad);
|
|
const y2 = cy + radius * Math.sin(endRad);
|
|
const gaugeEl = this.container.createDiv({ cls: "claudian-context-meter-gauge" });
|
|
gaugeEl.innerHTML = `
|
|
<svg width="${size}" height="${size}" viewBox="0 0 ${size} ${size}">
|
|
<path class="claudian-meter-bg"
|
|
d="M ${x1} ${y1} A ${radius} ${radius} 0 1 1 ${x2} ${y2}"
|
|
fill="none" stroke-width="${strokeWidth}" stroke-linecap="round"/>
|
|
<path class="claudian-meter-fill"
|
|
d="M ${x1} ${y1} A ${radius} ${radius} 0 1 1 ${x2} ${y2}"
|
|
fill="none" stroke-width="${strokeWidth}" stroke-linecap="round"
|
|
stroke-dasharray="${this.circumference}" stroke-dashoffset="${this.circumference}"/>
|
|
</svg>
|
|
`;
|
|
this.fillPath = gaugeEl.querySelector(".claudian-meter-fill");
|
|
this.percentEl = this.container.createSpan({ cls: "claudian-context-meter-percent" });
|
|
}
|
|
update(usage) {
|
|
if (!usage) {
|
|
this.container.style.display = "none";
|
|
return;
|
|
}
|
|
this.container.style.display = "flex";
|
|
const fillLength = usage.percentage / 100 * this.circumference;
|
|
if (this.fillPath) {
|
|
this.fillPath.style.strokeDashoffset = String(this.circumference - fillLength);
|
|
}
|
|
if (this.percentEl) {
|
|
this.percentEl.setText(`${usage.percentage}%`);
|
|
}
|
|
if (usage.percentage > 80) {
|
|
this.container.addClass("warning");
|
|
} else {
|
|
this.container.removeClass("warning");
|
|
}
|
|
const tooltip = `${this.formatTokens(usage.contextTokens)} / ${this.formatTokens(usage.contextWindow)}`;
|
|
this.container.setAttribute("data-tooltip", tooltip);
|
|
}
|
|
/** Format token count (e.g., 45000 -> "45k", 200000 -> "200k") */
|
|
formatTokens(tokens) {
|
|
if (tokens >= 1e3) {
|
|
return `${Math.round(tokens / 1e3)}k`;
|
|
}
|
|
return String(tokens);
|
|
}
|
|
};
|
|
function createInputToolbar(parentEl, callbacks) {
|
|
const modelSelector = new ModelSelector(parentEl, callbacks);
|
|
const thinkingBudgetSelector = new ThinkingBudgetSelector(parentEl, callbacks);
|
|
const contextUsageMeter = new ContextUsageMeter(parentEl);
|
|
const contextPathSelector = new ContextPathSelector(parentEl, callbacks);
|
|
const mcpServerSelector = new McpServerSelector(parentEl);
|
|
const permissionToggle = new PermissionToggle(parentEl, callbacks);
|
|
return { modelSelector, thinkingBudgetSelector, contextUsageMeter, contextPathSelector, mcpServerSelector, permissionToggle };
|
|
}
|
|
|
|
// src/ui/components/InstructionModeManager.ts
|
|
var INSTRUCTION_MODE_PLACEHOLDER = "# Save in custom system prompt";
|
|
var InstructionModeManager = class {
|
|
constructor(inputEl, callbacks) {
|
|
this.state = { active: false, rawInstruction: "" };
|
|
this.isSubmitting = false;
|
|
this.originalPlaceholder = "";
|
|
this.inputEl = inputEl;
|
|
this.callbacks = callbacks;
|
|
this.originalPlaceholder = inputEl.placeholder;
|
|
}
|
|
/**
|
|
* Handles keydown to detect # trigger.
|
|
* Returns true if the event was consumed (should prevent default).
|
|
*/
|
|
handleTriggerKey(e) {
|
|
if (!this.state.active && this.inputEl.value === "" && e.key === "#") {
|
|
if (this.enterMode()) {
|
|
e.preventDefault();
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
/** Handles input changes to track instruction text. */
|
|
handleInputChange() {
|
|
if (!this.state.active) return;
|
|
const text = this.inputEl.value;
|
|
if (text === "") {
|
|
this.exitMode();
|
|
} else {
|
|
this.state.rawInstruction = text;
|
|
}
|
|
}
|
|
/**
|
|
* Enters instruction mode.
|
|
* Only enters if the indicator can be successfully shown.
|
|
* Returns true if mode was entered, false otherwise.
|
|
*/
|
|
enterMode() {
|
|
const wrapper = this.callbacks.getInputWrapper();
|
|
if (!wrapper) return false;
|
|
wrapper.addClass("claudian-input-instruction-mode");
|
|
this.state = { active: true, rawInstruction: "" };
|
|
this.inputEl.placeholder = INSTRUCTION_MODE_PLACEHOLDER;
|
|
return true;
|
|
}
|
|
/** Exits instruction mode, restoring original state. */
|
|
exitMode() {
|
|
const wrapper = this.callbacks.getInputWrapper();
|
|
if (wrapper) {
|
|
wrapper.removeClass("claudian-input-instruction-mode");
|
|
}
|
|
this.state = { active: false, rawInstruction: "" };
|
|
this.inputEl.placeholder = this.originalPlaceholder;
|
|
}
|
|
/** Handles keydown events. Returns true if handled. */
|
|
handleKeydown(e) {
|
|
if (!this.state.active) return false;
|
|
if (e.key === "Enter" && !e.shiftKey) {
|
|
if (!this.state.rawInstruction.trim()) {
|
|
return false;
|
|
}
|
|
e.preventDefault();
|
|
this.submit();
|
|
return true;
|
|
}
|
|
if (e.key === "Escape") {
|
|
e.preventDefault();
|
|
this.cancel();
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
/** Checks if instruction mode is active. */
|
|
isActive() {
|
|
return this.state.active;
|
|
}
|
|
/** Gets the current raw instruction text. */
|
|
getRawInstruction() {
|
|
return this.state.rawInstruction;
|
|
}
|
|
/** Submits the instruction for refinement. */
|
|
async submit() {
|
|
if (this.isSubmitting) return;
|
|
const rawInstruction = this.state.rawInstruction.trim();
|
|
if (!rawInstruction) return;
|
|
this.isSubmitting = true;
|
|
try {
|
|
await this.callbacks.onSubmit(rawInstruction);
|
|
} finally {
|
|
this.isSubmitting = false;
|
|
}
|
|
}
|
|
/** Cancels instruction mode and clears input. */
|
|
cancel() {
|
|
this.inputEl.value = "";
|
|
this.exitMode();
|
|
}
|
|
/** Clears the input and resets state (called after successful submission). */
|
|
clear() {
|
|
this.inputEl.value = "";
|
|
this.exitMode();
|
|
}
|
|
/** Cleans up event listeners. */
|
|
destroy() {
|
|
const wrapper = this.callbacks.getInputWrapper();
|
|
if (wrapper) {
|
|
wrapper.removeClass("claudian-input-instruction-mode");
|
|
}
|
|
this.inputEl.placeholder = this.originalPlaceholder;
|
|
}
|
|
};
|
|
|
|
// src/ui/components/PlanApprovalPanel.ts
|
|
function findInputElements2(containerEl) {
|
|
const inputContainer = containerEl.querySelector(".claudian-input-container");
|
|
const inputWrapper = containerEl.querySelector(".claudian-input-wrapper");
|
|
return { inputContainer, inputWrapper };
|
|
}
|
|
var APPROVAL_OPTIONS = [
|
|
{ label: "Approve", isRevise: false },
|
|
{ label: "Approve && New Session", isRevise: false },
|
|
{ label: "Type here to tell Claudian what to change", isRevise: true }
|
|
];
|
|
var PlanApprovalPanel = class {
|
|
constructor(_app, options) {
|
|
this.isDestroyed = false;
|
|
this.reviseInputEl = null;
|
|
this.currentOptionIndex = 0;
|
|
this.optionsEl = null;
|
|
// Input area references (for hiding/showing)
|
|
this.inputContainer = null;
|
|
this.inputWrapper = null;
|
|
this.containerEl = options.containerEl;
|
|
this.onApprove = options.onApprove;
|
|
this.onApproveNewSession = options.onApproveNewSession;
|
|
this.onRevise = options.onRevise;
|
|
this.onCancel = options.onCancel;
|
|
const { inputContainer, inputWrapper } = findInputElements2(this.containerEl);
|
|
this.inputContainer = inputContainer;
|
|
this.inputWrapper = inputWrapper;
|
|
if (this.inputWrapper) {
|
|
this.inputWrapper.style.display = "none";
|
|
}
|
|
this.panelEl = this.createPanel();
|
|
if (this.inputContainer) {
|
|
this.inputContainer.appendChild(this.panelEl);
|
|
} else {
|
|
this.containerEl.appendChild(this.panelEl);
|
|
}
|
|
this.panelEl.focus();
|
|
}
|
|
/** Create the panel DOM structure. */
|
|
createPanel() {
|
|
const panel = document.createElement("div");
|
|
panel.className = "claudian-plan-approval-panel";
|
|
panel.setAttribute("tabindex", "0");
|
|
panel.setAttribute("role", "dialog");
|
|
panel.setAttribute("aria-label", "Review implementation plan");
|
|
panel.addEventListener("keydown", this.handleKeyDown.bind(this));
|
|
const headerEl = document.createElement("div");
|
|
headerEl.className = "claudian-plan-approval-header";
|
|
headerEl.textContent = "Would you like to proceed?";
|
|
panel.appendChild(headerEl);
|
|
this.optionsEl = document.createElement("div");
|
|
this.optionsEl.className = "claudian-plan-approval-options";
|
|
this.renderOptions();
|
|
panel.appendChild(this.optionsEl);
|
|
return panel;
|
|
}
|
|
/** Render the option rows. */
|
|
renderOptions() {
|
|
if (!this.optionsEl) return;
|
|
this.optionsEl.innerHTML = "";
|
|
APPROVAL_OPTIONS.forEach((option, index) => {
|
|
const optionEl = document.createElement("div");
|
|
optionEl.className = "claudian-plan-approval-option";
|
|
optionEl.setAttribute("data-option-index", String(index));
|
|
const caretEl = document.createElement("span");
|
|
caretEl.className = "claudian-plan-approval-caret";
|
|
caretEl.textContent = index === this.currentOptionIndex ? ">" : " ";
|
|
optionEl.appendChild(caretEl);
|
|
const numberEl = document.createElement("span");
|
|
numberEl.className = "claudian-plan-approval-number";
|
|
numberEl.textContent = `${index + 1}.`;
|
|
optionEl.appendChild(numberEl);
|
|
if (option.isRevise) {
|
|
this.reviseInputEl = document.createElement("input");
|
|
this.reviseInputEl.type = "text";
|
|
this.reviseInputEl.className = "claudian-plan-approval-revise-inline";
|
|
this.reviseInputEl.placeholder = option.label;
|
|
this.reviseInputEl.addEventListener("click", (e) => {
|
|
e.stopPropagation();
|
|
this.currentOptionIndex = index;
|
|
this.updateOptionFocus();
|
|
});
|
|
this.reviseInputEl.addEventListener("keydown", (e) => {
|
|
var _a;
|
|
if (e.key === "Enter") {
|
|
e.preventDefault();
|
|
this.handleReviseSubmit();
|
|
} else if (e.key === "Escape") {
|
|
e.preventDefault();
|
|
if ((_a = this.reviseInputEl) == null ? void 0 : _a.value) {
|
|
this.reviseInputEl.value = "";
|
|
} else {
|
|
this.handleCancel();
|
|
}
|
|
} else if (e.key === "ArrowUp") {
|
|
e.preventDefault();
|
|
this.currentOptionIndex = Math.max(0, this.currentOptionIndex - 1);
|
|
this.updateOptionFocus();
|
|
this.panelEl.focus();
|
|
}
|
|
e.stopPropagation();
|
|
});
|
|
this.reviseInputEl.addEventListener("focus", () => {
|
|
this.currentOptionIndex = index;
|
|
this.updateOptionFocus();
|
|
});
|
|
optionEl.appendChild(this.reviseInputEl);
|
|
} else {
|
|
const labelEl = document.createElement("span");
|
|
labelEl.className = "claudian-plan-approval-option-label";
|
|
labelEl.textContent = option.label;
|
|
optionEl.appendChild(labelEl);
|
|
}
|
|
optionEl.addEventListener("click", () => {
|
|
var _a;
|
|
this.currentOptionIndex = index;
|
|
this.updateOptionFocus();
|
|
if (!option.isRevise) {
|
|
this.selectCurrentOption();
|
|
} else {
|
|
(_a = this.reviseInputEl) == null ? void 0 : _a.focus();
|
|
}
|
|
});
|
|
optionEl.addEventListener("mouseenter", () => {
|
|
this.currentOptionIndex = index;
|
|
this.updateOptionFocus();
|
|
});
|
|
if (index === this.currentOptionIndex) {
|
|
optionEl.classList.add("focused");
|
|
}
|
|
this.optionsEl.appendChild(optionEl);
|
|
});
|
|
}
|
|
/** Update the visual focus indicator on options. */
|
|
updateOptionFocus() {
|
|
if (!this.optionsEl) return;
|
|
const options = this.optionsEl.querySelectorAll(".claudian-plan-approval-option");
|
|
options.forEach((opt, i) => {
|
|
const caret = opt.querySelector(".claudian-plan-approval-caret");
|
|
const isFocused = i === this.currentOptionIndex;
|
|
opt.classList.toggle("focused", isFocused);
|
|
if (caret) {
|
|
caret.textContent = isFocused ? ">" : " ";
|
|
}
|
|
});
|
|
if (this.currentOptionIndex !== 2 && this.reviseInputEl && document.activeElement === this.reviseInputEl) {
|
|
this.reviseInputEl.blur();
|
|
this.panelEl.focus();
|
|
}
|
|
if (this.currentOptionIndex === 2 && this.reviseInputEl) {
|
|
this.reviseInputEl.focus();
|
|
}
|
|
}
|
|
/** Select the currently focused option. */
|
|
selectCurrentOption() {
|
|
var _a;
|
|
switch (this.currentOptionIndex) {
|
|
case 0:
|
|
this.handleApprove();
|
|
break;
|
|
case 1:
|
|
this.handleApproveNewSession();
|
|
break;
|
|
case 2:
|
|
(_a = this.reviseInputEl) == null ? void 0 : _a.focus();
|
|
break;
|
|
}
|
|
}
|
|
/** Handle keyboard events. */
|
|
handleKeyDown(e) {
|
|
var _a;
|
|
if (this.isDestroyed) return;
|
|
if (document.activeElement === this.reviseInputEl) {
|
|
return;
|
|
}
|
|
switch (e.key) {
|
|
case "ArrowUp":
|
|
e.preventDefault();
|
|
this.currentOptionIndex = Math.max(0, this.currentOptionIndex - 1);
|
|
this.updateOptionFocus();
|
|
break;
|
|
case "ArrowDown":
|
|
e.preventDefault();
|
|
this.currentOptionIndex = Math.min(APPROVAL_OPTIONS.length - 1, this.currentOptionIndex + 1);
|
|
this.updateOptionFocus();
|
|
break;
|
|
case "Enter":
|
|
e.preventDefault();
|
|
this.selectCurrentOption();
|
|
break;
|
|
case "Escape":
|
|
e.preventDefault();
|
|
this.handleCancel();
|
|
break;
|
|
case "1":
|
|
e.preventDefault();
|
|
this.currentOptionIndex = 0;
|
|
this.updateOptionFocus();
|
|
this.selectCurrentOption();
|
|
break;
|
|
case "2":
|
|
e.preventDefault();
|
|
this.currentOptionIndex = 1;
|
|
this.updateOptionFocus();
|
|
this.selectCurrentOption();
|
|
break;
|
|
case "3":
|
|
e.preventDefault();
|
|
this.currentOptionIndex = 2;
|
|
this.updateOptionFocus();
|
|
(_a = this.reviseInputEl) == null ? void 0 : _a.focus();
|
|
break;
|
|
default:
|
|
if (this.currentOptionIndex === 2 && e.key.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey) {
|
|
e.preventDefault();
|
|
if (this.reviseInputEl) {
|
|
this.reviseInputEl.focus();
|
|
this.reviseInputEl.value = e.key;
|
|
this.reviseInputEl.setSelectionRange(1, 1);
|
|
}
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
/** Handle approve action. */
|
|
handleApprove() {
|
|
if (this.isDestroyed) return;
|
|
this.destroy();
|
|
this.onApprove();
|
|
}
|
|
/** Handle approve with new session action. */
|
|
handleApproveNewSession() {
|
|
if (this.isDestroyed) return;
|
|
this.destroy();
|
|
this.onApproveNewSession();
|
|
}
|
|
/** Handle cancel action (Esc). */
|
|
handleCancel() {
|
|
if (this.isDestroyed) return;
|
|
this.destroy();
|
|
this.onCancel();
|
|
}
|
|
/** Handle revise submission. */
|
|
handleReviseSubmit() {
|
|
var _a;
|
|
if (this.isDestroyed) return;
|
|
const feedback = (_a = this.reviseInputEl) == null ? void 0 : _a.value.trim();
|
|
if (!feedback) return;
|
|
this.destroy();
|
|
this.onRevise(feedback);
|
|
}
|
|
/** Destroy the panel and restore input area. */
|
|
destroy() {
|
|
if (this.isDestroyed) return;
|
|
this.isDestroyed = true;
|
|
this.panelEl.remove();
|
|
if (this.inputWrapper) {
|
|
this.inputWrapper.style.display = "";
|
|
}
|
|
}
|
|
};
|
|
function showPlanApprovalPanel(app, containerEl, planContent, component) {
|
|
return new Promise((resolve7) => {
|
|
new PlanApprovalPanel(app, {
|
|
containerEl,
|
|
planContent,
|
|
component,
|
|
onApprove: () => resolve7({ decision: "approve" }),
|
|
onApproveNewSession: () => resolve7({ decision: "approve_new_session" }),
|
|
onRevise: (feedback) => resolve7({ decision: "revise", feedback }),
|
|
onCancel: () => resolve7({ decision: "cancel" })
|
|
});
|
|
});
|
|
}
|
|
|
|
// src/ui/components/PlanBanner.ts
|
|
var import_obsidian7 = require("obsidian");
|
|
var PlanBanner = class {
|
|
constructor(options) {
|
|
this.containerEl = null;
|
|
this.bannerEl = null;
|
|
this.contentEl = null;
|
|
this.isExpanded = false;
|
|
this.planContent = "";
|
|
this.app = options.app;
|
|
this.component = options.component;
|
|
}
|
|
/**
|
|
* Mount the banner into the container.
|
|
* Should be called after the container is created, inserts between header and messages.
|
|
*/
|
|
mount(containerEl) {
|
|
this.containerEl = containerEl;
|
|
}
|
|
/**
|
|
* Show the banner with the given plan content.
|
|
*/
|
|
async show(planContent) {
|
|
if (!this.containerEl) return;
|
|
if (this.bannerEl) {
|
|
this.bannerEl.remove();
|
|
this.bannerEl = null;
|
|
this.contentEl = null;
|
|
}
|
|
this.planContent = planContent;
|
|
this.isExpanded = false;
|
|
this.bannerEl = document.createElement("div");
|
|
this.bannerEl.className = "claudian-plan-banner";
|
|
const headerEl = document.createElement("div");
|
|
headerEl.className = "claudian-plan-banner-header";
|
|
headerEl.addEventListener("click", () => this.toggle());
|
|
const chevronEl = document.createElement("span");
|
|
chevronEl.className = "claudian-plan-banner-chevron";
|
|
chevronEl.textContent = "\u25B6";
|
|
headerEl.appendChild(chevronEl);
|
|
const titleEl = document.createElement("span");
|
|
titleEl.className = "claudian-plan-banner-title";
|
|
titleEl.textContent = "Approved Plan";
|
|
headerEl.appendChild(titleEl);
|
|
this.bannerEl.appendChild(headerEl);
|
|
this.contentEl = document.createElement("div");
|
|
this.contentEl.className = "claudian-plan-banner-content";
|
|
this.contentEl.style.display = "none";
|
|
await this.renderContent();
|
|
this.bannerEl.appendChild(this.contentEl);
|
|
const messagesEl = this.containerEl.querySelector(".claudian-messages");
|
|
if (messagesEl) {
|
|
this.containerEl.insertBefore(this.bannerEl, messagesEl);
|
|
} else {
|
|
this.containerEl.appendChild(this.bannerEl);
|
|
}
|
|
}
|
|
/**
|
|
* Hide and remove the banner.
|
|
*/
|
|
hide() {
|
|
if (this.bannerEl) {
|
|
this.bannerEl.remove();
|
|
this.bannerEl = null;
|
|
this.contentEl = null;
|
|
}
|
|
this.isExpanded = false;
|
|
this.planContent = "";
|
|
}
|
|
/**
|
|
* Toggle the banner's expanded/collapsed state.
|
|
*/
|
|
toggle() {
|
|
this.isExpanded = !this.isExpanded;
|
|
this.updateDisplay();
|
|
}
|
|
/**
|
|
* Update the display based on expanded state.
|
|
*/
|
|
updateDisplay() {
|
|
if (!this.bannerEl || !this.contentEl) return;
|
|
const chevron = this.bannerEl.querySelector(".claudian-plan-banner-chevron");
|
|
if (chevron) {
|
|
chevron.textContent = this.isExpanded ? "\u25BC" : "\u25B6";
|
|
}
|
|
this.contentEl.style.display = this.isExpanded ? "block" : "none";
|
|
this.bannerEl.classList.toggle("expanded", this.isExpanded);
|
|
}
|
|
/**
|
|
* Render the plan content as markdown.
|
|
*/
|
|
async renderContent() {
|
|
if (!this.contentEl) return;
|
|
try {
|
|
await import_obsidian7.MarkdownRenderer.render(
|
|
this.app,
|
|
this.planContent,
|
|
this.contentEl,
|
|
"",
|
|
this.component
|
|
);
|
|
} catch (e) {
|
|
this.contentEl.textContent = this.planContent;
|
|
}
|
|
}
|
|
/**
|
|
* Check if the banner is currently visible.
|
|
*/
|
|
isVisible() {
|
|
return this.bannerEl !== null;
|
|
}
|
|
/**
|
|
* Get the current plan content.
|
|
*/
|
|
getPlanContent() {
|
|
return this.planContent;
|
|
}
|
|
};
|
|
|
|
// src/ui/components/SelectionHighlight.ts
|
|
var import_state = require("@codemirror/state");
|
|
var import_view = require("@codemirror/view");
|
|
function createSelectionHighlighter() {
|
|
const showHighlight = import_state.StateEffect.define();
|
|
const hideHighlight = import_state.StateEffect.define();
|
|
const selectionHighlightField = import_state.StateField.define({
|
|
create: () => import_view.Decoration.none,
|
|
update: (deco, tr) => {
|
|
for (const e of tr.effects) {
|
|
if (e.is(showHighlight)) {
|
|
const builder = new import_state.RangeSetBuilder();
|
|
builder.add(e.value.from, e.value.to, import_view.Decoration.mark({
|
|
class: "claudian-selection-highlight"
|
|
}));
|
|
return builder.finish();
|
|
} else if (e.is(hideHighlight)) {
|
|
return import_view.Decoration.none;
|
|
}
|
|
}
|
|
return deco.map(tr.changes);
|
|
},
|
|
provide: (f) => import_view.EditorView.decorations.from(f)
|
|
});
|
|
const installedEditors2 = /* @__PURE__ */ new WeakSet();
|
|
function ensureHighlightField(editorView) {
|
|
if (!installedEditors2.has(editorView)) {
|
|
editorView.dispatch({
|
|
effects: import_state.StateEffect.appendConfig.of(selectionHighlightField)
|
|
});
|
|
installedEditors2.add(editorView);
|
|
}
|
|
}
|
|
function show(editorView, from, to) {
|
|
ensureHighlightField(editorView);
|
|
editorView.dispatch({
|
|
effects: showHighlight.of({ from, to })
|
|
});
|
|
}
|
|
function hide(editorView) {
|
|
if (installedEditors2.has(editorView)) {
|
|
editorView.dispatch({
|
|
effects: hideHighlight.of(null)
|
|
});
|
|
}
|
|
}
|
|
return { show, hide };
|
|
}
|
|
var defaultHighlighter = createSelectionHighlighter();
|
|
function showSelectionHighlight(editorView, from, to) {
|
|
defaultHighlighter.show(editorView, from, to);
|
|
}
|
|
function hideSelectionHighlight(editorView) {
|
|
defaultHighlighter.hide(editorView);
|
|
}
|
|
|
|
// src/ui/components/SlashCommandDropdown.ts
|
|
var SlashCommandDropdown = class {
|
|
constructor(containerEl, inputEl, callbacks, options = {}) {
|
|
this.dropdownEl = null;
|
|
this.slashStartIndex = -1;
|
|
this.selectedIndex = 0;
|
|
this.filteredCommands = [];
|
|
var _a;
|
|
this.containerEl = containerEl;
|
|
this.inputEl = inputEl;
|
|
this.callbacks = callbacks;
|
|
this.isFixed = (_a = options.fixed) != null ? _a : false;
|
|
this.onInput = () => this.handleInputChange();
|
|
this.inputEl.addEventListener("input", this.onInput);
|
|
}
|
|
/** Handles input changes to detect / trigger. */
|
|
handleInputChange() {
|
|
const text = this.getInputValue();
|
|
const cursorPos = this.getCursorPosition();
|
|
const textBeforeCursor = text.substring(0, cursorPos);
|
|
const lastSlashIndex = textBeforeCursor.lastIndexOf("/");
|
|
if (lastSlashIndex === -1) {
|
|
this.hide();
|
|
return;
|
|
}
|
|
const charBeforeSlash = lastSlashIndex > 0 ? textBeforeCursor[lastSlashIndex - 1] : " ";
|
|
if (!/\s/.test(charBeforeSlash) && lastSlashIndex !== 0) {
|
|
this.hide();
|
|
return;
|
|
}
|
|
const searchText = textBeforeCursor.substring(lastSlashIndex + 1);
|
|
if (/\s/.test(searchText)) {
|
|
this.hide();
|
|
return;
|
|
}
|
|
this.slashStartIndex = lastSlashIndex;
|
|
this.showDropdown(searchText);
|
|
}
|
|
/** Handles keyboard navigation. Returns true if handled. */
|
|
handleKeydown(e) {
|
|
if (!this.isVisible()) return false;
|
|
switch (e.key) {
|
|
case "ArrowDown":
|
|
e.preventDefault();
|
|
this.navigate(1);
|
|
return true;
|
|
case "ArrowUp":
|
|
e.preventDefault();
|
|
this.navigate(-1);
|
|
return true;
|
|
case "Enter":
|
|
case "Tab":
|
|
if (this.filteredCommands.length > 0) {
|
|
e.preventDefault();
|
|
this.selectItem();
|
|
return true;
|
|
}
|
|
return false;
|
|
case "Escape":
|
|
e.preventDefault();
|
|
this.hide();
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
/** Checks if dropdown is currently visible. */
|
|
isVisible() {
|
|
var _a, _b;
|
|
return (_b = (_a = this.dropdownEl) == null ? void 0 : _a.hasClass("visible")) != null ? _b : false;
|
|
}
|
|
/** Hides the dropdown. */
|
|
hide() {
|
|
if (this.dropdownEl) {
|
|
this.dropdownEl.removeClass("visible");
|
|
}
|
|
this.slashStartIndex = -1;
|
|
this.callbacks.onHide();
|
|
}
|
|
/** Destroys the dropdown and cleans up. */
|
|
destroy() {
|
|
this.inputEl.removeEventListener("input", this.onInput);
|
|
if (this.dropdownEl) {
|
|
this.dropdownEl.remove();
|
|
this.dropdownEl = null;
|
|
}
|
|
}
|
|
getInputValue() {
|
|
return this.inputEl.value;
|
|
}
|
|
getCursorPosition() {
|
|
return this.inputEl.selectionStart || 0;
|
|
}
|
|
setInputValue(value) {
|
|
this.inputEl.value = value;
|
|
}
|
|
setCursorPosition(pos) {
|
|
this.inputEl.selectionStart = pos;
|
|
this.inputEl.selectionEnd = pos;
|
|
}
|
|
showDropdown(searchText) {
|
|
const allCommands = this.callbacks.getCommands();
|
|
const searchLower = searchText.toLowerCase();
|
|
this.filteredCommands = allCommands.filter(
|
|
(cmd) => {
|
|
var _a;
|
|
return cmd.name.toLowerCase().includes(searchLower) || ((_a = cmd.description) == null ? void 0 : _a.toLowerCase().includes(searchLower));
|
|
}
|
|
).slice(0, 10);
|
|
if (searchText.length > 0 && this.filteredCommands.length === 0) {
|
|
this.hide();
|
|
return;
|
|
}
|
|
this.selectedIndex = 0;
|
|
this.render();
|
|
}
|
|
render() {
|
|
if (!this.dropdownEl) {
|
|
this.dropdownEl = this.createDropdownElement();
|
|
}
|
|
this.dropdownEl.empty();
|
|
if (this.filteredCommands.length === 0) {
|
|
const emptyEl = this.dropdownEl.createDiv({ cls: "claudian-slash-empty" });
|
|
emptyEl.setText("No matching commands");
|
|
} else {
|
|
for (let i = 0; i < this.filteredCommands.length; i++) {
|
|
const cmd = this.filteredCommands[i];
|
|
const itemEl = this.dropdownEl.createDiv({ cls: "claudian-slash-item" });
|
|
if (i === this.selectedIndex) {
|
|
itemEl.addClass("selected");
|
|
}
|
|
const nameEl = itemEl.createSpan({ cls: "claudian-slash-name" });
|
|
nameEl.setText(`/${cmd.name}`);
|
|
if (cmd.argumentHint) {
|
|
const hintEl = itemEl.createSpan({ cls: "claudian-slash-hint" });
|
|
hintEl.setText(cmd.argumentHint);
|
|
}
|
|
if (cmd.description) {
|
|
const descEl = itemEl.createDiv({ cls: "claudian-slash-desc" });
|
|
descEl.setText(cmd.description);
|
|
}
|
|
itemEl.addEventListener("click", () => {
|
|
this.selectedIndex = i;
|
|
this.selectItem();
|
|
});
|
|
itemEl.addEventListener("mouseenter", () => {
|
|
this.selectedIndex = i;
|
|
this.updateSelection();
|
|
});
|
|
}
|
|
}
|
|
this.dropdownEl.addClass("visible");
|
|
if (this.isFixed) {
|
|
this.positionFixed();
|
|
}
|
|
}
|
|
createDropdownElement() {
|
|
if (this.isFixed) {
|
|
const dropdown = this.containerEl.createDiv({
|
|
cls: "claudian-slash-dropdown claudian-slash-dropdown-fixed"
|
|
});
|
|
return dropdown;
|
|
} else {
|
|
return this.containerEl.createDiv({ cls: "claudian-slash-dropdown" });
|
|
}
|
|
}
|
|
positionFixed() {
|
|
if (!this.dropdownEl || !this.isFixed) return;
|
|
const inputRect = this.inputEl.getBoundingClientRect();
|
|
this.dropdownEl.style.position = "fixed";
|
|
this.dropdownEl.style.bottom = `${window.innerHeight - inputRect.top + 4}px`;
|
|
this.dropdownEl.style.left = `${inputRect.left}px`;
|
|
this.dropdownEl.style.right = "auto";
|
|
this.dropdownEl.style.width = `${Math.max(inputRect.width, 280)}px`;
|
|
this.dropdownEl.style.zIndex = "10001";
|
|
}
|
|
navigate(direction) {
|
|
const maxIndex = this.filteredCommands.length - 1;
|
|
this.selectedIndex = Math.max(0, Math.min(maxIndex, this.selectedIndex + direction));
|
|
this.updateSelection();
|
|
}
|
|
updateSelection() {
|
|
var _a;
|
|
const items = (_a = this.dropdownEl) == null ? void 0 : _a.querySelectorAll(".claudian-slash-item");
|
|
items == null ? void 0 : items.forEach((item, index) => {
|
|
if (index === this.selectedIndex) {
|
|
item.addClass("selected");
|
|
item.scrollIntoView({ block: "nearest" });
|
|
} else {
|
|
item.removeClass("selected");
|
|
}
|
|
});
|
|
}
|
|
selectItem() {
|
|
if (this.filteredCommands.length === 0) return;
|
|
const selected = this.filteredCommands[this.selectedIndex];
|
|
if (!selected) return;
|
|
const text = this.getInputValue();
|
|
const beforeSlash = text.substring(0, this.slashStartIndex);
|
|
const afterCursor = text.substring(this.getCursorPosition());
|
|
const replacement = `/${selected.name} `;
|
|
this.setInputValue(beforeSlash + replacement + afterCursor);
|
|
this.setCursorPosition(beforeSlash.length + replacement.length);
|
|
this.hide();
|
|
this.callbacks.onSelect(selected);
|
|
this.inputEl.focus();
|
|
}
|
|
};
|
|
|
|
// src/ui/components/TodoPanel.ts
|
|
var import_obsidian8 = require("obsidian");
|
|
var TodoPanel = class {
|
|
constructor() {
|
|
this.containerEl = null;
|
|
this.panelEl = null;
|
|
this.todoContainerEl = null;
|
|
this.todoHeaderEl = null;
|
|
this.todoContentEl = null;
|
|
this.isExpanded = false;
|
|
this.currentTodos = null;
|
|
// Event handler references for cleanup
|
|
this.clickHandler = null;
|
|
this.keydownHandler = null;
|
|
}
|
|
/**
|
|
* Mount the panel into the messages container.
|
|
* Appends to the end of the messages area.
|
|
*/
|
|
mount(containerEl) {
|
|
this.containerEl = containerEl;
|
|
this.createPanel();
|
|
}
|
|
/**
|
|
* Remount the panel after the container was cleared.
|
|
* Called when messagesEl.empty() removes the panel from DOM.
|
|
*/
|
|
remount() {
|
|
if (!this.containerEl) {
|
|
console.warn("[TodoPanel] Cannot remount - no containerEl set");
|
|
return;
|
|
}
|
|
this.panelEl = null;
|
|
this.todoContainerEl = null;
|
|
this.todoHeaderEl = null;
|
|
this.todoContentEl = null;
|
|
this.createPanel();
|
|
}
|
|
/**
|
|
* Create the panel structure.
|
|
*/
|
|
createPanel() {
|
|
if (!this.containerEl) {
|
|
console.warn("[TodoPanel] Cannot create panel - containerEl not set. Was mount() called correctly?");
|
|
return;
|
|
}
|
|
this.panelEl = document.createElement("div");
|
|
this.panelEl.className = "claudian-todo-panel";
|
|
this.todoContainerEl = document.createElement("div");
|
|
this.todoContainerEl.className = "claudian-todo-panel-todos";
|
|
this.todoContainerEl.style.display = "none";
|
|
this.panelEl.appendChild(this.todoContainerEl);
|
|
this.todoHeaderEl = document.createElement("div");
|
|
this.todoHeaderEl.className = "claudian-todo-panel-header";
|
|
this.todoHeaderEl.setAttribute("tabindex", "0");
|
|
this.todoHeaderEl.setAttribute("role", "button");
|
|
this.clickHandler = () => this.toggle();
|
|
this.keydownHandler = (e) => {
|
|
if (e.key === "Enter" || e.key === " ") {
|
|
e.preventDefault();
|
|
this.toggle();
|
|
}
|
|
};
|
|
this.todoHeaderEl.addEventListener("click", this.clickHandler);
|
|
this.todoHeaderEl.addEventListener("keydown", this.keydownHandler);
|
|
this.todoContainerEl.appendChild(this.todoHeaderEl);
|
|
this.todoContentEl = document.createElement("div");
|
|
this.todoContentEl.className = "claudian-todo-panel-content";
|
|
this.todoContentEl.style.display = "none";
|
|
this.todoContainerEl.appendChild(this.todoContentEl);
|
|
this.containerEl.appendChild(this.panelEl);
|
|
}
|
|
/**
|
|
* Update the panel with new todo items.
|
|
* Called by ChatState.onTodosChanged callback when TodoWrite tool is used.
|
|
* Passing null or empty array hides the panel.
|
|
*/
|
|
updateTodos(todos) {
|
|
if (!this.todoContainerEl || !this.todoHeaderEl || !this.todoContentEl) {
|
|
if (todos && todos.length > 0) {
|
|
console.warn("[TodoPanel] Cannot update todos - component not mounted or destroyed");
|
|
}
|
|
return;
|
|
}
|
|
this.currentTodos = todos;
|
|
if (!todos || todos.length === 0) {
|
|
this.todoContainerEl.style.display = "none";
|
|
this.todoHeaderEl.empty();
|
|
this.todoContentEl.empty();
|
|
return;
|
|
}
|
|
this.todoContainerEl.style.display = "block";
|
|
const completedCount = todos.filter((t) => t.status === "completed").length;
|
|
const totalCount = todos.length;
|
|
const currentTask = todos.find((t) => t.status === "in_progress");
|
|
this.renderHeader(completedCount, totalCount, currentTask);
|
|
this.renderContent(todos);
|
|
this.updateAriaLabel(completedCount, totalCount);
|
|
this.scrollToBottom();
|
|
}
|
|
/**
|
|
* Render the collapsed header.
|
|
*/
|
|
renderHeader(completedCount, totalCount, currentTask) {
|
|
if (!this.todoHeaderEl) return;
|
|
this.todoHeaderEl.empty();
|
|
const icon = document.createElement("span");
|
|
icon.className = "claudian-todo-panel-icon";
|
|
(0, import_obsidian8.setIcon)(icon, "list-checks");
|
|
this.todoHeaderEl.appendChild(icon);
|
|
const label = document.createElement("span");
|
|
label.className = "claudian-todo-panel-label";
|
|
label.textContent = `Tasks (${completedCount}/${totalCount})`;
|
|
this.todoHeaderEl.appendChild(label);
|
|
if (!this.isExpanded && currentTask) {
|
|
const current = document.createElement("span");
|
|
current.className = "claudian-todo-panel-current";
|
|
current.textContent = currentTask.activeForm;
|
|
this.todoHeaderEl.appendChild(current);
|
|
}
|
|
}
|
|
/**
|
|
* Render the expanded content.
|
|
*/
|
|
renderContent(todos) {
|
|
if (!this.todoContentEl) return;
|
|
this.todoContentEl.empty();
|
|
for (const todo of todos) {
|
|
const itemEl = document.createElement("div");
|
|
itemEl.className = `claudian-todo-item claudian-todo-${todo.status}`;
|
|
const statusIcon = document.createElement("div");
|
|
statusIcon.className = "claudian-todo-status-icon";
|
|
statusIcon.setAttribute("aria-hidden", "true");
|
|
(0, import_obsidian8.setIcon)(statusIcon, this.getStatusIcon(todo.status));
|
|
itemEl.appendChild(statusIcon);
|
|
const text = document.createElement("div");
|
|
text.className = "claudian-todo-text";
|
|
text.textContent = todo.status === "in_progress" ? todo.activeForm : todo.content;
|
|
itemEl.appendChild(text);
|
|
this.todoContentEl.appendChild(itemEl);
|
|
}
|
|
}
|
|
/**
|
|
* Get status icon name for a todo item.
|
|
*/
|
|
getStatusIcon(status) {
|
|
switch (status) {
|
|
case "completed":
|
|
return "check-circle-2";
|
|
case "in_progress":
|
|
return "circle-dot";
|
|
case "pending":
|
|
default:
|
|
return "circle";
|
|
}
|
|
}
|
|
/**
|
|
* Toggle expanded/collapsed state.
|
|
*/
|
|
toggle() {
|
|
this.isExpanded = !this.isExpanded;
|
|
this.updateDisplay();
|
|
}
|
|
/**
|
|
* Update display based on expanded state.
|
|
*/
|
|
updateDisplay() {
|
|
if (!this.todoContentEl || !this.todoHeaderEl) return;
|
|
this.todoContentEl.style.display = this.isExpanded ? "block" : "none";
|
|
if (this.currentTodos && this.currentTodos.length > 0) {
|
|
const completedCount = this.currentTodos.filter((t) => t.status === "completed").length;
|
|
const totalCount = this.currentTodos.length;
|
|
const currentTask = this.currentTodos.find((t) => t.status === "in_progress");
|
|
this.renderHeader(completedCount, totalCount, currentTask);
|
|
this.updateAriaLabel(completedCount, totalCount);
|
|
}
|
|
this.scrollToBottom();
|
|
}
|
|
/**
|
|
* Update ARIA label.
|
|
*/
|
|
updateAriaLabel(completedCount, totalCount) {
|
|
if (!this.todoHeaderEl) return;
|
|
const action = this.isExpanded ? "Collapse" : "Expand";
|
|
this.todoHeaderEl.setAttribute(
|
|
"aria-label",
|
|
`${action} task list - ${completedCount} of ${totalCount} completed`
|
|
);
|
|
this.todoHeaderEl.setAttribute("aria-expanded", String(this.isExpanded));
|
|
}
|
|
/**
|
|
* Scroll messages container to bottom.
|
|
*/
|
|
scrollToBottom() {
|
|
if (this.containerEl) {
|
|
this.containerEl.scrollTop = this.containerEl.scrollHeight;
|
|
}
|
|
}
|
|
/**
|
|
* Destroy the panel.
|
|
*/
|
|
destroy() {
|
|
if (this.todoHeaderEl) {
|
|
if (this.clickHandler) {
|
|
this.todoHeaderEl.removeEventListener("click", this.clickHandler);
|
|
}
|
|
if (this.keydownHandler) {
|
|
this.todoHeaderEl.removeEventListener("keydown", this.keydownHandler);
|
|
}
|
|
}
|
|
this.clickHandler = null;
|
|
this.keydownHandler = null;
|
|
if (this.panelEl) {
|
|
this.panelEl.remove();
|
|
this.panelEl = null;
|
|
}
|
|
this.todoContainerEl = null;
|
|
this.todoHeaderEl = null;
|
|
this.todoContentEl = null;
|
|
this.containerEl = null;
|
|
this.currentTodos = null;
|
|
}
|
|
};
|
|
|
|
// src/ui/modals/ApprovalModal.ts
|
|
var import_obsidian9 = require("obsidian");
|
|
|
|
// src/core/tools/toolIcons.ts
|
|
var TOOL_ICONS = {
|
|
[TOOL_READ]: "file-text",
|
|
[TOOL_WRITE]: "edit-3",
|
|
[TOOL_EDIT]: "edit",
|
|
[TOOL_NOTEBOOK_EDIT]: "edit",
|
|
[TOOL_BASH]: "terminal",
|
|
[TOOL_BASH_OUTPUT]: "terminal",
|
|
[TOOL_KILL_SHELL]: "terminal",
|
|
[TOOL_GLOB]: "folder-search",
|
|
[TOOL_GREP]: "search",
|
|
[TOOL_LS]: "list",
|
|
[TOOL_TODO_WRITE]: "list-checks",
|
|
[TOOL_TASK]: "list-checks",
|
|
[TOOL_ASK_USER_QUESTION]: "help-circle",
|
|
[TOOL_LIST_MCP_RESOURCES]: "list",
|
|
[TOOL_READ_MCP_RESOURCE]: "file-text",
|
|
[TOOL_MCP]: "wrench",
|
|
[TOOL_WEB_SEARCH]: "globe",
|
|
[TOOL_WEB_FETCH]: "download",
|
|
[TOOL_AGENT_OUTPUT]: "bot",
|
|
[TOOL_SKILL]: "zap"
|
|
};
|
|
var MCP_ICON_MARKER = "__mcp_icon__";
|
|
function getToolIcon(toolName) {
|
|
if (toolName.startsWith("mcp__")) {
|
|
return MCP_ICON_MARKER;
|
|
}
|
|
return TOOL_ICONS[toolName] || "wrench";
|
|
}
|
|
|
|
// src/ui/modals/ApprovalModal.ts
|
|
var ApprovalModal = class extends import_obsidian9.Modal {
|
|
constructor(app, toolName, _input, description, resolve7, options = {}) {
|
|
super(app);
|
|
this.resolved = false;
|
|
this.buttons = [];
|
|
this.currentButtonIndex = 0;
|
|
this.documentKeydownHandler = null;
|
|
this.toolName = toolName;
|
|
this.description = description;
|
|
this.resolve = resolve7;
|
|
this.options = options;
|
|
}
|
|
onOpen() {
|
|
var _a, _b;
|
|
const { contentEl } = this;
|
|
contentEl.addClass("claudian-approval-modal");
|
|
this.setTitle((_a = this.options.title) != null ? _a : "Permission required");
|
|
const infoEl = contentEl.createDiv({ cls: "claudian-approval-info" });
|
|
const toolEl = infoEl.createDiv({ cls: "claudian-approval-tool" });
|
|
const iconEl = toolEl.createSpan({ cls: "claudian-approval-icon" });
|
|
iconEl.setAttribute("aria-hidden", "true");
|
|
(0, import_obsidian9.setIcon)(iconEl, getToolIcon(this.toolName));
|
|
toolEl.createSpan({ text: this.toolName, cls: "claudian-approval-tool-name" });
|
|
const descEl = contentEl.createDiv({ cls: "claudian-approval-desc" });
|
|
descEl.setText(this.description);
|
|
const buttonsEl = contentEl.createDiv({ cls: "claudian-approval-buttons" });
|
|
const denyBtn = buttonsEl.createEl("button", {
|
|
text: "Deny",
|
|
cls: "claudian-approval-btn claudian-deny-btn",
|
|
attr: { "aria-label": `Deny ${this.toolName} action` }
|
|
});
|
|
denyBtn.addEventListener("click", () => this.handleDecision("deny"));
|
|
const allowBtn = buttonsEl.createEl("button", {
|
|
text: "Allow once",
|
|
cls: "claudian-approval-btn claudian-allow-btn",
|
|
attr: { "aria-label": `Allow ${this.toolName} action once` }
|
|
});
|
|
allowBtn.addEventListener("click", () => this.handleDecision("allow"));
|
|
let alwaysBtn = null;
|
|
if ((_b = this.options.showAlwaysAllow) != null ? _b : true) {
|
|
alwaysBtn = buttonsEl.createEl("button", {
|
|
text: "Always allow",
|
|
cls: "claudian-approval-btn claudian-always-btn",
|
|
attr: { "aria-label": `Always allow ${this.toolName} actions` }
|
|
});
|
|
alwaysBtn.addEventListener("click", () => this.handleDecision("allow-always"));
|
|
}
|
|
this.buttons = [denyBtn, allowBtn];
|
|
if (alwaysBtn) {
|
|
this.buttons.push(alwaysBtn);
|
|
}
|
|
this.currentButtonIndex = 0;
|
|
this.focusCurrentButton();
|
|
this.attachDocumentHandler();
|
|
}
|
|
handleDecision(decision) {
|
|
if (!this.resolved) {
|
|
this.resolved = true;
|
|
this.resolve(decision);
|
|
this.close();
|
|
}
|
|
}
|
|
attachDocumentHandler() {
|
|
this.detachDocumentHandler();
|
|
this.documentKeydownHandler = (e) => {
|
|
if (!this.isNavigationKey(e)) {
|
|
return;
|
|
}
|
|
e.preventDefault();
|
|
e.stopPropagation();
|
|
this.handleNavigationKey(e);
|
|
};
|
|
document.addEventListener("keydown", this.documentKeydownHandler, true);
|
|
}
|
|
detachDocumentHandler() {
|
|
if (this.documentKeydownHandler) {
|
|
document.removeEventListener("keydown", this.documentKeydownHandler, true);
|
|
this.documentKeydownHandler = null;
|
|
}
|
|
}
|
|
isNavigationKey(e) {
|
|
return e.key === "ArrowUp" || e.key === "ArrowDown" || e.key === "ArrowLeft" || e.key === "ArrowRight" || e.key === "Tab";
|
|
}
|
|
handleNavigationKey(e) {
|
|
if (!this.buttons.length) return;
|
|
let direction = 0;
|
|
switch (e.key) {
|
|
case "ArrowUp":
|
|
case "ArrowLeft":
|
|
direction = -1;
|
|
break;
|
|
case "ArrowDown":
|
|
case "ArrowRight":
|
|
direction = 1;
|
|
break;
|
|
case "Tab":
|
|
direction = e.shiftKey ? -1 : 1;
|
|
break;
|
|
default:
|
|
return;
|
|
}
|
|
const total = this.buttons.length;
|
|
this.currentButtonIndex = (this.currentButtonIndex + direction + total) % total;
|
|
this.focusCurrentButton();
|
|
}
|
|
focusCurrentButton() {
|
|
const button = this.buttons[this.currentButtonIndex];
|
|
button == null ? void 0 : button.focus();
|
|
}
|
|
onClose() {
|
|
this.detachDocumentHandler();
|
|
if (!this.resolved) {
|
|
this.resolved = true;
|
|
this.resolve("cancel");
|
|
}
|
|
this.contentEl.empty();
|
|
}
|
|
};
|
|
|
|
// src/ui/modals/InlineEditModal.ts
|
|
var import_obsidian10 = require("obsidian");
|
|
var path11 = __toESM(require("path"));
|
|
|
|
// src/core/prompts/inlineEdit.ts
|
|
function getInlineEditSystemPrompt() {
|
|
return `Today is ${getTodayDate()}.
|
|
|
|
You are **Claudian**, an expert editor and writing assistant embedded in Obsidian. You help users refine their text, answer questions, and generate content with high precision.
|
|
|
|
## Core Directives
|
|
|
|
1. **Style Matching**: Mimic the user's tone, voice, and formatting style (indentation, bullet points, capitalization).
|
|
2. **Context Awareness**: Always Read the full file (or significant context) to understand the broader topic before editing. Do not rely solely on the selection.
|
|
3. **Silent Execution**: Use tools (Read, WebSearch) silently. Your final output must be ONLY the result.
|
|
4. **No Fluff**: No pleasantries, no "Here is the text", no "I have updated...". Just the content.
|
|
|
|
## Input Format
|
|
|
|
User messages use XML tags:
|
|
|
|
### Selection Mode
|
|
\`\`\`xml
|
|
<editor_selection path="path/to/file.md">
|
|
selected text here
|
|
</editor_selection>
|
|
|
|
<query>
|
|
user's instruction
|
|
</query>
|
|
\`\`\`
|
|
Use \`<replacement>\` tags for edits.
|
|
|
|
### Cursor Mode
|
|
\`\`\`xml
|
|
<editor_cursor path="path/to/file.md">
|
|
text before|text after #inline
|
|
</editor_cursor>
|
|
\`\`\`
|
|
Or between paragraphs:
|
|
\`\`\`xml
|
|
<editor_cursor path="path/to/file.md">
|
|
Previous paragraph
|
|
| #inbetween
|
|
Next paragraph
|
|
</editor_cursor>
|
|
\`\`\`
|
|
Use \`<insertion>\` tags to insert new content at the cursor position (\`|\`).
|
|
|
|
## Tools & Path Rules
|
|
|
|
- **Tools**: Read, Grep, Glob, LS, WebSearch, WebFetch. (All read-only).
|
|
- **Paths**: Must be RELATIVE to vault root (e.g., "notes/file.md").
|
|
|
|
## Thinking Process
|
|
|
|
Before generating the final output, mentally check:
|
|
1. **Context**: Have I read enough of the file to understand the *topic* and *structure*?
|
|
2. **Style**: What is the user's indentation (2 vs 4 spaces, tabs)? What is their tone?
|
|
3. **Type**: Is this **Prose** (flow, grammar, clarity) or **Code** (syntax, logic, variable names)?
|
|
- *Prose*: Ensure smooth transitions.
|
|
- *Code*: Preserve syntax validity; do not break surrounding brackets/indentation.
|
|
|
|
## Output Rules - CRITICAL
|
|
|
|
**ABSOLUTE RULE**: Your text output must contain ONLY the final answer, replacement, or insertion. NEVER output:
|
|
- "I'll read the file..." / "Let me check..." / "I will..."
|
|
- "I'm asked about..." / "The user wants..."
|
|
- "Based on my analysis..." / "After reading..."
|
|
- "Here's..." / "The answer is..."
|
|
- ANY announcement of what you're about to do or did
|
|
|
|
Use tools silently. Your text output = final result only.
|
|
|
|
### When Replacing Selected Text (Selection Mode)
|
|
|
|
If the user wants to MODIFY or REPLACE the selected text, wrap the replacement in <replacement> tags:
|
|
|
|
<replacement>your replacement text here</replacement>
|
|
|
|
The content inside the tags should be ONLY the replacement text - no explanation.
|
|
|
|
### When Inserting at Cursor (Cursor Mode)
|
|
|
|
If the user wants to INSERT new content at the cursor position, wrap the insertion in <insertion> tags:
|
|
|
|
<insertion>your inserted text here</insertion>
|
|
|
|
The content inside the tags should be ONLY the text to insert - no explanation.
|
|
|
|
### When Answering Questions or Providing Information
|
|
|
|
If the user is asking a QUESTION, respond WITHOUT tags. Output the answer directly.
|
|
|
|
WRONG: "I'll read the full context of this file to give you a better explanation. This is a guide about..."
|
|
CORRECT: "This is a guide about..."
|
|
|
|
### When Clarification is Needed
|
|
|
|
If the request is ambiguous, ask a clarifying question. Keep questions concise and specific.
|
|
|
|
## Examples
|
|
|
|
### Selection Mode
|
|
Input:
|
|
\`\`\`xml
|
|
<editor_selection path="notes/readme.md">
|
|
Hello world
|
|
</editor_selection>
|
|
|
|
<query>
|
|
translate to French
|
|
</query>
|
|
\`\`\`
|
|
|
|
CORRECT (replacement):
|
|
<replacement>Bonjour le monde</replacement>
|
|
|
|
Input:
|
|
\`\`\`xml
|
|
<editor_selection path="notes/code.md">
|
|
const x = arr.reduce((a, b) => a + b, 0);
|
|
</editor_selection>
|
|
|
|
<query>
|
|
what does this do?
|
|
</query>
|
|
\`\`\`
|
|
|
|
CORRECT (question - no tags):
|
|
This code sums all numbers in the array \`arr\`. It uses \`reduce\` to iterate through the array, accumulating the total starting from 0.
|
|
|
|
### Cursor Mode
|
|
|
|
Input:
|
|
\`\`\`xml
|
|
<editor_cursor path="notes/draft.md">
|
|
The quick brown | jumps over the lazy dog. #inline
|
|
</editor_cursor>
|
|
|
|
<query>
|
|
what animal?
|
|
</query>
|
|
\`\`\`
|
|
|
|
CORRECT (insertion):
|
|
<insertion>fox</insertion>
|
|
|
|
### Q&A
|
|
Input:
|
|
\`\`\`xml
|
|
<editor_cursor path="notes/readme.md">
|
|
# Introduction
|
|
This is my project.
|
|
| #inbetween
|
|
## Features
|
|
</editor_cursor>
|
|
|
|
<query>
|
|
add a brief description section
|
|
</query>
|
|
\`\`\`
|
|
|
|
CORRECT (insertion):
|
|
<insertion>
|
|
## Description
|
|
|
|
This project provides tools for managing your notes efficiently.
|
|
</insertion>
|
|
|
|
Input:
|
|
\`\`\`xml
|
|
<editor_selection path="notes/draft.md">
|
|
The bank was steep.
|
|
</editor_selection>
|
|
|
|
<query>
|
|
translate to Spanish
|
|
</query>
|
|
\`\`\`
|
|
|
|
CORRECT (asking for clarification):
|
|
"Bank" can mean a financial institution (banco) or a river bank (orilla). Which meaning should I use?
|
|
|
|
Then after user clarifies "river bank":
|
|
<replacement>La orilla era empinada.</replacement>`;
|
|
}
|
|
|
|
// src/features/inline-edit/InlineEditService.ts
|
|
var InlineEditService = class {
|
|
constructor(plugin) {
|
|
this.abortController = null;
|
|
this.resolvedClaudePath = null;
|
|
this.sessionId = null;
|
|
this.plugin = plugin;
|
|
}
|
|
/** Resets conversation state for a new edit session. */
|
|
resetConversation() {
|
|
this.sessionId = null;
|
|
}
|
|
findClaudeCLI() {
|
|
return findClaudeCLIPath();
|
|
}
|
|
/** Edits text according to instructions (initial request). */
|
|
async editText(request) {
|
|
this.sessionId = null;
|
|
const prompt = this.buildPrompt(request);
|
|
return this.sendMessage(prompt);
|
|
}
|
|
/** Continues conversation with a follow-up message. */
|
|
async continueConversation(message, contextFiles) {
|
|
if (!this.sessionId) {
|
|
return { success: false, error: "No active conversation to continue" };
|
|
}
|
|
let prompt = message;
|
|
if (contextFiles && contextFiles.length > 0) {
|
|
prompt = prependContextFiles(message, contextFiles);
|
|
}
|
|
return this.sendMessage(prompt);
|
|
}
|
|
async sendMessage(prompt) {
|
|
var _a;
|
|
const vaultPath = getVaultPath(this.plugin.app);
|
|
if (!vaultPath) {
|
|
return { success: false, error: "Could not determine vault path" };
|
|
}
|
|
if (!this.resolvedClaudePath) {
|
|
this.resolvedClaudePath = this.findClaudeCLI();
|
|
}
|
|
if (!this.resolvedClaudePath) {
|
|
return { success: false, error: "Claude CLI not found. Please install Claude Code CLI." };
|
|
}
|
|
this.abortController = new AbortController();
|
|
const customEnv = parseEnvironmentVariables(this.plugin.getActiveEnvironmentVariables());
|
|
const options = {
|
|
cwd: vaultPath,
|
|
systemPrompt: getInlineEditSystemPrompt(),
|
|
model: this.plugin.settings.model,
|
|
abortController: this.abortController,
|
|
pathToClaudeCodeExecutable: this.resolvedClaudePath,
|
|
env: {
|
|
...process.env,
|
|
...customEnv,
|
|
PATH: getEnhancedPath(customEnv.PATH)
|
|
},
|
|
allowedTools: [...READ_ONLY_TOOLS],
|
|
permissionMode: "bypassPermissions",
|
|
allowDangerouslySkipPermissions: true,
|
|
hooks: {
|
|
PreToolUse: [
|
|
this.createReadOnlyHook(),
|
|
this.createVaultRestrictionHook(vaultPath)
|
|
]
|
|
}
|
|
};
|
|
if (this.sessionId) {
|
|
options.resume = this.sessionId;
|
|
}
|
|
const budgetSetting = this.plugin.settings.thinkingBudget;
|
|
const budgetConfig = THINKING_BUDGETS.find((b) => b.value === budgetSetting);
|
|
if (budgetConfig && budgetConfig.tokens > 0) {
|
|
options.maxThinkingTokens = budgetConfig.tokens;
|
|
}
|
|
try {
|
|
const response = query({ prompt, options });
|
|
let responseText = "";
|
|
for await (const message of response) {
|
|
if ((_a = this.abortController) == null ? void 0 : _a.signal.aborted) {
|
|
await response.interrupt();
|
|
return { success: false, error: "Cancelled" };
|
|
}
|
|
if (message.type === "system" && message.subtype === "init" && message.session_id) {
|
|
this.sessionId = message.session_id;
|
|
}
|
|
const text = this.extractTextFromMessage(message);
|
|
if (text) {
|
|
responseText += text;
|
|
}
|
|
}
|
|
return this.parseResponse(responseText);
|
|
} catch (error2) {
|
|
console.error("[InlineEditService] Error:", error2);
|
|
const msg = error2 instanceof Error ? error2.message : "Unknown error";
|
|
return { success: false, error: msg };
|
|
} finally {
|
|
this.abortController = null;
|
|
}
|
|
}
|
|
/** Parses response text for <replacement> or <insertion> tag. */
|
|
parseResponse(responseText) {
|
|
const replacementMatch = responseText.match(/<replacement>([\s\S]*?)<\/replacement>/);
|
|
if (replacementMatch) {
|
|
return { success: true, editedText: replacementMatch[1] };
|
|
}
|
|
const insertionMatch = responseText.match(/<insertion>([\s\S]*?)<\/insertion>/);
|
|
if (insertionMatch) {
|
|
return { success: true, insertedText: insertionMatch[1] };
|
|
}
|
|
const trimmed = responseText.trim();
|
|
if (trimmed) {
|
|
return { success: true, clarification: trimmed };
|
|
}
|
|
return { success: false, error: "Empty response" };
|
|
}
|
|
buildPrompt(request) {
|
|
let prompt;
|
|
if (request.mode === "cursor") {
|
|
prompt = this.buildCursorPrompt(request);
|
|
} else {
|
|
const lineAttr = request.startLine && request.lineCount ? ` lines="${request.startLine}-${request.startLine + request.lineCount - 1}"` : "";
|
|
prompt = [
|
|
`<editor_selection path="${request.notePath}"${lineAttr}>`,
|
|
request.selectedText,
|
|
"</editor_selection>",
|
|
"",
|
|
"<query>",
|
|
request.instruction,
|
|
"</query>"
|
|
].join("\n");
|
|
}
|
|
if (request.contextFiles && request.contextFiles.length > 0) {
|
|
prompt = prependContextFiles(prompt, request.contextFiles);
|
|
}
|
|
return prompt;
|
|
}
|
|
buildCursorPrompt(request) {
|
|
const ctx = request.cursorContext;
|
|
const lineAttr = ` line="${ctx.line + 1}"`;
|
|
let cursorContent;
|
|
if (ctx.isInbetween) {
|
|
const parts = [];
|
|
if (ctx.beforeCursor) parts.push(ctx.beforeCursor);
|
|
parts.push("| #inbetween");
|
|
if (ctx.afterCursor) parts.push(ctx.afterCursor);
|
|
cursorContent = parts.join("\n");
|
|
} else {
|
|
cursorContent = `${ctx.beforeCursor}|${ctx.afterCursor} #inline`;
|
|
}
|
|
return [
|
|
`<editor_cursor path="${request.notePath}"${lineAttr}>`,
|
|
cursorContent,
|
|
"</editor_cursor>",
|
|
"",
|
|
"<query>",
|
|
request.instruction,
|
|
"</query>"
|
|
].join("\n");
|
|
}
|
|
/** Creates PreToolUse hook to enforce read-only mode. */
|
|
createReadOnlyHook() {
|
|
return {
|
|
hooks: [
|
|
async (hookInput) => {
|
|
const input = hookInput;
|
|
const toolName = input.tool_name;
|
|
if (isReadOnlyTool(toolName)) {
|
|
return { continue: true };
|
|
}
|
|
return {
|
|
continue: false,
|
|
hookSpecificOutput: {
|
|
hookEventName: "PreToolUse",
|
|
permissionDecision: "deny",
|
|
permissionDecisionReason: `Inline edit mode: tool "${toolName}" is not allowed (read-only)`
|
|
}
|
|
};
|
|
}
|
|
]
|
|
};
|
|
}
|
|
/** Creates PreToolUse hook to restrict file tools to the vault. */
|
|
createVaultRestrictionHook(vaultPath) {
|
|
const fileTools = [TOOL_READ, TOOL_GLOB, TOOL_GREP, TOOL_LS];
|
|
return {
|
|
hooks: [
|
|
async (hookInput) => {
|
|
const input = hookInput;
|
|
const toolName = input.tool_name;
|
|
if (!fileTools.includes(toolName)) {
|
|
return { continue: true };
|
|
}
|
|
const filePath = getPathFromToolInput(toolName, input.tool_input);
|
|
if (filePath && !isPathWithinVault(filePath, vaultPath)) {
|
|
return {
|
|
continue: false,
|
|
hookSpecificOutput: {
|
|
hookEventName: "PreToolUse",
|
|
permissionDecision: "deny",
|
|
permissionDecisionReason: `Access denied: Path "${filePath}" is outside the vault. Inline edit is restricted to vault directory only.`
|
|
}
|
|
};
|
|
}
|
|
return { continue: true };
|
|
}
|
|
]
|
|
};
|
|
}
|
|
extractTextFromMessage(message) {
|
|
var _a, _b, _c;
|
|
if (message.type === "assistant" && ((_a = message.message) == null ? void 0 : _a.content)) {
|
|
for (const block of message.message.content) {
|
|
if (block.type === "text" && block.text) {
|
|
return block.text;
|
|
}
|
|
}
|
|
}
|
|
if (message.type === "stream_event") {
|
|
const event = message.event;
|
|
if ((event == null ? void 0 : event.type) === "content_block_start" && ((_b = event.content_block) == null ? void 0 : _b.type) === "text") {
|
|
return event.content_block.text || null;
|
|
}
|
|
if ((event == null ? void 0 : event.type) === "content_block_delta" && ((_c = event.delta) == null ? void 0 : _c.type) === "text_delta") {
|
|
return event.delta.text || null;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
/** Cancels the current edit operation. */
|
|
cancel() {
|
|
if (this.abortController) {
|
|
this.abortController.abort();
|
|
}
|
|
}
|
|
};
|
|
|
|
// src/utils/inlineEdit.ts
|
|
function normalizeInsertionText(text) {
|
|
return text.replace(/^(?:\r?\n)+|(?:\r?\n)+$/g, "");
|
|
}
|
|
function escapeHtml(text) {
|
|
return text.replace(/</g, "<").replace(/>/g, ">");
|
|
}
|
|
|
|
// src/ui/modals/InlineEditModal.ts
|
|
var import_state2 = require("@codemirror/state");
|
|
var import_view2 = require("@codemirror/view");
|
|
var showInlineEdit = import_state2.StateEffect.define();
|
|
var showDiff = import_state2.StateEffect.define();
|
|
var showInsertion = import_state2.StateEffect.define();
|
|
var hideInlineEdit = import_state2.StateEffect.define();
|
|
var activeController = null;
|
|
var DiffWidget = class extends import_view2.WidgetType {
|
|
constructor(diffHtml, controller) {
|
|
super();
|
|
this.diffHtml = diffHtml;
|
|
this.controller = controller;
|
|
}
|
|
toDOM() {
|
|
const span = document.createElement("span");
|
|
span.className = "claudian-inline-diff-replace";
|
|
span.innerHTML = this.diffHtml;
|
|
const btns = document.createElement("span");
|
|
btns.className = "claudian-inline-diff-buttons";
|
|
const rejectBtn = document.createElement("button");
|
|
rejectBtn.className = "claudian-inline-diff-btn reject";
|
|
rejectBtn.textContent = "\u2715";
|
|
rejectBtn.title = "Reject (Esc)";
|
|
rejectBtn.onclick = () => this.controller.reject();
|
|
const acceptBtn = document.createElement("button");
|
|
acceptBtn.className = "claudian-inline-diff-btn accept";
|
|
acceptBtn.textContent = "\u2713";
|
|
acceptBtn.title = "Accept (Enter)";
|
|
acceptBtn.onclick = () => this.controller.accept();
|
|
btns.appendChild(rejectBtn);
|
|
btns.appendChild(acceptBtn);
|
|
span.appendChild(btns);
|
|
return span;
|
|
}
|
|
eq(other) {
|
|
return this.diffHtml === other.diffHtml;
|
|
}
|
|
ignoreEvent() {
|
|
return true;
|
|
}
|
|
};
|
|
var InputWidget = class extends import_view2.WidgetType {
|
|
constructor(controller) {
|
|
super();
|
|
this.controller = controller;
|
|
}
|
|
toDOM() {
|
|
return this.controller.createInputDOM();
|
|
}
|
|
eq() {
|
|
return false;
|
|
}
|
|
ignoreEvent() {
|
|
return true;
|
|
}
|
|
};
|
|
var inlineEditField = import_state2.StateField.define({
|
|
create: () => import_view2.Decoration.none,
|
|
update: (deco, tr) => {
|
|
var _a;
|
|
deco = deco.map(tr.changes);
|
|
for (const e of tr.effects) {
|
|
if (e.is(showInlineEdit)) {
|
|
const builder = new import_state2.RangeSetBuilder();
|
|
const isInbetween = (_a = e.value.isInbetween) != null ? _a : false;
|
|
builder.add(e.value.inputPos, e.value.inputPos, import_view2.Decoration.widget({
|
|
widget: new InputWidget(e.value.widget),
|
|
block: !isInbetween,
|
|
side: isInbetween ? 1 : -1
|
|
}));
|
|
deco = builder.finish();
|
|
} else if (e.is(showDiff)) {
|
|
const builder = new import_state2.RangeSetBuilder();
|
|
builder.add(e.value.from, e.value.to, import_view2.Decoration.replace({
|
|
widget: new DiffWidget(e.value.diffHtml, e.value.widget)
|
|
}));
|
|
deco = builder.finish();
|
|
} else if (e.is(showInsertion)) {
|
|
const builder = new import_state2.RangeSetBuilder();
|
|
builder.add(e.value.pos, e.value.pos, import_view2.Decoration.widget({
|
|
widget: new DiffWidget(e.value.diffHtml, e.value.widget),
|
|
side: 1
|
|
// Display after the position
|
|
}));
|
|
deco = builder.finish();
|
|
} else if (e.is(hideInlineEdit)) {
|
|
deco = import_view2.Decoration.none;
|
|
}
|
|
}
|
|
return deco;
|
|
},
|
|
provide: (f) => import_view2.EditorView.decorations.from(f)
|
|
});
|
|
var installedEditors = /* @__PURE__ */ new WeakSet();
|
|
function computeDiff(oldText, newText) {
|
|
const oldWords = oldText.split(/(\s+)/);
|
|
const newWords = newText.split(/(\s+)/);
|
|
const m = oldWords.length, n = newWords.length;
|
|
const dp = Array(m + 1).fill(null).map(() => Array(n + 1).fill(0));
|
|
for (let i2 = 1; i2 <= m; i2++) {
|
|
for (let j2 = 1; j2 <= n; j2++) {
|
|
dp[i2][j2] = oldWords[i2 - 1] === newWords[j2 - 1] ? dp[i2 - 1][j2 - 1] + 1 : Math.max(dp[i2 - 1][j2], dp[i2][j2 - 1]);
|
|
}
|
|
}
|
|
const ops = [];
|
|
let i = m, j = n;
|
|
const temp = [];
|
|
while (i > 0 || j > 0) {
|
|
if (i > 0 && j > 0 && oldWords[i - 1] === newWords[j - 1]) {
|
|
temp.push({ type: "equal", text: oldWords[i - 1] });
|
|
i--;
|
|
j--;
|
|
} else if (j > 0 && (i === 0 || dp[i][j - 1] >= dp[i - 1][j])) {
|
|
temp.push({ type: "insert", text: newWords[j - 1] });
|
|
j--;
|
|
} else {
|
|
temp.push({ type: "delete", text: oldWords[i - 1] });
|
|
i--;
|
|
}
|
|
}
|
|
temp.reverse();
|
|
for (const op of temp) {
|
|
if (ops.length > 0 && ops[ops.length - 1].type === op.type) {
|
|
ops[ops.length - 1].text += op.text;
|
|
} else {
|
|
ops.push({ ...op });
|
|
}
|
|
}
|
|
return ops;
|
|
}
|
|
function diffToHtml(ops) {
|
|
return ops.map((op) => {
|
|
const escaped = escapeHtml(op.text);
|
|
switch (op.type) {
|
|
case "delete":
|
|
return `<span class="claudian-diff-del">${escaped}</span>`;
|
|
case "insert":
|
|
return `<span class="claudian-diff-ins">${escaped}</span>`;
|
|
default:
|
|
return escaped;
|
|
}
|
|
}).join("");
|
|
}
|
|
var InlineEditModal = class {
|
|
constructor(app, plugin, editContext, notePath) {
|
|
this.app = app;
|
|
this.plugin = plugin;
|
|
this.editContext = editContext;
|
|
this.notePath = notePath;
|
|
this.controller = null;
|
|
}
|
|
async openAndWait() {
|
|
if (activeController) {
|
|
activeController.reject();
|
|
return { decision: "reject" };
|
|
}
|
|
const view = this.app.workspace.getActiveViewOfType(import_obsidian10.MarkdownView);
|
|
if (!view) return { decision: "reject" };
|
|
const editor = view.editor;
|
|
const editorView = editor.cm;
|
|
if (!editorView) return { decision: "reject" };
|
|
return new Promise((resolve7) => {
|
|
this.controller = new InlineEditController(
|
|
this.app,
|
|
this.plugin,
|
|
editorView,
|
|
editor,
|
|
this.editContext,
|
|
this.notePath,
|
|
resolve7
|
|
);
|
|
activeController = this.controller;
|
|
this.controller.show();
|
|
});
|
|
}
|
|
};
|
|
var InlineEditController = class {
|
|
constructor(app, plugin, editorView, editor, editContext, notePath, resolve7) {
|
|
this.app = app;
|
|
this.plugin = plugin;
|
|
this.editorView = editorView;
|
|
this.editor = editor;
|
|
this.notePath = notePath;
|
|
this.resolve = resolve7;
|
|
this.inputEl = null;
|
|
this.spinnerEl = null;
|
|
this.agentReplyEl = null;
|
|
this.containerEl = null;
|
|
this.editedText = null;
|
|
this.insertedText = null;
|
|
this.startLine = 0;
|
|
this.cursorContext = null;
|
|
this.escHandler = null;
|
|
this.selectionListener = null;
|
|
this.isConversing = false;
|
|
// True when agent asked clarification
|
|
this.slashCommandManager = null;
|
|
this.slashCommandDropdown = null;
|
|
this.mentionDropdown = null;
|
|
this.attachedFiles = /* @__PURE__ */ new Set();
|
|
this.inlineEditService = new InlineEditService(plugin);
|
|
this.mode = editContext.mode;
|
|
if (editContext.mode === "cursor") {
|
|
this.cursorContext = editContext.cursorContext;
|
|
this.selectedText = "";
|
|
} else {
|
|
this.selectedText = editContext.selectedText;
|
|
}
|
|
this.updatePositionsFromEditor();
|
|
}
|
|
updatePositionsFromEditor() {
|
|
const doc = this.editorView.state.doc;
|
|
if (this.mode === "cursor") {
|
|
const ctx = this.cursorContext;
|
|
const line = doc.line(ctx.line + 1);
|
|
this.selFrom = line.from + ctx.column;
|
|
this.selTo = this.selFrom;
|
|
} else {
|
|
const from = this.editor.getCursor("from");
|
|
const to = this.editor.getCursor("to");
|
|
const fromLine = doc.line(from.line + 1);
|
|
const toLine = doc.line(to.line + 1);
|
|
this.selFrom = fromLine.from + from.ch;
|
|
this.selTo = toLine.from + to.ch;
|
|
this.selectedText = this.editor.getSelection() || this.selectedText;
|
|
this.startLine = from.line + 1;
|
|
}
|
|
}
|
|
show() {
|
|
if (!installedEditors.has(this.editorView)) {
|
|
this.editorView.dispatch({
|
|
effects: import_state2.StateEffect.appendConfig.of(inlineEditField)
|
|
});
|
|
installedEditors.add(this.editorView);
|
|
}
|
|
this.updateHighlight();
|
|
if (this.mode === "selection") {
|
|
this.attachSelectionListeners();
|
|
}
|
|
this.escHandler = (e) => {
|
|
if (e.key === "Escape") {
|
|
this.reject();
|
|
}
|
|
};
|
|
document.addEventListener("keydown", this.escHandler);
|
|
}
|
|
updateHighlight() {
|
|
var _a;
|
|
const doc = this.editorView.state.doc;
|
|
const line = doc.lineAt(this.selFrom);
|
|
const isInbetween = this.mode === "cursor" && ((_a = this.cursorContext) == null ? void 0 : _a.isInbetween);
|
|
this.editorView.dispatch({
|
|
effects: showInlineEdit.of({
|
|
inputPos: isInbetween ? this.selFrom : line.from,
|
|
selFrom: this.selFrom,
|
|
selTo: this.selTo,
|
|
widget: this,
|
|
isInbetween
|
|
})
|
|
});
|
|
this.updateSelectionHighlight();
|
|
}
|
|
updateSelectionHighlight() {
|
|
if (this.mode === "selection" && this.selFrom !== this.selTo) {
|
|
showSelectionHighlight(this.editorView, this.selFrom, this.selTo);
|
|
} else {
|
|
hideSelectionHighlight(this.editorView);
|
|
}
|
|
}
|
|
attachSelectionListeners() {
|
|
this.removeSelectionListeners();
|
|
this.selectionListener = (e) => {
|
|
const target = e.target;
|
|
if (target && this.inputEl && (target === this.inputEl || this.inputEl.contains(target))) {
|
|
return;
|
|
}
|
|
const prevFrom = this.selFrom;
|
|
const prevTo = this.selTo;
|
|
const newSelection = this.editor.getSelection();
|
|
if (newSelection && newSelection.length > 0) {
|
|
this.updatePositionsFromEditor();
|
|
if (prevFrom !== this.selFrom || prevTo !== this.selTo) {
|
|
this.updateHighlight();
|
|
}
|
|
}
|
|
};
|
|
this.editorView.dom.addEventListener("mouseup", this.selectionListener);
|
|
this.editorView.dom.addEventListener("keyup", this.selectionListener);
|
|
}
|
|
createInputDOM() {
|
|
const container = document.createElement("div");
|
|
container.className = "claudian-inline-input-container";
|
|
this.containerEl = container;
|
|
this.agentReplyEl = document.createElement("div");
|
|
this.agentReplyEl.className = "claudian-inline-agent-reply";
|
|
this.agentReplyEl.style.display = "none";
|
|
container.appendChild(this.agentReplyEl);
|
|
const inputWrap = document.createElement("div");
|
|
inputWrap.className = "claudian-inline-input-wrap";
|
|
container.appendChild(inputWrap);
|
|
this.inputEl = document.createElement("input");
|
|
this.inputEl.type = "text";
|
|
this.inputEl.className = "claudian-inline-input";
|
|
this.inputEl.placeholder = this.mode === "cursor" ? "Insert instructions..." : "Edit instructions...";
|
|
this.inputEl.spellcheck = false;
|
|
inputWrap.appendChild(this.inputEl);
|
|
this.spinnerEl = document.createElement("div");
|
|
this.spinnerEl.className = "claudian-inline-spinner";
|
|
this.spinnerEl.style.display = "none";
|
|
inputWrap.appendChild(this.spinnerEl);
|
|
const vaultPath = getVaultPath(this.app);
|
|
if (vaultPath) {
|
|
this.slashCommandManager = new SlashCommandManager(this.app, vaultPath);
|
|
this.slashCommandManager.setCommands(this.plugin.settings.slashCommands);
|
|
this.slashCommandDropdown = new SlashCommandDropdown(
|
|
document.body,
|
|
// Use body for fixed positioning
|
|
this.inputEl,
|
|
{
|
|
onSelect: () => {
|
|
},
|
|
onHide: () => {
|
|
},
|
|
getCommands: () => this.plugin.settings.slashCommands
|
|
},
|
|
{ fixed: true }
|
|
);
|
|
}
|
|
this.mentionDropdown = new MentionDropdownController(
|
|
document.body,
|
|
this.inputEl,
|
|
{
|
|
onAttachFile: (filePath) => this.attachedFiles.add(filePath),
|
|
onMcpMentionChange: () => {
|
|
},
|
|
getMentionedMcpServers: () => /* @__PURE__ */ new Set(),
|
|
setMentionedMcpServers: () => false,
|
|
addMentionedMcpServer: () => {
|
|
},
|
|
getContextPaths: () => [],
|
|
getCachedMarkdownFiles: () => {
|
|
try {
|
|
return this.app.vault.getMarkdownFiles();
|
|
} catch (error2) {
|
|
console.error("[InlineEditModal] getCachedMarkdownFiles error:", error2);
|
|
return [];
|
|
}
|
|
},
|
|
normalizePathForVault: (rawPath) => this.normalizePathForVault(rawPath)
|
|
},
|
|
{ fixed: true }
|
|
);
|
|
this.inputEl.addEventListener("keydown", (e) => this.handleKeydown(e));
|
|
this.inputEl.addEventListener("input", () => {
|
|
var _a;
|
|
return (_a = this.mentionDropdown) == null ? void 0 : _a.handleInputChange();
|
|
});
|
|
setTimeout(() => {
|
|
var _a;
|
|
return (_a = this.inputEl) == null ? void 0 : _a.focus();
|
|
}, 50);
|
|
return container;
|
|
}
|
|
async generate() {
|
|
if (!this.inputEl || !this.spinnerEl) return;
|
|
let userMessage = this.inputEl.value.trim();
|
|
if (!userMessage) return;
|
|
if (this.slashCommandManager) {
|
|
this.slashCommandManager.setCommands(this.plugin.settings.slashCommands);
|
|
const detected = this.slashCommandManager.detectCommand(userMessage);
|
|
if (detected) {
|
|
const cmd = this.plugin.settings.slashCommands.find(
|
|
(c) => c.name.toLowerCase() === detected.commandName.toLowerCase()
|
|
);
|
|
if (cmd) {
|
|
const expansion = await this.slashCommandManager.expandCommand(cmd, detected.args, {
|
|
bash: {
|
|
enabled: true,
|
|
shouldBlockCommand: (bashCommand) => isCommandBlocked(
|
|
bashCommand,
|
|
getBashToolBlockedCommands(this.plugin.settings.blockedCommands),
|
|
this.plugin.settings.enableBlocklist
|
|
),
|
|
requestApproval: this.plugin.settings.permissionMode !== "yolo" ? (bashCommand) => this.requestInlineBashApproval(bashCommand) : void 0
|
|
}
|
|
});
|
|
userMessage = expansion.expandedPrompt;
|
|
if (expansion.errors.length > 0) {
|
|
new import_obsidian10.Notice(formatSlashCommandWarnings(expansion.errors));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
this.removeSelectionListeners();
|
|
this.inputEl.disabled = true;
|
|
this.spinnerEl.style.display = "block";
|
|
const contextFiles = Array.from(this.attachedFiles);
|
|
this.attachedFiles.clear();
|
|
let result;
|
|
if (this.isConversing) {
|
|
result = await this.inlineEditService.continueConversation(userMessage, contextFiles);
|
|
} else {
|
|
if (this.mode === "cursor") {
|
|
result = await this.inlineEditService.editText({
|
|
mode: "cursor",
|
|
instruction: userMessage,
|
|
notePath: this.notePath,
|
|
cursorContext: this.cursorContext,
|
|
contextFiles
|
|
});
|
|
} else {
|
|
const lineCount = this.selectedText.split(/\r?\n/).length;
|
|
result = await this.inlineEditService.editText({
|
|
mode: "selection",
|
|
instruction: userMessage,
|
|
notePath: this.notePath,
|
|
selectedText: this.selectedText,
|
|
startLine: this.startLine,
|
|
lineCount,
|
|
contextFiles
|
|
});
|
|
}
|
|
}
|
|
this.spinnerEl.style.display = "none";
|
|
if (result.success) {
|
|
if (result.editedText !== void 0) {
|
|
this.editedText = result.editedText;
|
|
this.showDiffInPlace();
|
|
} else if (result.insertedText !== void 0) {
|
|
this.insertedText = result.insertedText;
|
|
this.showInsertionInPlace();
|
|
} else if (result.clarification) {
|
|
this.showAgentReply(result.clarification);
|
|
this.isConversing = true;
|
|
this.inputEl.disabled = false;
|
|
this.inputEl.value = "";
|
|
this.inputEl.placeholder = "Reply to continue...";
|
|
this.inputEl.focus();
|
|
} else {
|
|
this.handleError("No response from agent");
|
|
}
|
|
} else {
|
|
this.handleError(result.error || "Error - try again");
|
|
}
|
|
}
|
|
/** Show agent's clarification message. */
|
|
showAgentReply(message) {
|
|
if (!this.agentReplyEl || !this.containerEl) return;
|
|
this.agentReplyEl.style.display = "block";
|
|
this.agentReplyEl.textContent = message;
|
|
this.containerEl.classList.add("has-agent-reply");
|
|
}
|
|
/** Handle error state. */
|
|
handleError(errorMessage) {
|
|
if (!this.inputEl) return;
|
|
this.inputEl.disabled = false;
|
|
this.inputEl.placeholder = errorMessage;
|
|
this.updatePositionsFromEditor();
|
|
this.updateHighlight();
|
|
this.attachSelectionListeners();
|
|
this.inputEl.focus();
|
|
}
|
|
showDiffInPlace() {
|
|
if (this.editedText === null) return;
|
|
hideSelectionHighlight(this.editorView);
|
|
const diffOps = computeDiff(this.selectedText, this.editedText);
|
|
const diffHtml = diffToHtml(diffOps);
|
|
this.editorView.dispatch({
|
|
effects: showDiff.of({
|
|
from: this.selFrom,
|
|
to: this.selTo,
|
|
diffHtml,
|
|
widget: this
|
|
})
|
|
});
|
|
if (this.escHandler) {
|
|
document.removeEventListener("keydown", this.escHandler);
|
|
}
|
|
this.escHandler = (e) => {
|
|
if (e.key === "Escape") {
|
|
this.reject();
|
|
} else if (e.key === "Enter") {
|
|
this.accept();
|
|
}
|
|
};
|
|
document.addEventListener("keydown", this.escHandler);
|
|
}
|
|
/** Show insertion preview (all green, no deletions) for cursor mode. */
|
|
showInsertionInPlace() {
|
|
if (this.insertedText === null) return;
|
|
hideSelectionHighlight(this.editorView);
|
|
const trimmedText = normalizeInsertionText(this.insertedText);
|
|
this.insertedText = trimmedText;
|
|
const escaped = escapeHtml(trimmedText);
|
|
const diffHtml = `<span class="claudian-diff-ins">${escaped}</span>`;
|
|
this.editorView.dispatch({
|
|
effects: showInsertion.of({
|
|
pos: this.selFrom,
|
|
diffHtml,
|
|
widget: this
|
|
})
|
|
});
|
|
if (this.escHandler) {
|
|
document.removeEventListener("keydown", this.escHandler);
|
|
}
|
|
this.escHandler = (e) => {
|
|
if (e.key === "Escape") {
|
|
this.reject();
|
|
} else if (e.key === "Enter") {
|
|
this.accept();
|
|
}
|
|
};
|
|
document.addEventListener("keydown", this.escHandler);
|
|
}
|
|
accept() {
|
|
var _a;
|
|
const textToInsert = (_a = this.editedText) != null ? _a : this.insertedText;
|
|
if (textToInsert !== null) {
|
|
const doc = this.editorView.state.doc;
|
|
const fromLine = doc.lineAt(this.selFrom);
|
|
const toLine = doc.lineAt(this.selTo);
|
|
const from = { line: fromLine.number - 1, ch: this.selFrom - fromLine.from };
|
|
const to = { line: toLine.number - 1, ch: this.selTo - toLine.from };
|
|
this.cleanup();
|
|
this.editor.replaceRange(textToInsert, from, to);
|
|
this.resolve({ decision: "accept", editedText: textToInsert });
|
|
} else {
|
|
this.cleanup();
|
|
this.resolve({ decision: "reject" });
|
|
}
|
|
}
|
|
reject() {
|
|
this.cleanup({ keepSelectionHighlight: true });
|
|
this.restoreSelectionHighlight();
|
|
this.resolve({ decision: "reject" });
|
|
}
|
|
removeSelectionListeners() {
|
|
if (this.selectionListener) {
|
|
this.editorView.dom.removeEventListener("mouseup", this.selectionListener);
|
|
this.editorView.dom.removeEventListener("keyup", this.selectionListener);
|
|
this.selectionListener = null;
|
|
}
|
|
}
|
|
cleanup(options) {
|
|
var _a, _b;
|
|
this.inlineEditService.cancel();
|
|
this.inlineEditService.resetConversation();
|
|
this.isConversing = false;
|
|
this.removeSelectionListeners();
|
|
if (this.escHandler) {
|
|
document.removeEventListener("keydown", this.escHandler);
|
|
}
|
|
(_a = this.slashCommandDropdown) == null ? void 0 : _a.destroy();
|
|
this.slashCommandDropdown = null;
|
|
this.slashCommandManager = null;
|
|
(_b = this.mentionDropdown) == null ? void 0 : _b.destroy();
|
|
this.mentionDropdown = null;
|
|
this.attachedFiles.clear();
|
|
if (activeController === this) {
|
|
activeController = null;
|
|
}
|
|
this.editorView.dispatch({
|
|
effects: hideInlineEdit.of(null)
|
|
});
|
|
if (!(options == null ? void 0 : options.keepSelectionHighlight)) {
|
|
hideSelectionHighlight(this.editorView);
|
|
}
|
|
}
|
|
restoreSelectionHighlight() {
|
|
if (this.mode !== "selection" || this.selFrom === this.selTo) {
|
|
return;
|
|
}
|
|
showSelectionHighlight(this.editorView, this.selFrom, this.selTo);
|
|
}
|
|
handleKeydown(e) {
|
|
var _a, _b;
|
|
if ((_a = this.mentionDropdown) == null ? void 0 : _a.handleKeydown(e)) {
|
|
return;
|
|
}
|
|
if ((_b = this.slashCommandDropdown) == null ? void 0 : _b.handleKeydown(e)) {
|
|
return;
|
|
}
|
|
if (e.key === "Enter" && !e.isComposing) {
|
|
e.preventDefault();
|
|
this.generate();
|
|
}
|
|
}
|
|
normalizePathForVault(rawPath) {
|
|
if (!rawPath) return null;
|
|
try {
|
|
const normalizedRaw = normalizePathForFilesystem(rawPath);
|
|
const vaultPath = getVaultPath(this.app);
|
|
if (vaultPath && isPathWithinVault(normalizedRaw, vaultPath)) {
|
|
const absolute = path11.isAbsolute(normalizedRaw) ? normalizedRaw : path11.resolve(vaultPath, normalizedRaw);
|
|
const relative5 = path11.relative(vaultPath, absolute);
|
|
return relative5 ? relative5.replace(/\\/g, "/") : null;
|
|
}
|
|
return normalizedRaw.replace(/\\/g, "/");
|
|
} catch (error2) {
|
|
console.error("[InlineEditModal] normalizePathForVault error:", error2);
|
|
new import_obsidian10.Notice("Failed to attach file: invalid path");
|
|
return null;
|
|
}
|
|
}
|
|
async requestInlineBashApproval(command) {
|
|
const description = `Execute inline bash command:
|
|
${command}`;
|
|
return new Promise((resolve7) => {
|
|
const modal = new ApprovalModal(
|
|
this.app,
|
|
TOOL_BASH,
|
|
{ command },
|
|
description,
|
|
(decision) => resolve7(decision === "allow" || decision === "allow-always"),
|
|
{ showAlwaysAllow: false, title: "Inline bash execution" }
|
|
);
|
|
modal.open();
|
|
});
|
|
}
|
|
};
|
|
|
|
// src/ui/modals/InstructionConfirmModal.ts
|
|
var import_obsidian11 = require("obsidian");
|
|
var InstructionModal = class extends import_obsidian11.Modal {
|
|
constructor(app, rawInstruction, callbacks) {
|
|
super(app);
|
|
this.state = "loading";
|
|
this.resolved = false;
|
|
// UI elements
|
|
this.contentSectionEl = null;
|
|
this.loadingEl = null;
|
|
this.clarificationEl = null;
|
|
this.confirmationEl = null;
|
|
this.buttonsEl = null;
|
|
// Clarification state
|
|
this.clarificationTextEl = null;
|
|
this.responseTextarea = null;
|
|
this.isSubmitting = false;
|
|
// Confirmation state
|
|
this.refinedInstruction = "";
|
|
this.editTextarea = null;
|
|
this.isEditing = false;
|
|
this.refinedDisplayEl = null;
|
|
this.editContainerEl = null;
|
|
this.editBtnEl = null;
|
|
this.rawInstruction = rawInstruction;
|
|
this.callbacks = callbacks;
|
|
}
|
|
onOpen() {
|
|
const { contentEl } = this;
|
|
contentEl.addClass("claudian-instruction-modal");
|
|
this.setTitle("Add Custom Instruction");
|
|
const inputSection = contentEl.createDiv({ cls: "claudian-instruction-section" });
|
|
const inputLabel = inputSection.createDiv({ cls: "claudian-instruction-label" });
|
|
inputLabel.setText("Your input:");
|
|
const inputText = inputSection.createDiv({ cls: "claudian-instruction-original" });
|
|
inputText.setText(this.rawInstruction);
|
|
this.contentSectionEl = contentEl.createDiv({ cls: "claudian-instruction-content-section" });
|
|
this.loadingEl = this.contentSectionEl.createDiv({ cls: "claudian-instruction-loading" });
|
|
this.loadingEl.createDiv({ cls: "claudian-instruction-spinner" });
|
|
this.loadingEl.createSpan({ text: "Processing your instruction..." });
|
|
this.clarificationEl = this.contentSectionEl.createDiv({ cls: "claudian-instruction-clarification-section" });
|
|
this.clarificationEl.style.display = "none";
|
|
this.clarificationTextEl = this.clarificationEl.createDiv({ cls: "claudian-instruction-clarification" });
|
|
const responseSection = this.clarificationEl.createDiv({ cls: "claudian-instruction-section" });
|
|
const responseLabel = responseSection.createDiv({ cls: "claudian-instruction-label" });
|
|
responseLabel.setText("Your response:");
|
|
this.responseTextarea = new import_obsidian11.TextAreaComponent(responseSection);
|
|
this.responseTextarea.inputEl.addClass("claudian-instruction-response-textarea");
|
|
this.responseTextarea.inputEl.rows = 3;
|
|
this.responseTextarea.inputEl.placeholder = "Provide more details...";
|
|
this.responseTextarea.inputEl.addEventListener("keydown", (e) => {
|
|
if (e.key === "Enter" && !e.shiftKey && !this.isSubmitting) {
|
|
e.preventDefault();
|
|
this.submitClarification();
|
|
}
|
|
});
|
|
this.confirmationEl = this.contentSectionEl.createDiv({ cls: "claudian-instruction-confirmation-section" });
|
|
this.confirmationEl.style.display = "none";
|
|
const refinedSection = this.confirmationEl.createDiv({ cls: "claudian-instruction-section" });
|
|
const refinedLabel = refinedSection.createDiv({ cls: "claudian-instruction-label" });
|
|
refinedLabel.setText("Refined snippet:");
|
|
this.refinedDisplayEl = refinedSection.createDiv({ cls: "claudian-instruction-refined" });
|
|
this.editContainerEl = refinedSection.createDiv({ cls: "claudian-instruction-edit-container" });
|
|
this.editContainerEl.style.display = "none";
|
|
this.editTextarea = new import_obsidian11.TextAreaComponent(this.editContainerEl);
|
|
this.editTextarea.inputEl.addClass("claudian-instruction-edit-textarea");
|
|
this.editTextarea.inputEl.rows = 4;
|
|
this.buttonsEl = contentEl.createDiv({ cls: "claudian-instruction-buttons" });
|
|
this.updateButtons();
|
|
this.showState("loading");
|
|
}
|
|
/** Shows clarification question from agent. */
|
|
showClarification(clarification) {
|
|
var _a;
|
|
if (this.clarificationTextEl) {
|
|
this.clarificationTextEl.setText(clarification);
|
|
}
|
|
if (this.responseTextarea) {
|
|
this.responseTextarea.setValue("");
|
|
}
|
|
this.isSubmitting = false;
|
|
this.showState("clarification");
|
|
(_a = this.responseTextarea) == null ? void 0 : _a.inputEl.focus();
|
|
}
|
|
/** Shows confirmation with refined instruction. */
|
|
showConfirmation(refinedInstruction) {
|
|
this.refinedInstruction = refinedInstruction;
|
|
if (this.refinedDisplayEl) {
|
|
this.refinedDisplayEl.setText(refinedInstruction);
|
|
}
|
|
if (this.editTextarea) {
|
|
this.editTextarea.setValue(refinedInstruction);
|
|
}
|
|
this.showState("confirmation");
|
|
}
|
|
/** Shows error and closes modal. */
|
|
showError(error2) {
|
|
this.resolved = true;
|
|
this.close();
|
|
}
|
|
/** Updates the modal to show loading state during clarification submit. */
|
|
showClarificationLoading() {
|
|
this.isSubmitting = true;
|
|
if (this.loadingEl) {
|
|
this.loadingEl.querySelector(".claudian-instruction-spinner");
|
|
const text = this.loadingEl.querySelector("span");
|
|
if (text) text.textContent = "Processing...";
|
|
}
|
|
this.showState("loading");
|
|
}
|
|
showState(state) {
|
|
this.state = state;
|
|
if (this.loadingEl) {
|
|
this.loadingEl.style.display = state === "loading" ? "flex" : "none";
|
|
}
|
|
if (this.clarificationEl) {
|
|
this.clarificationEl.style.display = state === "clarification" ? "block" : "none";
|
|
}
|
|
if (this.confirmationEl) {
|
|
this.confirmationEl.style.display = state === "confirmation" ? "block" : "none";
|
|
}
|
|
this.updateButtons();
|
|
}
|
|
updateButtons() {
|
|
if (!this.buttonsEl) return;
|
|
this.buttonsEl.empty();
|
|
const cancelBtn = this.buttonsEl.createEl("button", {
|
|
text: "Cancel",
|
|
cls: "claudian-instruction-btn claudian-instruction-reject-btn",
|
|
attr: { "aria-label": "Cancel" }
|
|
});
|
|
cancelBtn.addEventListener("click", () => this.handleReject());
|
|
if (this.state === "clarification") {
|
|
const submitBtn = this.buttonsEl.createEl("button", {
|
|
text: "Submit",
|
|
cls: "claudian-instruction-btn claudian-instruction-accept-btn",
|
|
attr: { "aria-label": "Submit response" }
|
|
});
|
|
submitBtn.addEventListener("click", () => this.submitClarification());
|
|
} else if (this.state === "confirmation") {
|
|
this.editBtnEl = this.buttonsEl.createEl("button", {
|
|
text: "Edit",
|
|
cls: "claudian-instruction-btn claudian-instruction-edit-btn",
|
|
attr: { "aria-label": "Edit instruction" }
|
|
});
|
|
this.editBtnEl.addEventListener("click", () => this.toggleEdit());
|
|
const acceptBtn = this.buttonsEl.createEl("button", {
|
|
text: "Accept",
|
|
cls: "claudian-instruction-btn claudian-instruction-accept-btn",
|
|
attr: { "aria-label": "Accept instruction" }
|
|
});
|
|
acceptBtn.addEventListener("click", () => this.handleAccept());
|
|
acceptBtn.focus();
|
|
}
|
|
}
|
|
async submitClarification() {
|
|
var _a;
|
|
const response = (_a = this.responseTextarea) == null ? void 0 : _a.getValue().trim();
|
|
if (!response || this.isSubmitting) return;
|
|
this.showClarificationLoading();
|
|
try {
|
|
await this.callbacks.onClarificationSubmit(response);
|
|
} catch (e) {
|
|
this.isSubmitting = false;
|
|
this.showState("clarification");
|
|
}
|
|
}
|
|
toggleEdit() {
|
|
var _a, _b;
|
|
this.isEditing = !this.isEditing;
|
|
if (this.isEditing) {
|
|
if (this.refinedDisplayEl) this.refinedDisplayEl.style.display = "none";
|
|
if (this.editContainerEl) this.editContainerEl.style.display = "block";
|
|
if (this.editBtnEl) this.editBtnEl.setText("Preview");
|
|
(_a = this.editTextarea) == null ? void 0 : _a.inputEl.focus();
|
|
} else {
|
|
const edited = ((_b = this.editTextarea) == null ? void 0 : _b.getValue()) || this.refinedInstruction;
|
|
this.refinedInstruction = edited;
|
|
if (this.refinedDisplayEl) {
|
|
this.refinedDisplayEl.setText(edited);
|
|
this.refinedDisplayEl.style.display = "block";
|
|
}
|
|
if (this.editContainerEl) this.editContainerEl.style.display = "none";
|
|
if (this.editBtnEl) this.editBtnEl.setText("Edit");
|
|
}
|
|
}
|
|
handleAccept() {
|
|
var _a;
|
|
if (this.resolved) return;
|
|
this.resolved = true;
|
|
const finalInstruction = this.isEditing ? ((_a = this.editTextarea) == null ? void 0 : _a.getValue()) || this.refinedInstruction : this.refinedInstruction;
|
|
this.callbacks.onAccept(finalInstruction);
|
|
this.close();
|
|
}
|
|
handleReject() {
|
|
if (this.resolved) return;
|
|
this.resolved = true;
|
|
this.callbacks.onReject();
|
|
this.close();
|
|
}
|
|
onClose() {
|
|
if (!this.resolved) {
|
|
this.resolved = true;
|
|
this.callbacks.onReject();
|
|
}
|
|
this.contentEl.empty();
|
|
}
|
|
};
|
|
|
|
// src/ui/modals/McpServerModal.ts
|
|
var import_obsidian12 = require("obsidian");
|
|
var McpServerModal = class extends import_obsidian12.Modal {
|
|
constructor(app, plugin, existingServer, onSave, initialType, prefillConfig) {
|
|
super(app);
|
|
// Form state
|
|
this.serverName = "";
|
|
this.serverType = "stdio";
|
|
this.enabled = DEFAULT_MCP_SERVER.enabled;
|
|
this.contextSaving = DEFAULT_MCP_SERVER.contextSaving;
|
|
// Stdio fields
|
|
this.command = "";
|
|
// Full command including args
|
|
this.env = "";
|
|
// SSE/HTTP fields
|
|
this.url = "";
|
|
this.headers = "";
|
|
// DOM references
|
|
this.typeFieldsEl = null;
|
|
this.nameInputEl = null;
|
|
this.plugin = plugin;
|
|
this.existingServer = existingServer;
|
|
this.onSave = onSave;
|
|
if (existingServer) {
|
|
this.serverName = existingServer.name;
|
|
this.serverType = getMcpServerType(existingServer.config);
|
|
this.enabled = existingServer.enabled;
|
|
this.contextSaving = existingServer.contextSaving;
|
|
this.initFromConfig(existingServer.config);
|
|
} else if (prefillConfig) {
|
|
this.serverName = prefillConfig.name;
|
|
this.serverType = getMcpServerType(prefillConfig.config);
|
|
this.initFromConfig(prefillConfig.config);
|
|
} else if (initialType) {
|
|
this.serverType = initialType;
|
|
}
|
|
}
|
|
/** Initialize form fields from a config object. */
|
|
initFromConfig(config2) {
|
|
const type = getMcpServerType(config2);
|
|
if (type === "stdio") {
|
|
const stdioConfig = config2;
|
|
if (stdioConfig.args && stdioConfig.args.length > 0) {
|
|
this.command = stdioConfig.command + " " + stdioConfig.args.join(" ");
|
|
} else {
|
|
this.command = stdioConfig.command;
|
|
}
|
|
this.env = this.envRecordToString(stdioConfig.env);
|
|
} else {
|
|
const urlConfig = config2;
|
|
this.url = urlConfig.url;
|
|
this.headers = this.envRecordToString(urlConfig.headers);
|
|
}
|
|
}
|
|
onOpen() {
|
|
this.setTitle(this.existingServer ? "Edit MCP Server" : "Add MCP Server");
|
|
this.modalEl.addClass("claudian-mcp-modal");
|
|
const { contentEl } = this;
|
|
new import_obsidian12.Setting(contentEl).setName("Server name").setDesc("Unique identifier for this server").addText((text) => {
|
|
this.nameInputEl = text.inputEl;
|
|
text.setValue(this.serverName);
|
|
text.setPlaceholder("my-mcp-server");
|
|
text.onChange((value) => {
|
|
this.serverName = value;
|
|
});
|
|
text.inputEl.addEventListener("keydown", (e) => this.handleKeyDown(e));
|
|
});
|
|
new import_obsidian12.Setting(contentEl).setName("Type").setDesc("Server connection type").addDropdown((dropdown) => {
|
|
dropdown.addOption("stdio", "stdio (local command)");
|
|
dropdown.addOption("sse", "sse (Server-Sent Events)");
|
|
dropdown.addOption("http", "http (HTTP endpoint)");
|
|
dropdown.setValue(this.serverType);
|
|
dropdown.onChange((value) => {
|
|
this.serverType = value;
|
|
this.renderTypeFields();
|
|
});
|
|
});
|
|
this.typeFieldsEl = contentEl.createDiv({ cls: "claudian-mcp-type-fields" });
|
|
this.renderTypeFields();
|
|
new import_obsidian12.Setting(contentEl).setName("Enabled").setDesc("Whether this server is active").addToggle((toggle) => {
|
|
toggle.setValue(this.enabled);
|
|
toggle.onChange((value) => {
|
|
this.enabled = value;
|
|
});
|
|
});
|
|
new import_obsidian12.Setting(contentEl).setName("Context-saving mode").setDesc("Hide tools from agent unless @-mentioned (saves context window)").addToggle((toggle) => {
|
|
toggle.setValue(this.contextSaving);
|
|
toggle.onChange((value) => {
|
|
this.contextSaving = value;
|
|
});
|
|
});
|
|
const buttonContainer = contentEl.createDiv({ cls: "claudian-mcp-buttons" });
|
|
const cancelBtn = buttonContainer.createEl("button", {
|
|
text: "Cancel",
|
|
cls: "claudian-cancel-btn"
|
|
});
|
|
cancelBtn.addEventListener("click", () => this.close());
|
|
const saveBtn = buttonContainer.createEl("button", {
|
|
text: this.existingServer ? "Update" : "Add",
|
|
cls: "claudian-save-btn mod-cta"
|
|
});
|
|
saveBtn.addEventListener("click", () => this.save());
|
|
}
|
|
renderTypeFields() {
|
|
if (!this.typeFieldsEl) return;
|
|
this.typeFieldsEl.empty();
|
|
if (this.serverType === "stdio") {
|
|
this.renderStdioFields();
|
|
} else {
|
|
this.renderUrlFields();
|
|
}
|
|
}
|
|
renderStdioFields() {
|
|
if (!this.typeFieldsEl) return;
|
|
const cmdSetting = new import_obsidian12.Setting(this.typeFieldsEl).setName("Command").setDesc("Full command with arguments");
|
|
cmdSetting.settingEl.addClass("claudian-mcp-cmd-setting");
|
|
const cmdTextarea = cmdSetting.controlEl.createEl("textarea", {
|
|
cls: "claudian-mcp-cmd-textarea"
|
|
});
|
|
cmdTextarea.value = this.command;
|
|
cmdTextarea.placeholder = "docker exec -i mcp-server python -m src.server";
|
|
cmdTextarea.rows = 2;
|
|
cmdTextarea.addEventListener("input", () => {
|
|
this.command = cmdTextarea.value;
|
|
});
|
|
const envSetting = new import_obsidian12.Setting(this.typeFieldsEl).setName("Environment variables").setDesc("KEY=VALUE per line (optional)");
|
|
envSetting.settingEl.addClass("claudian-mcp-env-setting");
|
|
const envTextarea = envSetting.controlEl.createEl("textarea", {
|
|
cls: "claudian-mcp-env-textarea"
|
|
});
|
|
envTextarea.value = this.env;
|
|
envTextarea.placeholder = "API_KEY=your-key";
|
|
envTextarea.rows = 2;
|
|
envTextarea.addEventListener("input", () => {
|
|
this.env = envTextarea.value;
|
|
});
|
|
}
|
|
renderUrlFields() {
|
|
if (!this.typeFieldsEl) return;
|
|
new import_obsidian12.Setting(this.typeFieldsEl).setName("URL").setDesc(this.serverType === "sse" ? "SSE endpoint URL" : "HTTP endpoint URL").addText((text) => {
|
|
text.setValue(this.url);
|
|
text.setPlaceholder("http://localhost:3000/sse");
|
|
text.onChange((value) => {
|
|
this.url = value;
|
|
});
|
|
text.inputEl.addEventListener("keydown", (e) => this.handleKeyDown(e));
|
|
});
|
|
const headersSetting = new import_obsidian12.Setting(this.typeFieldsEl).setName("Headers").setDesc("HTTP headers (KEY=VALUE per line)");
|
|
headersSetting.settingEl.addClass("claudian-mcp-env-setting");
|
|
const headersTextarea = headersSetting.controlEl.createEl("textarea", {
|
|
cls: "claudian-mcp-env-textarea"
|
|
});
|
|
headersTextarea.value = this.headers;
|
|
headersTextarea.placeholder = "Authorization=Bearer token\nContent-Type=application/json";
|
|
headersTextarea.rows = 3;
|
|
headersTextarea.addEventListener("input", () => {
|
|
this.headers = headersTextarea.value;
|
|
});
|
|
}
|
|
handleKeyDown(e) {
|
|
if (e.key === "Enter" && !e.shiftKey) {
|
|
e.preventDefault();
|
|
this.save();
|
|
} else if (e.key === "Escape") {
|
|
e.preventDefault();
|
|
this.close();
|
|
}
|
|
}
|
|
save() {
|
|
var _a, _b, _c;
|
|
const name = this.serverName.trim();
|
|
if (!name) {
|
|
new import_obsidian12.Notice("Please enter a server name");
|
|
(_a = this.nameInputEl) == null ? void 0 : _a.focus();
|
|
return;
|
|
}
|
|
if (!/^[a-zA-Z0-9._-]+$/.test(name)) {
|
|
new import_obsidian12.Notice("Server name can only contain letters, numbers, dots, hyphens, and underscores");
|
|
(_b = this.nameInputEl) == null ? void 0 : _b.focus();
|
|
return;
|
|
}
|
|
let config2;
|
|
if (this.serverType === "stdio") {
|
|
const fullCommand = this.command.trim();
|
|
if (!fullCommand) {
|
|
new import_obsidian12.Notice("Please enter a command");
|
|
return;
|
|
}
|
|
const parts = this.parseCommandString(fullCommand);
|
|
const stdioConfig = { command: parts.command };
|
|
if (parts.args.length > 0) {
|
|
stdioConfig.args = parts.args;
|
|
}
|
|
const env = this.parseEnvString(this.env);
|
|
if (Object.keys(env).length > 0) {
|
|
stdioConfig.env = env;
|
|
}
|
|
config2 = stdioConfig;
|
|
} else {
|
|
const url = this.url.trim();
|
|
if (!url) {
|
|
new import_obsidian12.Notice("Please enter a URL");
|
|
return;
|
|
}
|
|
if (this.serverType === "sse") {
|
|
const sseConfig = { type: "sse", url };
|
|
const headers = this.parseEnvString(this.headers);
|
|
if (Object.keys(headers).length > 0) {
|
|
sseConfig.headers = headers;
|
|
}
|
|
config2 = sseConfig;
|
|
} else {
|
|
const httpConfig = { type: "http", url };
|
|
const headers = this.parseEnvString(this.headers);
|
|
if (Object.keys(headers).length > 0) {
|
|
httpConfig.headers = headers;
|
|
}
|
|
config2 = httpConfig;
|
|
}
|
|
}
|
|
const server = {
|
|
name,
|
|
config: config2,
|
|
enabled: this.enabled,
|
|
contextSaving: this.contextSaving,
|
|
disabledTools: (_c = this.existingServer) == null ? void 0 : _c.disabledTools
|
|
};
|
|
this.onSave(server);
|
|
this.close();
|
|
}
|
|
/** Parse a command string into command and args, handling quoted strings. */
|
|
parseCommandString(cmdStr) {
|
|
const parts = [];
|
|
let current = "";
|
|
let inQuote = false;
|
|
let quoteChar = "";
|
|
for (let i = 0; i < cmdStr.length; i++) {
|
|
const char = cmdStr[i];
|
|
if ((char === '"' || char === "'") && !inQuote) {
|
|
inQuote = true;
|
|
quoteChar = char;
|
|
} else if (char === quoteChar && inQuote) {
|
|
inQuote = false;
|
|
quoteChar = "";
|
|
} else if (/\s/.test(char) && !inQuote) {
|
|
if (current) {
|
|
parts.push(current);
|
|
current = "";
|
|
}
|
|
} else {
|
|
current += char;
|
|
}
|
|
}
|
|
if (current) {
|
|
parts.push(current);
|
|
}
|
|
if (parts.length === 0) {
|
|
return { command: "", args: [] };
|
|
}
|
|
return {
|
|
command: parts[0],
|
|
args: parts.slice(1)
|
|
};
|
|
}
|
|
parseEnvString(envStr) {
|
|
const result = {};
|
|
if (!envStr.trim()) return result;
|
|
for (const line of envStr.split("\n")) {
|
|
const trimmed = line.trim();
|
|
if (!trimmed || trimmed.startsWith("#")) continue;
|
|
const eqIndex = trimmed.indexOf("=");
|
|
if (eqIndex === -1) continue;
|
|
const key = trimmed.substring(0, eqIndex).trim();
|
|
const value = trimmed.substring(eqIndex + 1).trim();
|
|
if (key) {
|
|
result[key] = value;
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
envRecordToString(env) {
|
|
if (!env) return "";
|
|
return Object.entries(env).map(([key, value]) => `${key}=${value}`).join("\n");
|
|
}
|
|
onClose() {
|
|
this.contentEl.empty();
|
|
}
|
|
};
|
|
|
|
// src/ui/modals/McpTestModal.ts
|
|
var import_obsidian13 = require("obsidian");
|
|
function formatToggleError(error2) {
|
|
if (!(error2 instanceof Error)) return "Failed to update tool setting";
|
|
const msg = error2.message.toLowerCase();
|
|
if (msg.includes("permission") || msg.includes("eacces")) {
|
|
return "Permission denied. Check .claude/ folder permissions.";
|
|
}
|
|
if (msg.includes("enospc") || msg.includes("disk full") || msg.includes("no space")) {
|
|
return "Disk full. Free up space and try again.";
|
|
}
|
|
if (msg.includes("json") || msg.includes("syntax")) {
|
|
return "Config file corrupted. Check .claude/mcp.json";
|
|
}
|
|
return error2.message || "Failed to update tool setting";
|
|
}
|
|
var McpTestModal = class extends import_obsidian13.Modal {
|
|
constructor(app, serverName, initialDisabledTools, onToolToggle, onBulkToggle) {
|
|
super(app);
|
|
this.result = null;
|
|
this.loading = true;
|
|
this.contentEl_ = null;
|
|
this.toolToggles = /* @__PURE__ */ new Map();
|
|
this.toolElements = /* @__PURE__ */ new Map();
|
|
this.toggleAllBtn = null;
|
|
this.pendingToggle = false;
|
|
this.serverName = serverName;
|
|
this.disabledTools = new Set(
|
|
(initialDisabledTools != null ? initialDisabledTools : []).map((tool) => tool.trim()).filter((tool) => tool.length > 0)
|
|
);
|
|
this.onToolToggle = onToolToggle;
|
|
this.onBulkToggle = onBulkToggle;
|
|
}
|
|
onOpen() {
|
|
this.setTitle(`Verify: ${this.serverName}`);
|
|
this.modalEl.addClass("claudian-mcp-test-modal");
|
|
this.contentEl_ = this.contentEl;
|
|
this.renderLoading();
|
|
}
|
|
/** Set the test result and update the display. */
|
|
setResult(result) {
|
|
this.result = result;
|
|
this.loading = false;
|
|
this.render();
|
|
}
|
|
/** Set error state. */
|
|
setError(error2) {
|
|
this.result = { success: false, tools: [], error: error2 };
|
|
this.loading = false;
|
|
this.render();
|
|
}
|
|
renderLoading() {
|
|
if (!this.contentEl_) return;
|
|
this.contentEl_.empty();
|
|
const loadingEl = this.contentEl_.createDiv({ cls: "claudian-mcp-test-loading" });
|
|
const spinnerEl = loadingEl.createDiv({ cls: "claudian-mcp-test-spinner" });
|
|
spinnerEl.innerHTML = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
<path d="M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4M4.93 19.07l2.83-2.83M16.24 7.76l2.83-2.83"/>
|
|
</svg>`;
|
|
loadingEl.createSpan({ text: "Connecting to MCP server..." });
|
|
}
|
|
render() {
|
|
if (!this.contentEl_) return;
|
|
this.contentEl_.empty();
|
|
if (!this.result) {
|
|
this.renderLoading();
|
|
return;
|
|
}
|
|
const statusEl = this.contentEl_.createDiv({ cls: "claudian-mcp-test-status" });
|
|
const iconEl = statusEl.createSpan({ cls: "claudian-mcp-test-icon" });
|
|
if (this.result.success) {
|
|
(0, import_obsidian13.setIcon)(iconEl, "check-circle");
|
|
iconEl.addClass("success");
|
|
} else {
|
|
(0, import_obsidian13.setIcon)(iconEl, "x-circle");
|
|
iconEl.addClass("error");
|
|
}
|
|
const textEl = statusEl.createSpan({ cls: "claudian-mcp-test-text" });
|
|
if (this.result.success) {
|
|
let statusText = "Connected successfully";
|
|
if (this.result.serverName) {
|
|
statusText += ` to ${this.result.serverName}`;
|
|
if (this.result.serverVersion) {
|
|
statusText += ` v${this.result.serverVersion}`;
|
|
}
|
|
}
|
|
textEl.setText(statusText);
|
|
} else {
|
|
textEl.setText("Connection failed");
|
|
}
|
|
if (this.result.error) {
|
|
const errorEl = this.contentEl_.createDiv({ cls: "claudian-mcp-test-error" });
|
|
errorEl.setText(this.result.error);
|
|
}
|
|
this.toolToggles.clear();
|
|
this.toolElements.clear();
|
|
if (this.result.tools.length > 0) {
|
|
const toolsSection = this.contentEl_.createDiv({ cls: "claudian-mcp-test-tools" });
|
|
const toolsHeader = toolsSection.createDiv({ cls: "claudian-mcp-test-tools-header" });
|
|
toolsHeader.setText(`Available Tools (${this.result.tools.length})`);
|
|
const toolsList = toolsSection.createDiv({ cls: "claudian-mcp-test-tools-list" });
|
|
for (const tool of this.result.tools) {
|
|
this.renderTool(toolsList, tool);
|
|
}
|
|
} else if (this.result.success) {
|
|
const noToolsEl = this.contentEl_.createDiv({ cls: "claudian-mcp-test-no-tools" });
|
|
noToolsEl.setText("No tools information available. Tools will be loaded when used in chat.");
|
|
}
|
|
const buttonContainer = this.contentEl_.createDiv({ cls: "claudian-mcp-test-buttons" });
|
|
if (this.result.tools.length > 0 && this.onToolToggle) {
|
|
this.toggleAllBtn = buttonContainer.createEl("button", {
|
|
cls: "claudian-mcp-toggle-all-btn"
|
|
});
|
|
this.updateToggleAllButton();
|
|
this.toggleAllBtn.addEventListener("click", () => this.handleToggleAll());
|
|
}
|
|
const closeBtn = buttonContainer.createEl("button", {
|
|
text: "Close",
|
|
cls: "mod-cta"
|
|
});
|
|
closeBtn.addEventListener("click", () => this.close());
|
|
}
|
|
renderTool(container, tool) {
|
|
const toolEl = container.createDiv({ cls: "claudian-mcp-test-tool" });
|
|
const headerEl = toolEl.createDiv({ cls: "claudian-mcp-test-tool-header" });
|
|
const iconEl = headerEl.createSpan({ cls: "claudian-mcp-test-tool-icon" });
|
|
(0, import_obsidian13.setIcon)(iconEl, "wrench");
|
|
const nameEl = headerEl.createSpan({ cls: "claudian-mcp-test-tool-name" });
|
|
nameEl.setText(tool.name);
|
|
const toggleEl = headerEl.createDiv({ cls: "claudian-mcp-test-tool-toggle" });
|
|
const toggleContainer = toggleEl.createDiv({ cls: "checkbox-container" });
|
|
const checkbox = toggleContainer.createEl("input", {
|
|
type: "checkbox",
|
|
attr: { tabindex: "0" }
|
|
});
|
|
const isEnabled = !this.disabledTools.has(tool.name);
|
|
checkbox.checked = isEnabled;
|
|
toggleContainer.toggleClass("is-enabled", isEnabled);
|
|
this.updateToolState(toolEl, isEnabled);
|
|
this.toolToggles.set(tool.name, { checkbox, container: toggleContainer });
|
|
this.toolElements.set(tool.name, toolEl);
|
|
if (!this.onToolToggle) {
|
|
checkbox.disabled = true;
|
|
} else {
|
|
toggleContainer.addEventListener("click", (e) => {
|
|
e.preventDefault();
|
|
e.stopPropagation();
|
|
if (checkbox.disabled) return;
|
|
checkbox.checked = !checkbox.checked;
|
|
this.handleToolToggle(tool.name, checkbox, toggleContainer);
|
|
});
|
|
}
|
|
if (tool.description) {
|
|
const descEl = toolEl.createDiv({ cls: "claudian-mcp-test-tool-desc" });
|
|
descEl.setText(tool.description);
|
|
}
|
|
}
|
|
async handleToolToggle(toolName, checkbox, container) {
|
|
var _a;
|
|
const toolEl = this.toolElements.get(toolName);
|
|
if (!toolEl) return;
|
|
const wasDisabled = this.disabledTools.has(toolName);
|
|
const nextDisabled = !checkbox.checked;
|
|
if (nextDisabled) {
|
|
this.disabledTools.add(toolName);
|
|
} else {
|
|
this.disabledTools.delete(toolName);
|
|
}
|
|
container.toggleClass("is-enabled", !nextDisabled);
|
|
this.updateToolState(toolEl, !nextDisabled);
|
|
this.updateToggleAllButton();
|
|
checkbox.disabled = true;
|
|
try {
|
|
await ((_a = this.onToolToggle) == null ? void 0 : _a.call(this, toolName, !nextDisabled));
|
|
} catch (error2) {
|
|
if (nextDisabled) {
|
|
this.disabledTools.delete(toolName);
|
|
} else {
|
|
this.disabledTools.add(toolName);
|
|
}
|
|
checkbox.checked = !wasDisabled;
|
|
container.toggleClass("is-enabled", !wasDisabled);
|
|
this.updateToolState(toolEl, !wasDisabled);
|
|
this.updateToggleAllButton();
|
|
new import_obsidian13.Notice(formatToggleError(error2));
|
|
} finally {
|
|
checkbox.disabled = false;
|
|
}
|
|
}
|
|
updateToolState(toolEl, enabled) {
|
|
toolEl.toggleClass("claudian-mcp-test-tool-disabled", !enabled);
|
|
}
|
|
updateToggleAllButton() {
|
|
if (!this.toggleAllBtn || !this.result) return;
|
|
const allEnabled = this.disabledTools.size === 0;
|
|
const allDisabled = this.disabledTools.size === this.result.tools.length;
|
|
if (allEnabled) {
|
|
this.toggleAllBtn.setText("Disable All");
|
|
this.toggleAllBtn.toggleClass("is-destructive", true);
|
|
} else {
|
|
this.toggleAllBtn.setText(allDisabled ? "Enable All" : "Enable All");
|
|
this.toggleAllBtn.toggleClass("is-destructive", false);
|
|
}
|
|
}
|
|
async handleToggleAll() {
|
|
if (!this.result || this.pendingToggle || !this.onBulkToggle) return;
|
|
const allEnabled = this.disabledTools.size === 0;
|
|
const previousDisabled = new Set(this.disabledTools);
|
|
const newDisabledTools = allEnabled ? this.result.tools.map((t) => t.name) : [];
|
|
this.pendingToggle = true;
|
|
if (this.toggleAllBtn) this.toggleAllBtn.disabled = true;
|
|
for (const { checkbox } of this.toolToggles.values()) {
|
|
checkbox.disabled = true;
|
|
}
|
|
this.disabledTools = new Set(newDisabledTools);
|
|
for (const tool of this.result.tools) {
|
|
const toggle = this.toolToggles.get(tool.name);
|
|
const toolEl = this.toolElements.get(tool.name);
|
|
if (!toggle || !toolEl) continue;
|
|
const isEnabled = !this.disabledTools.has(tool.name);
|
|
toggle.checkbox.checked = isEnabled;
|
|
toggle.container.toggleClass("is-enabled", isEnabled);
|
|
this.updateToolState(toolEl, isEnabled);
|
|
}
|
|
this.updateToggleAllButton();
|
|
try {
|
|
await this.onBulkToggle(newDisabledTools);
|
|
} catch (error2) {
|
|
this.disabledTools = previousDisabled;
|
|
for (const tool of this.result.tools) {
|
|
const toggle = this.toolToggles.get(tool.name);
|
|
const toolEl = this.toolElements.get(tool.name);
|
|
if (!toggle || !toolEl) continue;
|
|
const isEnabled = !this.disabledTools.has(tool.name);
|
|
toggle.checkbox.checked = isEnabled;
|
|
toggle.container.toggleClass("is-enabled", isEnabled);
|
|
this.updateToolState(toolEl, isEnabled);
|
|
}
|
|
this.updateToggleAllButton();
|
|
new import_obsidian13.Notice(formatToggleError(error2));
|
|
}
|
|
for (const { checkbox } of this.toolToggles.values()) {
|
|
checkbox.disabled = false;
|
|
}
|
|
this.pendingToggle = false;
|
|
if (this.toggleAllBtn) this.toggleAllBtn.disabled = false;
|
|
}
|
|
onClose() {
|
|
this.contentEl.empty();
|
|
}
|
|
};
|
|
|
|
// src/ui/renderers/AskUserQuestionRenderer.ts
|
|
var import_obsidian14 = require("obsidian");
|
|
function parseAskUserQuestionInput(input) {
|
|
if (!input || typeof input !== "object") return null;
|
|
const questions = input.questions;
|
|
if (!Array.isArray(questions)) return null;
|
|
return {
|
|
questions,
|
|
answers: input.answers
|
|
};
|
|
}
|
|
function formatAnswer(answer) {
|
|
if (Array.isArray(answer)) {
|
|
return answer.join(", ");
|
|
}
|
|
return answer;
|
|
}
|
|
function renderTreeQA(containerEl, questions, answers) {
|
|
const listEl = containerEl.createDiv({ cls: "claudian-ask-question-list" });
|
|
const treeEl = listEl.createSpan({ cls: "claudian-ask-question-tree" });
|
|
treeEl.setText("\u23BF ");
|
|
const alignedEl = listEl.createDiv({ cls: "claudian-ask-question-aligned" });
|
|
questions.forEach((question) => {
|
|
const answer = answers[question.question];
|
|
if (answer === void 0) return;
|
|
const itemEl = alignedEl.createDiv({ cls: "claudian-ask-question-item" });
|
|
const qEl = itemEl.createDiv({ cls: "claudian-ask-question-q" });
|
|
qEl.setText(`Q: ${question.question}`);
|
|
const aEl = itemEl.createDiv({ cls: "claudian-ask-question-a" });
|
|
aEl.setText(`A: ${formatAnswer(answer)}`);
|
|
});
|
|
}
|
|
function createAskUserQuestionBlock(parentEl, toolCall) {
|
|
const wrapperEl = parentEl.createDiv({ cls: "claudian-ask-question-block claudian-ask-question-pending" });
|
|
wrapperEl.dataset.toolId = toolCall.id;
|
|
wrapperEl.style.display = "none";
|
|
const headerEl = wrapperEl.createDiv({ cls: "claudian-ask-question-header" });
|
|
const contentEl = wrapperEl.createDiv({ cls: "claudian-ask-question-content" });
|
|
return {
|
|
wrapperEl,
|
|
contentEl,
|
|
headerEl,
|
|
toolId: toolCall.id
|
|
};
|
|
}
|
|
function finalizeAskUserQuestionBlock(state, answers, isError, questions) {
|
|
const questionList = questions || [];
|
|
const questionCount = questionList.length;
|
|
state.wrapperEl.style.display = "";
|
|
state.wrapperEl.removeClass("claudian-ask-question-pending");
|
|
if (isError) {
|
|
state.wrapperEl.addClass("error");
|
|
} else {
|
|
state.wrapperEl.addClass("done");
|
|
}
|
|
state.headerEl.empty();
|
|
state.headerEl.setAttribute("tabindex", "0");
|
|
state.headerEl.setAttribute("role", "button");
|
|
state.headerEl.setAttribute("aria-expanded", "false");
|
|
const iconEl = state.headerEl.createDiv({ cls: "claudian-ask-question-icon" });
|
|
iconEl.setAttribute("aria-hidden", "true");
|
|
(0, import_obsidian14.setIcon)(iconEl, "help-circle");
|
|
const labelEl = state.headerEl.createDiv({ cls: "claudian-ask-question-label" });
|
|
labelEl.setText("Clarification");
|
|
const countEl = state.headerEl.createDiv({ cls: "claudian-ask-question-count" });
|
|
countEl.setText(questionCount === 1 ? "1 question" : `${questionCount} questions`);
|
|
const statusEl = state.headerEl.createDiv({ cls: `claudian-ask-question-status status-${isError ? "error" : "completed"}` });
|
|
if (isError) {
|
|
(0, import_obsidian14.setIcon)(statusEl, "x");
|
|
} else {
|
|
(0, import_obsidian14.setIcon)(statusEl, "check");
|
|
}
|
|
state.contentEl.empty();
|
|
state.contentEl.style.display = "none";
|
|
if (isError || !answers) {
|
|
const errorEl = state.contentEl.createDiv({ cls: "claudian-ask-question-error" });
|
|
errorEl.setText(isError ? "Failed to get response" : "No response received");
|
|
} else {
|
|
renderTreeQA(state.contentEl, questionList, answers);
|
|
}
|
|
const toggleExpand = () => {
|
|
const expanded = state.wrapperEl.hasClass("expanded");
|
|
if (expanded) {
|
|
state.wrapperEl.removeClass("expanded");
|
|
state.contentEl.style.display = "none";
|
|
state.headerEl.setAttribute("aria-expanded", "false");
|
|
} else {
|
|
state.wrapperEl.addClass("expanded");
|
|
state.contentEl.style.display = "block";
|
|
state.headerEl.setAttribute("aria-expanded", "true");
|
|
}
|
|
};
|
|
state.headerEl.addEventListener("click", toggleExpand);
|
|
state.headerEl.addEventListener("keydown", (e) => {
|
|
if (e.key === "Enter" || e.key === " ") {
|
|
e.preventDefault();
|
|
toggleExpand();
|
|
}
|
|
});
|
|
}
|
|
function renderStoredAskUserQuestion(parentEl, toolCall) {
|
|
const parsed = parseAskUserQuestionInput(toolCall.input);
|
|
const questions = (parsed == null ? void 0 : parsed.questions) || [];
|
|
const answers = parsed == null ? void 0 : parsed.answers;
|
|
const questionCount = questions.length;
|
|
const isError = toolCall.status === "error" || toolCall.status === "blocked";
|
|
const isCompleted = toolCall.status === "completed";
|
|
const wrapperEl = parentEl.createDiv({ cls: "claudian-ask-question-block" });
|
|
wrapperEl.dataset.toolId = toolCall.id;
|
|
if (isCompleted) {
|
|
wrapperEl.addClass("done");
|
|
} else if (isError) {
|
|
wrapperEl.addClass("error");
|
|
}
|
|
const headerEl = wrapperEl.createDiv({ cls: "claudian-ask-question-header" });
|
|
headerEl.setAttribute("tabindex", "0");
|
|
headerEl.setAttribute("role", "button");
|
|
headerEl.setAttribute("aria-expanded", "false");
|
|
headerEl.setAttribute("aria-label", `Clarification - ${toolCall.status}`);
|
|
const iconEl = headerEl.createDiv({ cls: "claudian-ask-question-icon" });
|
|
iconEl.setAttribute("aria-hidden", "true");
|
|
(0, import_obsidian14.setIcon)(iconEl, "help-circle");
|
|
const labelEl = headerEl.createDiv({ cls: "claudian-ask-question-label" });
|
|
labelEl.setText("Clarification");
|
|
const countEl = headerEl.createDiv({ cls: "claudian-ask-question-count" });
|
|
countEl.setText(questionCount === 1 ? "1 question" : `${questionCount} questions`);
|
|
const statusEl = headerEl.createDiv({ cls: `claudian-ask-question-status status-${toolCall.status}` });
|
|
statusEl.setAttribute("aria-label", `Status: ${toolCall.status}`);
|
|
if (isCompleted) {
|
|
(0, import_obsidian14.setIcon)(statusEl, "check");
|
|
} else if (isError) {
|
|
(0, import_obsidian14.setIcon)(statusEl, "x");
|
|
}
|
|
const contentEl = wrapperEl.createDiv({ cls: "claudian-ask-question-content" });
|
|
contentEl.style.display = "none";
|
|
if (answers && Object.keys(answers).length > 0) {
|
|
renderTreeQA(contentEl, questions, answers);
|
|
} else if (isError) {
|
|
const errorEl = contentEl.createDiv({ cls: "claudian-ask-question-error" });
|
|
errorEl.setText("Failed to get response");
|
|
} else {
|
|
const noAnswerEl = contentEl.createDiv({ cls: "claudian-ask-question-error" });
|
|
noAnswerEl.setText("No response recorded");
|
|
}
|
|
const toggleExpand = () => {
|
|
const expanded = wrapperEl.hasClass("expanded");
|
|
if (expanded) {
|
|
wrapperEl.removeClass("expanded");
|
|
contentEl.style.display = "none";
|
|
headerEl.setAttribute("aria-expanded", "false");
|
|
} else {
|
|
wrapperEl.addClass("expanded");
|
|
contentEl.style.display = "block";
|
|
headerEl.setAttribute("aria-expanded", "true");
|
|
}
|
|
};
|
|
headerEl.addEventListener("click", toggleExpand);
|
|
headerEl.addEventListener("keydown", (e) => {
|
|
if (e.key === "Enter" || e.key === " ") {
|
|
e.preventDefault();
|
|
toggleExpand();
|
|
}
|
|
});
|
|
return wrapperEl;
|
|
}
|
|
|
|
// src/ui/renderers/DiffRenderer.ts
|
|
function computeLineDiff(oldText, newText) {
|
|
const oldLines = oldText.replace(/\r\n/g, "\n").split("\n");
|
|
const newLines = newText.replace(/\r\n/g, "\n").split("\n");
|
|
const m = oldLines.length;
|
|
const n = newLines.length;
|
|
const dp = Array(m + 1).fill(null).map(() => Array(n + 1).fill(0));
|
|
for (let i2 = 1; i2 <= m; i2++) {
|
|
for (let j2 = 1; j2 <= n; j2++) {
|
|
dp[i2][j2] = oldLines[i2 - 1] === newLines[j2 - 1] ? dp[i2 - 1][j2 - 1] + 1 : Math.max(dp[i2 - 1][j2], dp[i2][j2 - 1]);
|
|
}
|
|
}
|
|
const result = [];
|
|
let i = m, j = n;
|
|
const temp = [];
|
|
while (i > 0 || j > 0) {
|
|
if (i > 0 && j > 0 && oldLines[i - 1] === newLines[j - 1]) {
|
|
temp.push({ type: "equal", text: oldLines[i - 1] });
|
|
i--;
|
|
j--;
|
|
} else if (j > 0 && (i === 0 || dp[i][j - 1] >= dp[i - 1][j])) {
|
|
temp.push({ type: "insert", text: newLines[j - 1] });
|
|
j--;
|
|
} else {
|
|
temp.push({ type: "delete", text: oldLines[i - 1] });
|
|
i--;
|
|
}
|
|
}
|
|
temp.reverse();
|
|
let oldLineNum = 1;
|
|
let newLineNum = 1;
|
|
for (const line of temp) {
|
|
if (line.type === "equal") {
|
|
result.push({ ...line, oldLineNum: oldLineNum++, newLineNum: newLineNum++ });
|
|
} else if (line.type === "delete") {
|
|
result.push({ ...line, oldLineNum: oldLineNum++ });
|
|
} else {
|
|
result.push({ ...line, newLineNum: newLineNum++ });
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
function countLineChanges(diffLines) {
|
|
let added = 0;
|
|
let removed = 0;
|
|
for (const line of diffLines) {
|
|
if (line.type === "insert") added++;
|
|
else if (line.type === "delete") removed++;
|
|
}
|
|
return { added, removed };
|
|
}
|
|
function splitIntoHunks(diffLines, contextLines = 3) {
|
|
if (diffLines.length === 0) return [];
|
|
const changedIndices = [];
|
|
for (let i = 0; i < diffLines.length; i++) {
|
|
if (diffLines[i].type !== "equal") {
|
|
changedIndices.push(i);
|
|
}
|
|
}
|
|
if (changedIndices.length === 0) return [];
|
|
const ranges = [];
|
|
for (const idx of changedIndices) {
|
|
const start = Math.max(0, idx - contextLines);
|
|
const end = Math.min(diffLines.length - 1, idx + contextLines);
|
|
if (ranges.length > 0 && start <= ranges[ranges.length - 1].end + 1) {
|
|
ranges[ranges.length - 1].end = end;
|
|
} else {
|
|
ranges.push({ start, end });
|
|
}
|
|
}
|
|
const hunks = [];
|
|
for (const range of ranges) {
|
|
const lines = diffLines.slice(range.start, range.end + 1);
|
|
let oldStart = 1;
|
|
let newStart = 1;
|
|
for (let i = 0; i < range.start; i++) {
|
|
const line = diffLines[i];
|
|
if (line.type === "equal" || line.type === "delete") oldStart++;
|
|
if (line.type === "equal" || line.type === "insert") newStart++;
|
|
}
|
|
hunks.push({ lines, oldStart, newStart });
|
|
}
|
|
return hunks;
|
|
}
|
|
function renderDiffContent(containerEl, diffLines, contextLines = 3) {
|
|
containerEl.empty();
|
|
const hunks = splitIntoHunks(diffLines, contextLines);
|
|
if (hunks.length === 0) {
|
|
const noChanges = containerEl.createDiv({ cls: "claudian-diff-no-changes" });
|
|
noChanges.setText("No changes");
|
|
return;
|
|
}
|
|
hunks.forEach((hunk, hunkIndex) => {
|
|
if (hunkIndex > 0) {
|
|
const separator = containerEl.createDiv({ cls: "claudian-diff-separator" });
|
|
separator.setText("...");
|
|
}
|
|
const hunkEl = containerEl.createDiv({ cls: "claudian-diff-hunk" });
|
|
for (const line of hunk.lines) {
|
|
const lineEl = hunkEl.createDiv({ cls: `claudian-diff-line claudian-diff-${line.type}` });
|
|
const prefix = line.type === "insert" ? "+" : line.type === "delete" ? "-" : " ";
|
|
const prefixEl = lineEl.createSpan({ cls: "claudian-diff-prefix" });
|
|
prefixEl.setText(prefix);
|
|
const contentEl = lineEl.createSpan({ cls: "claudian-diff-text" });
|
|
contentEl.setText(line.text || " ");
|
|
}
|
|
});
|
|
}
|
|
function isBinaryContent(content) {
|
|
const nonPrintable = content.match(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g);
|
|
if (nonPrintable && nonPrintable.length > content.length * 0.1) {
|
|
return true;
|
|
}
|
|
return content.includes("\0");
|
|
}
|
|
|
|
// src/ui/renderers/SubagentRenderer.ts
|
|
var import_obsidian16 = require("obsidian");
|
|
|
|
// src/ui/utils/collapsible.ts
|
|
function setupCollapsible(wrapperEl, headerEl, contentEl, state, options = {}) {
|
|
const { initiallyExpanded = false, onToggle, baseAriaLabel } = options;
|
|
const updateAriaLabel = (isExpanded) => {
|
|
if (baseAriaLabel) {
|
|
const action = isExpanded ? "click to collapse" : "click to expand";
|
|
headerEl.setAttribute("aria-label", `${baseAriaLabel} - ${action}`);
|
|
}
|
|
};
|
|
state.isExpanded = initiallyExpanded;
|
|
if (initiallyExpanded) {
|
|
wrapperEl.addClass("expanded");
|
|
contentEl.style.display = "block";
|
|
headerEl.setAttribute("aria-expanded", "true");
|
|
} else {
|
|
contentEl.style.display = "none";
|
|
headerEl.setAttribute("aria-expanded", "false");
|
|
}
|
|
updateAriaLabel(initiallyExpanded);
|
|
const toggleExpand = () => {
|
|
state.isExpanded = !state.isExpanded;
|
|
if (state.isExpanded) {
|
|
wrapperEl.addClass("expanded");
|
|
contentEl.style.display = "block";
|
|
headerEl.setAttribute("aria-expanded", "true");
|
|
} else {
|
|
wrapperEl.removeClass("expanded");
|
|
contentEl.style.display = "none";
|
|
headerEl.setAttribute("aria-expanded", "false");
|
|
}
|
|
updateAriaLabel(state.isExpanded);
|
|
onToggle == null ? void 0 : onToggle(state.isExpanded);
|
|
};
|
|
headerEl.addEventListener("click", toggleExpand);
|
|
headerEl.addEventListener("keydown", (e) => {
|
|
if (e.key === "Enter" || e.key === " ") {
|
|
e.preventDefault();
|
|
toggleExpand();
|
|
}
|
|
});
|
|
}
|
|
function collapseElement(wrapperEl, headerEl, contentEl, state) {
|
|
state.isExpanded = false;
|
|
wrapperEl.removeClass("expanded");
|
|
contentEl.style.display = "none";
|
|
headerEl.setAttribute("aria-expanded", "false");
|
|
}
|
|
|
|
// src/ui/renderers/ToolCallRenderer.ts
|
|
var import_obsidian15 = require("obsidian");
|
|
function setToolIcon(el, name) {
|
|
const icon = getToolIcon(name);
|
|
if (icon === MCP_ICON_MARKER) {
|
|
el.innerHTML = MCP_ICON_SVG;
|
|
} else {
|
|
(0, import_obsidian15.setIcon)(el, icon);
|
|
}
|
|
}
|
|
function getToolLabel(name, input) {
|
|
switch (name) {
|
|
case "Read":
|
|
return `Read: ${shortenPath(input.file_path) || "file"}`;
|
|
case "Write":
|
|
return `Write: ${shortenPath(input.file_path) || "file"}`;
|
|
case "Edit":
|
|
return `Edit: ${shortenPath(input.file_path) || "file"}`;
|
|
case "Bash": {
|
|
const cmd = input.command || "command";
|
|
return `Bash: ${cmd.length > 40 ? cmd.substring(0, 40) + "..." : cmd}`;
|
|
}
|
|
case "Glob":
|
|
return `Glob: ${input.pattern || "files"}`;
|
|
case "Grep":
|
|
return `Grep: ${input.pattern || "pattern"}`;
|
|
case "WebSearch": {
|
|
const query2 = input.query || "search";
|
|
return `WebSearch: ${query2.length > 40 ? query2.substring(0, 40) + "..." : query2}`;
|
|
}
|
|
case "WebFetch": {
|
|
const url = input.url || "url";
|
|
return `WebFetch: ${url.length > 40 ? url.substring(0, 40) + "..." : url}`;
|
|
}
|
|
case "LS":
|
|
return `LS: ${shortenPath(input.path) || "."}`;
|
|
case "TodoWrite": {
|
|
const todos = input.todos;
|
|
if (todos && Array.isArray(todos)) {
|
|
const completed = todos.filter((t) => t.status === "completed").length;
|
|
return `Tasks (${completed}/${todos.length})`;
|
|
}
|
|
return "Tasks";
|
|
}
|
|
case "Skill": {
|
|
const skillName = input.skill || "skill";
|
|
return `Skill: ${skillName}`;
|
|
}
|
|
default:
|
|
return name;
|
|
}
|
|
}
|
|
function shortenPath(filePath) {
|
|
if (!filePath) return "";
|
|
const normalized = filePath.replace(/\\/g, "/");
|
|
const parts = normalized.split("/");
|
|
if (parts.length <= 3) return normalized;
|
|
return ".../" + parts.slice(-2).join("/");
|
|
}
|
|
function parseWebSearchResult(result) {
|
|
const linksMatch = result.match(/Links:\s*(\[[\s\S]*\])/);
|
|
if (!linksMatch) return null;
|
|
try {
|
|
const links = JSON.parse(linksMatch[1]);
|
|
if (!Array.isArray(links) || links.length === 0) return null;
|
|
return links;
|
|
} catch (e) {
|
|
return null;
|
|
}
|
|
}
|
|
function renderWebSearchResult(container, result, maxItems = 3) {
|
|
const links = parseWebSearchResult(result);
|
|
if (!links) return false;
|
|
container.empty();
|
|
const displayItems = links.slice(0, maxItems);
|
|
displayItems.forEach((link) => {
|
|
const item = container.createSpan({ cls: "claudian-tool-result-bullet" });
|
|
item.setText(`\u2022 ${link.title}`);
|
|
});
|
|
if (links.length > maxItems) {
|
|
const more = container.createSpan({ cls: "claudian-tool-result-item" });
|
|
more.setText(`${links.length - maxItems} more results`);
|
|
}
|
|
return true;
|
|
}
|
|
function renderReadResult(container, result) {
|
|
container.empty();
|
|
const lines = result.split(/\r?\n/).filter((line) => line.trim() !== "");
|
|
const item = container.createSpan({ cls: "claudian-tool-result-item" });
|
|
item.setText(`${lines.length} lines read`);
|
|
}
|
|
function renderResultLines(container, result, maxLines = 3) {
|
|
container.empty();
|
|
const lines = result.split(/\r?\n/);
|
|
const displayLines = lines.slice(0, maxLines);
|
|
displayLines.forEach((line) => {
|
|
const stripped = line.replace(/^\s*\d+→/, "");
|
|
const item = container.createSpan({ cls: "claudian-tool-result-item" });
|
|
item.setText(stripped);
|
|
});
|
|
if (lines.length > maxLines) {
|
|
const more = container.createSpan({ cls: "claudian-tool-result-item" });
|
|
more.setText(`${lines.length - maxLines} more lines`);
|
|
}
|
|
}
|
|
function isBlockedToolResult(content, isError) {
|
|
const lower = content.toLowerCase();
|
|
if (lower.includes("blocked by blocklist")) return true;
|
|
if (lower.includes("outside the vault")) return true;
|
|
if (lower.includes("access denied")) return true;
|
|
if (lower.includes("user denied")) return true;
|
|
if (lower.includes("approval")) return true;
|
|
if (isError && lower.includes("deny")) return true;
|
|
return false;
|
|
}
|
|
function renderToolCall(parentEl, toolCall, toolCallElements) {
|
|
const toolEl = parentEl.createDiv({ cls: "claudian-tool-call" });
|
|
toolEl.dataset.toolId = toolCall.id;
|
|
toolCallElements.set(toolCall.id, toolEl);
|
|
const header = toolEl.createDiv({ cls: "claudian-tool-header" });
|
|
header.setAttribute("tabindex", "0");
|
|
header.setAttribute("role", "button");
|
|
const iconEl = header.createSpan({ cls: "claudian-tool-icon" });
|
|
iconEl.setAttribute("aria-hidden", "true");
|
|
setToolIcon(iconEl, toolCall.name);
|
|
const labelEl = header.createSpan({ cls: "claudian-tool-label" });
|
|
labelEl.setText(getToolLabel(toolCall.name, toolCall.input));
|
|
const statusEl = header.createSpan({ cls: "claudian-tool-status" });
|
|
statusEl.addClass(`status-${toolCall.status}`);
|
|
statusEl.setAttribute("aria-label", `Status: ${toolCall.status}`);
|
|
if (toolCall.status === "running") {
|
|
statusEl.createSpan({ cls: "claudian-spinner" });
|
|
}
|
|
const content = toolEl.createDiv({ cls: "claudian-tool-content" });
|
|
const resultRow = content.createDiv({ cls: "claudian-tool-result-row" });
|
|
const branch = resultRow.createSpan({ cls: "claudian-tool-branch" });
|
|
branch.setText("\u2514\u2500");
|
|
const resultText = resultRow.createSpan({ cls: "claudian-tool-result-text" });
|
|
resultText.setText("Running...");
|
|
const state = { isExpanded: false };
|
|
toolCall.isExpanded = false;
|
|
setupCollapsible(toolEl, header, content, state, {
|
|
initiallyExpanded: false,
|
|
onToggle: (expanded) => {
|
|
toolCall.isExpanded = expanded;
|
|
},
|
|
baseAriaLabel: getToolLabel(toolCall.name, toolCall.input)
|
|
});
|
|
return toolEl;
|
|
}
|
|
function updateToolCallResult(toolId, toolCall, toolCallElements) {
|
|
const toolEl = toolCallElements.get(toolId);
|
|
if (!toolEl) return;
|
|
const statusEl = toolEl.querySelector(".claudian-tool-status");
|
|
if (statusEl) {
|
|
statusEl.className = "claudian-tool-status";
|
|
statusEl.addClass(`status-${toolCall.status}`);
|
|
statusEl.empty();
|
|
if (toolCall.status === "completed") {
|
|
(0, import_obsidian15.setIcon)(statusEl, "check");
|
|
} else if (toolCall.status === "error") {
|
|
(0, import_obsidian15.setIcon)(statusEl, "x");
|
|
} else if (toolCall.status === "blocked") {
|
|
(0, import_obsidian15.setIcon)(statusEl, "shield-off");
|
|
}
|
|
}
|
|
const resultText = toolEl.querySelector(".claudian-tool-result-text");
|
|
if (resultText && toolCall.result) {
|
|
if (toolCall.name === "WebSearch") {
|
|
if (!renderWebSearchResult(resultText, toolCall.result, 3)) {
|
|
renderResultLines(resultText, toolCall.result, 3);
|
|
}
|
|
} else if (toolCall.name === "Read") {
|
|
renderReadResult(resultText, toolCall.result);
|
|
} else {
|
|
renderResultLines(resultText, toolCall.result, 3);
|
|
}
|
|
}
|
|
}
|
|
function renderStoredToolCall(parentEl, toolCall) {
|
|
const toolEl = parentEl.createDiv({ cls: "claudian-tool-call" });
|
|
const header = toolEl.createDiv({ cls: "claudian-tool-header" });
|
|
header.setAttribute("tabindex", "0");
|
|
header.setAttribute("role", "button");
|
|
const iconEl = header.createSpan({ cls: "claudian-tool-icon" });
|
|
iconEl.setAttribute("aria-hidden", "true");
|
|
setToolIcon(iconEl, toolCall.name);
|
|
const labelEl = header.createSpan({ cls: "claudian-tool-label" });
|
|
labelEl.setText(getToolLabel(toolCall.name, toolCall.input));
|
|
const statusEl = header.createSpan({ cls: "claudian-tool-status" });
|
|
statusEl.addClass(`status-${toolCall.status}`);
|
|
statusEl.setAttribute("aria-label", `Status: ${toolCall.status}`);
|
|
if (toolCall.status === "completed") {
|
|
(0, import_obsidian15.setIcon)(statusEl, "check");
|
|
} else if (toolCall.status === "error") {
|
|
(0, import_obsidian15.setIcon)(statusEl, "x");
|
|
} else if (toolCall.status === "blocked") {
|
|
(0, import_obsidian15.setIcon)(statusEl, "shield-off");
|
|
}
|
|
const content = toolEl.createDiv({ cls: "claudian-tool-content" });
|
|
const resultRow = content.createDiv({ cls: "claudian-tool-result-row" });
|
|
const branch = resultRow.createSpan({ cls: "claudian-tool-branch" });
|
|
branch.setText("\u2514\u2500");
|
|
const resultText = resultRow.createSpan({ cls: "claudian-tool-result-text" });
|
|
if (toolCall.result) {
|
|
if (toolCall.name === "WebSearch") {
|
|
if (!renderWebSearchResult(resultText, toolCall.result, 3)) {
|
|
renderResultLines(resultText, toolCall.result, 3);
|
|
}
|
|
} else if (toolCall.name === "Read") {
|
|
renderReadResult(resultText, toolCall.result);
|
|
} else {
|
|
renderResultLines(resultText, toolCall.result, 3);
|
|
}
|
|
} else {
|
|
resultText.setText("No result");
|
|
}
|
|
const state = { isExpanded: false };
|
|
setupCollapsible(toolEl, header, content, state, {
|
|
initiallyExpanded: false,
|
|
baseAriaLabel: getToolLabel(toolCall.name, toolCall.input)
|
|
});
|
|
return toolEl;
|
|
}
|
|
|
|
// src/ui/renderers/SubagentRenderer.ts
|
|
function extractTaskDescription(input) {
|
|
return input.description || "Subagent task";
|
|
}
|
|
function truncateDescription(description, maxLength = 40) {
|
|
if (description.length <= maxLength) return description;
|
|
return description.substring(0, maxLength) + "...";
|
|
}
|
|
function truncateResult(result) {
|
|
const lines = result.split(/\r?\n/).filter((line) => line.trim());
|
|
if (lines.length <= 2) {
|
|
return lines.join("\n");
|
|
}
|
|
return lines.slice(0, 2).join("\n") + "...";
|
|
}
|
|
function createSubagentBlock(parentEl, taskToolId, taskInput) {
|
|
const description = extractTaskDescription(taskInput);
|
|
const info = {
|
|
id: taskToolId,
|
|
description,
|
|
status: "running",
|
|
toolCalls: [],
|
|
isExpanded: false
|
|
// Collapsed by default
|
|
};
|
|
const wrapperEl = parentEl.createDiv({ cls: "claudian-subagent-list" });
|
|
wrapperEl.dataset.subagentId = taskToolId;
|
|
const headerEl = wrapperEl.createDiv({ cls: "claudian-subagent-header" });
|
|
headerEl.setAttribute("tabindex", "0");
|
|
headerEl.setAttribute("role", "button");
|
|
headerEl.setAttribute("aria-expanded", "false");
|
|
headerEl.setAttribute("aria-label", `Subagent task: ${truncateDescription(description)} - click to expand`);
|
|
const iconEl = headerEl.createDiv({ cls: "claudian-subagent-icon" });
|
|
iconEl.setAttribute("aria-hidden", "true");
|
|
(0, import_obsidian16.setIcon)(iconEl, "bot");
|
|
const labelEl = headerEl.createDiv({ cls: "claudian-subagent-label" });
|
|
labelEl.setText(truncateDescription(description));
|
|
const countEl = headerEl.createDiv({ cls: "claudian-subagent-count" });
|
|
countEl.setText("0 tool uses");
|
|
const statusEl = headerEl.createDiv({ cls: "claudian-subagent-status status-running" });
|
|
statusEl.setAttribute("aria-label", "Status: running");
|
|
const contentEl = wrapperEl.createDiv({ cls: "claudian-subagent-content" });
|
|
setupCollapsible(wrapperEl, headerEl, contentEl, info);
|
|
return {
|
|
wrapperEl,
|
|
contentEl,
|
|
headerEl,
|
|
labelEl,
|
|
countEl,
|
|
statusEl,
|
|
info,
|
|
currentToolEl: null,
|
|
currentResultEl: null
|
|
};
|
|
}
|
|
function addSubagentToolCall(state, toolCall) {
|
|
state.info.toolCalls.push(toolCall);
|
|
const toolCount = state.info.toolCalls.length;
|
|
state.countEl.setText(`${toolCount} tool uses`);
|
|
state.contentEl.empty();
|
|
state.currentResultEl = null;
|
|
const itemEl = state.contentEl.createDiv({
|
|
cls: `claudian-subagent-tool-item claudian-subagent-tool-${toolCall.status}`
|
|
});
|
|
itemEl.dataset.toolId = toolCall.id;
|
|
state.currentToolEl = itemEl;
|
|
const toolRowEl = itemEl.createDiv({ cls: "claudian-subagent-tool-row" });
|
|
const branchEl = toolRowEl.createDiv({ cls: "claudian-subagent-branch" });
|
|
branchEl.setText("\u2514\u2500");
|
|
const labelEl = toolRowEl.createDiv({ cls: "claudian-subagent-tool-text" });
|
|
labelEl.setText(getToolLabel(toolCall.name, toolCall.input));
|
|
}
|
|
function updateSubagentToolResult(state, toolId, toolCall) {
|
|
const idx = state.info.toolCalls.findIndex((tc) => tc.id === toolId);
|
|
if (idx !== -1) {
|
|
state.info.toolCalls[idx] = toolCall;
|
|
}
|
|
if (state.currentToolEl && state.currentToolEl.dataset.toolId === toolId) {
|
|
state.currentToolEl.className = `claudian-subagent-tool-item claudian-subagent-tool-${toolCall.status}`;
|
|
if (toolCall.result) {
|
|
if (!state.currentResultEl) {
|
|
state.currentResultEl = state.currentToolEl.createDiv({ cls: "claudian-subagent-tool-result" });
|
|
const branchEl = state.currentResultEl.createDiv({ cls: "claudian-subagent-branch" });
|
|
branchEl.setText("\u2514\u2500");
|
|
const textEl = state.currentResultEl.createDiv({ cls: "claudian-subagent-result-text" });
|
|
textEl.setText(truncateResult(toolCall.result));
|
|
} else {
|
|
const textEl = state.currentResultEl.querySelector(".claudian-subagent-result-text");
|
|
if (textEl) {
|
|
textEl.setText(truncateResult(toolCall.result));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
function finalizeSubagentBlock(state, result, isError) {
|
|
state.info.status = isError ? "error" : "completed";
|
|
state.info.result = result;
|
|
state.labelEl.setText(truncateDescription(state.info.description));
|
|
const toolCount = state.info.toolCalls.length;
|
|
state.countEl.setText(`${toolCount} tool uses`);
|
|
state.statusEl.className = "claudian-subagent-status";
|
|
state.statusEl.addClass(`status-${state.info.status}`);
|
|
state.statusEl.empty();
|
|
if (state.info.status === "completed") {
|
|
(0, import_obsidian16.setIcon)(state.statusEl, "check");
|
|
} else {
|
|
(0, import_obsidian16.setIcon)(state.statusEl, "x");
|
|
}
|
|
if (state.info.status === "completed") {
|
|
state.wrapperEl.addClass("done");
|
|
} else if (state.info.status === "error") {
|
|
state.wrapperEl.addClass("error");
|
|
}
|
|
state.contentEl.empty();
|
|
state.currentToolEl = null;
|
|
state.currentResultEl = null;
|
|
const doneEl = state.contentEl.createDiv({ cls: "claudian-subagent-done" });
|
|
const branchEl = doneEl.createDiv({ cls: "claudian-subagent-branch" });
|
|
branchEl.setText("\u2514\u2500");
|
|
const textEl = doneEl.createDiv({ cls: "claudian-subagent-done-text" });
|
|
textEl.setText(isError ? "ERROR" : "DONE");
|
|
}
|
|
function renderStoredSubagent(parentEl, subagent) {
|
|
const wrapperEl = parentEl.createDiv({ cls: "claudian-subagent-list" });
|
|
if (subagent.status === "completed") {
|
|
wrapperEl.addClass("done");
|
|
} else if (subagent.status === "error") {
|
|
wrapperEl.addClass("error");
|
|
}
|
|
wrapperEl.dataset.subagentId = subagent.id;
|
|
const toolCount = subagent.toolCalls.length;
|
|
const headerEl = wrapperEl.createDiv({ cls: "claudian-subagent-header" });
|
|
headerEl.setAttribute("tabindex", "0");
|
|
headerEl.setAttribute("role", "button");
|
|
headerEl.setAttribute("aria-label", `Subagent task: ${truncateDescription(subagent.description)} - ${toolCount} tool uses - Status: ${subagent.status}`);
|
|
const iconEl = headerEl.createDiv({ cls: "claudian-subagent-icon" });
|
|
iconEl.setAttribute("aria-hidden", "true");
|
|
(0, import_obsidian16.setIcon)(iconEl, "bot");
|
|
const labelEl = headerEl.createDiv({ cls: "claudian-subagent-label" });
|
|
labelEl.setText(truncateDescription(subagent.description));
|
|
const countEl = headerEl.createDiv({ cls: "claudian-subagent-count" });
|
|
countEl.setText(`${toolCount} tool uses`);
|
|
const statusEl = headerEl.createDiv({ cls: `claudian-subagent-status status-${subagent.status}` });
|
|
statusEl.setAttribute("aria-label", `Status: ${subagent.status}`);
|
|
if (subagent.status === "completed") {
|
|
(0, import_obsidian16.setIcon)(statusEl, "check");
|
|
} else if (subagent.status === "error") {
|
|
(0, import_obsidian16.setIcon)(statusEl, "x");
|
|
} else {
|
|
statusEl.createSpan({ cls: "claudian-spinner" });
|
|
}
|
|
const contentEl = wrapperEl.createDiv({ cls: "claudian-subagent-content" });
|
|
if (subagent.status === "completed" || subagent.status === "error") {
|
|
const doneEl = contentEl.createDiv({ cls: "claudian-subagent-done" });
|
|
const branchEl = doneEl.createDiv({ cls: "claudian-subagent-branch" });
|
|
branchEl.setText("\u2514\u2500");
|
|
const textEl = doneEl.createDiv({ cls: "claudian-subagent-done-text" });
|
|
textEl.setText(subagent.status === "error" ? "ERROR" : "DONE");
|
|
} else {
|
|
const lastTool = subagent.toolCalls[subagent.toolCalls.length - 1];
|
|
if (lastTool) {
|
|
const itemEl = contentEl.createDiv({
|
|
cls: `claudian-subagent-tool-item claudian-subagent-tool-${lastTool.status}`
|
|
});
|
|
const toolRowEl = itemEl.createDiv({ cls: "claudian-subagent-tool-row" });
|
|
const branchEl = toolRowEl.createDiv({ cls: "claudian-subagent-branch" });
|
|
branchEl.setText("\u2514\u2500");
|
|
const toolLabelEl = toolRowEl.createDiv({ cls: "claudian-subagent-tool-text" });
|
|
toolLabelEl.setText(getToolLabel(lastTool.name, lastTool.input));
|
|
if (lastTool.result) {
|
|
const resultEl = itemEl.createDiv({ cls: "claudian-subagent-tool-result" });
|
|
const resultBranchEl = resultEl.createDiv({ cls: "claudian-subagent-branch" });
|
|
resultBranchEl.setText("\u2514\u2500");
|
|
const textEl = resultEl.createDiv({ cls: "claudian-subagent-result-text" });
|
|
textEl.setText(truncateResult(lastTool.result));
|
|
}
|
|
}
|
|
}
|
|
const state = { isExpanded: false };
|
|
setupCollapsible(wrapperEl, headerEl, contentEl, state);
|
|
return wrapperEl;
|
|
}
|
|
function setAsyncWrapperStatus(wrapperEl, status) {
|
|
const classes = ["pending", "running", "awaiting", "completed", "error", "orphaned", "async"];
|
|
classes.forEach((cls) => wrapperEl.removeClass(cls));
|
|
wrapperEl.addClass("async");
|
|
wrapperEl.addClass(status);
|
|
}
|
|
function getAsyncDisplayStatus(asyncStatus) {
|
|
if (asyncStatus === "completed") return "completed";
|
|
if (asyncStatus === "error") return "error";
|
|
if (asyncStatus === "orphaned") return "orphaned";
|
|
return "running";
|
|
}
|
|
function getAsyncStatusText(asyncStatus) {
|
|
const display = getAsyncDisplayStatus(asyncStatus);
|
|
if (display === "completed") return "Completed";
|
|
if (display === "error") return "Error";
|
|
if (display === "orphaned") return "Orphaned";
|
|
return "Running";
|
|
}
|
|
function updateAsyncLabel(state, _displayStatus) {
|
|
state.labelEl.setText(truncateDescription(state.info.description));
|
|
}
|
|
function createAsyncSubagentBlock(parentEl, taskToolId, taskInput) {
|
|
const description = taskInput.description || "Background task";
|
|
const info = {
|
|
id: taskToolId,
|
|
description,
|
|
mode: "async",
|
|
status: "running",
|
|
toolCalls: [],
|
|
isExpanded: false,
|
|
// Collapsed by default for async
|
|
asyncStatus: "pending"
|
|
};
|
|
const wrapperEl = parentEl.createDiv({ cls: "claudian-subagent-list" });
|
|
setAsyncWrapperStatus(wrapperEl, "pending");
|
|
wrapperEl.dataset.asyncSubagentId = taskToolId;
|
|
const headerEl = wrapperEl.createDiv({ cls: "claudian-subagent-header" });
|
|
headerEl.setAttribute("tabindex", "0");
|
|
headerEl.setAttribute("role", "button");
|
|
headerEl.setAttribute("aria-expanded", "false");
|
|
headerEl.setAttribute("aria-label", `Background task: ${description} - Status: running`);
|
|
const iconEl = headerEl.createDiv({ cls: "claudian-subagent-icon" });
|
|
iconEl.setAttribute("aria-hidden", "true");
|
|
(0, import_obsidian16.setIcon)(iconEl, "bot");
|
|
const labelEl = headerEl.createDiv({ cls: "claudian-subagent-label" });
|
|
labelEl.setText(truncateDescription(description));
|
|
const statusTextEl = headerEl.createDiv({ cls: "claudian-subagent-status-text" });
|
|
statusTextEl.setText("Running");
|
|
const statusEl = headerEl.createDiv({ cls: "claudian-subagent-status status-running" });
|
|
statusEl.setAttribute("aria-label", "Status: running");
|
|
const contentEl = wrapperEl.createDiv({ cls: "claudian-subagent-content" });
|
|
const statusRow = contentEl.createDiv({ cls: "claudian-subagent-done" });
|
|
const branchEl = statusRow.createDiv({ cls: "claudian-subagent-branch" });
|
|
branchEl.setText("\u2514\u2500");
|
|
const textEl = statusRow.createDiv({ cls: "claudian-subagent-done-text" });
|
|
textEl.setText("run in background");
|
|
setupCollapsible(wrapperEl, headerEl, contentEl, info);
|
|
return {
|
|
wrapperEl,
|
|
contentEl,
|
|
headerEl,
|
|
labelEl,
|
|
statusTextEl,
|
|
statusEl,
|
|
info
|
|
};
|
|
}
|
|
function updateAsyncSubagentRunning(state, agentId) {
|
|
state.info.asyncStatus = "running";
|
|
state.info.agentId = agentId;
|
|
setAsyncWrapperStatus(state.wrapperEl, "running");
|
|
updateAsyncLabel(state, "running");
|
|
state.statusTextEl.setText("Running");
|
|
state.contentEl.empty();
|
|
const statusRow = state.contentEl.createDiv({ cls: "claudian-subagent-done" });
|
|
const branchEl = statusRow.createDiv({ cls: "claudian-subagent-branch" });
|
|
branchEl.setText("\u2514\u2500");
|
|
const textEl = statusRow.createDiv({ cls: "claudian-subagent-done-text claudian-async-agent-id" });
|
|
const shortId = agentId.length > 12 ? agentId.substring(0, 12) + "..." : agentId;
|
|
textEl.setText(`run in background (${shortId})`);
|
|
}
|
|
function finalizeAsyncSubagent(state, result, isError) {
|
|
state.info.asyncStatus = isError ? "error" : "completed";
|
|
state.info.status = isError ? "error" : "completed";
|
|
state.info.result = result;
|
|
setAsyncWrapperStatus(state.wrapperEl, isError ? "error" : "completed");
|
|
updateAsyncLabel(state, isError ? "error" : "completed");
|
|
state.statusTextEl.setText(isError ? "Error" : "Completed");
|
|
state.statusEl.className = "claudian-subagent-status";
|
|
state.statusEl.addClass(`status-${isError ? "error" : "completed"}`);
|
|
state.statusEl.empty();
|
|
if (isError) {
|
|
(0, import_obsidian16.setIcon)(state.statusEl, "x");
|
|
} else {
|
|
(0, import_obsidian16.setIcon)(state.statusEl, "check");
|
|
}
|
|
if (isError) {
|
|
state.wrapperEl.addClass("error");
|
|
} else {
|
|
state.wrapperEl.addClass("done");
|
|
}
|
|
state.contentEl.empty();
|
|
const resultEl = state.contentEl.createDiv({ cls: "claudian-subagent-done" });
|
|
const branchEl = resultEl.createDiv({ cls: "claudian-subagent-branch" });
|
|
branchEl.setText("\u2514\u2500");
|
|
const textEl = resultEl.createDiv({ cls: "claudian-subagent-done-text" });
|
|
if (isError && result) {
|
|
const truncated = result.length > 80 ? result.substring(0, 80) + "..." : result;
|
|
textEl.setText(`ERROR: ${truncated}`);
|
|
} else {
|
|
textEl.setText(isError ? "ERROR" : "DONE");
|
|
}
|
|
}
|
|
function markAsyncSubagentOrphaned(state) {
|
|
state.info.asyncStatus = "orphaned";
|
|
state.info.status = "error";
|
|
state.info.result = "Conversation ended before task completed";
|
|
setAsyncWrapperStatus(state.wrapperEl, "orphaned");
|
|
updateAsyncLabel(state, "orphaned");
|
|
state.statusTextEl.setText("Orphaned");
|
|
state.statusEl.className = "claudian-subagent-status status-error";
|
|
state.statusEl.empty();
|
|
(0, import_obsidian16.setIcon)(state.statusEl, "alert-circle");
|
|
state.wrapperEl.addClass("error");
|
|
state.wrapperEl.addClass("orphaned");
|
|
state.contentEl.empty();
|
|
const orphanEl = state.contentEl.createDiv({ cls: "claudian-subagent-done claudian-async-orphaned" });
|
|
const branchEl = orphanEl.createDiv({ cls: "claudian-subagent-branch" });
|
|
branchEl.setText("\u2514\u2500");
|
|
const textEl = orphanEl.createDiv({ cls: "claudian-subagent-done-text" });
|
|
textEl.setText("\u26A0\uFE0F Task orphaned");
|
|
}
|
|
function renderStoredAsyncSubagent(parentEl, subagent) {
|
|
const wrapperEl = parentEl.createDiv({ cls: "claudian-subagent-list" });
|
|
const statusClass = getAsyncDisplayStatus(subagent.asyncStatus);
|
|
setAsyncWrapperStatus(wrapperEl, statusClass);
|
|
if (subagent.asyncStatus === "completed") {
|
|
wrapperEl.addClass("done");
|
|
} else if (subagent.asyncStatus === "error" || subagent.asyncStatus === "orphaned") {
|
|
wrapperEl.addClass("error");
|
|
}
|
|
wrapperEl.dataset.asyncSubagentId = subagent.id;
|
|
const displayStatus = getAsyncDisplayStatus(subagent.asyncStatus);
|
|
const statusText = getAsyncStatusText(subagent.asyncStatus);
|
|
const headerEl = wrapperEl.createDiv({ cls: "claudian-subagent-header" });
|
|
headerEl.setAttribute("tabindex", "0");
|
|
headerEl.setAttribute("role", "button");
|
|
headerEl.setAttribute("aria-label", `Background task: ${subagent.description} - Status: ${statusText}`);
|
|
const iconEl = headerEl.createDiv({ cls: "claudian-subagent-icon" });
|
|
iconEl.setAttribute("aria-hidden", "true");
|
|
(0, import_obsidian16.setIcon)(iconEl, "bot");
|
|
const labelEl = headerEl.createDiv({ cls: "claudian-subagent-label" });
|
|
labelEl.setText(truncateDescription(subagent.description));
|
|
const statusTextEl = headerEl.createDiv({ cls: "claudian-subagent-status-text" });
|
|
statusTextEl.setText(statusText);
|
|
const statusIconClass = displayStatus === "error" || displayStatus === "orphaned" ? "status-error" : displayStatus === "completed" ? "status-completed" : "status-running";
|
|
const statusEl = headerEl.createDiv({ cls: `claudian-subagent-status ${statusIconClass}` });
|
|
statusEl.setAttribute("aria-label", `Status: ${statusText}`);
|
|
if (subagent.asyncStatus === "completed") {
|
|
(0, import_obsidian16.setIcon)(statusEl, "check");
|
|
} else if (subagent.asyncStatus === "error" || subagent.asyncStatus === "orphaned") {
|
|
(0, import_obsidian16.setIcon)(statusEl, subagent.asyncStatus === "orphaned" ? "alert-circle" : "x");
|
|
}
|
|
const contentEl = wrapperEl.createDiv({ cls: "claudian-subagent-content" });
|
|
const statusRow = contentEl.createDiv({ cls: "claudian-subagent-done" });
|
|
const branchEl = statusRow.createDiv({ cls: "claudian-subagent-branch" });
|
|
branchEl.setText("\u2514\u2500");
|
|
const textEl = statusRow.createDiv({ cls: "claudian-subagent-done-text" });
|
|
if (subagent.asyncStatus === "completed") {
|
|
textEl.setText("DONE");
|
|
} else if (subagent.asyncStatus === "error") {
|
|
textEl.setText("ERROR");
|
|
} else if (subagent.asyncStatus === "orphaned") {
|
|
textEl.setText("\u26A0\uFE0F Task orphaned");
|
|
} else if (subagent.agentId) {
|
|
const shortId = subagent.agentId.length > 12 ? subagent.agentId.substring(0, 12) + "..." : subagent.agentId;
|
|
textEl.setText(`run in background (${shortId})`);
|
|
} else {
|
|
textEl.setText("run in background");
|
|
}
|
|
const state = { isExpanded: false };
|
|
setupCollapsible(wrapperEl, headerEl, contentEl, state);
|
|
return wrapperEl;
|
|
}
|
|
|
|
// src/ui/renderers/ThinkingBlockRenderer.ts
|
|
function createThinkingBlock(parentEl, renderContent) {
|
|
const wrapperEl = parentEl.createDiv({ cls: "claudian-thinking-block" });
|
|
const header = wrapperEl.createDiv({ cls: "claudian-thinking-header" });
|
|
header.setAttribute("tabindex", "0");
|
|
header.setAttribute("role", "button");
|
|
header.setAttribute("aria-expanded", "false");
|
|
header.setAttribute("aria-label", "Extended thinking - click to expand");
|
|
const labelEl = header.createSpan({ cls: "claudian-thinking-label" });
|
|
const startTime = Date.now();
|
|
labelEl.setText("Thinking 0s...");
|
|
const timerInterval = setInterval(() => {
|
|
const elapsed = Math.floor((Date.now() - startTime) / 1e3);
|
|
labelEl.setText(`Thinking ${elapsed}s...`);
|
|
}, 1e3);
|
|
const contentEl = wrapperEl.createDiv({ cls: "claudian-thinking-content" });
|
|
const state = {
|
|
wrapperEl,
|
|
contentEl,
|
|
labelEl,
|
|
content: "",
|
|
startTime,
|
|
timerInterval,
|
|
isExpanded: false
|
|
};
|
|
setupCollapsible(wrapperEl, header, contentEl, state);
|
|
return state;
|
|
}
|
|
async function appendThinkingContent(state, content, renderContent) {
|
|
state.content += content;
|
|
await renderContent(state.contentEl, state.content);
|
|
}
|
|
function finalizeThinkingBlock(state) {
|
|
if (state.timerInterval) {
|
|
clearInterval(state.timerInterval);
|
|
state.timerInterval = null;
|
|
}
|
|
const durationSeconds = Math.floor((Date.now() - state.startTime) / 1e3);
|
|
state.labelEl.setText(`Thought for ${durationSeconds}s`);
|
|
const header = state.wrapperEl.querySelector(".claudian-thinking-header");
|
|
if (header) {
|
|
collapseElement(state.wrapperEl, header, state.contentEl, state);
|
|
}
|
|
return durationSeconds;
|
|
}
|
|
function cleanupThinkingBlock(state) {
|
|
if (state == null ? void 0 : state.timerInterval) {
|
|
clearInterval(state.timerInterval);
|
|
}
|
|
}
|
|
function renderStoredThinkingBlock(parentEl, content, durationSeconds, renderContent) {
|
|
const wrapperEl = parentEl.createDiv({ cls: "claudian-thinking-block" });
|
|
const header = wrapperEl.createDiv({ cls: "claudian-thinking-header" });
|
|
header.setAttribute("tabindex", "0");
|
|
header.setAttribute("role", "button");
|
|
header.setAttribute("aria-label", "Extended thinking - click to expand");
|
|
const labelEl = header.createSpan({ cls: "claudian-thinking-label" });
|
|
const labelText = durationSeconds !== void 0 ? `Thought for ${durationSeconds}s` : "Thinking";
|
|
labelEl.setText(labelText);
|
|
const contentEl = wrapperEl.createDiv({ cls: "claudian-thinking-content" });
|
|
renderContent(contentEl, content);
|
|
const state = { isExpanded: false };
|
|
setupCollapsible(wrapperEl, header, contentEl, state);
|
|
return wrapperEl;
|
|
}
|
|
|
|
// src/ui/renderers/TodoListRenderer.ts
|
|
function isValidTodoItem(item) {
|
|
if (typeof item !== "object" || item === null) return false;
|
|
const record2 = item;
|
|
return typeof record2.content === "string" && record2.content.length > 0 && typeof record2.activeForm === "string" && record2.activeForm.length > 0 && typeof record2.status === "string" && ["pending", "in_progress", "completed"].includes(record2.status);
|
|
}
|
|
function parseTodoInput(input) {
|
|
if (!input.todos || !Array.isArray(input.todos)) {
|
|
return null;
|
|
}
|
|
const validTodos = [];
|
|
const invalidItems = [];
|
|
for (const item of input.todos) {
|
|
if (isValidTodoItem(item)) {
|
|
validTodos.push(item);
|
|
} else {
|
|
invalidItems.push(item);
|
|
}
|
|
}
|
|
if (invalidItems.length > 0) {
|
|
console.warn("[TodoListRenderer] Dropped invalid todo items:", {
|
|
dropped: invalidItems.length,
|
|
total: input.todos.length,
|
|
sample: invalidItems.slice(0, 3)
|
|
});
|
|
}
|
|
return validTodos.length > 0 ? validTodos : null;
|
|
}
|
|
function extractLastTodosFromMessages(messages) {
|
|
for (let i = messages.length - 1; i >= 0; i--) {
|
|
const msg = messages[i];
|
|
if (msg.role === "assistant" && msg.toolCalls) {
|
|
for (let j = msg.toolCalls.length - 1; j >= 0; j--) {
|
|
const toolCall = msg.toolCalls[j];
|
|
if (toolCall.name === TOOL_TODO_WRITE) {
|
|
const todos = parseTodoInput(toolCall.input);
|
|
if (!todos) {
|
|
console.warn("[TodoListRenderer] Failed to parse TodoWrite from saved conversation", {
|
|
messageIndex: i,
|
|
toolCallIndex: j,
|
|
inputKeys: Object.keys(toolCall.input)
|
|
});
|
|
}
|
|
return todos;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
// src/ui/renderers/WriteEditRenderer.ts
|
|
var import_obsidian17 = require("obsidian");
|
|
function shortenPath2(filePath, maxLength = 40) {
|
|
if (!filePath) return "file";
|
|
const normalized = filePath.replace(/\\/g, "/");
|
|
if (normalized.length <= maxLength) return normalized;
|
|
const parts = normalized.split("/");
|
|
if (parts.length <= 2) {
|
|
return "..." + normalized.slice(-maxLength + 3);
|
|
}
|
|
const filename = parts[parts.length - 1];
|
|
const firstDir = parts[0];
|
|
const available = maxLength - firstDir.length - filename.length - 5;
|
|
if (available < 0) {
|
|
return "..." + filename.slice(-maxLength + 3);
|
|
}
|
|
return `${firstDir}/.../${filename}`;
|
|
}
|
|
function createWriteEditBlock(parentEl, toolCall) {
|
|
const filePath = toolCall.input.file_path || "file";
|
|
const toolName = toolCall.name;
|
|
const wrapperEl = parentEl.createDiv({ cls: "claudian-write-edit-block" });
|
|
wrapperEl.dataset.toolId = toolCall.id;
|
|
const headerEl = wrapperEl.createDiv({ cls: "claudian-write-edit-header" });
|
|
headerEl.setAttribute("tabindex", "0");
|
|
headerEl.setAttribute("role", "button");
|
|
headerEl.setAttribute("aria-label", `${toolName}: ${shortenPath2(filePath)} - click to expand`);
|
|
const iconEl = headerEl.createDiv({ cls: "claudian-write-edit-icon" });
|
|
iconEl.setAttribute("aria-hidden", "true");
|
|
(0, import_obsidian17.setIcon)(iconEl, toolName === TOOL_EDIT ? "file-pen" : "file-plus");
|
|
const labelEl = headerEl.createDiv({ cls: "claudian-write-edit-label" });
|
|
labelEl.setText(`${toolName}: ${shortenPath2(filePath)}`);
|
|
const statsEl = headerEl.createDiv({ cls: "claudian-write-edit-stats" });
|
|
const statusEl = headerEl.createDiv({ cls: "claudian-write-edit-status status-running" });
|
|
statusEl.setAttribute("aria-label", "Status: running");
|
|
statusEl.createSpan({ cls: "claudian-spinner" });
|
|
const contentEl = wrapperEl.createDiv({ cls: "claudian-write-edit-content" });
|
|
const loadingRow = contentEl.createDiv({ cls: "claudian-write-edit-diff-row" });
|
|
const loadingEl = loadingRow.createDiv({ cls: "claudian-write-edit-loading" });
|
|
loadingEl.setText("Writing...");
|
|
const state = {
|
|
wrapperEl,
|
|
contentEl,
|
|
headerEl,
|
|
labelEl,
|
|
statsEl,
|
|
statusEl,
|
|
toolCall,
|
|
isExpanded: false
|
|
};
|
|
setupCollapsible(wrapperEl, headerEl, contentEl, state);
|
|
return state;
|
|
}
|
|
function updateWriteEditWithDiff(state, diffData) {
|
|
state.statsEl.empty();
|
|
state.contentEl.empty();
|
|
if (diffData.skippedReason === "too_large") {
|
|
const row2 = state.contentEl.createDiv({ cls: "claudian-write-edit-diff-row" });
|
|
const skipEl = row2.createDiv({ cls: "claudian-write-edit-binary" });
|
|
skipEl.setText("Diff skipped: file too large");
|
|
return;
|
|
}
|
|
if (diffData.skippedReason === "unavailable" || diffData.originalContent === void 0 || diffData.newContent === void 0) {
|
|
const row2 = state.contentEl.createDiv({ cls: "claudian-write-edit-diff-row" });
|
|
const skipEl = row2.createDiv({ cls: "claudian-write-edit-binary" });
|
|
skipEl.setText("Diff unavailable");
|
|
return;
|
|
}
|
|
const { originalContent, newContent } = diffData;
|
|
if (isBinaryContent(originalContent) || isBinaryContent(newContent)) {
|
|
const row2 = state.contentEl.createDiv({ cls: "claudian-write-edit-diff-row" });
|
|
const binaryEl = row2.createDiv({ cls: "claudian-write-edit-binary" });
|
|
binaryEl.setText("Binary file");
|
|
return;
|
|
}
|
|
const diffLines = computeLineDiff(originalContent, newContent);
|
|
state.diffLines = diffLines;
|
|
const stats = countLineChanges(diffLines);
|
|
if (stats.added > 0) {
|
|
const addedEl = state.statsEl.createSpan({ cls: "added" });
|
|
addedEl.setText(`+${stats.added}`);
|
|
}
|
|
if (stats.removed > 0) {
|
|
if (stats.added > 0) {
|
|
state.statsEl.createSpan({ text: " " });
|
|
}
|
|
const removedEl = state.statsEl.createSpan({ cls: "removed" });
|
|
removedEl.setText(`-${stats.removed}`);
|
|
}
|
|
const row = state.contentEl.createDiv({ cls: "claudian-write-edit-diff-row" });
|
|
const diffEl = row.createDiv({ cls: "claudian-write-edit-diff" });
|
|
renderDiffContent(diffEl, diffLines);
|
|
}
|
|
function finalizeWriteEditBlock(state, isError) {
|
|
state.statusEl.className = "claudian-write-edit-status";
|
|
state.statusEl.empty();
|
|
if (isError) {
|
|
state.statusEl.addClass("status-error");
|
|
(0, import_obsidian17.setIcon)(state.statusEl, "x");
|
|
state.statusEl.setAttribute("aria-label", "Status: error");
|
|
if (!state.diffLines) {
|
|
state.contentEl.empty();
|
|
const row = state.contentEl.createDiv({ cls: "claudian-write-edit-diff-row" });
|
|
const errorEl = row.createDiv({ cls: "claudian-write-edit-error" });
|
|
errorEl.setText(state.toolCall.result || "Error");
|
|
}
|
|
}
|
|
if (isError) {
|
|
state.wrapperEl.addClass("error");
|
|
} else {
|
|
state.wrapperEl.addClass("done");
|
|
}
|
|
}
|
|
function renderStoredWriteEdit(parentEl, toolCall) {
|
|
const filePath = toolCall.input.file_path || "file";
|
|
const toolName = toolCall.name;
|
|
const isError = toolCall.status === "error" || toolCall.status === "blocked";
|
|
const wrapperEl = parentEl.createDiv({ cls: "claudian-write-edit-block" });
|
|
if (isError) {
|
|
wrapperEl.addClass("error");
|
|
} else if (toolCall.status === "completed") {
|
|
wrapperEl.addClass("done");
|
|
}
|
|
wrapperEl.dataset.toolId = toolCall.id;
|
|
const headerEl = wrapperEl.createDiv({ cls: "claudian-write-edit-header" });
|
|
headerEl.setAttribute("tabindex", "0");
|
|
headerEl.setAttribute("role", "button");
|
|
const iconEl = headerEl.createDiv({ cls: "claudian-write-edit-icon" });
|
|
iconEl.setAttribute("aria-hidden", "true");
|
|
(0, import_obsidian17.setIcon)(iconEl, toolName === TOOL_EDIT ? "file-pen" : "file-plus");
|
|
const labelEl = headerEl.createDiv({ cls: "claudian-write-edit-label" });
|
|
labelEl.setText(`${toolName}: ${shortenPath2(filePath)}`);
|
|
const statsEl = headerEl.createDiv({ cls: "claudian-write-edit-stats" });
|
|
if (toolCall.diffData && !toolCall.diffData.skippedReason && toolCall.diffData.originalContent !== void 0 && toolCall.diffData.newContent !== void 0) {
|
|
const diffLines = computeLineDiff(toolCall.diffData.originalContent, toolCall.diffData.newContent);
|
|
const stats = countLineChanges(diffLines);
|
|
if (stats.added > 0) {
|
|
const addedEl = statsEl.createSpan({ cls: "added" });
|
|
addedEl.setText(`+${stats.added}`);
|
|
}
|
|
if (stats.removed > 0) {
|
|
if (stats.added > 0) {
|
|
statsEl.createSpan({ text: " " });
|
|
}
|
|
const removedEl = statsEl.createSpan({ cls: "removed" });
|
|
removedEl.setText(`-${stats.removed}`);
|
|
}
|
|
}
|
|
const statusEl = headerEl.createDiv({ cls: "claudian-write-edit-status" });
|
|
if (isError) {
|
|
statusEl.addClass("status-error");
|
|
(0, import_obsidian17.setIcon)(statusEl, "x");
|
|
}
|
|
const contentEl = wrapperEl.createDiv({ cls: "claudian-write-edit-content" });
|
|
const row = contentEl.createDiv({ cls: "claudian-write-edit-diff-row" });
|
|
if (toolCall.diffData) {
|
|
if (toolCall.diffData.skippedReason === "too_large") {
|
|
const skipEl = row.createDiv({ cls: "claudian-write-edit-binary" });
|
|
skipEl.setText("Diff skipped: file too large");
|
|
} else if (toolCall.diffData.skippedReason === "unavailable" || toolCall.diffData.originalContent === void 0 || toolCall.diffData.newContent === void 0) {
|
|
const skipEl = row.createDiv({ cls: "claudian-write-edit-binary" });
|
|
skipEl.setText("Diff unavailable");
|
|
} else {
|
|
const diffEl = row.createDiv({ cls: "claudian-write-edit-diff" });
|
|
const diffLines = computeLineDiff(toolCall.diffData.originalContent, toolCall.diffData.newContent);
|
|
renderDiffContent(diffEl, diffLines);
|
|
}
|
|
} else if (isError && toolCall.result) {
|
|
const errorEl = row.createDiv({ cls: "claudian-write-edit-error" });
|
|
errorEl.setText(toolCall.result);
|
|
} else {
|
|
const doneEl = row.createDiv({ cls: "claudian-write-edit-done-text" });
|
|
doneEl.setText(isError ? "ERROR" : "DONE");
|
|
}
|
|
const state = { isExpanded: false };
|
|
setupCollapsible(wrapperEl, headerEl, contentEl, state);
|
|
return wrapperEl;
|
|
}
|
|
|
|
// src/ui/settings/EnvSnippetManager.ts
|
|
var import_obsidian18 = require("obsidian");
|
|
var EnvSnippetModal = class extends import_obsidian18.Modal {
|
|
constructor(app, plugin, snippet, onSave) {
|
|
super(app);
|
|
this.plugin = plugin;
|
|
this.snippet = snippet;
|
|
this.onSave = onSave;
|
|
}
|
|
onOpen() {
|
|
const { contentEl } = this;
|
|
this.setTitle(this.snippet ? "Edit snippet" : "Save snippet");
|
|
this.modalEl.addClass("claudian-env-snippet-modal");
|
|
let nameEl;
|
|
let descEl;
|
|
let envVarsEl;
|
|
const handleKeyDown = (e) => {
|
|
if (e.key === "Enter") {
|
|
e.preventDefault();
|
|
saveSnippet();
|
|
} else if (e.key === "Escape") {
|
|
e.preventDefault();
|
|
this.close();
|
|
}
|
|
};
|
|
const saveSnippet = () => {
|
|
var _a;
|
|
const name = nameEl.value.trim();
|
|
if (!name) {
|
|
new import_obsidian18.Notice("Please enter a name for the snippet");
|
|
return;
|
|
}
|
|
const snippet = {
|
|
id: ((_a = this.snippet) == null ? void 0 : _a.id) || `snippet-${Date.now()}`,
|
|
name,
|
|
description: descEl.value.trim(),
|
|
envVars: envVarsEl.value
|
|
};
|
|
this.onSave(snippet);
|
|
this.close();
|
|
};
|
|
new import_obsidian18.Setting(contentEl).setName("Name").setDesc("A descriptive name for this environment configuration").addText((text) => {
|
|
var _a;
|
|
nameEl = text.inputEl;
|
|
text.setValue(((_a = this.snippet) == null ? void 0 : _a.name) || "");
|
|
text.inputEl.addEventListener("keydown", handleKeyDown);
|
|
});
|
|
new import_obsidian18.Setting(contentEl).setName("Description").setDesc("Optional description").addText((text) => {
|
|
var _a;
|
|
descEl = text.inputEl;
|
|
text.setValue(((_a = this.snippet) == null ? void 0 : _a.description) || "");
|
|
text.inputEl.addEventListener("keydown", handleKeyDown);
|
|
});
|
|
const envVarsSetting = new import_obsidian18.Setting(contentEl).setName("Environment variables").setDesc("KEY=VALUE format, one per line").addTextArea((text) => {
|
|
var _a, _b;
|
|
envVarsEl = text.inputEl;
|
|
const envVarsToShow = (_b = (_a = this.snippet) == null ? void 0 : _a.envVars) != null ? _b : this.plugin.settings.environmentVariables;
|
|
text.setValue(envVarsToShow);
|
|
text.inputEl.rows = 8;
|
|
});
|
|
envVarsSetting.settingEl.addClass("claudian-env-snippet-setting");
|
|
envVarsSetting.controlEl.addClass("claudian-env-snippet-control");
|
|
const buttonContainer = contentEl.createDiv({ cls: "claudian-snippet-buttons" });
|
|
const cancelBtn = buttonContainer.createEl("button", {
|
|
text: "Cancel",
|
|
cls: "claudian-cancel-btn"
|
|
});
|
|
cancelBtn.addEventListener("click", () => this.close());
|
|
const saveBtn = buttonContainer.createEl("button", {
|
|
text: this.snippet ? "Update" : "Save",
|
|
cls: "claudian-save-btn"
|
|
});
|
|
saveBtn.addEventListener("click", () => saveSnippet());
|
|
}
|
|
onClose() {
|
|
const { contentEl } = this;
|
|
contentEl.empty();
|
|
}
|
|
};
|
|
var EnvSnippetManager = class {
|
|
constructor(containerEl, plugin) {
|
|
this.containerEl = containerEl;
|
|
this.plugin = plugin;
|
|
this.render();
|
|
}
|
|
render() {
|
|
this.containerEl.empty();
|
|
const headerEl = this.containerEl.createDiv({ cls: "claudian-snippet-header" });
|
|
headerEl.createSpan({ text: "Snippets", cls: "claudian-snippet-label" });
|
|
const saveBtn = headerEl.createEl("button", {
|
|
cls: "claudian-settings-action-btn",
|
|
attr: { "aria-label": "Save current" }
|
|
});
|
|
(0, import_obsidian18.setIcon)(saveBtn, "plus");
|
|
saveBtn.addEventListener("click", () => this.saveCurrentEnv());
|
|
const snippets = this.plugin.settings.envSnippets;
|
|
if (snippets.length === 0) {
|
|
const emptyEl = this.containerEl.createDiv({ cls: "claudian-snippet-empty" });
|
|
emptyEl.setText('No saved environment snippets yet. Click "Save Current" to save your current environment configuration.');
|
|
return;
|
|
}
|
|
const sortedSnippets = snippets;
|
|
const listEl = this.containerEl.createDiv({ cls: "claudian-snippet-list" });
|
|
for (const snippet of sortedSnippets) {
|
|
const itemEl = listEl.createDiv({ cls: "claudian-snippet-item" });
|
|
const infoEl = itemEl.createDiv({ cls: "claudian-snippet-info" });
|
|
const nameEl = infoEl.createDiv({ cls: "claudian-snippet-name" });
|
|
nameEl.setText(snippet.name);
|
|
if (snippet.description) {
|
|
const descEl = infoEl.createDiv({ cls: "claudian-snippet-description" });
|
|
descEl.setText(snippet.description);
|
|
}
|
|
const actionsEl = itemEl.createDiv({ cls: "claudian-snippet-actions" });
|
|
const restoreBtn = actionsEl.createEl("button", {
|
|
cls: "claudian-settings-action-btn",
|
|
attr: { "aria-label": "Insert" }
|
|
});
|
|
(0, import_obsidian18.setIcon)(restoreBtn, "clipboard-paste");
|
|
restoreBtn.addEventListener("click", async () => {
|
|
await this.insertSnippet(snippet);
|
|
});
|
|
const editBtn = actionsEl.createEl("button", {
|
|
cls: "claudian-settings-action-btn",
|
|
attr: { "aria-label": "Edit" }
|
|
});
|
|
(0, import_obsidian18.setIcon)(editBtn, "pencil");
|
|
editBtn.addEventListener("click", () => {
|
|
this.editSnippet(snippet);
|
|
});
|
|
const deleteBtn = actionsEl.createEl("button", {
|
|
cls: "claudian-settings-action-btn claudian-settings-delete-btn",
|
|
attr: { "aria-label": "Delete" }
|
|
});
|
|
(0, import_obsidian18.setIcon)(deleteBtn, "trash-2");
|
|
deleteBtn.addEventListener("click", async () => {
|
|
if (confirm(`Delete environment snippet "${snippet.name}"?`)) {
|
|
await this.deleteSnippet(snippet);
|
|
}
|
|
});
|
|
}
|
|
}
|
|
async saveCurrentEnv() {
|
|
const modal = new EnvSnippetModal(
|
|
this.plugin.app,
|
|
this.plugin,
|
|
null,
|
|
async (snippet) => {
|
|
this.plugin.settings.envSnippets.push(snippet);
|
|
await this.plugin.saveSettings();
|
|
this.render();
|
|
new import_obsidian18.Notice(`Environment snippet "${snippet.name}" saved`);
|
|
}
|
|
);
|
|
modal.open();
|
|
}
|
|
async insertSnippet(snippet) {
|
|
var _a, _b;
|
|
const envTextarea = document.querySelector(".claudian-settings-env-textarea");
|
|
if (envTextarea) {
|
|
const snippetContent = snippet.envVars.trim();
|
|
envTextarea.value = snippetContent;
|
|
await this.plugin.applyEnvironmentVariables(snippetContent);
|
|
const view = (_a = this.plugin.app.workspace.getLeavesOfType("claudian-view")[0]) == null ? void 0 : _a.view;
|
|
if (view == null ? void 0 : view.modelSelector) {
|
|
view.modelSelector.updateDisplay();
|
|
view.modelSelector.renderOptions();
|
|
}
|
|
} else {
|
|
await this.plugin.applyEnvironmentVariables(snippet.envVars);
|
|
this.render();
|
|
const view = (_b = this.plugin.app.workspace.getLeavesOfType("claudian-view")[0]) == null ? void 0 : _b.view;
|
|
if (view == null ? void 0 : view.modelSelector) {
|
|
view.modelSelector.updateDisplay();
|
|
view.modelSelector.renderOptions();
|
|
}
|
|
}
|
|
}
|
|
editSnippet(snippet) {
|
|
const modal = new EnvSnippetModal(
|
|
this.plugin.app,
|
|
this.plugin,
|
|
snippet,
|
|
async (updatedSnippet) => {
|
|
const index = this.plugin.settings.envSnippets.findIndex((s) => s.id === snippet.id);
|
|
if (index !== -1) {
|
|
this.plugin.settings.envSnippets[index] = updatedSnippet;
|
|
await this.plugin.saveSettings();
|
|
this.render();
|
|
new import_obsidian18.Notice(`Environment snippet "${updatedSnippet.name}" updated`);
|
|
}
|
|
}
|
|
);
|
|
modal.open();
|
|
}
|
|
async deleteSnippet(snippet) {
|
|
this.plugin.settings.envSnippets = this.plugin.settings.envSnippets.filter((s) => s.id !== snippet.id);
|
|
await this.plugin.saveSettings();
|
|
this.render();
|
|
new import_obsidian18.Notice(`Environment snippet "${snippet.name}" deleted`);
|
|
}
|
|
refresh() {
|
|
this.render();
|
|
}
|
|
};
|
|
|
|
// src/ui/settings/McpSettingsManager.ts
|
|
var import_obsidian19 = require("obsidian");
|
|
|
|
// src/features/mcp/McpTester.ts
|
|
var import_child_process3 = require("child_process");
|
|
var http = __toESM(require("http"));
|
|
var https = __toESM(require("https"));
|
|
async function testMcpServer(server) {
|
|
const type = getMcpServerType(server.config);
|
|
try {
|
|
if (type === "stdio") {
|
|
return await testStdioServer(server);
|
|
} else if (type === "sse") {
|
|
return await testSseServer(server);
|
|
} else {
|
|
return await testHttpServer(server);
|
|
}
|
|
} catch (error2) {
|
|
return {
|
|
success: false,
|
|
tools: [],
|
|
error: error2 instanceof Error ? error2.message : "Unknown error"
|
|
};
|
|
}
|
|
}
|
|
async function testStdioServer(server) {
|
|
const config2 = server.config;
|
|
const { cmd, args } = parseCommand(config2.command, config2.args);
|
|
return new Promise((resolve7) => {
|
|
var _a, _b, _c, _d;
|
|
let child = null;
|
|
let stdout = "";
|
|
let stderr = "";
|
|
let resolved = false;
|
|
let initReceived = false;
|
|
let serverInfo = {};
|
|
const cleanup = () => {
|
|
if (child && !child.killed) {
|
|
child.kill();
|
|
}
|
|
};
|
|
const timeout = setTimeout(() => {
|
|
if (!resolved) {
|
|
resolved = true;
|
|
cleanup();
|
|
resolve7({
|
|
success: false,
|
|
tools: [],
|
|
error: "Connection timeout (10s)"
|
|
});
|
|
}
|
|
}, 1e4);
|
|
try {
|
|
if (!cmd) {
|
|
clearTimeout(timeout);
|
|
resolve7({
|
|
success: false,
|
|
tools: [],
|
|
error: "Missing command"
|
|
});
|
|
return;
|
|
}
|
|
child = (0, import_child_process3.spawn)(cmd, args, {
|
|
env: { ...process.env, ...config2.env, PATH: getEnhancedPath((_a = config2.env) == null ? void 0 : _a.PATH) },
|
|
stdio: ["pipe", "pipe", "pipe"]
|
|
});
|
|
(_b = child.stdout) == null ? void 0 : _b.on("data", (data) => {
|
|
var _a2, _b2, _c2, _d2, _e;
|
|
stdout += data.toString();
|
|
const lines = stdout.split("\n");
|
|
stdout = lines.pop() || "";
|
|
for (const line of lines) {
|
|
if (!line.trim()) continue;
|
|
try {
|
|
const msg = JSON.parse(line);
|
|
if (msg.id === 1) {
|
|
if (msg.error) {
|
|
if (!resolved) {
|
|
resolved = true;
|
|
clearTimeout(timeout);
|
|
cleanup();
|
|
resolve7({
|
|
success: false,
|
|
tools: [],
|
|
error: msg.error.message || "Initialize failed"
|
|
});
|
|
}
|
|
return;
|
|
}
|
|
if (msg.result) {
|
|
initReceived = true;
|
|
serverInfo = {
|
|
name: (_a2 = msg.result.serverInfo) == null ? void 0 : _a2.name,
|
|
version: (_b2 = msg.result.serverInfo) == null ? void 0 : _b2.version
|
|
};
|
|
const initializedNotification = {
|
|
jsonrpc: "2.0",
|
|
method: "notifications/initialized"
|
|
};
|
|
(_c2 = child == null ? void 0 : child.stdin) == null ? void 0 : _c2.write(JSON.stringify(initializedNotification) + "\n");
|
|
const toolsRequest = {
|
|
jsonrpc: "2.0",
|
|
id: 2,
|
|
method: "tools/list",
|
|
params: {}
|
|
};
|
|
(_d2 = child == null ? void 0 : child.stdin) == null ? void 0 : _d2.write(JSON.stringify(toolsRequest) + "\n");
|
|
}
|
|
}
|
|
if (msg.id === 2) {
|
|
if (!resolved) {
|
|
resolved = true;
|
|
clearTimeout(timeout);
|
|
cleanup();
|
|
if (msg.error) {
|
|
resolve7({
|
|
success: true,
|
|
serverName: serverInfo.name,
|
|
serverVersion: serverInfo.version,
|
|
tools: []
|
|
});
|
|
return;
|
|
}
|
|
const tools = (((_e = msg.result) == null ? void 0 : _e.tools) || []).map(
|
|
(t) => ({
|
|
name: t.name,
|
|
description: t.description,
|
|
inputSchema: t.inputSchema
|
|
})
|
|
);
|
|
resolve7({
|
|
success: true,
|
|
serverName: serverInfo.name,
|
|
serverVersion: serverInfo.version,
|
|
tools
|
|
});
|
|
}
|
|
return;
|
|
}
|
|
} catch (e) {
|
|
}
|
|
}
|
|
});
|
|
(_c = child.stderr) == null ? void 0 : _c.on("data", (data) => {
|
|
stderr += data.toString();
|
|
});
|
|
child.on("error", (error2) => {
|
|
if (!resolved) {
|
|
resolved = true;
|
|
clearTimeout(timeout);
|
|
resolve7({
|
|
success: false,
|
|
tools: [],
|
|
error: `Failed to start: ${error2.message}`
|
|
});
|
|
}
|
|
});
|
|
child.on("close", (code) => {
|
|
if (!resolved) {
|
|
resolved = true;
|
|
clearTimeout(timeout);
|
|
if (initReceived) {
|
|
resolve7({
|
|
success: true,
|
|
serverName: serverInfo.name,
|
|
serverVersion: serverInfo.version,
|
|
tools: []
|
|
});
|
|
} else if (code !== 0) {
|
|
resolve7({
|
|
success: false,
|
|
tools: [],
|
|
error: stderr || `Process exited with code ${code}`
|
|
});
|
|
}
|
|
}
|
|
});
|
|
const initRequest = {
|
|
jsonrpc: "2.0",
|
|
id: 1,
|
|
method: "initialize",
|
|
params: {
|
|
protocolVersion: "2024-11-05",
|
|
capabilities: {},
|
|
clientInfo: { name: "claudian-tester", version: "1.0.0" }
|
|
}
|
|
};
|
|
(_d = child.stdin) == null ? void 0 : _d.write(JSON.stringify(initRequest) + "\n");
|
|
} catch (error2) {
|
|
resolved = true;
|
|
clearTimeout(timeout);
|
|
resolve7({
|
|
success: false,
|
|
tools: [],
|
|
error: error2 instanceof Error ? error2.message : "Failed to spawn process"
|
|
});
|
|
}
|
|
});
|
|
}
|
|
function httpRequest(url, headers, body) {
|
|
return new Promise((resolve7, reject) => {
|
|
const isHttps = url.protocol === "https:";
|
|
const httpModule = isHttps ? https : http;
|
|
const req = httpModule.request(
|
|
{
|
|
hostname: url.hostname,
|
|
port: url.port || (isHttps ? 443 : 80),
|
|
path: url.pathname + url.search,
|
|
method: "POST",
|
|
headers: {
|
|
...headers,
|
|
"Content-Length": Buffer.byteLength(body)
|
|
}
|
|
},
|
|
(res) => {
|
|
let data = "";
|
|
res.on("data", (chunk) => {
|
|
data += chunk;
|
|
});
|
|
res.on("end", () => {
|
|
resolve7({ statusCode: res.statusCode || 0, data });
|
|
});
|
|
}
|
|
);
|
|
req.on("error", reject);
|
|
req.write(body);
|
|
req.end();
|
|
});
|
|
}
|
|
async function testHttpServer(server) {
|
|
const config2 = server.config;
|
|
return new Promise((resolve7) => {
|
|
const timeout = setTimeout(() => {
|
|
resolve7({
|
|
success: false,
|
|
tools: [],
|
|
error: "Connection timeout (10s)"
|
|
});
|
|
}, 1e4);
|
|
(async () => {
|
|
var _a, _b;
|
|
try {
|
|
const url = new URL(config2.url);
|
|
const headers = {
|
|
"Content-Type": "application/json",
|
|
Accept: "application/json, text/event-stream",
|
|
...config2.headers
|
|
};
|
|
const initRequest = JSON.stringify({
|
|
jsonrpc: "2.0",
|
|
id: 1,
|
|
method: "initialize",
|
|
params: {
|
|
protocolVersion: "2024-11-05",
|
|
capabilities: {},
|
|
clientInfo: { name: "claudian-tester", version: "1.0.0" }
|
|
}
|
|
});
|
|
const initResponse = await httpRequest(url, headers, initRequest);
|
|
let serverName;
|
|
let serverVersion;
|
|
try {
|
|
const initResult = JSON.parse(initResponse.data);
|
|
if (initResult.error) {
|
|
clearTimeout(timeout);
|
|
resolve7({
|
|
success: false,
|
|
tools: [],
|
|
error: initResult.error.message || "Server error"
|
|
});
|
|
return;
|
|
}
|
|
if ((_a = initResult.result) == null ? void 0 : _a.serverInfo) {
|
|
serverName = initResult.result.serverInfo.name;
|
|
serverVersion = initResult.result.serverInfo.version;
|
|
}
|
|
} catch (e) {
|
|
clearTimeout(timeout);
|
|
resolve7({
|
|
success: false,
|
|
tools: [],
|
|
error: `Invalid JSON response: ${initResponse.data.slice(0, 200)}`
|
|
});
|
|
return;
|
|
}
|
|
const initializedNotification = JSON.stringify({
|
|
jsonrpc: "2.0",
|
|
method: "notifications/initialized"
|
|
});
|
|
httpRequest(url, headers, initializedNotification).catch(() => {
|
|
});
|
|
const toolsRequest = JSON.stringify({
|
|
jsonrpc: "2.0",
|
|
id: 2,
|
|
method: "tools/list",
|
|
params: {}
|
|
});
|
|
const toolsResponse = await httpRequest(url, headers, toolsRequest);
|
|
try {
|
|
const toolsResult = JSON.parse(toolsResponse.data);
|
|
clearTimeout(timeout);
|
|
if (toolsResult.error) {
|
|
resolve7({
|
|
success: true,
|
|
serverName,
|
|
serverVersion,
|
|
tools: []
|
|
});
|
|
return;
|
|
}
|
|
const tools = (((_b = toolsResult.result) == null ? void 0 : _b.tools) || []).map(
|
|
(t) => ({
|
|
name: t.name,
|
|
description: t.description,
|
|
inputSchema: t.inputSchema
|
|
})
|
|
);
|
|
resolve7({
|
|
success: true,
|
|
serverName,
|
|
serverVersion,
|
|
tools
|
|
});
|
|
} catch (e) {
|
|
clearTimeout(timeout);
|
|
resolve7({
|
|
success: true,
|
|
serverName,
|
|
serverVersion,
|
|
tools: []
|
|
});
|
|
}
|
|
} catch (error2) {
|
|
clearTimeout(timeout);
|
|
resolve7({
|
|
success: false,
|
|
tools: [],
|
|
error: error2 instanceof Error ? error2.message : "Request failed"
|
|
});
|
|
}
|
|
})();
|
|
});
|
|
}
|
|
async function testSseServer(server) {
|
|
var _a, _b, _c, _d, _e;
|
|
const config2 = server.config;
|
|
const controller = new AbortController();
|
|
const timeout = setTimeout(() => controller.abort(), 1e4);
|
|
try {
|
|
const sseUrl = new URL(config2.url);
|
|
const headers = {
|
|
Accept: "text/event-stream",
|
|
...config2.headers
|
|
};
|
|
const response = await fetch(sseUrl.toString(), {
|
|
method: "GET",
|
|
headers,
|
|
signal: controller.signal
|
|
});
|
|
if (!response.ok || !response.body) {
|
|
clearTimeout(timeout);
|
|
return {
|
|
success: false,
|
|
tools: [],
|
|
error: `HTTP ${response.status}: ${response.statusText}`
|
|
};
|
|
}
|
|
let endpointResolved = false;
|
|
let resolveEndpoint = null;
|
|
const endpointPromise = new Promise((resolve7) => {
|
|
resolveEndpoint = resolve7;
|
|
});
|
|
const pending = /* @__PURE__ */ new Map();
|
|
const streamPromise = consumeSseStream(response.body, (event) => {
|
|
if (!endpointResolved) {
|
|
const candidate = resolveSseEndpoint(event.data, sseUrl);
|
|
if (candidate) {
|
|
endpointResolved = true;
|
|
resolveEndpoint == null ? void 0 : resolveEndpoint(candidate);
|
|
}
|
|
}
|
|
const payload = tryParseJson(event.data);
|
|
if (payload && typeof payload === "object") {
|
|
const record2 = payload;
|
|
const id = parseRpcId(record2.id);
|
|
if (id !== null) {
|
|
const handler = pending.get(id);
|
|
if (handler) {
|
|
handler(record2);
|
|
}
|
|
}
|
|
}
|
|
}).catch(() => {
|
|
});
|
|
let endpointTimeout = null;
|
|
const endpointTimeoutPromise = new Promise((_, reject) => {
|
|
endpointTimeout = setTimeout(() => reject(new Error("SSE endpoint not advertised")), 5e3);
|
|
});
|
|
let postUrl;
|
|
try {
|
|
postUrl = await Promise.race([endpointPromise, endpointTimeoutPromise]);
|
|
} finally {
|
|
if (endpointTimeout) clearTimeout(endpointTimeout);
|
|
}
|
|
const postOptions = { signal: controller.signal, timeoutMs: 8e3 };
|
|
const initRequest = {
|
|
jsonrpc: "2.0",
|
|
id: 1,
|
|
method: "initialize",
|
|
params: {
|
|
protocolVersion: "2024-11-05",
|
|
capabilities: {},
|
|
clientInfo: { name: "claudian-tester", version: "1.0.0" }
|
|
}
|
|
};
|
|
const initResponsePromise = waitForRpcResponse(pending, 1, 8e3);
|
|
initResponsePromise.catch(() => {
|
|
});
|
|
const initPost = await postJsonRpc(postUrl, (_a = config2.headers) != null ? _a : {}, initRequest, postOptions);
|
|
if (initPost.status >= 400) {
|
|
initResponsePromise.catch(() => {
|
|
});
|
|
clearTimeout(timeout);
|
|
controller.abort();
|
|
return {
|
|
success: false,
|
|
tools: [],
|
|
error: `HTTP ${initPost.status}: ${initPost.statusText}`
|
|
};
|
|
}
|
|
const initResponse = await initResponsePromise;
|
|
const initError = initResponse.error;
|
|
if (initError) {
|
|
clearTimeout(timeout);
|
|
controller.abort();
|
|
return {
|
|
success: false,
|
|
tools: [],
|
|
error: initError.message || "Initialize failed"
|
|
};
|
|
}
|
|
const serverInfo = initResponse.result;
|
|
const serverName = (_b = serverInfo == null ? void 0 : serverInfo.serverInfo) == null ? void 0 : _b.name;
|
|
const serverVersion = (_c = serverInfo == null ? void 0 : serverInfo.serverInfo) == null ? void 0 : _c.version;
|
|
await postJsonRpc(postUrl, (_d = config2.headers) != null ? _d : {}, {
|
|
jsonrpc: "2.0",
|
|
method: "notifications/initialized"
|
|
}, postOptions).catch(() => {
|
|
});
|
|
const toolsResponsePromise = waitForRpcResponse(pending, 2, 8e3);
|
|
toolsResponsePromise.catch(() => {
|
|
});
|
|
await postJsonRpc(postUrl, (_e = config2.headers) != null ? _e : {}, {
|
|
jsonrpc: "2.0",
|
|
id: 2,
|
|
method: "tools/list",
|
|
params: {}
|
|
}, postOptions);
|
|
let tools = [];
|
|
try {
|
|
const toolsResponse = await toolsResponsePromise;
|
|
const toolsError = toolsResponse.error;
|
|
if (!toolsError) {
|
|
const result = toolsResponse.result;
|
|
tools = ((result == null ? void 0 : result.tools) || []).map(
|
|
(t) => ({
|
|
name: t.name,
|
|
description: t.description,
|
|
inputSchema: t.inputSchema
|
|
})
|
|
);
|
|
}
|
|
} catch (e) {
|
|
}
|
|
clearTimeout(timeout);
|
|
controller.abort();
|
|
await streamPromise;
|
|
return {
|
|
success: true,
|
|
serverName,
|
|
serverVersion,
|
|
tools
|
|
};
|
|
} catch (error2) {
|
|
clearTimeout(timeout);
|
|
controller.abort();
|
|
return {
|
|
success: false,
|
|
tools: [],
|
|
error: error2 instanceof Error ? error2.message : "Request failed"
|
|
};
|
|
}
|
|
}
|
|
|
|
// src/ui/settings/McpSettingsManager.ts
|
|
var McpSettingsManager = class {
|
|
constructor(containerEl, plugin) {
|
|
this.servers = [];
|
|
this.containerEl = containerEl;
|
|
this.plugin = plugin;
|
|
this.loadAndRender();
|
|
}
|
|
async loadAndRender() {
|
|
this.servers = await this.plugin.storage.mcp.load();
|
|
this.render();
|
|
}
|
|
render() {
|
|
this.containerEl.empty();
|
|
const headerEl = this.containerEl.createDiv({ cls: "claudian-mcp-header" });
|
|
headerEl.createSpan({ text: "MCP Servers", cls: "claudian-mcp-label" });
|
|
const addContainer = headerEl.createDiv({ cls: "claudian-mcp-add-container" });
|
|
const addBtn = addContainer.createEl("button", {
|
|
cls: "claudian-settings-action-btn",
|
|
attr: { "aria-label": "Add" }
|
|
});
|
|
(0, import_obsidian19.setIcon)(addBtn, "plus");
|
|
const dropdown = addContainer.createDiv({ cls: "claudian-mcp-add-dropdown" });
|
|
const stdioOption = dropdown.createDiv({ cls: "claudian-mcp-add-option" });
|
|
(0, import_obsidian19.setIcon)(stdioOption.createSpan({ cls: "claudian-mcp-add-option-icon" }), "terminal");
|
|
stdioOption.createSpan({ text: "stdio (local command)" });
|
|
stdioOption.addEventListener("click", () => {
|
|
dropdown.removeClass("is-visible");
|
|
this.openModal(null, "stdio");
|
|
});
|
|
const httpOption = dropdown.createDiv({ cls: "claudian-mcp-add-option" });
|
|
(0, import_obsidian19.setIcon)(httpOption.createSpan({ cls: "claudian-mcp-add-option-icon" }), "globe");
|
|
httpOption.createSpan({ text: "http / sse (remote)" });
|
|
httpOption.addEventListener("click", () => {
|
|
dropdown.removeClass("is-visible");
|
|
this.openModal(null, "http");
|
|
});
|
|
const importOption = dropdown.createDiv({ cls: "claudian-mcp-add-option" });
|
|
(0, import_obsidian19.setIcon)(importOption.createSpan({ cls: "claudian-mcp-add-option-icon" }), "clipboard-paste");
|
|
importOption.createSpan({ text: "Import from clipboard" });
|
|
importOption.addEventListener("click", () => {
|
|
dropdown.removeClass("is-visible");
|
|
this.importFromClipboard();
|
|
});
|
|
addBtn.addEventListener("click", (e) => {
|
|
e.stopPropagation();
|
|
dropdown.toggleClass("is-visible", !dropdown.hasClass("is-visible"));
|
|
});
|
|
document.addEventListener("click", () => {
|
|
dropdown.removeClass("is-visible");
|
|
});
|
|
if (this.servers.length === 0) {
|
|
const emptyEl = this.containerEl.createDiv({ cls: "claudian-mcp-empty" });
|
|
emptyEl.setText('No MCP servers configured. Click "Add" to add one.');
|
|
return;
|
|
}
|
|
const listEl = this.containerEl.createDiv({ cls: "claudian-mcp-list" });
|
|
for (const server of this.servers) {
|
|
this.renderServerItem(listEl, server);
|
|
}
|
|
}
|
|
renderServerItem(listEl, server) {
|
|
const itemEl = listEl.createDiv({ cls: "claudian-mcp-item" });
|
|
if (!server.enabled) {
|
|
itemEl.addClass("claudian-mcp-item-disabled");
|
|
}
|
|
const statusEl = itemEl.createDiv({ cls: "claudian-mcp-status" });
|
|
statusEl.addClass(
|
|
server.enabled ? "claudian-mcp-status-enabled" : "claudian-mcp-status-disabled"
|
|
);
|
|
const infoEl = itemEl.createDiv({ cls: "claudian-mcp-info" });
|
|
const nameRow = infoEl.createDiv({ cls: "claudian-mcp-name-row" });
|
|
const nameEl = nameRow.createSpan({ cls: "claudian-mcp-name" });
|
|
nameEl.setText(server.name);
|
|
const serverType = getMcpServerType(server.config);
|
|
const typeEl = nameRow.createSpan({ cls: "claudian-mcp-type-badge" });
|
|
typeEl.setText(serverType);
|
|
if (server.contextSaving) {
|
|
const csEl = nameRow.createSpan({ cls: "claudian-mcp-context-saving-badge" });
|
|
csEl.setText("@");
|
|
csEl.setAttribute("title", "Context-saving: mention with @" + server.name + " to enable");
|
|
}
|
|
const previewEl = infoEl.createDiv({ cls: "claudian-mcp-preview" });
|
|
if (server.description) {
|
|
previewEl.setText(server.description);
|
|
} else {
|
|
previewEl.setText(this.getServerPreview(server, serverType));
|
|
}
|
|
const actionsEl = itemEl.createDiv({ cls: "claudian-mcp-actions" });
|
|
const testBtn = actionsEl.createEl("button", {
|
|
cls: "claudian-mcp-action-btn",
|
|
attr: { "aria-label": "Verify (show tools)" }
|
|
});
|
|
(0, import_obsidian19.setIcon)(testBtn, "zap");
|
|
testBtn.addEventListener("click", () => this.testServer(server));
|
|
const toggleBtn = actionsEl.createEl("button", {
|
|
cls: "claudian-mcp-action-btn",
|
|
attr: { "aria-label": server.enabled ? "Disable" : "Enable" }
|
|
});
|
|
(0, import_obsidian19.setIcon)(toggleBtn, server.enabled ? "toggle-right" : "toggle-left");
|
|
toggleBtn.addEventListener("click", () => this.toggleServer(server));
|
|
const editBtn = actionsEl.createEl("button", {
|
|
cls: "claudian-mcp-action-btn",
|
|
attr: { "aria-label": "Edit" }
|
|
});
|
|
(0, import_obsidian19.setIcon)(editBtn, "pencil");
|
|
editBtn.addEventListener("click", () => this.openModal(server));
|
|
const deleteBtn = actionsEl.createEl("button", {
|
|
cls: "claudian-mcp-action-btn claudian-mcp-delete-btn",
|
|
attr: { "aria-label": "Delete" }
|
|
});
|
|
(0, import_obsidian19.setIcon)(deleteBtn, "trash-2");
|
|
deleteBtn.addEventListener("click", () => this.deleteServer(server));
|
|
}
|
|
async testServer(server) {
|
|
const modal = new McpTestModal(
|
|
this.plugin.app,
|
|
server.name,
|
|
server.disabledTools,
|
|
async (toolName, enabled) => {
|
|
await this.updateDisabledTool(server, toolName, enabled);
|
|
},
|
|
async (disabledTools) => {
|
|
await this.updateAllDisabledTools(server, disabledTools);
|
|
}
|
|
);
|
|
modal.open();
|
|
try {
|
|
const result = await testMcpServer(server);
|
|
modal.setResult(result);
|
|
} catch (error2) {
|
|
modal.setError(error2 instanceof Error ? error2.message : "Verification failed");
|
|
}
|
|
}
|
|
/**
|
|
* Helper to update server.disabledTools with save and reload.
|
|
* Rolls back on save failure; warns on reload failure (since save succeeded).
|
|
*/
|
|
async updateServerDisabledTools(server, newDisabledTools) {
|
|
const previous = server.disabledTools ? [...server.disabledTools] : void 0;
|
|
server.disabledTools = newDisabledTools;
|
|
try {
|
|
await this.plugin.storage.mcp.save(this.servers);
|
|
} catch (error2) {
|
|
server.disabledTools = previous;
|
|
throw error2;
|
|
}
|
|
try {
|
|
await this.plugin.agentService.reloadMcpServers();
|
|
} catch (error2) {
|
|
console.warn("[Claudian] MCP reload failed after save:", error2);
|
|
new import_obsidian19.Notice("Setting saved but reload failed. Changes will apply on next session.");
|
|
}
|
|
}
|
|
async updateDisabledTool(server, toolName, enabled) {
|
|
var _a;
|
|
const disabledTools = new Set((_a = server.disabledTools) != null ? _a : []);
|
|
if (enabled) {
|
|
disabledTools.delete(toolName);
|
|
} else {
|
|
disabledTools.add(toolName);
|
|
}
|
|
await this.updateServerDisabledTools(
|
|
server,
|
|
disabledTools.size > 0 ? Array.from(disabledTools) : void 0
|
|
);
|
|
}
|
|
async updateAllDisabledTools(server, disabledTools) {
|
|
await this.updateServerDisabledTools(
|
|
server,
|
|
disabledTools.length > 0 ? disabledTools : void 0
|
|
);
|
|
}
|
|
getServerPreview(server, type) {
|
|
var _a;
|
|
if (type === "stdio") {
|
|
const config2 = server.config;
|
|
const args = ((_a = config2.args) == null ? void 0 : _a.join(" ")) || "";
|
|
return args ? `${config2.command} ${args}` : config2.command;
|
|
} else {
|
|
const config2 = server.config;
|
|
return config2.url;
|
|
}
|
|
}
|
|
openModal(existing, initialType) {
|
|
const modal = new McpServerModal(
|
|
this.plugin.app,
|
|
this.plugin,
|
|
existing,
|
|
async (server) => {
|
|
await this.saveServer(server, existing);
|
|
},
|
|
initialType
|
|
);
|
|
modal.open();
|
|
}
|
|
async importFromClipboard() {
|
|
try {
|
|
const text = await navigator.clipboard.readText();
|
|
if (!text.trim()) {
|
|
new import_obsidian19.Notice("Clipboard is empty");
|
|
return;
|
|
}
|
|
const parsed = McpStorage.tryParseClipboardConfig(text);
|
|
if (!parsed || parsed.servers.length === 0) {
|
|
new import_obsidian19.Notice("No valid MCP configuration found in clipboard");
|
|
return;
|
|
}
|
|
if (parsed.needsName || parsed.servers.length === 1) {
|
|
const server = parsed.servers[0];
|
|
const type = getMcpServerType(server.config);
|
|
const modal = new McpServerModal(
|
|
this.plugin.app,
|
|
this.plugin,
|
|
null,
|
|
async (savedServer) => {
|
|
await this.saveServer(savedServer, null);
|
|
},
|
|
type,
|
|
server
|
|
// Pre-fill with parsed config
|
|
);
|
|
modal.open();
|
|
if (parsed.needsName) {
|
|
new import_obsidian19.Notice("Enter a name for the server");
|
|
}
|
|
return;
|
|
}
|
|
await this.importServers(parsed.servers);
|
|
} catch (e) {
|
|
new import_obsidian19.Notice("Failed to read clipboard");
|
|
}
|
|
}
|
|
async saveServer(server, existing) {
|
|
if (existing) {
|
|
const index = this.servers.findIndex((s) => s.name === existing.name);
|
|
if (index !== -1) {
|
|
if (server.name !== existing.name) {
|
|
const conflict = this.servers.find((s) => s.name === server.name);
|
|
if (conflict) {
|
|
new import_obsidian19.Notice(`Server "${server.name}" already exists`);
|
|
return;
|
|
}
|
|
}
|
|
this.servers[index] = server;
|
|
}
|
|
} else {
|
|
const conflict = this.servers.find((s) => s.name === server.name);
|
|
if (conflict) {
|
|
new import_obsidian19.Notice(`Server "${server.name}" already exists`);
|
|
return;
|
|
}
|
|
this.servers.push(server);
|
|
}
|
|
await this.plugin.storage.mcp.save(this.servers);
|
|
await this.plugin.agentService.reloadMcpServers();
|
|
this.render();
|
|
new import_obsidian19.Notice(existing ? `MCP server "${server.name}" updated` : `MCP server "${server.name}" added`);
|
|
}
|
|
async importServers(servers) {
|
|
const added = [];
|
|
const skipped = [];
|
|
for (const server of servers) {
|
|
const name = server.name.trim();
|
|
if (!name || !/^[a-zA-Z0-9._-]+$/.test(name)) {
|
|
skipped.push(server.name || "<unnamed>");
|
|
continue;
|
|
}
|
|
const conflict = this.servers.find((s) => s.name === name);
|
|
if (conflict) {
|
|
skipped.push(name);
|
|
continue;
|
|
}
|
|
this.servers.push({
|
|
name,
|
|
config: server.config,
|
|
enabled: DEFAULT_MCP_SERVER.enabled,
|
|
contextSaving: DEFAULT_MCP_SERVER.contextSaving
|
|
});
|
|
added.push(name);
|
|
}
|
|
if (added.length === 0) {
|
|
new import_obsidian19.Notice("No new MCP servers imported");
|
|
return;
|
|
}
|
|
await this.plugin.storage.mcp.save(this.servers);
|
|
await this.plugin.agentService.reloadMcpServers();
|
|
this.render();
|
|
let message = `Imported ${added.length} MCP server${added.length > 1 ? "s" : ""}`;
|
|
if (skipped.length > 0) {
|
|
message += ` (${skipped.length} skipped)`;
|
|
}
|
|
new import_obsidian19.Notice(message);
|
|
}
|
|
async toggleServer(server) {
|
|
server.enabled = !server.enabled;
|
|
await this.plugin.storage.mcp.save(this.servers);
|
|
await this.plugin.agentService.reloadMcpServers();
|
|
this.render();
|
|
new import_obsidian19.Notice(`MCP server "${server.name}" ${server.enabled ? "enabled" : "disabled"}`);
|
|
}
|
|
async deleteServer(server) {
|
|
if (!confirm(`Delete MCP server "${server.name}"?`)) {
|
|
return;
|
|
}
|
|
this.servers = this.servers.filter((s) => s.name !== server.name);
|
|
await this.plugin.storage.mcp.save(this.servers);
|
|
await this.plugin.agentService.reloadMcpServers();
|
|
this.render();
|
|
new import_obsidian19.Notice(`MCP server "${server.name}" deleted`);
|
|
}
|
|
/** Refresh the server list (call after external changes). */
|
|
refresh() {
|
|
this.loadAndRender();
|
|
}
|
|
};
|
|
|
|
// src/ui/settings/SlashCommandSettings.ts
|
|
var import_obsidian20 = require("obsidian");
|
|
var SlashCommandModal = class extends import_obsidian20.Modal {
|
|
constructor(app, plugin, existingCmd, onSave) {
|
|
super(app);
|
|
this.plugin = plugin;
|
|
this.existingCmd = existingCmd;
|
|
this.onSave = onSave;
|
|
}
|
|
onOpen() {
|
|
this.setTitle(this.existingCmd ? "Edit Slash Command" : "Add Slash Command");
|
|
this.modalEl.addClass("claudian-slash-modal");
|
|
const { contentEl } = this;
|
|
let nameInput;
|
|
let descInput;
|
|
let hintInput;
|
|
let modelInput;
|
|
let toolsInput;
|
|
new import_obsidian20.Setting(contentEl).setName("Command name").setDesc('The name used after / (e.g., "review" for /review)').addText((text) => {
|
|
var _a;
|
|
nameInput = text.inputEl;
|
|
text.setValue(((_a = this.existingCmd) == null ? void 0 : _a.name) || "").setPlaceholder("review-code");
|
|
});
|
|
new import_obsidian20.Setting(contentEl).setName("Description").setDesc("Optional description shown in dropdown").addText((text) => {
|
|
var _a;
|
|
descInput = text.inputEl;
|
|
text.setValue(((_a = this.existingCmd) == null ? void 0 : _a.description) || "");
|
|
});
|
|
new import_obsidian20.Setting(contentEl).setName("Argument hint").setDesc('Placeholder text for arguments (e.g., "[file] [focus]")').addText((text) => {
|
|
var _a;
|
|
hintInput = text.inputEl;
|
|
text.setValue(((_a = this.existingCmd) == null ? void 0 : _a.argumentHint) || "");
|
|
});
|
|
new import_obsidian20.Setting(contentEl).setName("Model override").setDesc("Optional model to use for this command").addText((text) => {
|
|
var _a;
|
|
modelInput = text.inputEl;
|
|
text.setValue(((_a = this.existingCmd) == null ? void 0 : _a.model) || "").setPlaceholder("claude-sonnet-4-5");
|
|
});
|
|
new import_obsidian20.Setting(contentEl).setName("Allowed tools").setDesc("Comma-separated list of tools to allow (empty = all)").addText((text) => {
|
|
var _a, _b;
|
|
toolsInput = text.inputEl;
|
|
text.setValue(((_b = (_a = this.existingCmd) == null ? void 0 : _a.allowedTools) == null ? void 0 : _b.join(", ")) || "");
|
|
});
|
|
new import_obsidian20.Setting(contentEl).setName("Prompt template").setDesc("Use $ARGUMENTS, $1, $2, @file, !`bash`");
|
|
const contentArea = contentEl.createEl("textarea", {
|
|
cls: "claudian-slash-content-area",
|
|
attr: {
|
|
rows: "10",
|
|
placeholder: "Review this code for:\n$ARGUMENTS\n\n@$1"
|
|
}
|
|
});
|
|
const initialContent = this.existingCmd ? parseSlashCommandContent(this.existingCmd.content).promptContent : "";
|
|
contentArea.value = initialContent;
|
|
const buttonContainer = contentEl.createDiv({ cls: "claudian-slash-modal-buttons" });
|
|
const cancelBtn = buttonContainer.createEl("button", {
|
|
text: "Cancel",
|
|
cls: "claudian-cancel-btn"
|
|
});
|
|
cancelBtn.addEventListener("click", () => this.close());
|
|
const saveBtn = buttonContainer.createEl("button", {
|
|
text: "Save",
|
|
cls: "claudian-save-btn"
|
|
});
|
|
saveBtn.addEventListener("click", async () => {
|
|
var _a;
|
|
const name = nameInput.value.trim();
|
|
if (!name) {
|
|
new import_obsidian20.Notice("Command name is required");
|
|
return;
|
|
}
|
|
const content = contentArea.value;
|
|
if (!content.trim()) {
|
|
new import_obsidian20.Notice("Prompt template is required");
|
|
return;
|
|
}
|
|
if (!/^[a-zA-Z0-9_/-]+$/.test(name)) {
|
|
new import_obsidian20.Notice("Command name can only contain letters, numbers, hyphens, underscores, and slashes");
|
|
return;
|
|
}
|
|
const existing = this.plugin.settings.slashCommands.find(
|
|
(c) => {
|
|
var _a2;
|
|
return c.name.toLowerCase() === name.toLowerCase() && c.id !== ((_a2 = this.existingCmd) == null ? void 0 : _a2.id);
|
|
}
|
|
);
|
|
if (existing) {
|
|
new import_obsidian20.Notice(`A command named "/${name}" already exists`);
|
|
return;
|
|
}
|
|
const parsed = parseSlashCommandContent(content);
|
|
const promptContent = parsed.promptContent;
|
|
const cmd = {
|
|
id: ((_a = this.existingCmd) == null ? void 0 : _a.id) || `cmd-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`,
|
|
name,
|
|
description: descInput.value.trim() || parsed.description || void 0,
|
|
argumentHint: hintInput.value.trim() || parsed.argumentHint || void 0,
|
|
model: modelInput.value.trim() || parsed.model || void 0,
|
|
allowedTools: toolsInput.value.trim() ? toolsInput.value.split(",").map((s) => s.trim()).filter(Boolean) : parsed.allowedTools && parsed.allowedTools.length > 0 ? parsed.allowedTools : void 0,
|
|
content: promptContent
|
|
};
|
|
this.onSave(cmd);
|
|
this.close();
|
|
});
|
|
const handleKeyDown = (e) => {
|
|
if (e.key === "Escape") {
|
|
e.preventDefault();
|
|
this.close();
|
|
}
|
|
};
|
|
contentEl.addEventListener("keydown", handleKeyDown);
|
|
}
|
|
onClose() {
|
|
this.contentEl.empty();
|
|
}
|
|
};
|
|
var SlashCommandSettings = class {
|
|
constructor(containerEl, plugin) {
|
|
this.containerEl = containerEl;
|
|
this.plugin = plugin;
|
|
this.render();
|
|
}
|
|
render() {
|
|
this.containerEl.empty();
|
|
const headerEl = this.containerEl.createDiv({ cls: "claudian-slash-header" });
|
|
headerEl.createSpan({ text: "Slash Commands", cls: "claudian-slash-label" });
|
|
const actionsEl = headerEl.createDiv({ cls: "claudian-slash-header-actions" });
|
|
const importBtn = actionsEl.createEl("button", {
|
|
cls: "claudian-settings-action-btn",
|
|
attr: { "aria-label": "Import" }
|
|
});
|
|
(0, import_obsidian20.setIcon)(importBtn, "download");
|
|
importBtn.addEventListener("click", () => this.importCommands());
|
|
const exportBtn = actionsEl.createEl("button", {
|
|
cls: "claudian-settings-action-btn",
|
|
attr: { "aria-label": "Export" }
|
|
});
|
|
(0, import_obsidian20.setIcon)(exportBtn, "upload");
|
|
exportBtn.addEventListener("click", () => this.exportCommands());
|
|
const addBtn = actionsEl.createEl("button", {
|
|
cls: "claudian-settings-action-btn",
|
|
attr: { "aria-label": "Add" }
|
|
});
|
|
(0, import_obsidian20.setIcon)(addBtn, "plus");
|
|
addBtn.addEventListener("click", () => this.openCommandModal(null));
|
|
const commands = this.plugin.settings.slashCommands;
|
|
if (commands.length === 0) {
|
|
const emptyEl = this.containerEl.createDiv({ cls: "claudian-slash-empty-state" });
|
|
emptyEl.setText('No slash commands configured. Click "Add" to create one.');
|
|
return;
|
|
}
|
|
const listEl = this.containerEl.createDiv({ cls: "claudian-slash-list" });
|
|
for (const cmd of commands) {
|
|
this.renderCommandItem(listEl, cmd);
|
|
}
|
|
}
|
|
renderCommandItem(listEl, cmd) {
|
|
const itemEl = listEl.createDiv({ cls: "claudian-slash-item-settings" });
|
|
const infoEl = itemEl.createDiv({ cls: "claudian-slash-info" });
|
|
const headerRow = infoEl.createDiv({ cls: "claudian-slash-item-header" });
|
|
const nameEl = headerRow.createSpan({ cls: "claudian-slash-item-name" });
|
|
nameEl.setText(`/${cmd.name}`);
|
|
if (cmd.argumentHint) {
|
|
const hintEl = headerRow.createSpan({ cls: "claudian-slash-item-hint" });
|
|
hintEl.setText(cmd.argumentHint);
|
|
}
|
|
if (cmd.description) {
|
|
const descEl = infoEl.createDiv({ cls: "claudian-slash-item-desc" });
|
|
descEl.setText(cmd.description);
|
|
}
|
|
const actionsEl = itemEl.createDiv({ cls: "claudian-slash-item-actions" });
|
|
const editBtn = actionsEl.createEl("button", {
|
|
cls: "claudian-settings-action-btn",
|
|
attr: { "aria-label": "Edit" }
|
|
});
|
|
(0, import_obsidian20.setIcon)(editBtn, "pencil");
|
|
editBtn.addEventListener("click", () => this.openCommandModal(cmd));
|
|
const deleteBtn = actionsEl.createEl("button", {
|
|
cls: "claudian-settings-action-btn claudian-settings-delete-btn",
|
|
attr: { "aria-label": "Delete" }
|
|
});
|
|
(0, import_obsidian20.setIcon)(deleteBtn, "trash-2");
|
|
deleteBtn.addEventListener("click", async () => {
|
|
await this.deleteCommand(cmd);
|
|
});
|
|
}
|
|
openCommandModal(existingCmd) {
|
|
const modal = new SlashCommandModal(
|
|
this.plugin.app,
|
|
this.plugin,
|
|
existingCmd,
|
|
async (cmd) => {
|
|
await this.saveCommand(cmd, existingCmd);
|
|
}
|
|
);
|
|
modal.open();
|
|
}
|
|
async saveCommand(cmd, existing) {
|
|
await this.plugin.storage.commands.save(cmd);
|
|
if (existing && existing.name !== cmd.name) {
|
|
await this.plugin.storage.commands.delete(existing.id);
|
|
}
|
|
await this.reloadCommands();
|
|
this.render();
|
|
new import_obsidian20.Notice(`Slash command "/${cmd.name}" ${existing ? "updated" : "created"}`);
|
|
}
|
|
async deleteCommand(cmd) {
|
|
await this.plugin.storage.commands.delete(cmd.id);
|
|
await this.reloadCommands();
|
|
this.render();
|
|
new import_obsidian20.Notice(`Slash command "/${cmd.name}" deleted`);
|
|
}
|
|
/** Reload commands from storage and update in-memory settings. */
|
|
async reloadCommands() {
|
|
const commands = await this.plugin.storage.commands.loadAll();
|
|
this.plugin.settings.slashCommands = commands;
|
|
}
|
|
exportCommands() {
|
|
const commands = this.plugin.settings.slashCommands;
|
|
if (commands.length === 0) {
|
|
new import_obsidian20.Notice("No slash commands to export");
|
|
return;
|
|
}
|
|
const json = JSON.stringify(commands, null, 2);
|
|
const blob = new Blob([json], { type: "application/json" });
|
|
const url = URL.createObjectURL(blob);
|
|
const a = document.createElement("a");
|
|
a.href = url;
|
|
a.download = "claudian-slash-commands.json";
|
|
a.click();
|
|
URL.revokeObjectURL(url);
|
|
new import_obsidian20.Notice(`Exported ${commands.length} slash command(s)`);
|
|
}
|
|
importCommands() {
|
|
const input = document.createElement("input");
|
|
input.type = "file";
|
|
input.accept = ".json";
|
|
input.addEventListener("change", async (e) => {
|
|
var _a;
|
|
const file = (_a = e.target.files) == null ? void 0 : _a[0];
|
|
if (!file) return;
|
|
try {
|
|
const text = await file.text();
|
|
const commands = JSON.parse(text);
|
|
if (!Array.isArray(commands)) {
|
|
throw new Error("Invalid format: expected an array");
|
|
}
|
|
const existingCommands = await this.plugin.storage.commands.loadAll();
|
|
const existingNames = new Set(existingCommands.map((c) => c.name.toLowerCase()));
|
|
let imported = 0;
|
|
for (const cmd of commands) {
|
|
if (!cmd.name || !cmd.content) {
|
|
continue;
|
|
}
|
|
if (typeof cmd.name !== "string" || typeof cmd.content !== "string") {
|
|
continue;
|
|
}
|
|
if (!/^[a-zA-Z0-9_/-]+$/.test(cmd.name)) {
|
|
continue;
|
|
}
|
|
cmd.id = `cmd-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;
|
|
if (cmd.allowedTools && !Array.isArray(cmd.allowedTools)) {
|
|
cmd.allowedTools = void 0;
|
|
}
|
|
if (Array.isArray(cmd.allowedTools)) {
|
|
cmd.allowedTools = cmd.allowedTools.filter((t) => typeof t === "string" && t.trim().length > 0);
|
|
if (cmd.allowedTools.length === 0) {
|
|
cmd.allowedTools = void 0;
|
|
}
|
|
}
|
|
if (cmd.description && typeof cmd.description !== "string") {
|
|
cmd.description = void 0;
|
|
}
|
|
if (cmd.argumentHint && typeof cmd.argumentHint !== "string") {
|
|
cmd.argumentHint = void 0;
|
|
}
|
|
if (cmd.model && typeof cmd.model !== "string") {
|
|
cmd.model = void 0;
|
|
}
|
|
const parsed = parseSlashCommandContent(cmd.content);
|
|
cmd.description = cmd.description || parsed.description;
|
|
cmd.argumentHint = cmd.argumentHint || parsed.argumentHint;
|
|
cmd.model = cmd.model || parsed.model;
|
|
cmd.allowedTools = cmd.allowedTools || parsed.allowedTools;
|
|
cmd.content = parsed.promptContent;
|
|
if (existingNames.has(cmd.name.toLowerCase())) {
|
|
continue;
|
|
}
|
|
await this.plugin.storage.commands.save(cmd);
|
|
existingNames.add(cmd.name.toLowerCase());
|
|
imported++;
|
|
}
|
|
await this.reloadCommands();
|
|
this.render();
|
|
new import_obsidian20.Notice(`Imported ${imported} slash command(s)`);
|
|
} catch (e2) {
|
|
new import_obsidian20.Notice("Failed to import slash commands. Check file format.");
|
|
}
|
|
});
|
|
input.click();
|
|
}
|
|
refresh() {
|
|
this.render();
|
|
}
|
|
};
|
|
|
|
// src/features/chat/controllers/ConversationController.ts
|
|
var import_obsidian21 = require("obsidian");
|
|
var ConversationController = class {
|
|
constructor(deps, callbacks = {}) {
|
|
this.deps = deps;
|
|
this.callbacks = callbacks;
|
|
}
|
|
// ============================================
|
|
// Conversation Lifecycle
|
|
// ============================================
|
|
/** Creates a new conversation, or switches to an existing empty one. */
|
|
async createNew() {
|
|
var _a, _b, _c, _d, _e, _f, _g;
|
|
const { plugin, state, asyncSubagentManager } = this.deps;
|
|
if (state.isStreaming) return;
|
|
if (state.messages.length > 0) {
|
|
await this.save();
|
|
}
|
|
asyncSubagentManager.orphanAllActive();
|
|
state.asyncSubagentStates.clear();
|
|
const emptyConv = plugin.findEmptyConversation();
|
|
const conversation = emptyConv ? (_a = await plugin.switchConversation(emptyConv.id)) != null ? _a : await plugin.createConversation() : await plugin.createConversation();
|
|
state.currentConversationId = conversation.id;
|
|
state.clearMessages();
|
|
state.usage = null;
|
|
state.currentTodos = null;
|
|
this.deps.setApprovedPlan(null);
|
|
this.deps.hidePlanBanner();
|
|
state.pendingPlanContent = null;
|
|
this.restorePlanModeState();
|
|
const messagesEl = this.deps.getMessagesEl();
|
|
messagesEl.empty();
|
|
(_b = this.deps.getTodoPanel()) == null ? void 0 : _b.remount();
|
|
const welcomeEl = messagesEl.createDiv({ cls: "claudian-welcome" });
|
|
welcomeEl.createDiv({ cls: "claudian-welcome-greeting", text: this.getGreeting() });
|
|
this.deps.setWelcomeEl(welcomeEl);
|
|
this.deps.getInputEl().value = "";
|
|
const fileCtx = this.deps.getFileContextManager();
|
|
fileCtx == null ? void 0 : fileCtx.resetForNewConversation();
|
|
fileCtx == null ? void 0 : fileCtx.autoAttachActiveFile();
|
|
(_c = this.deps.getImageContextManager()) == null ? void 0 : _c.clearImages();
|
|
(_d = this.deps.getMcpServerSelector()) == null ? void 0 : _d.clearEnabled();
|
|
(_e = this.deps.getContextPathSelector()) == null ? void 0 : _e.clearContextPaths();
|
|
this.deps.clearQueuedMessage();
|
|
(_g = (_f = this.callbacks).onNewConversation) == null ? void 0 : _g.call(_f);
|
|
}
|
|
/** Loads the active conversation or creates a new one. */
|
|
async loadActive() {
|
|
var _a, _b, _c, _d;
|
|
const { plugin, state, renderer } = this.deps;
|
|
let conversation = plugin.getActiveConversation();
|
|
const isNewConversation = !conversation;
|
|
if (!conversation) {
|
|
conversation = await plugin.createConversation();
|
|
}
|
|
state.currentConversationId = conversation.id;
|
|
state.messages = [...conversation.messages];
|
|
state.usage = (_a = conversation.usage) != null ? _a : null;
|
|
plugin.agentService.setSessionId(conversation.sessionId);
|
|
if (conversation.approvedPlan) {
|
|
this.deps.setApprovedPlan(conversation.approvedPlan);
|
|
this.deps.showPlanBanner(conversation.approvedPlan);
|
|
} else {
|
|
this.deps.setApprovedPlan(null);
|
|
this.deps.hidePlanBanner();
|
|
}
|
|
state.pendingPlanContent = (_b = conversation.pendingPlanContent) != null ? _b : null;
|
|
this.restorePlanModeState();
|
|
const hasMessages = state.messages.length > 0;
|
|
const fileCtx = this.deps.getFileContextManager();
|
|
fileCtx == null ? void 0 : fileCtx.resetForLoadedConversation(hasMessages);
|
|
if (conversation.currentNote) {
|
|
fileCtx == null ? void 0 : fileCtx.setCurrentNote(conversation.currentNote);
|
|
} else if (isNewConversation || !hasMessages) {
|
|
fileCtx == null ? void 0 : fileCtx.autoAttachActiveFile();
|
|
}
|
|
const contextPathSelector = this.deps.getContextPathSelector();
|
|
if (conversation.sessionContextPaths && conversation.sessionContextPaths.length > 0) {
|
|
contextPathSelector == null ? void 0 : contextPathSelector.setContextPaths(conversation.sessionContextPaths);
|
|
} else {
|
|
contextPathSelector == null ? void 0 : contextPathSelector.clearContextPaths();
|
|
}
|
|
const welcomeEl = renderer.renderMessages(
|
|
state.messages,
|
|
() => this.getGreeting()
|
|
);
|
|
this.deps.setWelcomeEl(welcomeEl);
|
|
this.updateWelcomeVisibility();
|
|
state.currentTodos = extractLastTodosFromMessages(state.messages);
|
|
(_d = (_c = this.callbacks).onConversationLoaded) == null ? void 0 : _d.call(_c);
|
|
if (conversation.pendingPlanContent && !conversation.approvedPlan) {
|
|
this.deps.triggerPendingPlanApproval(conversation.pendingPlanContent);
|
|
}
|
|
}
|
|
/** Switches to a different conversation. */
|
|
async switchTo(id) {
|
|
var _a, _b, _c, _d, _e, _f;
|
|
const { plugin, state, renderer, asyncSubagentManager } = this.deps;
|
|
if (id === state.currentConversationId) return;
|
|
if (state.isStreaming) return;
|
|
await this.save();
|
|
asyncSubagentManager.orphanAllActive();
|
|
state.asyncSubagentStates.clear();
|
|
const conversation = await plugin.switchConversation(id);
|
|
if (!conversation) return;
|
|
state.currentConversationId = conversation.id;
|
|
state.messages = [...conversation.messages];
|
|
state.usage = (_a = conversation.usage) != null ? _a : null;
|
|
if (conversation.approvedPlan) {
|
|
this.deps.setApprovedPlan(conversation.approvedPlan);
|
|
this.deps.showPlanBanner(conversation.approvedPlan);
|
|
} else {
|
|
this.deps.setApprovedPlan(null);
|
|
this.deps.hidePlanBanner();
|
|
}
|
|
state.pendingPlanContent = (_b = conversation.pendingPlanContent) != null ? _b : null;
|
|
this.restorePlanModeState();
|
|
this.deps.getInputEl().value = "";
|
|
this.deps.clearQueuedMessage();
|
|
const fileCtx = this.deps.getFileContextManager();
|
|
fileCtx == null ? void 0 : fileCtx.resetForLoadedConversation(state.messages.length > 0);
|
|
if (conversation.currentNote) {
|
|
fileCtx == null ? void 0 : fileCtx.setCurrentNote(conversation.currentNote);
|
|
}
|
|
const contextPathSelector = this.deps.getContextPathSelector();
|
|
if (conversation.sessionContextPaths && conversation.sessionContextPaths.length > 0) {
|
|
contextPathSelector == null ? void 0 : contextPathSelector.setContextPaths(conversation.sessionContextPaths);
|
|
} else {
|
|
contextPathSelector == null ? void 0 : contextPathSelector.clearContextPaths();
|
|
}
|
|
(_c = this.deps.getMcpServerSelector()) == null ? void 0 : _c.clearEnabled();
|
|
const welcomeEl = renderer.renderMessages(
|
|
state.messages,
|
|
() => this.getGreeting()
|
|
);
|
|
this.deps.setWelcomeEl(welcomeEl);
|
|
state.currentTodos = extractLastTodosFromMessages(state.messages);
|
|
(_d = this.deps.getHistoryDropdown()) == null ? void 0 : _d.removeClass("visible");
|
|
this.updateWelcomeVisibility();
|
|
(_f = (_e = this.callbacks).onConversationSwitched) == null ? void 0 : _f.call(_e);
|
|
if (conversation.pendingPlanContent && !conversation.approvedPlan) {
|
|
this.deps.triggerPendingPlanApproval(conversation.pendingPlanContent);
|
|
}
|
|
}
|
|
/** Saves the current conversation. */
|
|
async save(updateLastResponse = false) {
|
|
var _a, _b, _c, _d, _e;
|
|
const { plugin, state } = this.deps;
|
|
if (!state.currentConversationId) return;
|
|
const sessionId = plugin.agentService.getSessionId();
|
|
const fileCtx = this.deps.getFileContextManager();
|
|
const currentNote = (fileCtx == null ? void 0 : fileCtx.getCurrentNotePath()) || void 0;
|
|
const contextPathSelector = this.deps.getContextPathSelector();
|
|
const sessionContextPaths = (_a = contextPathSelector == null ? void 0 : contextPathSelector.getContextPaths()) != null ? _a : [];
|
|
const approvedPlan = this.deps.getApprovedPlan();
|
|
const updates = {
|
|
messages: state.getPersistedMessages(),
|
|
sessionId,
|
|
currentNote,
|
|
sessionContextPaths: sessionContextPaths.length > 0 ? sessionContextPaths : void 0,
|
|
usage: (_b = state.usage) != null ? _b : void 0,
|
|
approvedPlan: approvedPlan != null ? approvedPlan : void 0,
|
|
pendingPlanContent: (_c = state.pendingPlanContent) != null ? _c : void 0,
|
|
isInPlanMode: (_e = (_d = state.planModeState) == null ? void 0 : _d.isActive) != null ? _e : void 0
|
|
};
|
|
if (updateLastResponse) {
|
|
updates.lastResponseAt = Date.now();
|
|
}
|
|
await plugin.updateConversation(state.currentConversationId, updates);
|
|
}
|
|
/**
|
|
* Restores plan mode state based on current permission mode.
|
|
* Resets transient flags and sets up planModeState appropriately.
|
|
*/
|
|
restorePlanModeState() {
|
|
var _a, _b;
|
|
const { plugin, state } = this.deps;
|
|
state.planModeRequested = false;
|
|
state.planModeActivationPending = false;
|
|
const isPlanMode = plugin.settings.permissionMode === "plan";
|
|
if (isPlanMode) {
|
|
const wasAgentInitiated = (_b = (_a = state.planModeState) == null ? void 0 : _a.agentInitiated) != null ? _b : false;
|
|
state.planModeState = {
|
|
isActive: true,
|
|
planFilePath: null,
|
|
planContent: null,
|
|
originalQuery: null,
|
|
agentInitiated: wasAgentInitiated
|
|
};
|
|
} else {
|
|
state.resetPlanModeState();
|
|
}
|
|
this.deps.setPlanModeActive(isPlanMode);
|
|
}
|
|
// ============================================
|
|
// History Dropdown
|
|
// ============================================
|
|
/** Toggles the history dropdown visibility. */
|
|
toggleHistoryDropdown() {
|
|
const dropdown = this.deps.getHistoryDropdown();
|
|
if (!dropdown) return;
|
|
const isVisible = dropdown.hasClass("visible");
|
|
if (isVisible) {
|
|
dropdown.removeClass("visible");
|
|
} else {
|
|
this.updateHistoryDropdown();
|
|
dropdown.addClass("visible");
|
|
}
|
|
}
|
|
/** Updates the history dropdown content. */
|
|
updateHistoryDropdown() {
|
|
var _a;
|
|
const dropdown = this.deps.getHistoryDropdown();
|
|
if (!dropdown) return;
|
|
const { plugin, state } = this.deps;
|
|
dropdown.empty();
|
|
const dropdownHeader = dropdown.createDiv({ cls: "claudian-history-header" });
|
|
dropdownHeader.createSpan({ text: "Conversations" });
|
|
const list = dropdown.createDiv({ cls: "claudian-history-list" });
|
|
const allConversations = plugin.getConversationList();
|
|
if (allConversations.length === 0) {
|
|
list.createDiv({ cls: "claudian-history-empty", text: "No conversations" });
|
|
return;
|
|
}
|
|
const conversations = [...allConversations].sort((a, b) => {
|
|
var _a2, _b;
|
|
return ((_a2 = b.lastResponseAt) != null ? _a2 : b.createdAt) - ((_b = a.lastResponseAt) != null ? _b : a.createdAt);
|
|
});
|
|
for (const conv of conversations) {
|
|
const isCurrent = conv.id === state.currentConversationId;
|
|
const item = list.createDiv({
|
|
cls: `claudian-history-item${isCurrent ? " active" : ""}`
|
|
});
|
|
const iconEl = item.createDiv({ cls: "claudian-history-item-icon" });
|
|
(0, import_obsidian21.setIcon)(iconEl, isCurrent ? "message-square-dot" : "message-square");
|
|
const content = item.createDiv({ cls: "claudian-history-item-content" });
|
|
const titleEl = content.createDiv({ cls: "claudian-history-item-title", text: conv.title });
|
|
titleEl.setAttribute("title", conv.title);
|
|
content.createDiv({
|
|
cls: "claudian-history-item-date",
|
|
text: isCurrent ? "Current session" : this.formatDate((_a = conv.lastResponseAt) != null ? _a : conv.createdAt)
|
|
});
|
|
if (!isCurrent) {
|
|
content.addEventListener("click", async (e) => {
|
|
e.stopPropagation();
|
|
await this.switchTo(conv.id);
|
|
});
|
|
}
|
|
const actions = item.createDiv({ cls: "claudian-history-item-actions" });
|
|
if (conv.titleGenerationStatus === "pending") {
|
|
const loadingEl = actions.createEl("span", { cls: "claudian-action-btn claudian-action-loading" });
|
|
(0, import_obsidian21.setIcon)(loadingEl, "loader-2");
|
|
loadingEl.setAttribute("aria-label", "Generating title...");
|
|
} else if (conv.titleGenerationStatus === "failed") {
|
|
const regenerateBtn = actions.createEl("button", { cls: "claudian-action-btn" });
|
|
(0, import_obsidian21.setIcon)(regenerateBtn, "refresh-cw");
|
|
regenerateBtn.setAttribute("aria-label", "Regenerate title");
|
|
regenerateBtn.addEventListener("click", async (e) => {
|
|
e.stopPropagation();
|
|
try {
|
|
await this.regenerateTitle(conv.id);
|
|
} catch (error2) {
|
|
console.error("[ConversationController] Failed to regenerate title:", error2);
|
|
}
|
|
});
|
|
}
|
|
const renameBtn = actions.createEl("button", { cls: "claudian-action-btn" });
|
|
(0, import_obsidian21.setIcon)(renameBtn, "pencil");
|
|
renameBtn.setAttribute("aria-label", "Rename");
|
|
renameBtn.addEventListener("click", (e) => {
|
|
e.stopPropagation();
|
|
this.showRenameInput(item, conv.id, conv.title);
|
|
});
|
|
const deleteBtn = actions.createEl("button", { cls: "claudian-action-btn claudian-delete-btn" });
|
|
(0, import_obsidian21.setIcon)(deleteBtn, "trash-2");
|
|
deleteBtn.setAttribute("aria-label", "Delete");
|
|
deleteBtn.addEventListener("click", async (e) => {
|
|
e.stopPropagation();
|
|
if (state.isStreaming) return;
|
|
await plugin.deleteConversation(conv.id);
|
|
this.updateHistoryDropdown();
|
|
if (conv.id === state.currentConversationId) {
|
|
await this.loadActive();
|
|
}
|
|
});
|
|
}
|
|
}
|
|
/** Shows inline rename input for a conversation. */
|
|
showRenameInput(item, convId, currentTitle) {
|
|
const titleEl = item.querySelector(".claudian-history-item-title");
|
|
if (!titleEl) return;
|
|
const input = document.createElement("input");
|
|
input.type = "text";
|
|
input.className = "claudian-rename-input";
|
|
input.value = currentTitle;
|
|
titleEl.replaceWith(input);
|
|
input.focus();
|
|
input.select();
|
|
const finishRename = async () => {
|
|
const newTitle = input.value.trim() || currentTitle;
|
|
await this.deps.plugin.renameConversation(convId, newTitle);
|
|
this.updateHistoryDropdown();
|
|
};
|
|
input.addEventListener("blur", finishRename);
|
|
input.addEventListener("keydown", async (e) => {
|
|
if (e.key === "Enter") {
|
|
input.blur();
|
|
} else if (e.key === "Escape") {
|
|
input.value = currentTitle;
|
|
input.blur();
|
|
}
|
|
});
|
|
}
|
|
// ============================================
|
|
// Welcome & Greeting
|
|
// ============================================
|
|
/** Generates a dynamic greeting based on time/day. */
|
|
getGreeting() {
|
|
var _a;
|
|
const now = /* @__PURE__ */ new Date();
|
|
const hour = now.getHours();
|
|
const day = now.getDay();
|
|
const name = (_a = this.deps.plugin.settings.userName) == null ? void 0 : _a.trim();
|
|
const dayGreetings = name ? {
|
|
0: [`Happy Sunday, ${name}`, "Sunday session?", "Welcome to the weekend"],
|
|
1: [`Happy Monday, ${name}`, `Back at it, ${name}`],
|
|
2: [`Happy Tuesday, ${name}`],
|
|
3: [`Happy Wednesday, ${name}`],
|
|
4: [`Happy Thursday, ${name}`],
|
|
5: [`Happy Friday, ${name}`, `That Friday feeling, ${name}`],
|
|
6: [`Happy Saturday, ${name}`, `Welcome to the weekend, ${name}`]
|
|
} : {
|
|
0: ["Happy Sunday", "Sunday session?", "Welcome to the weekend"],
|
|
1: ["Happy Monday", "Back at it!"],
|
|
2: ["Happy Tuesday"],
|
|
3: ["Happy Wednesday"],
|
|
4: ["Happy Thursday"],
|
|
5: ["Happy Friday", "That Friday feeling"],
|
|
6: ["Happy Saturday!", "Welcome to the weekend"]
|
|
};
|
|
const getTimeGreetings = () => {
|
|
if (hour >= 5 && hour < 12) {
|
|
return name ? [`Good morning, ${name}`, "Coffee and Claudian time?"] : ["Good morning", "Coffee and Claudian time?"];
|
|
} else if (hour >= 12 && hour < 18) {
|
|
return name ? [`Good afternoon, ${name}`, `Hey there, ${name}`, `How's it going, ${name}?`] : ["Good afternoon", "Hey there", "How's it going?"];
|
|
} else if (hour >= 18 && hour < 22) {
|
|
return name ? [`Good evening, ${name}`, `Evening, ${name}`, `How was your day, ${name}?`] : ["Good evening", "Evening", "How was your day?"];
|
|
} else {
|
|
return name ? ["Hello, night owl", `Evening, ${name}`] : ["Hello, night owl", "Evening"];
|
|
}
|
|
};
|
|
const generalGreetings = name ? [
|
|
`Hey there, ${name}`,
|
|
`Hi ${name}, how are you?`,
|
|
`How's it going, ${name}?`,
|
|
`Welcome Back!, ${name}`,
|
|
`What's new, ${name}?`,
|
|
`${name} returns!`
|
|
] : [
|
|
"Hey there",
|
|
"Hi, how are you?",
|
|
"How's it going?",
|
|
"Welcome Back!",
|
|
"What's new?"
|
|
];
|
|
const allGreetings = [
|
|
...dayGreetings[day] || [],
|
|
...getTimeGreetings(),
|
|
...generalGreetings
|
|
];
|
|
return allGreetings[Math.floor(Math.random() * allGreetings.length)];
|
|
}
|
|
/** Updates welcome element visibility based on message count. */
|
|
updateWelcomeVisibility() {
|
|
const welcomeEl = this.deps.getWelcomeEl();
|
|
if (!welcomeEl) return;
|
|
if (this.deps.state.messages.length === 0) {
|
|
welcomeEl.style.display = "";
|
|
} else {
|
|
welcomeEl.style.display = "none";
|
|
}
|
|
}
|
|
// ============================================
|
|
// Utilities
|
|
// ============================================
|
|
/** Generates a fallback title from the first message (used when AI fails). */
|
|
generateFallbackTitle(firstMessage) {
|
|
const firstSentence = firstMessage.split(/[.!?\n]/)[0].trim();
|
|
const autoTitle = firstSentence.substring(0, 50);
|
|
const suffix = firstSentence.length > 50 ? "..." : "";
|
|
return `${autoTitle}${suffix}`;
|
|
}
|
|
/** Regenerates AI title for a conversation. */
|
|
async regenerateTitle(conversationId) {
|
|
var _a;
|
|
const { plugin } = this.deps;
|
|
if (!plugin.settings.enableAutoTitleGeneration) return;
|
|
const titleService = this.deps.getTitleGenerationService();
|
|
if (!titleService) return;
|
|
const fullConv = plugin.getConversationById(conversationId);
|
|
if (!fullConv || fullConv.messages.length < 2) return;
|
|
const firstUserMsg = fullConv.messages.find((m) => m.role === "user");
|
|
const firstAssistantMsg = fullConv.messages.find((m) => m.role === "assistant");
|
|
if (!firstUserMsg || !firstAssistantMsg) return;
|
|
const userContent = firstUserMsg.displayContent || firstUserMsg.content;
|
|
const assistantText = firstAssistantMsg.content || ((_a = firstAssistantMsg.contentBlocks) == null ? void 0 : _a.filter((b) => b.type === "text").map((b) => b.content).join("\n")) || "";
|
|
if (!assistantText) return;
|
|
const isPlan = fullConv.title.startsWith("[Plan]");
|
|
const expectedTitle = fullConv.title;
|
|
await plugin.updateConversation(conversationId, { titleGenerationStatus: "pending" });
|
|
this.updateHistoryDropdown();
|
|
await titleService.generateTitle(
|
|
conversationId,
|
|
userContent,
|
|
assistantText,
|
|
async (convId, result) => {
|
|
const currentConv = plugin.getConversationById(convId);
|
|
if (!currentConv) return;
|
|
const userManuallyRenamed = currentConv.title !== expectedTitle;
|
|
if (result.success && result.title && !userManuallyRenamed) {
|
|
const newTitle = isPlan ? `[Plan] ${result.title}` : result.title;
|
|
await plugin.renameConversation(convId, newTitle);
|
|
await plugin.updateConversation(convId, { titleGenerationStatus: "success" });
|
|
} else if (!userManuallyRenamed) {
|
|
await plugin.updateConversation(convId, { titleGenerationStatus: "failed" });
|
|
} else {
|
|
await plugin.updateConversation(convId, { titleGenerationStatus: void 0 });
|
|
}
|
|
this.updateHistoryDropdown();
|
|
}
|
|
);
|
|
}
|
|
/** Formats a timestamp for display. */
|
|
formatDate(timestamp) {
|
|
const date3 = new Date(timestamp);
|
|
const now = /* @__PURE__ */ new Date();
|
|
if (date3.toDateString() === now.toDateString()) {
|
|
return date3.toLocaleTimeString(void 0, { hour: "2-digit", minute: "2-digit", hour12: false });
|
|
}
|
|
return date3.toLocaleDateString(void 0, { month: "short", day: "numeric" });
|
|
}
|
|
};
|
|
|
|
// src/features/chat/controllers/InputController.ts
|
|
var import_obsidian22 = require("obsidian");
|
|
|
|
// src/utils/editor.ts
|
|
function findNearestNonEmptyLine(getLine, lineCount, startLine, direction) {
|
|
const step = direction === "before" ? -1 : 1;
|
|
for (let i = startLine + step; i >= 0 && i < lineCount; i += step) {
|
|
const content = getLine(i);
|
|
if (content.trim().length > 0) {
|
|
return content;
|
|
}
|
|
}
|
|
return "";
|
|
}
|
|
function buildCursorContext(getLine, lineCount, line, column) {
|
|
const lineContent = getLine(line);
|
|
const beforeCursor = lineContent.substring(0, column);
|
|
const afterCursor = lineContent.substring(column);
|
|
const lineIsEmpty = lineContent.trim().length === 0;
|
|
const nothingBefore = beforeCursor.trim().length === 0;
|
|
const nothingAfter = afterCursor.trim().length === 0;
|
|
const isInbetween = lineIsEmpty || nothingBefore && nothingAfter;
|
|
let contextBefore = beforeCursor;
|
|
let contextAfter = afterCursor;
|
|
if (isInbetween) {
|
|
contextBefore = findNearestNonEmptyLine(getLine, lineCount, line, "before");
|
|
contextAfter = findNearestNonEmptyLine(getLine, lineCount, line, "after");
|
|
}
|
|
return { beforeCursor: contextBefore, afterCursor: contextAfter, isInbetween, line, column };
|
|
}
|
|
function formatEditorContext(context) {
|
|
if (context.mode === "selection" && context.selectedText) {
|
|
const lineAttr = context.startLine && context.lineCount ? ` lines="${context.startLine}-${context.startLine + context.lineCount - 1}"` : "";
|
|
return `<editor_selection path="${context.notePath}"${lineAttr}>
|
|
${context.selectedText}
|
|
</editor_selection>`;
|
|
} else if (context.mode === "cursor" && context.cursorContext) {
|
|
const ctx = context.cursorContext;
|
|
let content;
|
|
if (ctx.isInbetween) {
|
|
const parts = [];
|
|
if (ctx.beforeCursor) parts.push(ctx.beforeCursor);
|
|
parts.push("| #inbetween");
|
|
if (ctx.afterCursor) parts.push(ctx.afterCursor);
|
|
content = parts.join("\n");
|
|
} else {
|
|
content = `${ctx.beforeCursor}|${ctx.afterCursor} #inline`;
|
|
}
|
|
return `<editor_cursor path="${context.notePath}">
|
|
${content}
|
|
</editor_cursor>`;
|
|
}
|
|
return "";
|
|
}
|
|
function prependEditorContext(prompt, context) {
|
|
const formatted = formatEditorContext(context);
|
|
return formatted ? `${formatted}
|
|
|
|
${prompt}` : prompt;
|
|
}
|
|
|
|
// src/utils/markdown.ts
|
|
function appendMarkdownSnippet(existingPrompt, snippet) {
|
|
const trimmedSnippet = snippet.trim();
|
|
if (!trimmedSnippet) {
|
|
return existingPrompt;
|
|
}
|
|
if (!existingPrompt.trim()) {
|
|
return trimmedSnippet;
|
|
}
|
|
const separator = existingPrompt.endsWith("\n\n") ? "" : existingPrompt.endsWith("\n") ? "\n" : "\n\n";
|
|
return existingPrompt + separator + trimmedSnippet;
|
|
}
|
|
|
|
// src/features/chat/controllers/InputController.ts
|
|
var PLAN_MODE_REQUEST_PREFIX = "User requested plan mode. Call EnterPlanMode before responding.";
|
|
var InputController = class {
|
|
constructor(deps) {
|
|
this.deps = deps;
|
|
}
|
|
// ============================================
|
|
// Message Sending
|
|
// ============================================
|
|
/** Sends a message with optional editor context override. */
|
|
async sendMessage(options) {
|
|
var _a, _b, _c;
|
|
const { plugin, state, renderer, streamController, selectionController, conversationController } = this.deps;
|
|
const inputEl = this.deps.getInputEl();
|
|
const imageContextManager = this.deps.getImageContextManager();
|
|
const fileContextManager = this.deps.getFileContextManager();
|
|
const slashCommandManager = this.deps.getSlashCommandManager();
|
|
const mcpServerSelector = this.deps.getMcpServerSelector();
|
|
const contentOverride = options == null ? void 0 : options.content;
|
|
const shouldUseInput = contentOverride === void 0;
|
|
let content = (contentOverride != null ? contentOverride : inputEl.value).trim();
|
|
const hasImages = (_a = imageContextManager == null ? void 0 : imageContextManager.hasImages()) != null ? _a : false;
|
|
if (!content && !hasImages) return;
|
|
if (state.isStreaming) {
|
|
const images2 = hasImages ? [...(imageContextManager == null ? void 0 : imageContextManager.getAttachedImages()) || []] : void 0;
|
|
const editorContext2 = selectionController.getContext();
|
|
const promptPrefix = options == null ? void 0 : options.promptPrefix;
|
|
if (state.queuedMessage) {
|
|
state.queuedMessage.content += "\n\n" + content;
|
|
if (images2 && images2.length > 0) {
|
|
state.queuedMessage.images = [...state.queuedMessage.images || [], ...images2];
|
|
}
|
|
state.queuedMessage.editorContext = editorContext2;
|
|
state.queuedMessage.hidden = state.queuedMessage.hidden || (options == null ? void 0 : options.hidden);
|
|
if (promptPrefix) {
|
|
state.queuedMessage.promptPrefix = (_b = state.queuedMessage.promptPrefix) != null ? _b : promptPrefix;
|
|
}
|
|
} else {
|
|
state.queuedMessage = {
|
|
content,
|
|
images: images2,
|
|
editorContext: editorContext2,
|
|
hidden: options == null ? void 0 : options.hidden,
|
|
promptPrefix
|
|
};
|
|
}
|
|
if (shouldUseInput) {
|
|
inputEl.value = "";
|
|
}
|
|
imageContextManager == null ? void 0 : imageContextManager.clearImages();
|
|
this.updateQueueIndicator();
|
|
return;
|
|
}
|
|
if (shouldUseInput) {
|
|
inputEl.value = "";
|
|
}
|
|
state.isStreaming = true;
|
|
state.cancelRequested = false;
|
|
state.ignoreUsageUpdates = false;
|
|
state.subagentsSpawnedThisStream = 0;
|
|
const welcomeEl = this.deps.getWelcomeEl();
|
|
if (welcomeEl) {
|
|
welcomeEl.style.display = "none";
|
|
}
|
|
fileContextManager == null ? void 0 : fileContextManager.startSession();
|
|
const displayContent = content;
|
|
let queryOptions;
|
|
if (content && slashCommandManager) {
|
|
slashCommandManager.setCommands(plugin.settings.slashCommands);
|
|
const detected = slashCommandManager.detectCommand(content);
|
|
if (detected) {
|
|
const cmd = plugin.settings.slashCommands.find(
|
|
(c) => c.name.toLowerCase() === detected.commandName.toLowerCase()
|
|
);
|
|
if (cmd) {
|
|
const result = await slashCommandManager.expandCommand(cmd, detected.args, {
|
|
bash: {
|
|
enabled: true,
|
|
shouldBlockCommand: (bashCommand) => isCommandBlocked(
|
|
bashCommand,
|
|
getBashToolBlockedCommands(plugin.settings.blockedCommands),
|
|
plugin.settings.enableBlocklist
|
|
),
|
|
requestApproval: plugin.settings.permissionMode !== "yolo" ? (bashCommand) => this.requestInlineBashApproval(bashCommand) : void 0
|
|
}
|
|
});
|
|
content = result.expandedPrompt;
|
|
if (result.errors.length > 0) {
|
|
new import_obsidian22.Notice(formatSlashCommandWarnings(result.errors));
|
|
}
|
|
if (result.allowedTools || result.model) {
|
|
queryOptions = {
|
|
allowedTools: result.allowedTools,
|
|
model: result.model
|
|
};
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if (content && imageContextManager) {
|
|
const result = await imageContextManager.handleImagePathInText(content);
|
|
if (result.imageLoaded) {
|
|
content = result.text;
|
|
}
|
|
}
|
|
const images = (imageContextManager == null ? void 0 : imageContextManager.getAttachedImages()) || [];
|
|
const imagesForMessage = images.length > 0 ? [...images] : void 0;
|
|
if (shouldUseInput) {
|
|
imageContextManager == null ? void 0 : imageContextManager.clearImages();
|
|
}
|
|
const currentNotePath = (fileContextManager == null ? void 0 : fileContextManager.getCurrentNotePath()) || null;
|
|
const shouldSendCurrentNote = (_c = fileContextManager == null ? void 0 : fileContextManager.shouldSendCurrentNote(currentNotePath)) != null ? _c : false;
|
|
const editorContextOverride = options == null ? void 0 : options.editorContextOverride;
|
|
const editorContext = editorContextOverride !== void 0 ? editorContextOverride : selectionController.getContext();
|
|
let promptToSend = `<query>
|
|
${content}
|
|
</query>`;
|
|
let currentNoteForMessage;
|
|
if (editorContext) {
|
|
promptToSend = prependEditorContext(promptToSend, editorContext);
|
|
}
|
|
if (shouldSendCurrentNote && currentNotePath) {
|
|
promptToSend = prependCurrentNote(promptToSend, currentNotePath);
|
|
currentNoteForMessage = currentNotePath;
|
|
}
|
|
if (options == null ? void 0 : options.promptPrefix) {
|
|
promptToSend = `${options.promptPrefix}
|
|
|
|
${promptToSend}`;
|
|
}
|
|
fileContextManager == null ? void 0 : fileContextManager.markCurrentNoteSent();
|
|
const userMsg = {
|
|
id: this.deps.generateId(),
|
|
role: "user",
|
|
content,
|
|
displayContent: displayContent !== content ? displayContent : void 0,
|
|
timestamp: Date.now(),
|
|
currentNote: currentNoteForMessage,
|
|
images: imagesForMessage,
|
|
hidden: options == null ? void 0 : options.hidden
|
|
};
|
|
state.addMessage(userMsg);
|
|
if (!(options == null ? void 0 : options.hidden)) {
|
|
renderer.addMessage(userMsg);
|
|
}
|
|
const assistantMsg = {
|
|
id: this.deps.generateId(),
|
|
role: "assistant",
|
|
content: "",
|
|
timestamp: Date.now(),
|
|
toolCalls: [],
|
|
contentBlocks: []
|
|
};
|
|
state.addMessage(assistantMsg);
|
|
const msgEl = renderer.addMessage(assistantMsg);
|
|
const contentEl = msgEl.querySelector(".claudian-message-content");
|
|
state.toolCallElements.clear();
|
|
state.currentContentEl = contentEl;
|
|
state.currentTextEl = null;
|
|
state.currentTextContent = "";
|
|
streamController.showThinkingIndicator(contentEl);
|
|
const mcpMentions = plugin.mcpService.extractMentions(promptToSend);
|
|
promptToSend = plugin.mcpService.transformMentions(promptToSend);
|
|
const enabledMcpServers = mcpServerSelector == null ? void 0 : mcpServerSelector.getEnabledServers();
|
|
if (mcpMentions.size > 0 || enabledMcpServers && enabledMcpServers.size > 0) {
|
|
queryOptions = {
|
|
...queryOptions,
|
|
mcpMentions,
|
|
enabledMcpServers
|
|
};
|
|
}
|
|
let wasInterrupted = false;
|
|
try {
|
|
for await (const chunk of plugin.agentService.query(promptToSend, imagesForMessage, state.messages, queryOptions)) {
|
|
if (state.cancelRequested) {
|
|
wasInterrupted = true;
|
|
break;
|
|
}
|
|
await streamController.handleStreamChunk(chunk, assistantMsg);
|
|
}
|
|
} catch (error2) {
|
|
const errorMsg = error2 instanceof Error ? error2.message : "Unknown error";
|
|
await streamController.appendText(`
|
|
|
|
**Error:** ${errorMsg}`);
|
|
} finally {
|
|
if (wasInterrupted) {
|
|
await streamController.appendText('\n\n<span class="claudian-interrupted">Interrupted</span> <span class="claudian-interrupted-hint">\xB7 What should Claudian do instead?</span>');
|
|
}
|
|
streamController.hideThinkingIndicator();
|
|
state.isStreaming = false;
|
|
state.cancelRequested = false;
|
|
state.currentContentEl = null;
|
|
streamController.finalizeCurrentThinkingBlock(assistantMsg);
|
|
streamController.finalizeCurrentTextBlock(assistantMsg);
|
|
state.activeSubagents.clear();
|
|
await conversationController.save(true);
|
|
await this.activatePendingPlanMode();
|
|
await this.triggerTitleGeneration();
|
|
this.processQueuedMessage();
|
|
}
|
|
}
|
|
// ============================================
|
|
// Plan Mode
|
|
// ============================================
|
|
setPlanModeRequested(active) {
|
|
const { state } = this.deps;
|
|
if (state.planModeRequested === active) {
|
|
return;
|
|
}
|
|
state.planModeRequested = active;
|
|
this.deps.setPlanModeActive(active);
|
|
}
|
|
ensurePlanModeState(agentInitiated) {
|
|
var _a;
|
|
const { state, plugin } = this.deps;
|
|
if (plugin.settings.permissionMode !== "plan") {
|
|
return;
|
|
}
|
|
if ((_a = state.planModeState) == null ? void 0 : _a.isActive) {
|
|
if (!state.planModeState.agentInitiated && agentInitiated) {
|
|
state.planModeState.agentInitiated = true;
|
|
}
|
|
return;
|
|
}
|
|
state.planModeState = {
|
|
isActive: true,
|
|
planFilePath: null,
|
|
planContent: null,
|
|
originalQuery: null,
|
|
agentInitiated
|
|
};
|
|
}
|
|
async activatePendingPlanMode() {
|
|
const { plugin, state } = this.deps;
|
|
if (!state.planModeActivationPending) {
|
|
return;
|
|
}
|
|
state.planModeActivationPending = false;
|
|
if (plugin.settings.permissionMode !== "plan") {
|
|
plugin.settings.lastNonPlanPermissionMode = plugin.settings.permissionMode;
|
|
plugin.settings.permissionMode = "plan";
|
|
await plugin.saveSettings();
|
|
}
|
|
state.planModeRequested = false;
|
|
this.ensurePlanModeState(true);
|
|
plugin.agentService.setCurrentPlanFilePath(null);
|
|
this.deps.setPlanModeActive(true);
|
|
}
|
|
async exitPlanPermissionMode() {
|
|
var _a;
|
|
const { plugin, state } = this.deps;
|
|
const restored = (_a = plugin.settings.lastNonPlanPermissionMode) != null ? _a : "yolo";
|
|
if (plugin.settings.permissionMode === "plan") {
|
|
plugin.settings.permissionMode = restored;
|
|
plugin.settings.lastNonPlanPermissionMode = restored;
|
|
await plugin.saveSettings();
|
|
}
|
|
state.resetPlanModeState();
|
|
state.planModeRequested = false;
|
|
state.planModeActivationPending = false;
|
|
this.deps.setPlanModeActive(false);
|
|
}
|
|
/** Sends a message in plan mode (read-only exploration). */
|
|
async sendPlanModeMessage() {
|
|
var _a, _b;
|
|
const { state, plugin } = this.deps;
|
|
const inputEl = this.deps.getInputEl();
|
|
const content = inputEl.value.trim();
|
|
if (!content) return;
|
|
if (state.isStreaming) {
|
|
new import_obsidian22.Notice("Cannot request plan mode while agent is working");
|
|
return;
|
|
}
|
|
if (plugin.settings.permissionMode === "plan") {
|
|
plugin.agentService.setCurrentPlanFilePath(null);
|
|
const wasAgentInitiated = (_b = (_a = state.planModeState) == null ? void 0 : _a.agentInitiated) != null ? _b : false;
|
|
this.ensurePlanModeState(wasAgentInitiated);
|
|
state.planModeState = {
|
|
isActive: true,
|
|
planFilePath: null,
|
|
planContent: null,
|
|
originalQuery: content,
|
|
agentInitiated: wasAgentInitiated
|
|
};
|
|
inputEl.value = "";
|
|
await this.sendMessageWithPlanMode({ content });
|
|
return;
|
|
}
|
|
await this.sendMessage({ promptPrefix: PLAN_MODE_REQUEST_PREFIX });
|
|
}
|
|
/**
|
|
* Handles agent-initiated EnterPlanMode tool call.
|
|
* Sets up state for re-sending with plan mode after current stream ends.
|
|
*/
|
|
async handleEnterPlanMode() {
|
|
const { state, plugin } = this.deps;
|
|
if (plugin.settings.permissionMode === "plan") {
|
|
this.ensurePlanModeState(true);
|
|
return;
|
|
}
|
|
state.planModeActivationPending = true;
|
|
}
|
|
/** Internal: sends message with plan mode options. */
|
|
async sendMessageWithPlanMode(options) {
|
|
var _a, _b, _c, _d, _e, _f, _g, _h, _i;
|
|
const { plugin, state, renderer, streamController, selectionController, conversationController } = this.deps;
|
|
const inputEl = this.deps.getInputEl();
|
|
const imageContextManager = this.deps.getImageContextManager();
|
|
const fileContextManager = this.deps.getFileContextManager();
|
|
const mcpServerSelector = this.deps.getMcpServerSelector();
|
|
if (plugin.settings.permissionMode !== "plan") {
|
|
await this.sendMessage({ promptPrefix: PLAN_MODE_REQUEST_PREFIX });
|
|
return;
|
|
}
|
|
this.ensurePlanModeState((_b = (_a = state.planModeState) == null ? void 0 : _a.agentInitiated) != null ? _b : false);
|
|
const content = ((_c = options == null ? void 0 : options.content) != null ? _c : inputEl.value).trim();
|
|
if (!content) return;
|
|
const skipUserMessage = (_d = options == null ? void 0 : options.skipUserMessage) != null ? _d : false;
|
|
if ((options == null ? void 0 : options.content) === void 0) {
|
|
inputEl.value = "";
|
|
}
|
|
state.isStreaming = true;
|
|
state.cancelRequested = false;
|
|
state.ignoreUsageUpdates = false;
|
|
state.subagentsSpawnedThisStream = 0;
|
|
const welcomeEl = this.deps.getWelcomeEl();
|
|
if (welcomeEl) {
|
|
welcomeEl.style.display = "none";
|
|
}
|
|
fileContextManager == null ? void 0 : fileContextManager.startSession();
|
|
const images = skipUserMessage ? (_e = options == null ? void 0 : options.images) != null ? _e : [] : (_f = options == null ? void 0 : options.images) != null ? _f : (imageContextManager == null ? void 0 : imageContextManager.getAttachedImages()) || [];
|
|
const imagesForMessage = images.length > 0 ? [...images] : void 0;
|
|
if (!skipUserMessage && !(options == null ? void 0 : options.images)) {
|
|
imageContextManager == null ? void 0 : imageContextManager.clearImages();
|
|
}
|
|
let currentNote = null;
|
|
let shouldSendCurrentNote = false;
|
|
let currentNoteForMessage;
|
|
if (skipUserMessage || (options == null ? void 0 : options.currentNote)) {
|
|
currentNote = (options == null ? void 0 : options.currentNote) || null;
|
|
} else {
|
|
currentNote = (fileContextManager == null ? void 0 : fileContextManager.getCurrentNotePath()) || null;
|
|
}
|
|
shouldSendCurrentNote = (_g = fileContextManager == null ? void 0 : fileContextManager.shouldSendCurrentNote(currentNote)) != null ? _g : false;
|
|
if (shouldSendCurrentNote && currentNote) {
|
|
currentNoteForMessage = currentNote;
|
|
}
|
|
const editorContext = (_h = options == null ? void 0 : options.editorContext) != null ? _h : selectionController.getContext();
|
|
let promptToSend = `[Plan Mode]
|
|
Explore the codebase and create an implementation plan. Call the ExitPlanMode tool when the plan is ready for user approval.
|
|
|
|
<query>
|
|
${content}
|
|
</query>`;
|
|
if (editorContext) {
|
|
promptToSend = prependEditorContext(promptToSend, editorContext);
|
|
}
|
|
if (shouldSendCurrentNote && currentNote) {
|
|
promptToSend = prependCurrentNote(promptToSend, currentNote);
|
|
currentNoteForMessage = currentNote;
|
|
}
|
|
fileContextManager == null ? void 0 : fileContextManager.markCurrentNoteSent();
|
|
if (!skipUserMessage) {
|
|
const displayContent = (_i = options == null ? void 0 : options.displayContent) != null ? _i : content;
|
|
const userMsg = {
|
|
id: this.deps.generateId(),
|
|
role: "user",
|
|
content,
|
|
displayContent: displayContent !== content ? displayContent : void 0,
|
|
timestamp: Date.now(),
|
|
currentNote: currentNoteForMessage,
|
|
images: imagesForMessage,
|
|
hidden: options == null ? void 0 : options.hidden
|
|
};
|
|
state.addMessage(userMsg);
|
|
if (!(options == null ? void 0 : options.hidden)) {
|
|
renderer.addMessage(userMsg);
|
|
}
|
|
}
|
|
const assistantMsg = {
|
|
id: this.deps.generateId(),
|
|
role: "assistant",
|
|
content: "",
|
|
timestamp: Date.now(),
|
|
toolCalls: [],
|
|
contentBlocks: []
|
|
};
|
|
state.addMessage(assistantMsg);
|
|
const msgEl = renderer.addMessage(assistantMsg);
|
|
const contentEl = msgEl.querySelector(".claudian-message-content");
|
|
state.toolCallElements.clear();
|
|
state.currentContentEl = contentEl;
|
|
state.currentTextEl = null;
|
|
state.currentTextContent = "";
|
|
streamController.showThinkingIndicator(contentEl);
|
|
const mcpMentions = plugin.mcpService.extractMentions(promptToSend);
|
|
promptToSend = plugin.mcpService.transformMentions(promptToSend);
|
|
const enabledMcpServers = mcpServerSelector == null ? void 0 : mcpServerSelector.getEnabledServers();
|
|
const queryOptions = {
|
|
...options == null ? void 0 : options.queryOptions,
|
|
planMode: true,
|
|
mcpMentions,
|
|
enabledMcpServers
|
|
};
|
|
let wasInterrupted = false;
|
|
try {
|
|
for await (const chunk of plugin.agentService.query(promptToSend, imagesForMessage, state.messages, queryOptions)) {
|
|
if (state.cancelRequested) {
|
|
wasInterrupted = true;
|
|
break;
|
|
}
|
|
await streamController.handleStreamChunk(chunk, assistantMsg);
|
|
}
|
|
} catch (error2) {
|
|
const errorMsg = error2 instanceof Error ? error2.message : "Unknown error";
|
|
await streamController.appendText(`
|
|
|
|
**Error:** ${errorMsg}`);
|
|
} finally {
|
|
if (wasInterrupted) {
|
|
await streamController.appendText('\n\n<span class="claudian-interrupted">Plan mode interrupted</span>');
|
|
plugin.agentService.setCurrentPlanFilePath(null);
|
|
}
|
|
streamController.hideThinkingIndicator();
|
|
state.isStreaming = false;
|
|
state.cancelRequested = false;
|
|
state.currentContentEl = null;
|
|
streamController.finalizeCurrentThinkingBlock(assistantMsg);
|
|
streamController.finalizeCurrentTextBlock(assistantMsg);
|
|
state.activeSubagents.clear();
|
|
await conversationController.save(true);
|
|
await this.activatePendingPlanMode();
|
|
await this.triggerTitleGeneration({ isPlanMode: true });
|
|
this.processQueuedMessage();
|
|
}
|
|
}
|
|
// ============================================
|
|
// Queue Management
|
|
// ============================================
|
|
/** Updates the queue indicator UI. */
|
|
updateQueueIndicator() {
|
|
var _a, _b;
|
|
const { state } = this.deps;
|
|
if (!state.queueIndicatorEl) return;
|
|
if (state.queuedMessage) {
|
|
const rawContent = state.queuedMessage.content.trim();
|
|
const preview = rawContent.length > 40 ? rawContent.slice(0, 40) + "..." : rawContent;
|
|
const hasImages = ((_b = (_a = state.queuedMessage.images) == null ? void 0 : _a.length) != null ? _b : 0) > 0;
|
|
let display = preview;
|
|
if (hasImages) {
|
|
display = display ? `${display} [images]` : "[images]";
|
|
}
|
|
state.queueIndicatorEl.setText(`\u2319 Queued: ${display}`);
|
|
state.queueIndicatorEl.style.display = "block";
|
|
} else {
|
|
state.queueIndicatorEl.style.display = "none";
|
|
}
|
|
}
|
|
/** Clears the queued message. */
|
|
clearQueuedMessage() {
|
|
const { state } = this.deps;
|
|
state.queuedMessage = null;
|
|
this.updateQueueIndicator();
|
|
}
|
|
/** Processes the queued message. */
|
|
processQueuedMessage() {
|
|
var _a;
|
|
const { state } = this.deps;
|
|
if (!state.queuedMessage) return;
|
|
const { content, images, editorContext, hidden, promptPrefix } = state.queuedMessage;
|
|
state.queuedMessage = null;
|
|
this.updateQueueIndicator();
|
|
const isPlanMode = this.deps.plugin.settings.permissionMode === "plan";
|
|
if (isPlanMode) {
|
|
setTimeout(
|
|
() => this.sendMessageWithPlanMode({ content, images, editorContext, hidden }),
|
|
0
|
|
);
|
|
return;
|
|
}
|
|
const inputEl = this.deps.getInputEl();
|
|
inputEl.value = content;
|
|
if (images && images.length > 0) {
|
|
(_a = this.deps.getImageContextManager()) == null ? void 0 : _a.setImages(images);
|
|
}
|
|
setTimeout(() => this.sendMessage({ editorContextOverride: editorContext, hidden, promptPrefix }), 0);
|
|
}
|
|
// ============================================
|
|
// Title Generation
|
|
// ============================================
|
|
/**
|
|
* Triggers AI title generation after first exchange.
|
|
* Handles setting fallback title, firing async generation, and updating UI.
|
|
*/
|
|
async triggerTitleGeneration(options = {}) {
|
|
var _a;
|
|
const { plugin, state, conversationController } = this.deps;
|
|
const { isPlanMode = false } = options;
|
|
if (state.messages.length !== 2 || !state.currentConversationId) {
|
|
return;
|
|
}
|
|
const firstUserMsg = state.messages.find((m) => m.role === "user");
|
|
const firstAssistantMsg = state.messages.find((m) => m.role === "assistant");
|
|
if (!firstUserMsg || !firstAssistantMsg) {
|
|
return;
|
|
}
|
|
const userContent = firstUserMsg.displayContent || firstUserMsg.content;
|
|
const assistantText = firstAssistantMsg.content || ((_a = firstAssistantMsg.contentBlocks) == null ? void 0 : _a.filter((b) => b.type === "text").map((b) => b.content).join("\n")) || "";
|
|
const fallbackTitle = conversationController.generateFallbackTitle(userContent);
|
|
const displayTitle = isPlanMode ? `[Plan] ${fallbackTitle}` : fallbackTitle;
|
|
await plugin.renameConversation(state.currentConversationId, displayTitle);
|
|
if (!plugin.settings.enableAutoTitleGeneration) {
|
|
return;
|
|
}
|
|
const titleService = this.deps.getTitleGenerationService();
|
|
if (!titleService || !assistantText) {
|
|
return;
|
|
}
|
|
await plugin.updateConversation(state.currentConversationId, { titleGenerationStatus: "pending" });
|
|
conversationController.updateHistoryDropdown();
|
|
const convId = state.currentConversationId;
|
|
const expectedTitle = displayTitle;
|
|
titleService.generateTitle(
|
|
convId,
|
|
userContent,
|
|
assistantText,
|
|
async (conversationId, result) => {
|
|
const currentConv = plugin.getConversationById(conversationId);
|
|
if (!currentConv) return;
|
|
const userManuallyRenamed = currentConv.title !== expectedTitle;
|
|
if (result.success && !userManuallyRenamed) {
|
|
const newTitle = isPlanMode ? `[Plan] ${result.title}` : result.title;
|
|
await plugin.renameConversation(conversationId, newTitle);
|
|
await plugin.updateConversation(conversationId, { titleGenerationStatus: "success" });
|
|
} else if (!userManuallyRenamed) {
|
|
await plugin.updateConversation(conversationId, { titleGenerationStatus: "failed" });
|
|
} else {
|
|
await plugin.updateConversation(conversationId, { titleGenerationStatus: void 0 });
|
|
}
|
|
conversationController.updateHistoryDropdown();
|
|
}
|
|
).catch((error2) => {
|
|
console.error("[InputController] Title generation failed:", error2 instanceof Error ? error2.message : error2);
|
|
});
|
|
}
|
|
// ============================================
|
|
// Streaming Control
|
|
// ============================================
|
|
/** Cancels the current streaming operation. */
|
|
cancelStreaming() {
|
|
const { plugin, state, streamController } = this.deps;
|
|
if (!state.isStreaming) return;
|
|
state.cancelRequested = true;
|
|
this.clearQueuedMessage();
|
|
plugin.agentService.cancel();
|
|
streamController.hideThinkingIndicator();
|
|
}
|
|
// ============================================
|
|
// Instruction Mode
|
|
// ============================================
|
|
/** Handles instruction mode submission. */
|
|
async handleInstructionSubmit(rawInstruction) {
|
|
const { plugin } = this.deps;
|
|
const instructionRefineService = this.deps.getInstructionRefineService();
|
|
const instructionModeManager = this.deps.getInstructionModeManager();
|
|
if (!instructionRefineService) return;
|
|
const existingPrompt = plugin.settings.systemPrompt;
|
|
let modal = null;
|
|
let wasCancelled = false;
|
|
try {
|
|
modal = new InstructionModal(
|
|
plugin.app,
|
|
rawInstruction,
|
|
{
|
|
onAccept: async (finalInstruction) => {
|
|
const currentPrompt = plugin.settings.systemPrompt;
|
|
plugin.settings.systemPrompt = appendMarkdownSnippet(currentPrompt, finalInstruction);
|
|
await plugin.saveSettings();
|
|
new import_obsidian22.Notice("Instruction added to custom system prompt");
|
|
instructionModeManager == null ? void 0 : instructionModeManager.clear();
|
|
},
|
|
onReject: () => {
|
|
wasCancelled = true;
|
|
instructionRefineService.cancel();
|
|
instructionModeManager == null ? void 0 : instructionModeManager.clear();
|
|
},
|
|
onClarificationSubmit: async (response) => {
|
|
const result2 = await instructionRefineService.continueConversation(response);
|
|
if (wasCancelled) {
|
|
return;
|
|
}
|
|
if (!result2.success) {
|
|
if (result2.error === "Cancelled") {
|
|
return;
|
|
}
|
|
new import_obsidian22.Notice(result2.error || "Failed to process response");
|
|
modal == null ? void 0 : modal.showError(result2.error || "Failed to process response");
|
|
return;
|
|
}
|
|
if (result2.clarification) {
|
|
modal == null ? void 0 : modal.showClarification(result2.clarification);
|
|
} else if (result2.refinedInstruction) {
|
|
modal == null ? void 0 : modal.showConfirmation(result2.refinedInstruction);
|
|
}
|
|
}
|
|
}
|
|
);
|
|
modal.open();
|
|
instructionRefineService.resetConversation();
|
|
const result = await instructionRefineService.refineInstruction(
|
|
rawInstruction,
|
|
existingPrompt
|
|
);
|
|
if (wasCancelled) {
|
|
return;
|
|
}
|
|
if (!result.success) {
|
|
if (result.error === "Cancelled") {
|
|
instructionModeManager == null ? void 0 : instructionModeManager.clear();
|
|
return;
|
|
}
|
|
new import_obsidian22.Notice(result.error || "Failed to refine instruction");
|
|
modal.showError(result.error || "Failed to refine instruction");
|
|
instructionModeManager == null ? void 0 : instructionModeManager.clear();
|
|
return;
|
|
}
|
|
if (result.clarification) {
|
|
modal.showClarification(result.clarification);
|
|
} else if (result.refinedInstruction) {
|
|
modal.showConfirmation(result.refinedInstruction);
|
|
} else {
|
|
new import_obsidian22.Notice("No instruction received");
|
|
modal.showError("No instruction received");
|
|
instructionModeManager == null ? void 0 : instructionModeManager.clear();
|
|
}
|
|
} catch (error2) {
|
|
const errorMsg = error2 instanceof Error ? error2.message : "Unknown error";
|
|
new import_obsidian22.Notice(`Error: ${errorMsg}`);
|
|
modal == null ? void 0 : modal.showError(errorMsg);
|
|
instructionModeManager == null ? void 0 : instructionModeManager.clear();
|
|
}
|
|
}
|
|
// ============================================
|
|
// Approval Dialogs
|
|
// ============================================
|
|
/** Handles tool approval requests. */
|
|
async handleApprovalRequest(toolName, input, description) {
|
|
const { plugin } = this.deps;
|
|
return new Promise((resolve7) => {
|
|
const modal = new ApprovalModal(plugin.app, toolName, input, description, resolve7);
|
|
modal.open();
|
|
});
|
|
}
|
|
/** Requests approval for inline bash commands. */
|
|
async requestInlineBashApproval(command) {
|
|
const { plugin } = this.deps;
|
|
const description = `Execute inline bash command:
|
|
${command}`;
|
|
return new Promise((resolve7) => {
|
|
const modal = new ApprovalModal(
|
|
plugin.app,
|
|
TOOL_BASH,
|
|
{ command },
|
|
description,
|
|
(decision) => resolve7(decision === "allow" || decision === "allow-always"),
|
|
{ showAlwaysAllow: false, title: "Inline bash execution" }
|
|
);
|
|
modal.open();
|
|
});
|
|
}
|
|
/** Handles AskUserQuestion tool calls by showing a floating panel. */
|
|
async handleAskUserQuestion(input) {
|
|
const { plugin } = this.deps;
|
|
const messagesEl = this.deps.getMessagesEl();
|
|
const containerEl = messagesEl.parentElement;
|
|
if (!containerEl) {
|
|
return null;
|
|
}
|
|
return showAskUserQuestionPanel(plugin.app, containerEl, input);
|
|
}
|
|
// ============================================
|
|
// Plan Mode Approval
|
|
// ============================================
|
|
/** Handles ExitPlanMode tool by showing plan approval panel. */
|
|
async handleExitPlanMode(planContent) {
|
|
const { state, renderer, conversationController, streamController } = this.deps;
|
|
const messagesEl = this.deps.getMessagesEl();
|
|
const containerEl = messagesEl.parentElement;
|
|
if (!containerEl) {
|
|
return { decision: "cancel" };
|
|
}
|
|
if (state.planModeState) {
|
|
state.planModeState.planContent = planContent;
|
|
}
|
|
streamController.hideThinkingIndicator();
|
|
const planMsg = {
|
|
id: this.deps.generateId(),
|
|
role: "assistant",
|
|
content: planContent,
|
|
timestamp: Date.now(),
|
|
isPlanMessage: true
|
|
};
|
|
state.addMessage(planMsg);
|
|
renderer.addMessage(planMsg);
|
|
const lastMsgEl = messagesEl.lastElementChild;
|
|
if (lastMsgEl) {
|
|
lastMsgEl.classList.add("claudian-message-plan");
|
|
const contentEl = lastMsgEl.querySelector(".claudian-message-content");
|
|
if (contentEl) {
|
|
const textEl = contentEl.createDiv({ cls: "claudian-text-block" });
|
|
await renderer.renderContent(textEl, planContent);
|
|
state.currentContentEl = contentEl;
|
|
state.currentTextEl = null;
|
|
state.currentTextContent = "";
|
|
state.currentThinkingState = null;
|
|
}
|
|
}
|
|
renderer.scrollToBottom();
|
|
state.pendingPlanContent = planContent;
|
|
await conversationController.save();
|
|
return this.showApprovalPanelAndHandleDecision(planContent, containerEl);
|
|
}
|
|
/**
|
|
* Restores pending plan approval panel when loading a conversation.
|
|
* Called when a conversation with pendingPlanContent is loaded.
|
|
*/
|
|
restorePendingPlanApproval(planContent) {
|
|
const messagesEl = this.deps.getMessagesEl();
|
|
const containerEl = messagesEl.parentElement;
|
|
if (!containerEl) {
|
|
return;
|
|
}
|
|
void this.showApprovalPanelAndHandleDecision(planContent, containerEl);
|
|
}
|
|
/** Shows approval panel and handles the decision. */
|
|
async showApprovalPanelAndHandleDecision(planContent, containerEl) {
|
|
const { plugin, state, conversationController } = this.deps;
|
|
const result = await showPlanApprovalPanel(
|
|
plugin.app,
|
|
containerEl,
|
|
planContent,
|
|
this.deps.getComponent()
|
|
);
|
|
state.pendingPlanContent = null;
|
|
if (result.decision === "approve") {
|
|
this.addApprovalIndicator("approve");
|
|
plugin.agentService.setApprovedPlanContent(planContent);
|
|
const planBanner = this.deps.getPlanBanner();
|
|
if (planBanner) {
|
|
void planBanner.show(planContent);
|
|
}
|
|
await this.exitPlanPermissionMode();
|
|
plugin.agentService.setCurrentPlanFilePath(null);
|
|
await conversationController.save();
|
|
setTimeout(
|
|
() => this.sendMessage({ hidden: true, content: "Please implement the approved plan." }),
|
|
100
|
|
);
|
|
return { decision: "approve" };
|
|
} else if (result.decision === "approve_new_session") {
|
|
this.addApprovalIndicator("approve_new_session");
|
|
const planBanner = this.deps.getPlanBanner();
|
|
if (planBanner) {
|
|
void planBanner.show(planContent);
|
|
}
|
|
await this.exitPlanPermissionMode();
|
|
plugin.agentService.setCurrentPlanFilePath(null);
|
|
plugin.agentService.resetSession();
|
|
plugin.agentService.setApprovedPlanContent(planContent);
|
|
state.ignoreUsageUpdates = true;
|
|
state.usage = null;
|
|
this.deps.resetContextMeter();
|
|
await conversationController.save();
|
|
setTimeout(
|
|
() => this.sendMessage({ hidden: true, content: "Please implement the approved plan." }),
|
|
100
|
|
);
|
|
return { decision: "approve_new_session" };
|
|
} else if (result.decision === "revise") {
|
|
this.addApprovalIndicator("revise", result.feedback);
|
|
await conversationController.save();
|
|
plugin.agentService.setCurrentPlanFilePath(null);
|
|
setTimeout(
|
|
() => this.sendMessageWithPlanMode({ content: result.feedback, hidden: true, images: [] }),
|
|
100
|
|
);
|
|
return { decision: "revise", feedback: result.feedback };
|
|
} else {
|
|
plugin.agentService.setCurrentPlanFilePath(null);
|
|
await conversationController.save();
|
|
return { decision: "cancel" };
|
|
}
|
|
}
|
|
/** Hides the plan banner. */
|
|
hidePlanBanner() {
|
|
const planBanner = this.deps.getPlanBanner();
|
|
if (planBanner) {
|
|
planBanner.hide();
|
|
}
|
|
}
|
|
/** Adds an approval indicator message to the chat. */
|
|
addApprovalIndicator(type, feedback) {
|
|
const { state, renderer } = this.deps;
|
|
const indicatorMsg = {
|
|
id: `indicator-${Date.now()}`,
|
|
role: "user",
|
|
content: "",
|
|
// Empty content, rendered via approvalIndicator
|
|
timestamp: Date.now(),
|
|
approvalIndicator: {
|
|
type,
|
|
feedback
|
|
}
|
|
};
|
|
state.addMessage(indicatorMsg);
|
|
renderer.addMessage(indicatorMsg);
|
|
renderer.scrollToBottom();
|
|
}
|
|
};
|
|
|
|
// src/features/chat/controllers/NavigationController.ts
|
|
var SCROLL_SPEED = 8;
|
|
var NavigationController = class {
|
|
constructor(deps) {
|
|
this.scrollDirection = null;
|
|
this.animationFrameId = null;
|
|
this.initialized = false;
|
|
this.disposed = false;
|
|
this.scrollLoop = () => {
|
|
if (this.scrollDirection === null || this.disposed) return;
|
|
const messagesEl = this.deps.getMessagesEl();
|
|
if (!messagesEl) {
|
|
this.stopScrolling();
|
|
return;
|
|
}
|
|
const scrollAmount = this.scrollDirection === "up" ? -SCROLL_SPEED : SCROLL_SPEED;
|
|
messagesEl.scrollTop += scrollAmount;
|
|
this.animationFrameId = requestAnimationFrame(this.scrollLoop);
|
|
};
|
|
this.deps = deps;
|
|
this.boundMessagesKeydown = this.handleMessagesKeydown.bind(this);
|
|
this.boundKeyup = this.handleKeyup.bind(this);
|
|
this.boundInputKeydown = this.handleInputKeydown.bind(this);
|
|
}
|
|
// ============================================
|
|
// Lifecycle
|
|
// ============================================
|
|
/** Initializes navigation by making messagesEl focusable and attaching listeners. */
|
|
initialize() {
|
|
if (this.initialized || this.disposed) return;
|
|
const messagesEl = this.deps.getMessagesEl();
|
|
const inputEl = this.deps.getInputEl();
|
|
if (!messagesEl || !inputEl) return;
|
|
messagesEl.setAttribute("tabindex", "0");
|
|
messagesEl.addClass("claudian-messages-focusable");
|
|
messagesEl.addEventListener("keydown", this.boundMessagesKeydown);
|
|
document.addEventListener("keyup", this.boundKeyup);
|
|
inputEl.addEventListener("keydown", this.boundInputKeydown, { capture: true });
|
|
this.initialized = true;
|
|
}
|
|
/** Cleans up event listeners and animation frames. */
|
|
dispose() {
|
|
if (this.disposed) return;
|
|
this.disposed = true;
|
|
this.stopScrolling();
|
|
document.removeEventListener("keyup", this.boundKeyup);
|
|
const messagesEl = this.deps.getMessagesEl();
|
|
messagesEl == null ? void 0 : messagesEl.removeEventListener("keydown", this.boundMessagesKeydown);
|
|
messagesEl == null ? void 0 : messagesEl.removeClass("claudian-messages-focusable");
|
|
const inputEl = this.deps.getInputEl();
|
|
inputEl == null ? void 0 : inputEl.removeEventListener("keydown", this.boundInputKeydown, { capture: true });
|
|
}
|
|
// ============================================
|
|
// Messages Panel Keyboard Handling
|
|
// ============================================
|
|
handleMessagesKeydown(e) {
|
|
if (e.ctrlKey || e.metaKey || e.altKey || e.shiftKey) return;
|
|
const settings = this.deps.getSettings();
|
|
const key = e.key.toLowerCase();
|
|
if (key === settings.scrollUpKey.toLowerCase()) {
|
|
e.preventDefault();
|
|
this.startScrolling("up");
|
|
return;
|
|
}
|
|
if (key === settings.scrollDownKey.toLowerCase()) {
|
|
e.preventDefault();
|
|
this.startScrolling("down");
|
|
return;
|
|
}
|
|
if (key === settings.focusInputKey.toLowerCase()) {
|
|
e.preventDefault();
|
|
this.deps.getInputEl().focus();
|
|
return;
|
|
}
|
|
}
|
|
handleKeyup(e) {
|
|
const settings = this.deps.getSettings();
|
|
const key = e.key.toLowerCase();
|
|
if (key === settings.scrollUpKey.toLowerCase() || key === settings.scrollDownKey.toLowerCase()) {
|
|
this.stopScrolling();
|
|
}
|
|
}
|
|
// ============================================
|
|
// Input Keyboard Handling (Escape)
|
|
// ============================================
|
|
handleInputKeydown(e) {
|
|
var _a, _b;
|
|
if (e.key !== "Escape") return;
|
|
if (this.deps.isStreaming()) {
|
|
return;
|
|
}
|
|
try {
|
|
if ((_b = (_a = this.deps).shouldSkipEscapeHandling) == null ? void 0 : _b.call(_a)) {
|
|
return;
|
|
}
|
|
} catch (e2) {
|
|
}
|
|
e.preventDefault();
|
|
e.stopPropagation();
|
|
this.deps.getInputEl().blur();
|
|
this.deps.getMessagesEl().focus();
|
|
}
|
|
// ============================================
|
|
// Continuous Scrolling with requestAnimationFrame
|
|
// ============================================
|
|
startScrolling(direction) {
|
|
if (this.scrollDirection === direction) {
|
|
return;
|
|
}
|
|
this.scrollDirection = direction;
|
|
this.scrollLoop();
|
|
}
|
|
stopScrolling() {
|
|
this.scrollDirection = null;
|
|
if (this.animationFrameId !== null) {
|
|
cancelAnimationFrame(this.animationFrameId);
|
|
this.animationFrameId = null;
|
|
}
|
|
}
|
|
// ============================================
|
|
// Public API
|
|
// ============================================
|
|
/** Focuses the messages panel. */
|
|
focusMessages() {
|
|
this.deps.getMessagesEl().focus();
|
|
}
|
|
/** Focuses the input. */
|
|
focusInput() {
|
|
this.deps.getInputEl().focus();
|
|
}
|
|
};
|
|
|
|
// src/features/chat/controllers/SelectionController.ts
|
|
var import_obsidian23 = require("obsidian");
|
|
var SELECTION_POLL_INTERVAL = 250;
|
|
var SelectionController = class {
|
|
constructor(app, indicatorEl, inputEl) {
|
|
this.storedSelection = null;
|
|
this.pollInterval = null;
|
|
this.app = app;
|
|
this.indicatorEl = indicatorEl;
|
|
this.inputEl = inputEl;
|
|
}
|
|
// ============================================
|
|
// Lifecycle
|
|
// ============================================
|
|
/** Starts polling for editor selection changes. */
|
|
start() {
|
|
if (this.pollInterval) return;
|
|
this.pollInterval = setInterval(() => this.poll(), SELECTION_POLL_INTERVAL);
|
|
}
|
|
/** Stops polling and clears state. */
|
|
stop() {
|
|
if (this.pollInterval) {
|
|
clearInterval(this.pollInterval);
|
|
this.pollInterval = null;
|
|
}
|
|
this.clear();
|
|
}
|
|
/** Cleans up resources. Same as stop(). */
|
|
dispose() {
|
|
this.stop();
|
|
}
|
|
// ============================================
|
|
// Selection Polling
|
|
// ============================================
|
|
/** Polls editor selection and updates stored selection. */
|
|
poll() {
|
|
var _a, _b, _c, _d;
|
|
const view = this.app.workspace.getActiveViewOfType(import_obsidian23.MarkdownView);
|
|
if (!view) return;
|
|
const editor = view.editor;
|
|
const editorView = editor.cm;
|
|
if (!editorView) return;
|
|
const selectedText = editor.getSelection();
|
|
if (selectedText.trim()) {
|
|
const fromPos = editor.getCursor("from");
|
|
const toPos = editor.getCursor("to");
|
|
const from = editor.posToOffset(fromPos);
|
|
const to = editor.posToOffset(toPos);
|
|
const startLine = fromPos.line + 1;
|
|
const notePath = ((_a = view.file) == null ? void 0 : _a.path) || "unknown";
|
|
const lineCount = selectedText.split(/\r?\n/).length;
|
|
const sameRange = this.storedSelection && this.storedSelection.editorView === editorView && this.storedSelection.from === from && this.storedSelection.to === to && this.storedSelection.notePath === notePath;
|
|
const sameText = sameRange && ((_b = this.storedSelection) == null ? void 0 : _b.selectedText) === selectedText;
|
|
const sameLineCount = sameRange && ((_c = this.storedSelection) == null ? void 0 : _c.lineCount) === lineCount;
|
|
const sameStartLine = sameRange && ((_d = this.storedSelection) == null ? void 0 : _d.startLine) === startLine;
|
|
if (!sameRange || !sameText || !sameLineCount || !sameStartLine) {
|
|
if (this.storedSelection && !sameRange) {
|
|
this.clearHighlight();
|
|
}
|
|
this.storedSelection = { notePath, selectedText, lineCount, startLine, from, to, editorView };
|
|
this.updateIndicator();
|
|
}
|
|
} else if (document.activeElement !== this.inputEl) {
|
|
this.clearHighlight();
|
|
this.storedSelection = null;
|
|
this.updateIndicator();
|
|
}
|
|
}
|
|
// ============================================
|
|
// Highlight Management
|
|
// ============================================
|
|
/** Shows the selection highlight in the editor. */
|
|
showHighlight() {
|
|
if (!this.storedSelection) return;
|
|
const { from, to, editorView } = this.storedSelection;
|
|
showSelectionHighlight(editorView, from, to);
|
|
}
|
|
/** Clears the selection highlight from the editor. */
|
|
clearHighlight() {
|
|
if (!this.storedSelection) return;
|
|
hideSelectionHighlight(this.storedSelection.editorView);
|
|
}
|
|
// ============================================
|
|
// Indicator
|
|
// ============================================
|
|
/** Updates selection indicator based on stored selection. */
|
|
updateIndicator() {
|
|
if (!this.indicatorEl) return;
|
|
if (this.storedSelection) {
|
|
const lineText = this.storedSelection.lineCount === 1 ? "line" : "lines";
|
|
this.indicatorEl.textContent = `${this.storedSelection.lineCount} ${lineText} selected`;
|
|
this.indicatorEl.style.display = "block";
|
|
} else {
|
|
this.indicatorEl.style.display = "none";
|
|
}
|
|
}
|
|
// ============================================
|
|
// Context Access
|
|
// ============================================
|
|
/** Returns stored selection as EditorSelectionContext, or null if none. */
|
|
getContext() {
|
|
if (!this.storedSelection) return null;
|
|
return {
|
|
notePath: this.storedSelection.notePath,
|
|
mode: "selection",
|
|
selectedText: this.storedSelection.selectedText,
|
|
lineCount: this.storedSelection.lineCount,
|
|
startLine: this.storedSelection.startLine
|
|
};
|
|
}
|
|
/** Checks if there is a stored selection. */
|
|
hasSelection() {
|
|
return this.storedSelection !== null;
|
|
}
|
|
// ============================================
|
|
// Clear
|
|
// ============================================
|
|
/** Clears the stored selection and highlight. */
|
|
clear() {
|
|
this.clearHighlight();
|
|
this.storedSelection = null;
|
|
this.updateIndicator();
|
|
}
|
|
};
|
|
|
|
// src/features/chat/controllers/StreamController.ts
|
|
var StreamController = class {
|
|
constructor(deps) {
|
|
this.deps = deps;
|
|
}
|
|
// ============================================
|
|
// Stream Chunk Handling
|
|
// ============================================
|
|
/** Processes a stream chunk and updates the message. */
|
|
async handleStreamChunk(chunk, msg) {
|
|
var _a;
|
|
const { state, plugin } = this.deps;
|
|
if ("parentToolUseId" in chunk && chunk.parentToolUseId) {
|
|
await this.handleSubagentChunk(chunk, msg);
|
|
this.scrollToBottom();
|
|
return;
|
|
}
|
|
switch (chunk.type) {
|
|
case "thinking":
|
|
if (state.currentTextEl) {
|
|
this.finalizeCurrentTextBlock(msg);
|
|
}
|
|
await this.appendThinking(chunk.content, msg);
|
|
break;
|
|
case "text":
|
|
if (state.currentThinkingState) {
|
|
this.finalizeCurrentThinkingBlock(msg);
|
|
}
|
|
msg.content += chunk.content;
|
|
await this.appendText(chunk.content);
|
|
if (state.currentContentEl) {
|
|
this.showThinkingIndicator(state.currentContentEl);
|
|
}
|
|
break;
|
|
case "tool_use": {
|
|
if (state.currentThinkingState) {
|
|
this.finalizeCurrentThinkingBlock(msg);
|
|
}
|
|
this.finalizeCurrentTextBlock(msg);
|
|
if (chunk.name === TOOL_TASK) {
|
|
state.subagentsSpawnedThisStream++;
|
|
const isAsync2 = this.deps.asyncSubagentManager.isAsyncTask(chunk.input);
|
|
if (isAsync2) {
|
|
await this.handleAsyncTaskToolUse(chunk, msg);
|
|
} else {
|
|
await this.handleTaskToolUse(chunk, msg);
|
|
}
|
|
break;
|
|
}
|
|
if (chunk.name === TOOL_AGENT_OUTPUT) {
|
|
this.handleAgentOutputToolUse(chunk, msg);
|
|
break;
|
|
}
|
|
if (chunk.name === TOOL_ASK_USER_QUESTION) {
|
|
this.handleAskUserQuestionToolUse(chunk, msg);
|
|
break;
|
|
}
|
|
if (isPlanModeTool(chunk.name)) {
|
|
break;
|
|
}
|
|
this.handleRegularToolUse(chunk, msg);
|
|
break;
|
|
}
|
|
case "tool_result": {
|
|
this.handleToolResult(chunk, msg);
|
|
break;
|
|
}
|
|
case "blocked":
|
|
await this.appendText(`
|
|
|
|
\u26A0\uFE0F **Blocked:** ${chunk.content}`);
|
|
break;
|
|
case "error":
|
|
await this.appendText(`
|
|
|
|
\u274C **Error:** ${chunk.content}`);
|
|
break;
|
|
case "done":
|
|
break;
|
|
case "usage": {
|
|
const currentSessionId = plugin.agentService.getSessionId();
|
|
const chunkSessionId = (_a = chunk.sessionId) != null ? _a : null;
|
|
if (chunkSessionId && currentSessionId && chunkSessionId !== currentSessionId || chunkSessionId && !currentSessionId) {
|
|
break;
|
|
}
|
|
if (state.subagentsSpawnedThisStream > 0) {
|
|
break;
|
|
}
|
|
if (!state.ignoreUsageUpdates) {
|
|
state.usage = chunk.usage;
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
this.scrollToBottom();
|
|
}
|
|
// ============================================
|
|
// Tool Use Handling
|
|
// ============================================
|
|
/** Handles regular tool_use chunks. */
|
|
handleRegularToolUse(chunk, msg) {
|
|
const { plugin, state } = this.deps;
|
|
const isPlanMode = plugin.settings.permissionMode === "plan";
|
|
if (isPlanMode && isWriteEditTool(chunk.name)) {
|
|
return;
|
|
}
|
|
const toolCall = {
|
|
id: chunk.id,
|
|
name: chunk.name,
|
|
input: chunk.input,
|
|
status: "running",
|
|
isExpanded: false
|
|
};
|
|
msg.toolCalls = msg.toolCalls || [];
|
|
msg.toolCalls.push(toolCall);
|
|
if (chunk.name === TOOL_TODO_WRITE) {
|
|
const todos = parseTodoInput(chunk.input);
|
|
if (todos) {
|
|
this.deps.state.currentTodos = todos;
|
|
} else {
|
|
console.warn("[StreamController] TodoWrite input parsing failed", {
|
|
toolId: chunk.id,
|
|
inputKeys: Object.keys(chunk.input)
|
|
});
|
|
if (state.currentContentEl) {
|
|
msg.contentBlocks = msg.contentBlocks || [];
|
|
msg.contentBlocks.push({ type: "tool_use", toolId: chunk.id });
|
|
renderToolCall(state.currentContentEl, toolCall, state.toolCallElements);
|
|
}
|
|
}
|
|
} else {
|
|
msg.contentBlocks = msg.contentBlocks || [];
|
|
msg.contentBlocks.push({ type: "tool_use", toolId: chunk.id });
|
|
if (isWriteEditTool(chunk.name)) {
|
|
const writeEditState = createWriteEditBlock(state.currentContentEl, toolCall);
|
|
state.writeEditStates.set(chunk.id, writeEditState);
|
|
state.toolCallElements.set(chunk.id, writeEditState.wrapperEl);
|
|
} else {
|
|
renderToolCall(state.currentContentEl, toolCall, state.toolCallElements);
|
|
}
|
|
}
|
|
if (state.currentContentEl) {
|
|
this.showThinkingIndicator(state.currentContentEl);
|
|
}
|
|
}
|
|
/** Handles AskUserQuestion tool_use chunks. */
|
|
handleAskUserQuestionToolUse(chunk, msg) {
|
|
const { state } = this.deps;
|
|
if (!state.currentContentEl) return;
|
|
const toolCall = {
|
|
id: chunk.id,
|
|
name: chunk.name,
|
|
input: chunk.input,
|
|
status: "running",
|
|
isExpanded: false
|
|
};
|
|
msg.toolCalls = msg.toolCalls || [];
|
|
msg.toolCalls.push(toolCall);
|
|
msg.contentBlocks = msg.contentBlocks || [];
|
|
msg.contentBlocks.push({ type: "tool_use", toolId: chunk.id });
|
|
const askQuestionState = createAskUserQuestionBlock(state.currentContentEl, toolCall);
|
|
state.askUserQuestionStates.set(chunk.id, askQuestionState);
|
|
state.toolCallElements.set(chunk.id, askQuestionState.wrapperEl);
|
|
if (state.currentContentEl) {
|
|
this.showThinkingIndicator(state.currentContentEl);
|
|
}
|
|
}
|
|
/** Handles tool_result chunks. */
|
|
handleToolResult(chunk, msg) {
|
|
var _a;
|
|
const { plugin, state } = this.deps;
|
|
const subagentState = state.activeSubagents.get(chunk.id);
|
|
if (subagentState) {
|
|
this.finalizeSubagent(chunk, msg, subagentState);
|
|
return;
|
|
}
|
|
if (this.handleAsyncTaskToolResult(chunk, msg)) {
|
|
if (state.currentContentEl) {
|
|
this.showThinkingIndicator(state.currentContentEl);
|
|
}
|
|
return;
|
|
}
|
|
if (this.handleAgentOutputToolResult(chunk, msg)) {
|
|
if (state.currentContentEl) {
|
|
this.showThinkingIndicator(state.currentContentEl);
|
|
}
|
|
return;
|
|
}
|
|
const existingToolCall = (_a = msg.toolCalls) == null ? void 0 : _a.find((tc) => tc.id === chunk.id);
|
|
const askQuestionState = state.askUserQuestionStates.get(chunk.id);
|
|
if ((existingToolCall == null ? void 0 : existingToolCall.name) === TOOL_ASK_USER_QUESTION || askQuestionState) {
|
|
const isBlocked2 = isBlockedToolResult(chunk.content, chunk.isError);
|
|
if (existingToolCall) {
|
|
existingToolCall.status = isBlocked2 ? "blocked" : chunk.isError ? "error" : "completed";
|
|
existingToolCall.result = chunk.content;
|
|
}
|
|
const storedAnswers = plugin.agentService.getAskUserQuestionAnswers(chunk.id);
|
|
const parsed = existingToolCall ? parseAskUserQuestionInput(existingToolCall.input) : null;
|
|
const answers = storedAnswers || (parsed == null ? void 0 : parsed.answers);
|
|
if (existingToolCall && answers) {
|
|
existingToolCall.input = { ...existingToolCall.input, answers };
|
|
}
|
|
if (askQuestionState && existingToolCall) {
|
|
finalizeAskUserQuestionBlock(
|
|
askQuestionState,
|
|
answers,
|
|
chunk.isError || isBlocked2,
|
|
parsed == null ? void 0 : parsed.questions
|
|
);
|
|
}
|
|
if (askQuestionState) {
|
|
state.askUserQuestionStates.delete(chunk.id);
|
|
}
|
|
if (state.currentContentEl) {
|
|
this.showThinkingIndicator(state.currentContentEl);
|
|
}
|
|
return;
|
|
}
|
|
const isBlocked = isBlockedToolResult(chunk.content, chunk.isError);
|
|
if (existingToolCall) {
|
|
existingToolCall.status = isBlocked ? "blocked" : chunk.isError ? "error" : "completed";
|
|
existingToolCall.result = chunk.content;
|
|
const writeEditState = state.writeEditStates.get(chunk.id);
|
|
if (writeEditState && isWriteEditTool(existingToolCall.name)) {
|
|
if (!chunk.isError && !isBlocked) {
|
|
const diffData = plugin.agentService.getDiffData(chunk.id);
|
|
if (diffData) {
|
|
existingToolCall.diffData = diffData;
|
|
updateWriteEditWithDiff(writeEditState, diffData);
|
|
}
|
|
}
|
|
finalizeWriteEditBlock(writeEditState, chunk.isError || isBlocked);
|
|
} else {
|
|
updateToolCallResult(chunk.id, existingToolCall, state.toolCallElements);
|
|
}
|
|
}
|
|
if (state.currentContentEl) {
|
|
this.showThinkingIndicator(state.currentContentEl);
|
|
}
|
|
}
|
|
// ============================================
|
|
// Text Block Management
|
|
// ============================================
|
|
/** Appends text to the current text block. */
|
|
async appendText(text) {
|
|
const { state, renderer } = this.deps;
|
|
if (!state.currentContentEl) return;
|
|
if (!state.currentTextEl) {
|
|
state.currentTextEl = state.currentContentEl.createDiv({ cls: "claudian-text-block" });
|
|
state.currentTextContent = "";
|
|
}
|
|
state.currentTextContent += text;
|
|
await renderer.renderContent(state.currentTextEl, state.currentTextContent);
|
|
}
|
|
/** Finalizes the current text block. */
|
|
finalizeCurrentTextBlock(msg) {
|
|
const { state } = this.deps;
|
|
if (msg && state.currentTextContent) {
|
|
msg.contentBlocks = msg.contentBlocks || [];
|
|
msg.contentBlocks.push({ type: "text", content: state.currentTextContent });
|
|
}
|
|
state.currentTextEl = null;
|
|
state.currentTextContent = "";
|
|
}
|
|
// ============================================
|
|
// Thinking Block Management
|
|
// ============================================
|
|
/** Appends thinking content. */
|
|
async appendThinking(content, msg) {
|
|
const { state, renderer } = this.deps;
|
|
if (!state.currentContentEl) return;
|
|
this.hideThinkingIndicator();
|
|
if (!state.currentThinkingState) {
|
|
state.currentThinkingState = createThinkingBlock(
|
|
state.currentContentEl,
|
|
(el, md) => renderer.renderContent(el, md)
|
|
);
|
|
}
|
|
await appendThinkingContent(state.currentThinkingState, content, (el, md) => renderer.renderContent(el, md));
|
|
}
|
|
/** Finalizes the current thinking block. */
|
|
finalizeCurrentThinkingBlock(msg) {
|
|
const { state } = this.deps;
|
|
if (!state.currentThinkingState) return;
|
|
const durationSeconds = finalizeThinkingBlock(state.currentThinkingState);
|
|
if (state.currentContentEl) {
|
|
this.showThinkingIndicator(state.currentContentEl);
|
|
}
|
|
if (msg && state.currentThinkingState.content) {
|
|
msg.contentBlocks = msg.contentBlocks || [];
|
|
msg.contentBlocks.push({
|
|
type: "thinking",
|
|
content: state.currentThinkingState.content,
|
|
durationSeconds
|
|
});
|
|
}
|
|
state.currentThinkingState = null;
|
|
}
|
|
// ============================================
|
|
// Sync Subagent Handling
|
|
// ============================================
|
|
/** Handles Task tool_use by creating a sync subagent block. */
|
|
async handleTaskToolUse(chunk, msg) {
|
|
const { state } = this.deps;
|
|
if (!state.currentContentEl) return;
|
|
const subagentState = createSubagentBlock(state.currentContentEl, chunk.id, chunk.input);
|
|
state.activeSubagents.set(chunk.id, subagentState);
|
|
msg.subagents = msg.subagents || [];
|
|
msg.subagents.push(subagentState.info);
|
|
msg.contentBlocks = msg.contentBlocks || [];
|
|
msg.contentBlocks.push({ type: "subagent", subagentId: chunk.id });
|
|
if (state.currentContentEl) {
|
|
this.showThinkingIndicator(state.currentContentEl);
|
|
}
|
|
}
|
|
/** Routes chunks from subagents. */
|
|
async handleSubagentChunk(chunk, msg) {
|
|
if (!("parentToolUseId" in chunk) || !chunk.parentToolUseId) {
|
|
return;
|
|
}
|
|
const parentToolUseId = chunk.parentToolUseId;
|
|
const { state } = this.deps;
|
|
const subagentState = state.activeSubagents.get(parentToolUseId);
|
|
if (!subagentState) {
|
|
return;
|
|
}
|
|
switch (chunk.type) {
|
|
case "tool_use": {
|
|
const toolCall = {
|
|
id: chunk.id,
|
|
name: chunk.name,
|
|
input: chunk.input,
|
|
status: "running",
|
|
isExpanded: false
|
|
};
|
|
addSubagentToolCall(subagentState, toolCall);
|
|
if (state.currentContentEl) {
|
|
this.showThinkingIndicator(state.currentContentEl);
|
|
}
|
|
break;
|
|
}
|
|
case "tool_result": {
|
|
const toolCall = subagentState.info.toolCalls.find((tc) => tc.id === chunk.id);
|
|
if (toolCall) {
|
|
const isBlocked = isBlockedToolResult(chunk.content, chunk.isError);
|
|
toolCall.status = isBlocked ? "blocked" : chunk.isError ? "error" : "completed";
|
|
toolCall.result = chunk.content;
|
|
updateSubagentToolResult(subagentState, chunk.id, toolCall);
|
|
this.deps.plugin.agentService.getDiffData(chunk.id);
|
|
}
|
|
break;
|
|
}
|
|
case "text":
|
|
case "thinking":
|
|
break;
|
|
}
|
|
}
|
|
/** Finalizes a sync subagent when its Task tool_result is received. */
|
|
finalizeSubagent(chunk, msg, subagentState) {
|
|
var _a;
|
|
const { state } = this.deps;
|
|
const isError = chunk.isError || false;
|
|
finalizeSubagentBlock(subagentState, chunk.content, isError);
|
|
const subagentInfo = (_a = msg.subagents) == null ? void 0 : _a.find((s) => s.id === chunk.id);
|
|
if (subagentInfo) {
|
|
subagentInfo.status = isError ? "error" : "completed";
|
|
subagentInfo.result = chunk.content;
|
|
}
|
|
state.activeSubagents.delete(chunk.id);
|
|
if (state.currentContentEl) {
|
|
this.showThinkingIndicator(state.currentContentEl);
|
|
}
|
|
}
|
|
// ============================================
|
|
// Async Subagent Handling
|
|
// ============================================
|
|
/** Handles async Task tool_use (run_in_background=true). */
|
|
async handleAsyncTaskToolUse(chunk, msg) {
|
|
const { state, asyncSubagentManager } = this.deps;
|
|
if (!state.currentContentEl) return;
|
|
const subagentInfo = asyncSubagentManager.createAsyncSubagent(chunk.id, chunk.input);
|
|
const asyncState = createAsyncSubagentBlock(state.currentContentEl, chunk.id, chunk.input);
|
|
state.asyncSubagentStates.set(chunk.id, asyncState);
|
|
msg.subagents = msg.subagents || [];
|
|
msg.subagents.push(subagentInfo);
|
|
msg.contentBlocks = msg.contentBlocks || [];
|
|
msg.contentBlocks.push({ type: "subagent", subagentId: chunk.id, mode: "async" });
|
|
if (state.currentContentEl) {
|
|
this.showThinkingIndicator(state.currentContentEl);
|
|
}
|
|
}
|
|
/** Handles AgentOutputTool tool_use (invisible, links to async subagent). */
|
|
handleAgentOutputToolUse(chunk, _msg) {
|
|
const toolCall = {
|
|
id: chunk.id,
|
|
name: chunk.name,
|
|
input: chunk.input,
|
|
status: "running",
|
|
isExpanded: false
|
|
};
|
|
this.deps.asyncSubagentManager.handleAgentOutputToolUse(toolCall);
|
|
}
|
|
/** Handles async Task tool_result to extract agent_id. */
|
|
handleAsyncTaskToolResult(chunk, _msg) {
|
|
const { asyncSubagentManager } = this.deps;
|
|
if (!asyncSubagentManager.isPendingAsyncTask(chunk.id)) {
|
|
return false;
|
|
}
|
|
asyncSubagentManager.handleTaskToolResult(chunk.id, chunk.content, chunk.isError);
|
|
return true;
|
|
}
|
|
/** Handles AgentOutputTool result to finalize async subagent. */
|
|
handleAgentOutputToolResult(chunk, _msg) {
|
|
const { asyncSubagentManager } = this.deps;
|
|
const isLinked = asyncSubagentManager.isLinkedAgentOutputTool(chunk.id);
|
|
const handled = asyncSubagentManager.handleAgentOutputToolResult(
|
|
chunk.id,
|
|
chunk.content,
|
|
chunk.isError || false
|
|
);
|
|
return isLinked || handled !== void 0;
|
|
}
|
|
/** Callback from AsyncSubagentManager when state changes. */
|
|
onAsyncSubagentStateChange(subagent) {
|
|
const { state } = this.deps;
|
|
let asyncState = state.asyncSubagentStates.get(subagent.id);
|
|
if (!asyncState) {
|
|
for (const s of state.asyncSubagentStates.values()) {
|
|
if (s.info.agentId === subagent.agentId) {
|
|
asyncState = s;
|
|
break;
|
|
}
|
|
}
|
|
if (!asyncState) return;
|
|
}
|
|
this.updateAsyncSubagentUI(asyncState, subagent);
|
|
}
|
|
/** Updates async subagent UI based on state. */
|
|
updateAsyncSubagentUI(asyncState, subagent) {
|
|
asyncState.info = subagent;
|
|
switch (subagent.asyncStatus) {
|
|
case "running":
|
|
updateAsyncSubagentRunning(asyncState, subagent.agentId || "");
|
|
break;
|
|
case "completed":
|
|
case "error":
|
|
finalizeAsyncSubagent(asyncState, subagent.result || "", subagent.asyncStatus === "error");
|
|
break;
|
|
case "orphaned":
|
|
markAsyncSubagentOrphaned(asyncState);
|
|
break;
|
|
}
|
|
this.updateSubagentInMessages(subagent);
|
|
this.scrollToBottom();
|
|
}
|
|
/** Updates subagent info in messages array. */
|
|
updateSubagentInMessages(subagent) {
|
|
const { state } = this.deps;
|
|
for (let i = state.messages.length - 1; i >= 0; i--) {
|
|
const msg = state.messages[i];
|
|
if (msg.role === "assistant" && msg.subagents) {
|
|
const idx = msg.subagents.findIndex((s) => s.id === subagent.id);
|
|
if (idx !== -1) {
|
|
msg.subagents[idx] = subagent;
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
// ============================================
|
|
// Thinking Indicator
|
|
// ============================================
|
|
/** Shows the thinking indicator. */
|
|
showThinkingIndicator(parentEl) {
|
|
const { state } = this.deps;
|
|
if (state.thinkingEl) {
|
|
parentEl.appendChild(state.thinkingEl);
|
|
this.deps.updateQueueIndicator();
|
|
return;
|
|
}
|
|
state.thinkingEl = parentEl.createDiv({ cls: "claudian-thinking" });
|
|
const randomText = FLAVOR_TEXTS[Math.floor(Math.random() * FLAVOR_TEXTS.length)];
|
|
state.thinkingEl.createSpan({ text: randomText });
|
|
state.thinkingEl.createSpan({ text: " (esc to interrupt)", cls: "claudian-thinking-hint" });
|
|
state.queueIndicatorEl = state.thinkingEl.createDiv({ cls: "claudian-queue-indicator" });
|
|
this.deps.updateQueueIndicator();
|
|
}
|
|
/** Hides the thinking indicator. */
|
|
hideThinkingIndicator() {
|
|
const { state } = this.deps;
|
|
if (state.thinkingEl) {
|
|
state.thinkingEl.remove();
|
|
state.thinkingEl = null;
|
|
}
|
|
state.queueIndicatorEl = null;
|
|
}
|
|
// ============================================
|
|
// Utilities
|
|
// ============================================
|
|
/** Scrolls messages to bottom. */
|
|
scrollToBottom() {
|
|
const messagesEl = this.deps.getMessagesEl();
|
|
messagesEl.scrollTop = messagesEl.scrollHeight;
|
|
}
|
|
/** Resets streaming state after completion. */
|
|
resetStreamingState() {
|
|
const { state } = this.deps;
|
|
this.hideThinkingIndicator();
|
|
state.currentContentEl = null;
|
|
state.currentTextEl = null;
|
|
state.currentTextContent = "";
|
|
state.currentThinkingState = null;
|
|
state.activeSubagents.clear();
|
|
}
|
|
};
|
|
|
|
// src/features/chat/rendering/MessageRenderer.ts
|
|
var import_obsidian24 = require("obsidian");
|
|
var MessageRenderer = class {
|
|
constructor(app, component, messagesEl) {
|
|
this.app = app;
|
|
this.component = component;
|
|
this.messagesEl = messagesEl;
|
|
}
|
|
/** Sets the messages container element. */
|
|
setMessagesEl(el) {
|
|
this.messagesEl = el;
|
|
}
|
|
// ============================================
|
|
// Streaming Message Rendering
|
|
// ============================================
|
|
/**
|
|
* Adds a new message to the chat during streaming.
|
|
* Returns the message element for content updates.
|
|
*/
|
|
addMessage(msg) {
|
|
var _a, _b;
|
|
if (msg.hidden) {
|
|
this.ensureTodoPanelAtBottom();
|
|
this.scrollToBottom();
|
|
const lastChild = this.messagesEl.lastElementChild;
|
|
return lastChild != null ? lastChild : this.messagesEl;
|
|
}
|
|
if (msg.approvalIndicator) {
|
|
const indicatorEl = this.renderApprovalIndicator(msg.approvalIndicator);
|
|
this.ensureTodoPanelAtBottom();
|
|
this.scrollToBottom();
|
|
return indicatorEl;
|
|
}
|
|
if (msg.role === "user" && msg.images && msg.images.length > 0) {
|
|
this.renderMessageImages(this.messagesEl, msg.images);
|
|
}
|
|
if (msg.role === "user") {
|
|
const textToShow = (_a = msg.displayContent) != null ? _a : msg.content;
|
|
if (!textToShow) {
|
|
this.ensureTodoPanelAtBottom();
|
|
this.scrollToBottom();
|
|
const lastChild = this.messagesEl.lastElementChild;
|
|
return lastChild != null ? lastChild : this.messagesEl;
|
|
}
|
|
}
|
|
const msgEl = this.messagesEl.createDiv({
|
|
cls: `claudian-message claudian-message-${msg.role}`
|
|
});
|
|
const contentEl = msgEl.createDiv({ cls: "claudian-message-content" });
|
|
if (msg.role === "user") {
|
|
const textToShow = (_b = msg.displayContent) != null ? _b : msg.content;
|
|
if (textToShow) {
|
|
const textEl = contentEl.createDiv({ cls: "claudian-text-block" });
|
|
void this.renderContent(textEl, textToShow);
|
|
}
|
|
}
|
|
this.ensureTodoPanelAtBottom();
|
|
this.scrollToBottom();
|
|
return msgEl;
|
|
}
|
|
// ============================================
|
|
// Stored Message Rendering (Batch/Replay)
|
|
// ============================================
|
|
/**
|
|
* Renders all messages for conversation load/switch.
|
|
* @param messages Array of messages to render
|
|
* @param getGreeting Function to get greeting text
|
|
* @returns The newly created welcome element
|
|
*/
|
|
renderMessages(messages, getGreeting) {
|
|
const existingTodoPanel = this.messagesEl.querySelector(".claudian-todo-panel");
|
|
this.messagesEl.empty();
|
|
const newWelcomeEl = this.messagesEl.createDiv({ cls: "claudian-welcome" });
|
|
newWelcomeEl.createDiv({ cls: "claudian-welcome-greeting", text: getGreeting() });
|
|
for (const msg of messages) {
|
|
this.renderStoredMessage(msg);
|
|
}
|
|
this.ensureTodoPanelAtBottom(existingTodoPanel);
|
|
this.scrollToBottom();
|
|
return newWelcomeEl;
|
|
}
|
|
/**
|
|
* Renders a persisted message from history.
|
|
*/
|
|
renderStoredMessage(msg) {
|
|
var _a, _b;
|
|
if (msg.hidden) {
|
|
return;
|
|
}
|
|
if (msg.approvalIndicator) {
|
|
this.renderApprovalIndicator(msg.approvalIndicator);
|
|
return;
|
|
}
|
|
if (msg.role === "user" && msg.images && msg.images.length > 0) {
|
|
this.renderMessageImages(this.messagesEl, msg.images);
|
|
}
|
|
if (msg.role === "user") {
|
|
const textToShow = (_a = msg.displayContent) != null ? _a : msg.content;
|
|
if (!textToShow) {
|
|
return;
|
|
}
|
|
}
|
|
const msgEl = this.messagesEl.createDiv({
|
|
cls: `claudian-message claudian-message-${msg.role}`
|
|
});
|
|
if (msg.isPlanMessage) {
|
|
msgEl.classList.add("claudian-message-plan");
|
|
}
|
|
const contentEl = msgEl.createDiv({ cls: "claudian-message-content" });
|
|
if (msg.role === "user") {
|
|
const textToShow = (_b = msg.displayContent) != null ? _b : msg.content;
|
|
if (textToShow) {
|
|
const textEl = contentEl.createDiv({ cls: "claudian-text-block" });
|
|
void this.renderContent(textEl, textToShow);
|
|
}
|
|
} else if (msg.role === "assistant") {
|
|
this.renderAssistantContent(msg, contentEl);
|
|
}
|
|
}
|
|
/**
|
|
* Renders an approval indicator for plan mode decisions.
|
|
*/
|
|
renderApprovalIndicator(indicator) {
|
|
const indicatorEl = this.messagesEl.createDiv({
|
|
cls: "claudian-approval-indicator"
|
|
});
|
|
const iconEl = indicatorEl.createSpan({ cls: "claudian-approval-indicator-icon" });
|
|
const textEl = indicatorEl.createSpan({ cls: "claudian-approval-indicator-text" });
|
|
switch (indicator.type) {
|
|
case "approve":
|
|
indicatorEl.classList.add("claudian-approval-indicator-approve");
|
|
(0, import_obsidian24.setIcon)(iconEl, "check");
|
|
textEl.textContent = "User approved plan.";
|
|
break;
|
|
case "approve_new_session":
|
|
indicatorEl.classList.add("claudian-approval-indicator-approve");
|
|
(0, import_obsidian24.setIcon)(iconEl, "check");
|
|
textEl.textContent = "User approved plan, implement in new session.";
|
|
break;
|
|
case "revise":
|
|
indicatorEl.classList.add("claudian-approval-indicator-revise");
|
|
(0, import_obsidian24.setIcon)(iconEl, "x");
|
|
textEl.textContent = indicator.feedback || "User requested revision.";
|
|
break;
|
|
}
|
|
return indicatorEl;
|
|
}
|
|
/**
|
|
* Renders assistant message content (content blocks or fallback).
|
|
*/
|
|
renderAssistantContent(msg, contentEl) {
|
|
var _a, _b;
|
|
if (msg.contentBlocks && msg.contentBlocks.length > 0) {
|
|
for (const block of msg.contentBlocks) {
|
|
if (block.type === "thinking") {
|
|
renderStoredThinkingBlock(
|
|
contentEl,
|
|
block.content,
|
|
block.durationSeconds,
|
|
(el, md) => this.renderContent(el, md)
|
|
);
|
|
} else if (block.type === "text") {
|
|
const textEl = contentEl.createDiv({ cls: "claudian-text-block" });
|
|
void this.renderContent(textEl, block.content);
|
|
} else if (block.type === "tool_use") {
|
|
const toolCall = (_a = msg.toolCalls) == null ? void 0 : _a.find((tc) => tc.id === block.toolId);
|
|
if (toolCall) {
|
|
this.renderToolCall(contentEl, toolCall);
|
|
}
|
|
} else if (block.type === "subagent") {
|
|
const subagent = (_b = msg.subagents) == null ? void 0 : _b.find((s) => s.id === block.subagentId);
|
|
if (subagent) {
|
|
const mode = block.mode || subagent.mode || "sync";
|
|
if (mode === "async") {
|
|
renderStoredAsyncSubagent(contentEl, subagent);
|
|
} else {
|
|
renderStoredSubagent(contentEl, subagent);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
} else {
|
|
if (msg.content) {
|
|
const textEl = contentEl.createDiv({ cls: "claudian-text-block" });
|
|
void this.renderContent(textEl, msg.content);
|
|
}
|
|
if (msg.toolCalls) {
|
|
for (const toolCall of msg.toolCalls) {
|
|
this.renderToolCall(contentEl, toolCall);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
/**
|
|
* Renders a tool call with special handling for Write/Edit, and AskUserQuestion.
|
|
* TodoWrite is not rendered inline - it only shows in the bottom panel.
|
|
*/
|
|
renderToolCall(contentEl, toolCall) {
|
|
if (toolCall.name === TOOL_TODO_WRITE) {
|
|
return;
|
|
} else if (toolCall.name === TOOL_ASK_USER_QUESTION) {
|
|
renderStoredAskUserQuestion(contentEl, toolCall);
|
|
} else if (isWriteEditTool(toolCall.name)) {
|
|
renderStoredWriteEdit(contentEl, toolCall);
|
|
} else {
|
|
renderStoredToolCall(contentEl, toolCall);
|
|
}
|
|
}
|
|
// ============================================
|
|
// Image Rendering
|
|
// ============================================
|
|
/**
|
|
* Renders image attachments above a message.
|
|
*/
|
|
renderMessageImages(containerEl, images) {
|
|
const imagesEl = containerEl.createDiv({ cls: "claudian-message-images" });
|
|
for (const image of images) {
|
|
const imageWrapper = imagesEl.createDiv({ cls: "claudian-message-image" });
|
|
const imgEl = imageWrapper.createEl("img", {
|
|
attr: {
|
|
alt: image.name
|
|
}
|
|
});
|
|
void this.setImageSrc(imgEl, image);
|
|
imgEl.addEventListener("click", () => {
|
|
void this.showFullImage(image);
|
|
});
|
|
}
|
|
}
|
|
/**
|
|
* Shows full-size image in modal overlay.
|
|
*/
|
|
async showFullImage(image) {
|
|
const dataUri = getImageAttachmentDataUri(this.app, image);
|
|
if (!dataUri) return;
|
|
const overlay = document.body.createDiv({ cls: "claudian-image-modal-overlay" });
|
|
const modal = overlay.createDiv({ cls: "claudian-image-modal" });
|
|
modal.createEl("img", {
|
|
attr: {
|
|
src: dataUri,
|
|
alt: image.name
|
|
}
|
|
});
|
|
const closeBtn = modal.createDiv({ cls: "claudian-image-modal-close" });
|
|
closeBtn.setText("\xD7");
|
|
const handleEsc = (e) => {
|
|
if (e.key === "Escape") {
|
|
close();
|
|
}
|
|
};
|
|
const close = () => {
|
|
document.removeEventListener("keydown", handleEsc);
|
|
overlay.remove();
|
|
};
|
|
closeBtn.addEventListener("click", close);
|
|
overlay.addEventListener("click", (e) => {
|
|
if (e.target === overlay) close();
|
|
});
|
|
document.addEventListener("keydown", handleEsc);
|
|
}
|
|
/**
|
|
* Sets image src from attachment data.
|
|
*/
|
|
async setImageSrc(imgEl, image) {
|
|
const dataUri = getImageAttachmentDataUri(this.app, image);
|
|
if (dataUri) {
|
|
imgEl.setAttribute("src", dataUri);
|
|
} else {
|
|
imgEl.setAttribute("alt", `${image.name} (missing)`);
|
|
}
|
|
}
|
|
// ============================================
|
|
// Content Rendering
|
|
// ============================================
|
|
/**
|
|
* Renders markdown content with code block enhancements.
|
|
*/
|
|
async renderContent(el, markdown) {
|
|
el.empty();
|
|
await import_obsidian24.MarkdownRenderer.renderMarkdown(markdown, el, "", this.component);
|
|
el.querySelectorAll("pre").forEach((pre) => {
|
|
var _a, _b;
|
|
if ((_a = pre.parentElement) == null ? void 0 : _a.classList.contains("claudian-code-wrapper")) return;
|
|
const wrapper = createEl("div", { cls: "claudian-code-wrapper" });
|
|
(_b = pre.parentElement) == null ? void 0 : _b.insertBefore(wrapper, pre);
|
|
wrapper.appendChild(pre);
|
|
const code = pre.querySelector('code[class*="language-"]');
|
|
if (code) {
|
|
const match = code.className.match(/language-(\w+)/);
|
|
if (match) {
|
|
wrapper.classList.add("has-language");
|
|
const label = createEl("span", {
|
|
cls: "claudian-code-lang-label",
|
|
text: match[1]
|
|
});
|
|
wrapper.appendChild(label);
|
|
label.addEventListener("click", async () => {
|
|
await navigator.clipboard.writeText(code.textContent || "");
|
|
label.setText("copied!");
|
|
setTimeout(() => label.setText(match[1]), 1500);
|
|
});
|
|
}
|
|
}
|
|
const copyBtn = pre.querySelector(".copy-code-button");
|
|
if (copyBtn) {
|
|
wrapper.appendChild(copyBtn);
|
|
}
|
|
});
|
|
}
|
|
// ============================================
|
|
// Utilities
|
|
// ============================================
|
|
/** Scrolls messages container to bottom. */
|
|
scrollToBottom() {
|
|
this.messagesEl.scrollTop = this.messagesEl.scrollHeight;
|
|
}
|
|
/** Scrolls to bottom if already near bottom (within threshold). */
|
|
scrollToBottomIfNeeded(threshold = 100) {
|
|
const { scrollTop, scrollHeight, clientHeight } = this.messagesEl;
|
|
const isNearBottom = scrollHeight - scrollTop - clientHeight < threshold;
|
|
if (isNearBottom) {
|
|
requestAnimationFrame(() => {
|
|
this.messagesEl.scrollTop = this.messagesEl.scrollHeight;
|
|
});
|
|
}
|
|
}
|
|
/** Keeps the persistent todo panel pinned to the bottom of the messages container. */
|
|
ensureTodoPanelAtBottom(panelEl) {
|
|
const todoPanel = panelEl != null ? panelEl : this.messagesEl.querySelector(".claudian-todo-panel");
|
|
if (todoPanel) {
|
|
this.messagesEl.appendChild(todoPanel);
|
|
}
|
|
}
|
|
};
|
|
|
|
// src/features/chat/services/AsyncSubagentManager.ts
|
|
var AsyncSubagentManager = class {
|
|
constructor(onStateChange) {
|
|
this.activeAsyncSubagents = /* @__PURE__ */ new Map();
|
|
this.pendingAsyncSubagents = /* @__PURE__ */ new Map();
|
|
this.taskIdToAgentId = /* @__PURE__ */ new Map();
|
|
this.outputToolIdToAgentId = /* @__PURE__ */ new Map();
|
|
this.onStateChange = onStateChange;
|
|
}
|
|
/** Checks if a Task tool input indicates async mode (run_in_background=true). */
|
|
isAsyncTask(taskInput) {
|
|
return taskInput.run_in_background === true;
|
|
}
|
|
/** Creates an async subagent in pending state. */
|
|
createAsyncSubagent(taskToolId, taskInput) {
|
|
const description = taskInput.description || "Background task";
|
|
const subagent = {
|
|
id: taskToolId,
|
|
description,
|
|
mode: "async",
|
|
isExpanded: false,
|
|
status: "running",
|
|
toolCalls: [],
|
|
asyncStatus: "pending"
|
|
};
|
|
this.pendingAsyncSubagents.set(taskToolId, subagent);
|
|
return subagent;
|
|
}
|
|
/** Handles Task tool_result to extract agent_id. Transitions: pending → running/error. */
|
|
handleTaskToolResult(taskToolId, result, isError) {
|
|
const subagent = this.pendingAsyncSubagents.get(taskToolId);
|
|
if (!subagent) {
|
|
return;
|
|
}
|
|
if (isError) {
|
|
subagent.asyncStatus = "error";
|
|
subagent.status = "error";
|
|
subagent.result = result || "Task failed to start";
|
|
subagent.completedAt = Date.now();
|
|
this.pendingAsyncSubagents.delete(taskToolId);
|
|
this.onStateChange(subagent);
|
|
return;
|
|
}
|
|
const agentId = this.parseAgentId(result);
|
|
if (!agentId) {
|
|
subagent.asyncStatus = "error";
|
|
subagent.status = "error";
|
|
const truncatedResult = result.length > 100 ? result.substring(0, 100) + "..." : result;
|
|
subagent.result = `Failed to parse agent_id. Result: ${truncatedResult}`;
|
|
subagent.completedAt = Date.now();
|
|
this.pendingAsyncSubagents.delete(taskToolId);
|
|
this.onStateChange(subagent);
|
|
return;
|
|
}
|
|
subagent.asyncStatus = "running";
|
|
subagent.agentId = agentId;
|
|
subagent.startedAt = Date.now();
|
|
this.pendingAsyncSubagents.delete(taskToolId);
|
|
this.activeAsyncSubagents.set(agentId, subagent);
|
|
this.taskIdToAgentId.set(taskToolId, agentId);
|
|
this.onStateChange(subagent);
|
|
}
|
|
/** Links AgentOutputTool to its async subagent for result routing. */
|
|
handleAgentOutputToolUse(toolCall) {
|
|
const agentId = this.extractAgentIdFromInput(toolCall.input);
|
|
if (!agentId) {
|
|
return;
|
|
}
|
|
const subagent = this.activeAsyncSubagents.get(agentId);
|
|
if (!subagent) {
|
|
return;
|
|
}
|
|
subagent.outputToolId = toolCall.id;
|
|
this.outputToolIdToAgentId.set(toolCall.id, agentId);
|
|
}
|
|
/** Handles AgentOutputTool result. Transitions: running → completed/error (if done). */
|
|
handleAgentOutputToolResult(toolId, result, isError) {
|
|
let agentId = this.outputToolIdToAgentId.get(toolId);
|
|
let subagent = agentId ? this.activeAsyncSubagents.get(agentId) : void 0;
|
|
if (!subagent) {
|
|
const inferredAgentId = this.inferAgentIdFromResult(result);
|
|
if (inferredAgentId) {
|
|
agentId = inferredAgentId;
|
|
subagent = this.activeAsyncSubagents.get(inferredAgentId);
|
|
}
|
|
}
|
|
if (!subagent) {
|
|
return void 0;
|
|
}
|
|
if (agentId) {
|
|
subagent.agentId = subagent.agentId || agentId;
|
|
this.outputToolIdToAgentId.set(toolId, agentId);
|
|
}
|
|
const validStates = ["running"];
|
|
if (!validStates.includes(subagent.asyncStatus)) {
|
|
return void 0;
|
|
}
|
|
const stillRunning = this.isStillRunningResult(result, isError);
|
|
if (stillRunning) {
|
|
this.outputToolIdToAgentId.delete(toolId);
|
|
return subagent;
|
|
}
|
|
const extractedResult = this.extractAgentResult(result, agentId != null ? agentId : "");
|
|
subagent.asyncStatus = isError ? "error" : "completed";
|
|
subagent.status = isError ? "error" : "completed";
|
|
subagent.result = extractedResult;
|
|
subagent.completedAt = Date.now();
|
|
if (agentId) this.activeAsyncSubagents.delete(agentId);
|
|
this.outputToolIdToAgentId.delete(toolId);
|
|
this.onStateChange(subagent);
|
|
return subagent;
|
|
}
|
|
/** Checks if AgentOutputTool result indicates the task is still running. */
|
|
isStillRunningResult(result, isError) {
|
|
const trimmed = (result == null ? void 0 : result.trim()) || "";
|
|
const unwrapTextPayload = (raw) => {
|
|
try {
|
|
const parsed = JSON.parse(raw);
|
|
if (Array.isArray(parsed)) {
|
|
const textBlock = parsed.find((b) => b && typeof b.text === "string");
|
|
if (textBlock == null ? void 0 : textBlock.text) return textBlock.text;
|
|
} else if (parsed && typeof parsed === "object" && typeof parsed.text === "string") {
|
|
return parsed.text;
|
|
}
|
|
} catch (e) {
|
|
}
|
|
return raw;
|
|
};
|
|
const payload = unwrapTextPayload(trimmed);
|
|
if (isError) {
|
|
return false;
|
|
}
|
|
if (!trimmed) {
|
|
return false;
|
|
}
|
|
try {
|
|
const parsed = JSON.parse(payload);
|
|
const status = parsed.retrieval_status || parsed.status;
|
|
const hasAgents = parsed.agents && Object.keys(parsed.agents).length > 0;
|
|
if (status === "not_ready" || status === "running" || status === "pending") {
|
|
return true;
|
|
}
|
|
if (hasAgents) {
|
|
const agentStatuses = Object.values(parsed.agents).map((a) => a && typeof a.status === "string" ? a.status.toLowerCase() : "");
|
|
const anyRunning = agentStatuses.some(
|
|
(s) => s === "running" || s === "pending" || s === "not_ready"
|
|
);
|
|
if (anyRunning) return true;
|
|
return false;
|
|
}
|
|
if (status === "success" || status === "completed") {
|
|
return false;
|
|
}
|
|
return false;
|
|
} catch (e) {
|
|
}
|
|
const lowerResult = payload.toLowerCase();
|
|
if (lowerResult.includes("not_ready") || lowerResult.includes("not ready")) {
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
/** Extracts the actual result content from AgentOutputTool response. */
|
|
extractAgentResult(result, agentId) {
|
|
const unwrap = (raw) => {
|
|
try {
|
|
const parsed = JSON.parse(raw);
|
|
if (Array.isArray(parsed)) {
|
|
const textBlock = parsed.find((b) => b && typeof b.text === "string");
|
|
if (textBlock == null ? void 0 : textBlock.text) return textBlock.text;
|
|
} else if (parsed && typeof parsed === "object" && typeof parsed.text === "string") {
|
|
return parsed.text;
|
|
}
|
|
} catch (e) {
|
|
}
|
|
return raw;
|
|
};
|
|
const payload = unwrap(result);
|
|
try {
|
|
const parsed = JSON.parse(payload);
|
|
if (parsed.agents && agentId && parsed.agents[agentId]) {
|
|
const agentData = parsed.agents[agentId];
|
|
if (agentData.result) {
|
|
return agentData.result;
|
|
}
|
|
return JSON.stringify(agentData, null, 2);
|
|
}
|
|
if (parsed.agents) {
|
|
const agentIds = Object.keys(parsed.agents);
|
|
if (agentIds.length > 0) {
|
|
const firstAgent = parsed.agents[agentIds[0]];
|
|
if (firstAgent.result) {
|
|
return firstAgent.result;
|
|
}
|
|
return JSON.stringify(firstAgent, null, 2);
|
|
}
|
|
}
|
|
} catch (e) {
|
|
}
|
|
return payload;
|
|
}
|
|
/** Orphans all active async subagents when conversation ends. */
|
|
orphanAllActive() {
|
|
const orphaned = [];
|
|
for (const subagent of this.pendingAsyncSubagents.values()) {
|
|
subagent.asyncStatus = "orphaned";
|
|
subagent.status = "error";
|
|
subagent.result = "Conversation ended before task completed";
|
|
subagent.completedAt = Date.now();
|
|
orphaned.push(subagent);
|
|
this.onStateChange(subagent);
|
|
}
|
|
for (const subagent of this.activeAsyncSubagents.values()) {
|
|
if (subagent.asyncStatus === "running") {
|
|
subagent.asyncStatus = "orphaned";
|
|
subagent.status = "error";
|
|
subagent.result = "Conversation ended before task completed";
|
|
subagent.completedAt = Date.now();
|
|
orphaned.push(subagent);
|
|
this.onStateChange(subagent);
|
|
}
|
|
}
|
|
this.pendingAsyncSubagents.clear();
|
|
this.activeAsyncSubagents.clear();
|
|
this.outputToolIdToAgentId.clear();
|
|
return orphaned;
|
|
}
|
|
/** Clears all state for a new conversation. */
|
|
clear() {
|
|
this.pendingAsyncSubagents.clear();
|
|
this.activeAsyncSubagents.clear();
|
|
this.taskIdToAgentId.clear();
|
|
this.outputToolIdToAgentId.clear();
|
|
}
|
|
/** Gets async subagent by agent_id. */
|
|
getByAgentId(agentId) {
|
|
return this.activeAsyncSubagents.get(agentId);
|
|
}
|
|
/** Gets async subagent by task tool_use_id. */
|
|
getByTaskId(taskToolId) {
|
|
const pending = this.pendingAsyncSubagents.get(taskToolId);
|
|
if (pending) return pending;
|
|
const agentId = this.taskIdToAgentId.get(taskToolId);
|
|
if (agentId) {
|
|
return this.activeAsyncSubagents.get(agentId);
|
|
}
|
|
return void 0;
|
|
}
|
|
/** Checks if a task tool_id is a pending async subagent. */
|
|
isPendingAsyncTask(taskToolId) {
|
|
return this.pendingAsyncSubagents.has(taskToolId);
|
|
}
|
|
/** Checks if a tool_id is an AgentOutputTool linked to an async subagent. */
|
|
isLinkedAgentOutputTool(toolId) {
|
|
return this.outputToolIdToAgentId.has(toolId);
|
|
}
|
|
/** Gets all active async subagents (pending + running). */
|
|
getAllActive() {
|
|
return [
|
|
...this.pendingAsyncSubagents.values(),
|
|
...this.activeAsyncSubagents.values()
|
|
];
|
|
}
|
|
/** Checks if there are any active async subagents. */
|
|
hasActiveAsync() {
|
|
return this.pendingAsyncSubagents.size > 0 || this.activeAsyncSubagents.size > 0;
|
|
}
|
|
/** Parses agent_id from Task tool_result. */
|
|
parseAgentId(result) {
|
|
var _a;
|
|
const regexPatterns = [
|
|
/"agent_id"\s*:\s*"([^"]+)"/,
|
|
// JSON style: "agent_id": "value"
|
|
/"agentId"\s*:\s*"([^"]+)"/,
|
|
// camelCase JSON
|
|
/agent_id[=:]\s*"?([a-zA-Z0-9_-]+)"?/i,
|
|
// Flexible format
|
|
/agentId[=:]\s*"?([a-zA-Z0-9_-]+)"?/i,
|
|
// camelCase flexible
|
|
/\b([a-f0-9]{8})\b/
|
|
// Short hex ID (8 chars)
|
|
];
|
|
for (const pattern of regexPatterns) {
|
|
const match = result.match(pattern);
|
|
if (match && match[1]) {
|
|
return match[1];
|
|
}
|
|
}
|
|
try {
|
|
const parsed = JSON.parse(result);
|
|
const agentId = parsed.agent_id || parsed.agentId;
|
|
if (typeof agentId === "string" && agentId.length > 0) {
|
|
return agentId;
|
|
}
|
|
if ((_a = parsed.data) == null ? void 0 : _a.agent_id) {
|
|
return parsed.data.agent_id;
|
|
}
|
|
if (parsed.id && typeof parsed.id === "string") {
|
|
return parsed.id;
|
|
}
|
|
} catch (e) {
|
|
}
|
|
return null;
|
|
}
|
|
/** Infers agent_id from AgentOutputTool result payload. */
|
|
inferAgentIdFromResult(result) {
|
|
try {
|
|
const parsed = JSON.parse(result);
|
|
if (parsed.agents && typeof parsed.agents === "object") {
|
|
const keys = Object.keys(parsed.agents);
|
|
if (keys.length > 0) {
|
|
return keys[0];
|
|
}
|
|
}
|
|
} catch (e) {
|
|
}
|
|
return null;
|
|
}
|
|
/** Extracts agentId from AgentOutputTool input. */
|
|
extractAgentIdFromInput(input) {
|
|
const agentId = input.agentId || input.agent_id;
|
|
return agentId || null;
|
|
}
|
|
};
|
|
|
|
// src/core/prompts/instructionRefine.ts
|
|
function buildRefineSystemPrompt(existingInstructions) {
|
|
const existingSection = existingInstructions.trim() ? `
|
|
|
|
EXISTING INSTRUCTIONS (already in the user's system prompt):
|
|
\`\`\`
|
|
${existingInstructions.trim()}
|
|
\`\`\`
|
|
|
|
When refining the new instruction:
|
|
- Consider how it fits with existing instructions
|
|
- Avoid duplicating existing instructions
|
|
- If the new instruction conflicts with an existing one, refine it to be complementary or note the conflict
|
|
- Match the format of existing instructions (section, heading, bullet points, style, etc.)` : "";
|
|
return `You are an expert Prompt Engineer. You help users craft precise, effective system instructions for their AI assistant.
|
|
|
|
**Your Goal**: Transform vague or simple user requests into **high-quality, actionable, and non-conflicting** system prompt instructions.
|
|
|
|
**Process**:
|
|
1. **Analyze Intent**: What behavior does the user want to enforce or change?
|
|
2. **Check Context**: Does this conflict with existing instructions?
|
|
- *No Conflict*: Add as new.
|
|
- *Conflict*: Propose a **merged instruction** that resolves the contradiction (or ask if unsure).
|
|
3. **Refine**: Draft a clear, positive instruction (e.g., "Do X" instead of "Don't do Y").
|
|
4. **Format**: Return *only* the Markdown snippet wrapped in \`<instruction>\` tags.
|
|
|
|
**Guidelines**:
|
|
- **Clarity**: Use precise language. Avoid ambiguity.
|
|
- **Scope**: Keep it focused. Don't add unrelated rules.
|
|
- **Format**: Valid Markdown (bullets \`-\` or sections \`##\`).
|
|
- **No Header**: Do NOT include a top-level header like \`# Custom Instructions\`.
|
|
- **Conflict Handling**: If the new rule directly contradicts an existing one, rewrite the *new* one to override specific cases or ask for clarification.
|
|
|
|
**Output Format**:
|
|
- **Success**: \`<instruction>...markdown content...</instruction>\`
|
|
- **Ambiguity**: Plain text question.
|
|
|
|
${existingSection}
|
|
|
|
**Examples**:
|
|
|
|
Input: "typescript for code"
|
|
Output: <instruction>- **Code Language**: Always use TypeScript for code examples. Include proper type annotations and interfaces.</instruction>
|
|
|
|
Input: "be concise"
|
|
Output: <instruction>- **Conciseness**: Provide brief, direct responses. Omit conversational filler and unnecessary explanations.</instruction>
|
|
|
|
Input: "organize coding style rules"
|
|
Output: <instruction>## Coding Standards
|
|
|
|
- **Language**: Use TypeScript.
|
|
- **Style**: Prefer functional patterns.
|
|
- **Review**: Keep diffs small.</instruction>
|
|
|
|
Input: "use that thing from before"
|
|
Output: I'm not sure what you're referring to. Could you please clarify?`;
|
|
}
|
|
|
|
// src/features/chat/services/InstructionRefineService.ts
|
|
var READ_ONLY_TOOLS2 = [TOOL_READ, TOOL_GREP, TOOL_GLOB];
|
|
var InstructionRefineService = class {
|
|
constructor(plugin) {
|
|
this.abortController = null;
|
|
this.resolvedClaudePath = null;
|
|
this.sessionId = null;
|
|
this.existingInstructions = "";
|
|
this.plugin = plugin;
|
|
}
|
|
/** Resets conversation state for a new refinement session. */
|
|
resetConversation() {
|
|
this.sessionId = null;
|
|
}
|
|
findClaudeCLI() {
|
|
return findClaudeCLIPath();
|
|
}
|
|
/** Refines a raw instruction from user input. */
|
|
async refineInstruction(rawInstruction, existingInstructions, onProgress) {
|
|
this.sessionId = null;
|
|
this.existingInstructions = existingInstructions;
|
|
const prompt = `Please refine this instruction: "${rawInstruction}"`;
|
|
return this.sendMessage(prompt, onProgress);
|
|
}
|
|
/** Continues conversation with a follow-up message (for clarifications). */
|
|
async continueConversation(message, onProgress) {
|
|
if (!this.sessionId) {
|
|
return { success: false, error: "No active conversation to continue" };
|
|
}
|
|
return this.sendMessage(message, onProgress);
|
|
}
|
|
/** Cancels any ongoing query. */
|
|
cancel() {
|
|
if (this.abortController) {
|
|
this.abortController.abort();
|
|
this.abortController = null;
|
|
}
|
|
}
|
|
async sendMessage(prompt, onProgress) {
|
|
var _a;
|
|
const vaultPath = getVaultPath(this.plugin.app);
|
|
if (!vaultPath) {
|
|
return { success: false, error: "Could not determine vault path" };
|
|
}
|
|
if (!this.resolvedClaudePath) {
|
|
this.resolvedClaudePath = this.findClaudeCLI();
|
|
}
|
|
if (!this.resolvedClaudePath) {
|
|
return { success: false, error: "Claude CLI not found. Please install Claude Code CLI." };
|
|
}
|
|
this.abortController = new AbortController();
|
|
const customEnv = parseEnvironmentVariables(this.plugin.getActiveEnvironmentVariables());
|
|
const options = {
|
|
cwd: vaultPath,
|
|
systemPrompt: buildRefineSystemPrompt(this.existingInstructions),
|
|
model: this.plugin.settings.model,
|
|
abortController: this.abortController,
|
|
pathToClaudeCodeExecutable: this.resolvedClaudePath,
|
|
env: {
|
|
...process.env,
|
|
...customEnv,
|
|
PATH: getEnhancedPath(customEnv.PATH)
|
|
},
|
|
allowedTools: [...READ_ONLY_TOOLS2],
|
|
permissionMode: "bypassPermissions",
|
|
allowDangerouslySkipPermissions: true,
|
|
hooks: {
|
|
PreToolUse: [
|
|
this.createReadOnlyHook(),
|
|
this.createVaultRestrictionHook(vaultPath)
|
|
]
|
|
}
|
|
};
|
|
if (this.sessionId) {
|
|
options.resume = this.sessionId;
|
|
}
|
|
const budgetSetting = this.plugin.settings.thinkingBudget;
|
|
const budgetConfig = THINKING_BUDGETS.find((b) => b.value === budgetSetting);
|
|
if (budgetConfig && budgetConfig.tokens > 0) {
|
|
options.maxThinkingTokens = budgetConfig.tokens;
|
|
}
|
|
try {
|
|
const response = query({ prompt, options });
|
|
let responseText = "";
|
|
for await (const message of response) {
|
|
if ((_a = this.abortController) == null ? void 0 : _a.signal.aborted) {
|
|
await response.interrupt();
|
|
return { success: false, error: "Cancelled" };
|
|
}
|
|
if (message.type === "system" && message.subtype === "init" && message.session_id) {
|
|
this.sessionId = message.session_id;
|
|
}
|
|
const text = this.extractTextFromMessage(message);
|
|
if (text) {
|
|
responseText += text;
|
|
if (onProgress) {
|
|
const partialResult = this.parseResponse(responseText);
|
|
onProgress(partialResult);
|
|
}
|
|
}
|
|
}
|
|
return this.parseResponse(responseText);
|
|
} catch (error2) {
|
|
const msg = error2 instanceof Error ? error2.message : "Unknown error";
|
|
return { success: false, error: msg };
|
|
} finally {
|
|
this.abortController = null;
|
|
}
|
|
}
|
|
/** Parses response text for <instruction> tag. */
|
|
parseResponse(responseText) {
|
|
const instructionMatch = responseText.match(/<instruction>([\s\S]*?)<\/instruction>/);
|
|
if (instructionMatch) {
|
|
return { success: true, refinedInstruction: instructionMatch[1].trim() };
|
|
}
|
|
const trimmed = responseText.trim();
|
|
if (trimmed) {
|
|
return { success: true, clarification: trimmed };
|
|
}
|
|
return { success: false, error: "Empty response" };
|
|
}
|
|
/** Extracts text content from SDK message. */
|
|
extractTextFromMessage(message) {
|
|
var _a;
|
|
if (message.type !== "assistant" || !((_a = message.message) == null ? void 0 : _a.content)) {
|
|
return "";
|
|
}
|
|
return message.message.content.filter((block) => block.type === "text" && !!block.text).map((block) => block.text).join("");
|
|
}
|
|
/** Creates PreToolUse hook to enforce read-only mode. */
|
|
createReadOnlyHook() {
|
|
return {
|
|
hooks: [
|
|
async (hookInput) => {
|
|
const input = hookInput;
|
|
const toolName = input.tool_name;
|
|
if (READ_ONLY_TOOLS2.includes(toolName)) {
|
|
return { continue: true };
|
|
}
|
|
return {
|
|
continue: false,
|
|
hookSpecificOutput: {
|
|
hookEventName: "PreToolUse",
|
|
permissionDecision: "deny",
|
|
permissionDecisionReason: `Instruction refine mode: tool "${toolName}" is not allowed (read-only)`
|
|
}
|
|
};
|
|
}
|
|
]
|
|
};
|
|
}
|
|
/** Creates PreToolUse hook to restrict file access to vault. */
|
|
createVaultRestrictionHook(vaultPath) {
|
|
return {
|
|
hooks: [
|
|
async (hookInput) => {
|
|
const input = hookInput;
|
|
const toolName = input.tool_name;
|
|
const toolInput = input.tool_input;
|
|
if (toolName === "Read" || toolName === "Glob" || toolName === "Grep") {
|
|
const filePath = toolName === "Read" ? toolInput.file_path || "" : toolInput.path || toolInput.pattern || "";
|
|
if (filePath && !isPathWithinVault(filePath, vaultPath)) {
|
|
return {
|
|
continue: false,
|
|
hookSpecificOutput: {
|
|
hookEventName: "PreToolUse",
|
|
permissionDecision: "deny",
|
|
permissionDecisionReason: `Access denied: "${filePath}" is outside the vault`
|
|
}
|
|
};
|
|
}
|
|
}
|
|
return { continue: true };
|
|
}
|
|
]
|
|
};
|
|
}
|
|
};
|
|
|
|
// src/core/prompts/titleGeneration.ts
|
|
var TITLE_GENERATION_SYSTEM_PROMPT = `You are a specialist in summarizing intent.
|
|
|
|
**Task**: Generate a **concise, descriptive title** (max 50 chars) for this conversation based on the first interaction.
|
|
|
|
**Rules**:
|
|
1. **Format**: Sentence case. No periods/quotes.
|
|
2. **Structure**: Start with a **strong verb** (e.g., Create, Fix, Debug, Explain, Analyze).
|
|
3. **Forbidden**: "Conversation with...", "Help me...", "Question about...", "I need...".
|
|
4. **Tech Context**: Detect and include the primary language/framework if code is present (e.g., "Debug Python script", "Refactor React hook").
|
|
|
|
**Output**: Return ONLY the raw title text.`;
|
|
|
|
// src/features/chat/services/TitleGenerationService.ts
|
|
var TitleGenerationService = class {
|
|
constructor(plugin) {
|
|
this.resolvedClaudePath = null;
|
|
/** Map of conversationId to AbortController for concurrent generation support. */
|
|
this.activeGenerations = /* @__PURE__ */ new Map();
|
|
this.plugin = plugin;
|
|
}
|
|
/**
|
|
* Generates a title for a conversation based on first messages.
|
|
* Non-blocking: calls callback when complete.
|
|
*/
|
|
async generateTitle(conversationId, userMessage, assistantResponse, callback) {
|
|
const vaultPath = getVaultPath(this.plugin.app);
|
|
if (!vaultPath) {
|
|
console.warn("[TitleGeneration] Could not determine vault path");
|
|
await this.safeCallback(callback, conversationId, {
|
|
success: false,
|
|
error: "Could not determine vault path"
|
|
});
|
|
return;
|
|
}
|
|
if (!this.resolvedClaudePath) {
|
|
this.resolvedClaudePath = findClaudeCLIPath();
|
|
}
|
|
if (!this.resolvedClaudePath) {
|
|
console.warn("[TitleGeneration] Claude CLI not found");
|
|
await this.safeCallback(callback, conversationId, {
|
|
success: false,
|
|
error: "Claude CLI not found"
|
|
});
|
|
return;
|
|
}
|
|
const envVars = parseEnvironmentVariables(
|
|
this.plugin.getActiveEnvironmentVariables()
|
|
);
|
|
const titleModel = this.plugin.settings.titleGenerationModel || envVars.ANTHROPIC_DEFAULT_HAIKU_MODEL || "claude-haiku-4-5";
|
|
const existingController = this.activeGenerations.get(conversationId);
|
|
if (existingController) {
|
|
existingController.abort();
|
|
}
|
|
const abortController = new AbortController();
|
|
this.activeGenerations.set(conversationId, abortController);
|
|
const truncatedUser = this.truncateText(userMessage, 500);
|
|
const truncatedAssistant = this.truncateText(assistantResponse, 500);
|
|
const prompt = `User's first message:
|
|
"""
|
|
${truncatedUser}
|
|
"""
|
|
|
|
AI's response:
|
|
"""
|
|
${truncatedAssistant}
|
|
"""
|
|
|
|
Generate a title for this conversation:`;
|
|
const customEnv = parseEnvironmentVariables(
|
|
this.plugin.getActiveEnvironmentVariables()
|
|
);
|
|
const options = {
|
|
cwd: vaultPath,
|
|
systemPrompt: TITLE_GENERATION_SYSTEM_PROMPT,
|
|
model: titleModel,
|
|
abortController,
|
|
pathToClaudeCodeExecutable: this.resolvedClaudePath,
|
|
env: {
|
|
...process.env,
|
|
...customEnv,
|
|
PATH: getEnhancedPath(customEnv.PATH)
|
|
},
|
|
allowedTools: [],
|
|
// No tools needed for title generation
|
|
permissionMode: "bypassPermissions",
|
|
allowDangerouslySkipPermissions: true
|
|
};
|
|
try {
|
|
const response = query({ prompt, options });
|
|
let responseText = "";
|
|
for await (const message of response) {
|
|
if (abortController.signal.aborted) {
|
|
await this.safeCallback(callback, conversationId, {
|
|
success: false,
|
|
error: "Cancelled"
|
|
});
|
|
return;
|
|
}
|
|
const text = this.extractTextFromMessage(message);
|
|
if (text) {
|
|
responseText += text;
|
|
}
|
|
}
|
|
const title = this.parseTitle(responseText);
|
|
if (title) {
|
|
await this.safeCallback(callback, conversationId, { success: true, title });
|
|
} else {
|
|
console.warn("[TitleGeneration] Failed to parse title from response");
|
|
await this.safeCallback(callback, conversationId, {
|
|
success: false,
|
|
error: "Failed to parse title from response"
|
|
});
|
|
}
|
|
} catch (error2) {
|
|
if (error2 instanceof Error && error2.name !== "AbortError") {
|
|
console.error("[TitleGeneration] Error generating title:", error2.message);
|
|
}
|
|
const msg = error2 instanceof Error ? error2.message : "Unknown error";
|
|
await this.safeCallback(callback, conversationId, { success: false, error: msg });
|
|
} finally {
|
|
this.activeGenerations.delete(conversationId);
|
|
}
|
|
}
|
|
/** Cancels all ongoing title generations. */
|
|
cancel() {
|
|
for (const controller of this.activeGenerations.values()) {
|
|
controller.abort();
|
|
}
|
|
this.activeGenerations.clear();
|
|
}
|
|
/** Truncates text to a maximum length with ellipsis. */
|
|
truncateText(text, maxLength) {
|
|
if (text.length <= maxLength) return text;
|
|
return text.substring(0, maxLength) + "...";
|
|
}
|
|
/** Extracts text content from SDK message. */
|
|
extractTextFromMessage(message) {
|
|
var _a;
|
|
if (message.type !== "assistant" || !((_a = message.message) == null ? void 0 : _a.content)) {
|
|
return "";
|
|
}
|
|
return message.message.content.filter(
|
|
(block) => block.type === "text" && !!block.text
|
|
).map((block) => block.text).join("");
|
|
}
|
|
/** Parses and cleans the title from response. */
|
|
parseTitle(responseText) {
|
|
const trimmed = responseText.trim();
|
|
if (!trimmed) return null;
|
|
let title = trimmed;
|
|
if (title.startsWith('"') && title.endsWith('"') || title.startsWith("'") && title.endsWith("'")) {
|
|
title = title.slice(1, -1);
|
|
}
|
|
title = title.replace(/[.!?:;,]+$/, "");
|
|
if (title.length > 50) {
|
|
title = title.substring(0, 47) + "...";
|
|
}
|
|
return title || null;
|
|
}
|
|
/** Safely invokes callback with try-catch to prevent unhandled errors. */
|
|
async safeCallback(callback, conversationId, result) {
|
|
try {
|
|
await callback(conversationId, result);
|
|
} catch (error2) {
|
|
console.error("[TitleGeneration] Error in callback:", error2 instanceof Error ? error2.message : error2);
|
|
}
|
|
}
|
|
};
|
|
|
|
// src/features/chat/state/ChatState.ts
|
|
function createInitialState() {
|
|
return {
|
|
messages: [],
|
|
isStreaming: false,
|
|
cancelRequested: false,
|
|
currentConversationId: null,
|
|
queuedMessage: null,
|
|
currentContentEl: null,
|
|
currentTextEl: null,
|
|
currentTextContent: "",
|
|
currentThinkingState: null,
|
|
thinkingEl: null,
|
|
queueIndicatorEl: null,
|
|
toolCallElements: /* @__PURE__ */ new Map(),
|
|
activeSubagents: /* @__PURE__ */ new Map(),
|
|
asyncSubagentStates: /* @__PURE__ */ new Map(),
|
|
writeEditStates: /* @__PURE__ */ new Map(),
|
|
askUserQuestionStates: /* @__PURE__ */ new Map(),
|
|
usage: null,
|
|
ignoreUsageUpdates: false,
|
|
subagentsSpawnedThisStream: 0,
|
|
planModeState: null,
|
|
planModeRequested: false,
|
|
planModeActivationPending: false,
|
|
pendingPlanContent: null,
|
|
currentTodos: null
|
|
};
|
|
}
|
|
var ChatState = class {
|
|
constructor(callbacks = {}) {
|
|
this.state = createInitialState();
|
|
this.callbacks = callbacks;
|
|
}
|
|
// ============================================
|
|
// Messages
|
|
// ============================================
|
|
get messages() {
|
|
return this.state.messages;
|
|
}
|
|
set messages(value) {
|
|
var _a, _b;
|
|
this.state.messages = value;
|
|
(_b = (_a = this.callbacks).onMessagesChanged) == null ? void 0 : _b.call(_a);
|
|
}
|
|
addMessage(msg) {
|
|
var _a, _b;
|
|
this.state.messages.push(msg);
|
|
(_b = (_a = this.callbacks).onMessagesChanged) == null ? void 0 : _b.call(_a);
|
|
}
|
|
clearMessages() {
|
|
var _a, _b;
|
|
this.state.messages = [];
|
|
(_b = (_a = this.callbacks).onMessagesChanged) == null ? void 0 : _b.call(_a);
|
|
}
|
|
// ============================================
|
|
// Streaming Control
|
|
// ============================================
|
|
get isStreaming() {
|
|
return this.state.isStreaming;
|
|
}
|
|
set isStreaming(value) {
|
|
var _a, _b;
|
|
this.state.isStreaming = value;
|
|
(_b = (_a = this.callbacks).onStreamingStateChanged) == null ? void 0 : _b.call(_a, value);
|
|
}
|
|
get cancelRequested() {
|
|
return this.state.cancelRequested;
|
|
}
|
|
set cancelRequested(value) {
|
|
this.state.cancelRequested = value;
|
|
}
|
|
// ============================================
|
|
// Conversation
|
|
// ============================================
|
|
get currentConversationId() {
|
|
return this.state.currentConversationId;
|
|
}
|
|
set currentConversationId(value) {
|
|
var _a, _b;
|
|
this.state.currentConversationId = value;
|
|
(_b = (_a = this.callbacks).onConversationChanged) == null ? void 0 : _b.call(_a, value);
|
|
}
|
|
// ============================================
|
|
// Queued Message
|
|
// ============================================
|
|
get queuedMessage() {
|
|
return this.state.queuedMessage;
|
|
}
|
|
set queuedMessage(value) {
|
|
this.state.queuedMessage = value;
|
|
}
|
|
// ============================================
|
|
// Streaming DOM State
|
|
// ============================================
|
|
get currentContentEl() {
|
|
return this.state.currentContentEl;
|
|
}
|
|
set currentContentEl(value) {
|
|
this.state.currentContentEl = value;
|
|
}
|
|
get currentTextEl() {
|
|
return this.state.currentTextEl;
|
|
}
|
|
set currentTextEl(value) {
|
|
this.state.currentTextEl = value;
|
|
}
|
|
get currentTextContent() {
|
|
return this.state.currentTextContent;
|
|
}
|
|
set currentTextContent(value) {
|
|
this.state.currentTextContent = value;
|
|
}
|
|
get currentThinkingState() {
|
|
return this.state.currentThinkingState;
|
|
}
|
|
set currentThinkingState(value) {
|
|
this.state.currentThinkingState = value;
|
|
}
|
|
get thinkingEl() {
|
|
return this.state.thinkingEl;
|
|
}
|
|
set thinkingEl(value) {
|
|
this.state.thinkingEl = value;
|
|
}
|
|
get queueIndicatorEl() {
|
|
return this.state.queueIndicatorEl;
|
|
}
|
|
set queueIndicatorEl(value) {
|
|
this.state.queueIndicatorEl = value;
|
|
}
|
|
// ============================================
|
|
// Tool and Subagent Tracking Maps
|
|
// ============================================
|
|
get toolCallElements() {
|
|
return this.state.toolCallElements;
|
|
}
|
|
get activeSubagents() {
|
|
return this.state.activeSubagents;
|
|
}
|
|
get asyncSubagentStates() {
|
|
return this.state.asyncSubagentStates;
|
|
}
|
|
get writeEditStates() {
|
|
return this.state.writeEditStates;
|
|
}
|
|
get askUserQuestionStates() {
|
|
return this.state.askUserQuestionStates;
|
|
}
|
|
// ============================================
|
|
// Usage State
|
|
// ============================================
|
|
get usage() {
|
|
return this.state.usage;
|
|
}
|
|
set usage(value) {
|
|
var _a, _b;
|
|
this.state.usage = value;
|
|
(_b = (_a = this.callbacks).onUsageChanged) == null ? void 0 : _b.call(_a, value);
|
|
}
|
|
get ignoreUsageUpdates() {
|
|
return this.state.ignoreUsageUpdates;
|
|
}
|
|
set ignoreUsageUpdates(value) {
|
|
this.state.ignoreUsageUpdates = value;
|
|
}
|
|
get subagentsSpawnedThisStream() {
|
|
return this.state.subagentsSpawnedThisStream;
|
|
}
|
|
set subagentsSpawnedThisStream(value) {
|
|
this.state.subagentsSpawnedThisStream = value;
|
|
}
|
|
// ============================================
|
|
// Plan Mode State
|
|
// ============================================
|
|
get planModeState() {
|
|
return this.state.planModeState;
|
|
}
|
|
set planModeState(value) {
|
|
this.state.planModeState = value;
|
|
}
|
|
/** Resets plan mode state. */
|
|
resetPlanModeState() {
|
|
this.state.planModeState = null;
|
|
}
|
|
get planModeRequested() {
|
|
return this.state.planModeRequested;
|
|
}
|
|
set planModeRequested(value) {
|
|
this.state.planModeRequested = value;
|
|
}
|
|
get planModeActivationPending() {
|
|
return this.state.planModeActivationPending;
|
|
}
|
|
set planModeActivationPending(value) {
|
|
this.state.planModeActivationPending = value;
|
|
}
|
|
// ============================================
|
|
// Pending Plan Content (for approval persistence)
|
|
// ============================================
|
|
get pendingPlanContent() {
|
|
return this.state.pendingPlanContent;
|
|
}
|
|
set pendingPlanContent(value) {
|
|
this.state.pendingPlanContent = value;
|
|
}
|
|
// ============================================
|
|
// Current Todos (for persistent bottom panel)
|
|
// ============================================
|
|
get currentTodos() {
|
|
return this.state.currentTodos;
|
|
}
|
|
set currentTodos(value) {
|
|
var _a, _b;
|
|
const normalizedValue = value && value.length > 0 ? value : null;
|
|
this.state.currentTodos = normalizedValue;
|
|
(_b = (_a = this.callbacks).onTodosChanged) == null ? void 0 : _b.call(_a, normalizedValue);
|
|
}
|
|
// ============================================
|
|
// Reset Methods
|
|
// ============================================
|
|
/** Resets streaming-related state. */
|
|
resetStreamingState() {
|
|
this.state.currentContentEl = null;
|
|
this.state.currentTextEl = null;
|
|
this.state.currentTextContent = "";
|
|
this.state.currentThinkingState = null;
|
|
this.state.isStreaming = false;
|
|
this.state.cancelRequested = false;
|
|
}
|
|
/** Clears all maps for a new conversation. */
|
|
clearMaps() {
|
|
this.state.toolCallElements.clear();
|
|
this.state.activeSubagents.clear();
|
|
this.state.asyncSubagentStates.clear();
|
|
this.state.writeEditStates.clear();
|
|
this.state.askUserQuestionStates.clear();
|
|
}
|
|
/** Resets all state for a new conversation. */
|
|
resetForNewConversation() {
|
|
this.clearMessages();
|
|
this.resetStreamingState();
|
|
this.clearMaps();
|
|
this.state.queuedMessage = null;
|
|
this.state.planModeRequested = false;
|
|
this.state.planModeActivationPending = false;
|
|
this.usage = null;
|
|
this.currentTodos = null;
|
|
}
|
|
/** Gets persisted messages (strips image data). */
|
|
getPersistedMessages() {
|
|
return this.state.messages.map((msg) => {
|
|
var _a;
|
|
return {
|
|
...msg,
|
|
images: (_a = msg.images) == null ? void 0 : _a.map((img) => {
|
|
const { data, ...rest } = img;
|
|
return { ...rest };
|
|
})
|
|
};
|
|
});
|
|
}
|
|
};
|
|
|
|
// src/features/chat/ClaudianView.ts
|
|
var ClaudianView = class extends import_obsidian25.ItemView {
|
|
constructor(leaf, plugin) {
|
|
super(leaf);
|
|
// Controllers
|
|
this.selectionController = null;
|
|
this.conversationController = null;
|
|
this.streamController = null;
|
|
this.inputController = null;
|
|
this.navigationController = null;
|
|
// Rendering
|
|
this.renderer = null;
|
|
this.instructionRefineService = null;
|
|
this.titleGenerationService = null;
|
|
// DOM Elements
|
|
this.messagesEl = null;
|
|
this.inputEl = null;
|
|
this.inputWrapper = null;
|
|
this.historyDropdown = null;
|
|
this.welcomeEl = null;
|
|
this.selectionIndicatorEl = null;
|
|
// UI Components
|
|
this.fileContextManager = null;
|
|
this.imageContextManager = null;
|
|
this.modelSelector = null;
|
|
this.thinkingBudgetSelector = null;
|
|
this.contextPathSelector = null;
|
|
this.mcpServerSelector = null;
|
|
this.permissionToggle = null;
|
|
this.slashCommandManager = null;
|
|
this.slashCommandDropdown = null;
|
|
this.instructionModeManager = null;
|
|
this.contextUsageMeter = null;
|
|
this.planBanner = null;
|
|
this.todoPanel = null;
|
|
this.plugin = plugin;
|
|
this.state = new ChatState({
|
|
onUsageChanged: (usage) => {
|
|
var _a;
|
|
return (_a = this.contextUsageMeter) == null ? void 0 : _a.update(usage);
|
|
},
|
|
onTodosChanged: (todos) => {
|
|
var _a;
|
|
return (_a = this.todoPanel) == null ? void 0 : _a.updateTodos(todos);
|
|
}
|
|
});
|
|
this.asyncSubagentManager = new AsyncSubagentManager(
|
|
(subagent) => {
|
|
var _a;
|
|
return (_a = this.streamController) == null ? void 0 : _a.onAsyncSubagentStateChange(subagent);
|
|
}
|
|
);
|
|
}
|
|
getViewType() {
|
|
return VIEW_TYPE_CLAUDIAN;
|
|
}
|
|
getDisplayText() {
|
|
return "Claudian";
|
|
}
|
|
getIcon() {
|
|
return "bot";
|
|
}
|
|
async onOpen() {
|
|
var _a, _b;
|
|
const container = this.containerEl.children[1];
|
|
container.empty();
|
|
container.addClass("claudian-container");
|
|
const header = container.createDiv({ cls: "claudian-header" });
|
|
this.buildHeader(header);
|
|
this.planBanner = new PlanBanner({
|
|
app: this.plugin.app,
|
|
component: this
|
|
});
|
|
this.planBanner.mount(container);
|
|
this.messagesEl = container.createDiv({ cls: "claudian-messages" });
|
|
this.welcomeEl = this.messagesEl.createDiv({ cls: "claudian-welcome" });
|
|
this.todoPanel = new TodoPanel();
|
|
this.todoPanel.mount(this.messagesEl);
|
|
const inputContainerEl = container.createDiv({ cls: "claudian-input-container" });
|
|
this.buildInputArea(inputContainerEl);
|
|
this.renderer = new MessageRenderer(
|
|
this.plugin.app,
|
|
this,
|
|
this.messagesEl
|
|
);
|
|
this.initializeControllers();
|
|
this.wireEventHandlers();
|
|
(_a = this.selectionController) == null ? void 0 : _a.start();
|
|
await ((_b = this.conversationController) == null ? void 0 : _b.loadActive());
|
|
}
|
|
async onClose() {
|
|
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
|
|
(_a = this.selectionController) == null ? void 0 : _a.stop();
|
|
(_b = this.selectionController) == null ? void 0 : _b.clear();
|
|
(_c = this.navigationController) == null ? void 0 : _c.dispose();
|
|
cleanupThinkingBlock(this.state.currentThinkingState);
|
|
this.state.currentThinkingState = null;
|
|
this.plugin.agentService.setApprovalCallback(null);
|
|
this.plugin.agentService.setAskUserQuestionCallback(null);
|
|
(_d = this.fileContextManager) == null ? void 0 : _d.destroy();
|
|
(_e = this.slashCommandDropdown) == null ? void 0 : _e.destroy();
|
|
this.slashCommandDropdown = null;
|
|
this.slashCommandManager = null;
|
|
(_f = this.instructionModeManager) == null ? void 0 : _f.destroy();
|
|
this.instructionModeManager = null;
|
|
(_g = this.instructionRefineService) == null ? void 0 : _g.cancel();
|
|
this.instructionRefineService = null;
|
|
(_h = this.titleGenerationService) == null ? void 0 : _h.cancel();
|
|
this.titleGenerationService = null;
|
|
(_i = this.todoPanel) == null ? void 0 : _i.destroy();
|
|
this.todoPanel = null;
|
|
this.asyncSubagentManager.orphanAllActive();
|
|
this.state.asyncSubagentStates.clear();
|
|
await ((_j = this.conversationController) == null ? void 0 : _j.save());
|
|
}
|
|
// ============================================
|
|
// UI Building
|
|
// ============================================
|
|
buildHeader(header) {
|
|
const titleContainer = header.createDiv({ cls: "claudian-title" });
|
|
const logoEl = titleContainer.createSpan({ cls: "claudian-logo" });
|
|
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
|
|
svg.setAttribute("viewBox", LOGO_SVG.viewBox);
|
|
svg.setAttribute("width", LOGO_SVG.width);
|
|
svg.setAttribute("height", LOGO_SVG.height);
|
|
svg.setAttribute("fill", "none");
|
|
const path12 = document.createElementNS("http://www.w3.org/2000/svg", "path");
|
|
path12.setAttribute("d", LOGO_SVG.path);
|
|
path12.setAttribute("fill", LOGO_SVG.fill);
|
|
svg.appendChild(path12);
|
|
logoEl.appendChild(svg);
|
|
titleContainer.createEl("h4", { text: "Claudian" });
|
|
const headerActions = header.createDiv({ cls: "claudian-header-actions" });
|
|
const historyContainer = headerActions.createDiv({ cls: "claudian-history-container" });
|
|
const trigger = historyContainer.createDiv({ cls: "claudian-header-btn" });
|
|
(0, import_obsidian25.setIcon)(trigger, "history");
|
|
trigger.setAttribute("aria-label", "Chat history");
|
|
this.historyDropdown = historyContainer.createDiv({ cls: "claudian-history-menu" });
|
|
trigger.addEventListener("click", (e) => {
|
|
var _a;
|
|
e.stopPropagation();
|
|
(_a = this.conversationController) == null ? void 0 : _a.toggleHistoryDropdown();
|
|
});
|
|
const newBtn = headerActions.createDiv({ cls: "claudian-header-btn" });
|
|
(0, import_obsidian25.setIcon)(newBtn, "plus");
|
|
newBtn.setAttribute("aria-label", "New conversation");
|
|
newBtn.addEventListener("click", () => {
|
|
var _a;
|
|
return (_a = this.conversationController) == null ? void 0 : _a.createNew();
|
|
});
|
|
}
|
|
buildInputArea(inputContainerEl) {
|
|
this.inputWrapper = inputContainerEl.createDiv({ cls: "claudian-input-wrapper" });
|
|
this.selectionIndicatorEl = this.inputWrapper.createDiv({ cls: "claudian-selection-indicator" });
|
|
this.selectionIndicatorEl.style.display = "none";
|
|
this.inputEl = this.inputWrapper.createEl("textarea", {
|
|
cls: "claudian-input",
|
|
attr: {
|
|
placeholder: "How can I help you today?",
|
|
rows: "3"
|
|
}
|
|
});
|
|
this.fileContextManager = new FileContextManager(
|
|
this.plugin.app,
|
|
inputContainerEl,
|
|
this.inputEl,
|
|
{
|
|
getExcludedTags: () => this.plugin.settings.excludedTags,
|
|
onChipsChanged: () => {
|
|
var _a;
|
|
return (_a = this.renderer) == null ? void 0 : _a.scrollToBottomIfNeeded();
|
|
},
|
|
getContextPaths: () => {
|
|
var _a;
|
|
return ((_a = this.contextPathSelector) == null ? void 0 : _a.getContextPaths()) || [];
|
|
}
|
|
}
|
|
);
|
|
this.fileContextManager.setMcpService(this.plugin.mcpService);
|
|
this.imageContextManager = new ImageContextManager(
|
|
this.plugin.app,
|
|
inputContainerEl,
|
|
this.inputEl,
|
|
{
|
|
onImagesChanged: () => {
|
|
var _a;
|
|
return (_a = this.renderer) == null ? void 0 : _a.scrollToBottomIfNeeded();
|
|
},
|
|
getMediaFolder: () => this.plugin.settings.mediaFolder
|
|
}
|
|
);
|
|
const vaultPath = getVaultPath(this.plugin.app);
|
|
if (vaultPath) {
|
|
this.slashCommandManager = new SlashCommandManager(this.plugin.app, vaultPath);
|
|
this.slashCommandManager.setCommands(this.plugin.settings.slashCommands);
|
|
this.slashCommandDropdown = new SlashCommandDropdown(
|
|
inputContainerEl,
|
|
this.inputEl,
|
|
{
|
|
onSelect: () => {
|
|
},
|
|
onHide: () => {
|
|
},
|
|
getCommands: () => this.plugin.settings.slashCommands
|
|
}
|
|
);
|
|
}
|
|
this.instructionRefineService = new InstructionRefineService(this.plugin);
|
|
this.titleGenerationService = new TitleGenerationService(this.plugin);
|
|
this.instructionModeManager = new InstructionModeManager(
|
|
this.inputEl,
|
|
{
|
|
onSubmit: async (rawInstruction) => {
|
|
var _a;
|
|
await ((_a = this.inputController) == null ? void 0 : _a.handleInstructionSubmit(rawInstruction));
|
|
},
|
|
getInputWrapper: () => this.inputWrapper
|
|
}
|
|
);
|
|
const inputToolbar = this.inputWrapper.createDiv({ cls: "claudian-input-toolbar" });
|
|
const toolbarComponents = createInputToolbar(inputToolbar, {
|
|
getSettings: () => ({
|
|
model: this.plugin.settings.model,
|
|
thinkingBudget: this.plugin.settings.thinkingBudget,
|
|
permissionMode: this.plugin.settings.permissionMode,
|
|
lastNonPlanPermissionMode: this.plugin.settings.lastNonPlanPermissionMode
|
|
}),
|
|
getEnvironmentVariables: () => this.plugin.getActiveEnvironmentVariables(),
|
|
isAgentInitiatedPlanMode: () => {
|
|
var _a, _b;
|
|
return (_b = (_a = this.state.planModeState) == null ? void 0 : _a.agentInitiated) != null ? _b : false;
|
|
},
|
|
isPlanModeRequested: () => this.state.planModeRequested,
|
|
onModelChange: async (model) => {
|
|
var _a, _b, _c;
|
|
this.plugin.settings.model = model;
|
|
const isDefaultModel = DEFAULT_CLAUDE_MODELS.find((m) => m.value === model);
|
|
if (isDefaultModel) {
|
|
this.plugin.settings.thinkingBudget = DEFAULT_THINKING_BUDGET[model];
|
|
this.plugin.settings.lastClaudeModel = model;
|
|
} else {
|
|
this.plugin.settings.lastCustomModel = model;
|
|
}
|
|
await this.plugin.saveSettings();
|
|
(_a = this.thinkingBudgetSelector) == null ? void 0 : _a.updateDisplay();
|
|
(_b = this.modelSelector) == null ? void 0 : _b.updateDisplay();
|
|
(_c = this.modelSelector) == null ? void 0 : _c.renderOptions();
|
|
},
|
|
onThinkingBudgetChange: async (budget) => {
|
|
this.plugin.settings.thinkingBudget = budget;
|
|
await this.plugin.saveSettings();
|
|
},
|
|
onPermissionModeChange: async (mode) => {
|
|
var _a;
|
|
const current = this.plugin.settings.permissionMode;
|
|
if (mode === "plan") {
|
|
if (current !== "plan") {
|
|
this.plugin.settings.lastNonPlanPermissionMode = current;
|
|
}
|
|
} else {
|
|
this.plugin.settings.lastNonPlanPermissionMode = mode;
|
|
}
|
|
this.plugin.settings.permissionMode = mode;
|
|
await this.plugin.saveSettings();
|
|
if (mode === "plan") {
|
|
if (!((_a = this.state.planModeState) == null ? void 0 : _a.isActive)) {
|
|
this.state.planModeState = {
|
|
isActive: true,
|
|
planFilePath: null,
|
|
planContent: null,
|
|
originalQuery: null,
|
|
agentInitiated: true
|
|
};
|
|
}
|
|
} else {
|
|
this.state.resetPlanModeState();
|
|
}
|
|
this.updatePlanModeUiState();
|
|
}
|
|
});
|
|
this.modelSelector = toolbarComponents.modelSelector;
|
|
this.thinkingBudgetSelector = toolbarComponents.thinkingBudgetSelector;
|
|
this.contextUsageMeter = toolbarComponents.contextUsageMeter;
|
|
this.contextPathSelector = toolbarComponents.contextPathSelector;
|
|
this.mcpServerSelector = toolbarComponents.mcpServerSelector;
|
|
this.permissionToggle = toolbarComponents.permissionToggle;
|
|
this.mcpServerSelector.setMcpService(this.plugin.mcpService);
|
|
this.fileContextManager.setOnMcpMentionChange((servers) => {
|
|
var _a;
|
|
(_a = this.mcpServerSelector) == null ? void 0 : _a.addMentionedServers(servers);
|
|
});
|
|
this.contextPathSelector.setOnChange(() => {
|
|
var _a;
|
|
(_a = this.fileContextManager) == null ? void 0 : _a.preScanContextPaths();
|
|
});
|
|
}
|
|
// ============================================
|
|
// Controller Initialization
|
|
// ============================================
|
|
initializeControllers() {
|
|
var _a;
|
|
this.selectionController = new SelectionController(
|
|
this.plugin.app,
|
|
this.selectionIndicatorEl,
|
|
this.inputEl
|
|
);
|
|
this.streamController = new StreamController({
|
|
plugin: this.plugin,
|
|
state: this.state,
|
|
renderer: this.renderer,
|
|
asyncSubagentManager: this.asyncSubagentManager,
|
|
getMessagesEl: () => this.messagesEl,
|
|
getFileContextManager: () => this.fileContextManager,
|
|
updateQueueIndicator: () => {
|
|
var _a2;
|
|
return (_a2 = this.inputController) == null ? void 0 : _a2.updateQueueIndicator();
|
|
},
|
|
setPlanModeActive: (_active) => {
|
|
this.updatePlanModeUiState();
|
|
}
|
|
});
|
|
this.conversationController = new ConversationController(
|
|
{
|
|
plugin: this.plugin,
|
|
state: this.state,
|
|
renderer: this.renderer,
|
|
asyncSubagentManager: this.asyncSubagentManager,
|
|
getHistoryDropdown: () => this.historyDropdown,
|
|
getWelcomeEl: () => this.welcomeEl,
|
|
setWelcomeEl: (el) => {
|
|
this.welcomeEl = el;
|
|
},
|
|
getMessagesEl: () => this.messagesEl,
|
|
getInputEl: () => this.inputEl,
|
|
getFileContextManager: () => this.fileContextManager,
|
|
getImageContextManager: () => this.imageContextManager,
|
|
getMcpServerSelector: () => this.mcpServerSelector,
|
|
getContextPathSelector: () => this.contextPathSelector,
|
|
clearQueuedMessage: () => {
|
|
var _a2;
|
|
return (_a2 = this.inputController) == null ? void 0 : _a2.clearQueuedMessage();
|
|
},
|
|
getApprovedPlan: () => this.plugin.agentService.getApprovedPlanContent(),
|
|
setApprovedPlan: (plan) => this.plugin.agentService.setApprovedPlanContent(plan),
|
|
showPlanBanner: (content) => {
|
|
var _a2;
|
|
void ((_a2 = this.planBanner) == null ? void 0 : _a2.show(content));
|
|
},
|
|
hidePlanBanner: () => {
|
|
var _a2;
|
|
return (_a2 = this.planBanner) == null ? void 0 : _a2.hide();
|
|
},
|
|
triggerPendingPlanApproval: (content) => {
|
|
var _a2;
|
|
return (_a2 = this.inputController) == null ? void 0 : _a2.restorePendingPlanApproval(content);
|
|
},
|
|
getTitleGenerationService: () => this.titleGenerationService,
|
|
setPlanModeActive: (_active) => {
|
|
this.updatePlanModeUiState();
|
|
},
|
|
getTodoPanel: () => this.todoPanel
|
|
},
|
|
{}
|
|
);
|
|
this.inputController = new InputController({
|
|
plugin: this.plugin,
|
|
state: this.state,
|
|
renderer: this.renderer,
|
|
streamController: this.streamController,
|
|
selectionController: this.selectionController,
|
|
conversationController: this.conversationController,
|
|
getInputEl: () => this.inputEl,
|
|
getWelcomeEl: () => this.welcomeEl,
|
|
getMessagesEl: () => this.messagesEl,
|
|
getFileContextManager: () => this.fileContextManager,
|
|
getImageContextManager: () => this.imageContextManager,
|
|
getSlashCommandManager: () => this.slashCommandManager,
|
|
getMcpServerSelector: () => this.mcpServerSelector,
|
|
getInstructionModeManager: () => this.instructionModeManager,
|
|
getInstructionRefineService: () => this.instructionRefineService,
|
|
getTitleGenerationService: () => this.titleGenerationService,
|
|
getComponent: () => this,
|
|
setPlanModeActive: (_active) => {
|
|
this.updatePlanModeUiState();
|
|
},
|
|
getPlanBanner: () => this.planBanner,
|
|
generateId: () => this.generateId(),
|
|
resetContextMeter: () => {
|
|
var _a2;
|
|
return (_a2 = this.contextUsageMeter) == null ? void 0 : _a2.update(null);
|
|
}
|
|
});
|
|
(_a = this.permissionToggle) == null ? void 0 : _a.setOnPlanModeToggle((active) => {
|
|
var _a2;
|
|
(_a2 = this.inputController) == null ? void 0 : _a2.setPlanModeRequested(active);
|
|
});
|
|
this.plugin.agentService.setApprovalCallback(
|
|
(toolName, input, description) => this.inputController.handleApprovalRequest(toolName, input, description)
|
|
);
|
|
this.plugin.agentService.setAskUserQuestionCallback(
|
|
(input) => this.inputController.handleAskUserQuestion(input)
|
|
);
|
|
this.plugin.agentService.setExitPlanModeCallback(
|
|
(planFilePath) => this.inputController.handleExitPlanMode(planFilePath)
|
|
);
|
|
this.plugin.agentService.setEnterPlanModeCallback(
|
|
() => this.inputController.handleEnterPlanMode()
|
|
);
|
|
this.navigationController = new NavigationController({
|
|
getMessagesEl: () => this.messagesEl,
|
|
getInputEl: () => this.inputEl,
|
|
getSettings: () => this.plugin.settings.keyboardNavigation,
|
|
isStreaming: () => this.state.isStreaming,
|
|
shouldSkipEscapeHandling: () => {
|
|
var _a2, _b, _c;
|
|
if ((_a2 = this.instructionModeManager) == null ? void 0 : _a2.isActive()) return true;
|
|
if ((_b = this.slashCommandDropdown) == null ? void 0 : _b.isVisible()) return true;
|
|
if ((_c = this.fileContextManager) == null ? void 0 : _c.isMentionDropdownVisible()) return true;
|
|
return false;
|
|
}
|
|
});
|
|
this.navigationController.initialize();
|
|
}
|
|
// ============================================
|
|
// Event Wiring
|
|
// ============================================
|
|
wireEventHandlers() {
|
|
this.registerDomEvent(document, "click", () => {
|
|
var _a;
|
|
(_a = this.historyDropdown) == null ? void 0 : _a.removeClass("visible");
|
|
});
|
|
this.registerDomEvent(document, "keydown", (e) => {
|
|
var _a;
|
|
if (e.key === "Escape" && this.state.isStreaming) {
|
|
e.preventDefault();
|
|
(_a = this.inputController) == null ? void 0 : _a.cancelStreaming();
|
|
}
|
|
});
|
|
this.registerEvent(this.plugin.app.vault.on("create", () => {
|
|
var _a;
|
|
return (_a = this.fileContextManager) == null ? void 0 : _a.markFilesCacheDirty();
|
|
}));
|
|
this.registerEvent(this.plugin.app.vault.on("delete", () => {
|
|
var _a;
|
|
return (_a = this.fileContextManager) == null ? void 0 : _a.markFilesCacheDirty();
|
|
}));
|
|
this.registerEvent(this.plugin.app.vault.on("rename", () => {
|
|
var _a;
|
|
return (_a = this.fileContextManager) == null ? void 0 : _a.markFilesCacheDirty();
|
|
}));
|
|
this.registerEvent(this.plugin.app.vault.on("modify", () => {
|
|
var _a;
|
|
return (_a = this.fileContextManager) == null ? void 0 : _a.markFilesCacheDirty();
|
|
}));
|
|
this.registerEvent(
|
|
this.plugin.app.workspace.on("file-open", (file) => {
|
|
var _a;
|
|
if (file) {
|
|
(_a = this.fileContextManager) == null ? void 0 : _a.handleFileOpen(file);
|
|
}
|
|
})
|
|
);
|
|
this.registerDomEvent(document, "click", (e) => {
|
|
var _a, _b;
|
|
if (!((_a = this.fileContextManager) == null ? void 0 : _a.containsElement(e.target)) && e.target !== this.inputEl) {
|
|
(_b = this.fileContextManager) == null ? void 0 : _b.hideMentionDropdown();
|
|
}
|
|
});
|
|
this.inputEl.addEventListener("keydown", (e) => {
|
|
var _a;
|
|
if (e.key === "Tab" && e.shiftKey && !this.state.isStreaming) {
|
|
e.preventDefault();
|
|
e.stopPropagation();
|
|
(_a = this.permissionToggle) == null ? void 0 : _a.togglePlanMode();
|
|
}
|
|
}, { capture: true });
|
|
this.inputEl.addEventListener("keydown", (e) => {
|
|
var _a, _b, _c, _d, _e, _f, _g, _h;
|
|
if ((_a = this.instructionModeManager) == null ? void 0 : _a.handleTriggerKey(e)) {
|
|
return;
|
|
}
|
|
if ((_b = this.instructionModeManager) == null ? void 0 : _b.handleKeydown(e)) {
|
|
return;
|
|
}
|
|
if ((_c = this.slashCommandDropdown) == null ? void 0 : _c.handleKeydown(e)) {
|
|
return;
|
|
}
|
|
if ((_d = this.fileContextManager) == null ? void 0 : _d.handleMentionKeydown(e)) {
|
|
return;
|
|
}
|
|
if (e.key === "Escape" && this.state.isStreaming) {
|
|
e.preventDefault();
|
|
(_e = this.inputController) == null ? void 0 : _e.cancelStreaming();
|
|
return;
|
|
}
|
|
if (e.key === "Enter" && !e.shiftKey && !e.isComposing) {
|
|
e.preventDefault();
|
|
if ((_f = this.permissionToggle) == null ? void 0 : _f.isPlanModeActive()) {
|
|
void ((_g = this.inputController) == null ? void 0 : _g.sendPlanModeMessage());
|
|
} else {
|
|
void ((_h = this.inputController) == null ? void 0 : _h.sendMessage());
|
|
}
|
|
}
|
|
});
|
|
this.inputEl.addEventListener("input", () => {
|
|
var _a, _b;
|
|
(_a = this.fileContextManager) == null ? void 0 : _a.handleInputChange();
|
|
(_b = this.instructionModeManager) == null ? void 0 : _b.handleInputChange();
|
|
});
|
|
this.inputEl.addEventListener("focus", () => {
|
|
var _a;
|
|
(_a = this.selectionController) == null ? void 0 : _a.showHighlight();
|
|
});
|
|
}
|
|
// ============================================
|
|
// Utilities
|
|
// ============================================
|
|
generateId() {
|
|
return `msg-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;
|
|
}
|
|
updatePlanModeUiState() {
|
|
var _a;
|
|
const isPlanMode = this.plugin.settings.permissionMode === "plan";
|
|
const isPlanModeRequested = this.state.planModeRequested;
|
|
(_a = this.permissionToggle) == null ? void 0 : _a.setPlanModeActive(isPlanMode || isPlanModeRequested);
|
|
}
|
|
};
|
|
|
|
// src/core/mcp/McpServerManager.ts
|
|
var McpServerManager = class {
|
|
constructor(storage) {
|
|
this.servers = [];
|
|
this.storage = storage;
|
|
}
|
|
/** Load servers from storage. */
|
|
async loadServers() {
|
|
this.servers = await this.storage.load();
|
|
}
|
|
/** Get all loaded servers. */
|
|
getServers() {
|
|
return this.servers;
|
|
}
|
|
/** Get enabled servers count. */
|
|
getEnabledCount() {
|
|
return this.servers.filter((s) => s.enabled).length;
|
|
}
|
|
/**
|
|
* Get servers to include in SDK options.
|
|
*
|
|
* A server is included if:
|
|
* - It is enabled AND
|
|
* - Either context-saving is disabled OR the server is @-mentioned
|
|
*
|
|
* @param mentionedNames Set of server names that were @-mentioned in the prompt
|
|
*/
|
|
getActiveServers(mentionedNames) {
|
|
const result = {};
|
|
for (const server of this.servers) {
|
|
if (!server.enabled) continue;
|
|
if (server.contextSaving && !mentionedNames.has(server.name)) {
|
|
continue;
|
|
}
|
|
result[server.name] = server.config;
|
|
}
|
|
return result;
|
|
}
|
|
/**
|
|
* Get disabled MCP tools formatted for SDK disallowedTools option.
|
|
*
|
|
* Only returns disabled tools from servers that would be active (same filter as getActiveServers).
|
|
*
|
|
* @param mentionedNames Set of server names that were @-mentioned in the prompt
|
|
*/
|
|
getDisallowedMcpTools(mentionedNames) {
|
|
const disallowed = /* @__PURE__ */ new Set();
|
|
for (const server of this.servers) {
|
|
if (!server.enabled) continue;
|
|
if (server.contextSaving && !mentionedNames.has(server.name)) {
|
|
continue;
|
|
}
|
|
if (!server.disabledTools || server.disabledTools.length === 0) continue;
|
|
for (const tool of server.disabledTools) {
|
|
const normalized = tool.trim();
|
|
if (!normalized) continue;
|
|
disallowed.add(`mcp__${server.name}__${normalized}`);
|
|
}
|
|
}
|
|
return Array.from(disallowed);
|
|
}
|
|
/** Check if any MCP servers are configured. */
|
|
hasServers() {
|
|
return this.servers.length > 0;
|
|
}
|
|
};
|
|
|
|
// src/features/mcp/McpService.ts
|
|
var McpService = class {
|
|
constructor(plugin) {
|
|
this.manager = new McpServerManager(plugin.storage.mcp);
|
|
}
|
|
// ============================================
|
|
// Delegated to McpServerManager (core)
|
|
// ============================================
|
|
/** Load servers from storage. */
|
|
async loadServers() {
|
|
return this.manager.loadServers();
|
|
}
|
|
/** Get all loaded servers. */
|
|
getServers() {
|
|
return this.manager.getServers();
|
|
}
|
|
/** Get enabled servers count. */
|
|
getEnabledCount() {
|
|
return this.manager.getEnabledCount();
|
|
}
|
|
/** Get servers to include in SDK options. */
|
|
getActiveServers(mentionedNames) {
|
|
return this.manager.getActiveServers(mentionedNames);
|
|
}
|
|
/** Check if any MCP servers are configured. */
|
|
hasServers() {
|
|
return this.manager.hasServers();
|
|
}
|
|
// ============================================
|
|
// Feature-specific: @-mention detection & UI
|
|
// ============================================
|
|
/** Get all server names for @-mention validation. */
|
|
getServerNames() {
|
|
return this.manager.getServers().map((s) => s.name);
|
|
}
|
|
/** Get enabled server names for @-mention validation. */
|
|
getEnabledServerNames() {
|
|
return this.manager.getServers().filter((s) => s.enabled).map((s) => s.name);
|
|
}
|
|
/** Get servers with context-saving enabled (for @-mention autocomplete). */
|
|
getContextSavingServers() {
|
|
return this.manager.getServers().filter((s) => s.enabled && s.contextSaving);
|
|
}
|
|
/** Check if a server name is valid for @-mention. */
|
|
isValidMcpMention(name) {
|
|
return this.manager.getServers().some((s) => s.name === name && s.enabled && s.contextSaving);
|
|
}
|
|
/**
|
|
* Extract MCP mentions from text.
|
|
* Only matches against enabled servers with context-saving mode.
|
|
*/
|
|
extractMentions(text) {
|
|
const validNames = new Set(
|
|
this.manager.getServers().filter((s) => s.enabled && s.contextSaving).map((s) => s.name)
|
|
);
|
|
return extractMcpMentions(text, validNames);
|
|
}
|
|
/** Check if any context-saving servers are enabled. */
|
|
hasContextSavingServers() {
|
|
return this.manager.getServers().some((s) => s.enabled && s.contextSaving);
|
|
}
|
|
/**
|
|
* Transform MCP mentions in text by appending " MCP" after each valid @mention.
|
|
* This is applied to API requests only, not shown in UI.
|
|
*/
|
|
transformMentions(text) {
|
|
const validNames = new Set(
|
|
this.manager.getServers().filter((s) => s.enabled && s.contextSaving).map((s) => s.name)
|
|
);
|
|
return transformMcpMentions(text, validNames);
|
|
}
|
|
// ============================================
|
|
// Access to underlying manager (for core layer)
|
|
// ============================================
|
|
/** Get the underlying server manager. */
|
|
getManager() {
|
|
return this.manager;
|
|
}
|
|
};
|
|
|
|
// src/features/settings/ClaudianSettings.ts
|
|
var fs9 = __toESM(require("fs"));
|
|
var import_obsidian26 = require("obsidian");
|
|
|
|
// src/features/settings/keyboardNavigation.ts
|
|
var NAV_ACTIONS = ["scrollUp", "scrollDown", "focusInput"];
|
|
var buildNavMappingText = (settings) => {
|
|
return [
|
|
`map ${settings.scrollUpKey} scrollUp`,
|
|
`map ${settings.scrollDownKey} scrollDown`,
|
|
`map ${settings.focusInputKey} focusInput`
|
|
].join("\n");
|
|
};
|
|
var parseNavMappings = (value) => {
|
|
const parsed = {};
|
|
const usedKeys = /* @__PURE__ */ new Map();
|
|
const lines = value.split("\n");
|
|
for (const rawLine of lines) {
|
|
const line = rawLine.trim();
|
|
if (!line) continue;
|
|
const parts = line.split(/\s+/);
|
|
if (parts.length !== 3 || parts[0] !== "map") {
|
|
return { error: 'Each line must follow "map <key> <action>"' };
|
|
}
|
|
const key = parts[1];
|
|
const action = parts[2];
|
|
if (!NAV_ACTIONS.includes(action)) {
|
|
return { error: `Unknown action: ${parts[2]}` };
|
|
}
|
|
if (key.length !== 1) {
|
|
return { error: `Key must be a single character for ${action}` };
|
|
}
|
|
const normalizedKey = key.toLowerCase();
|
|
if (usedKeys.has(normalizedKey)) {
|
|
return { error: "Navigation keys must be unique" };
|
|
}
|
|
if (parsed[action]) {
|
|
return { error: `Duplicate mapping for ${action}` };
|
|
}
|
|
usedKeys.set(normalizedKey, action);
|
|
parsed[action] = key;
|
|
}
|
|
const missing = NAV_ACTIONS.filter((action) => !parsed[action]);
|
|
if (missing.length > 0) {
|
|
return { error: `Missing mapping for ${missing.join(", ")}` };
|
|
}
|
|
return { settings: parsed };
|
|
};
|
|
|
|
// src/features/settings/ClaudianSettings.ts
|
|
function formatHotkey(hotkey) {
|
|
const isMac = navigator.platform.includes("Mac");
|
|
const modMap = isMac ? { Mod: "\u2318", Ctrl: "\u2303", Alt: "\u2325", Shift: "\u21E7", Meta: "\u2318" } : { Mod: "Ctrl", Ctrl: "Ctrl", Alt: "Alt", Shift: "Shift", Meta: "Win" };
|
|
const mods = hotkey.modifiers.map((m) => modMap[m] || m);
|
|
const key = hotkey.key.length === 1 ? hotkey.key.toUpperCase() : hotkey.key;
|
|
return isMac ? [...mods, key].join("") : [...mods, key].join("+");
|
|
}
|
|
function openHotkeySettings(app) {
|
|
const setting = app.setting;
|
|
setting.open();
|
|
setting.openTabById("hotkeys");
|
|
setTimeout(() => {
|
|
var _a, _b, _c;
|
|
const tab = setting.activeTab;
|
|
if (tab) {
|
|
const searchEl = (_b = tab.searchInputEl) != null ? _b : (_a = tab.searchComponent) == null ? void 0 : _a.inputEl;
|
|
if (searchEl) {
|
|
searchEl.value = "Claudian";
|
|
(_c = tab.updateHotkeyVisibility) == null ? void 0 : _c.call(tab);
|
|
}
|
|
}
|
|
}, 100);
|
|
}
|
|
function getHotkeyForCommand(app, commandId) {
|
|
var _a, _b;
|
|
const hotkeyManager = app.hotkeyManager;
|
|
if (!hotkeyManager) return null;
|
|
const customHotkeys = (_a = hotkeyManager.customKeys) == null ? void 0 : _a[commandId];
|
|
const defaultHotkeys = (_b = hotkeyManager.defaultKeys) == null ? void 0 : _b[commandId];
|
|
const hotkeys = (customHotkeys == null ? void 0 : customHotkeys.length) > 0 ? customHotkeys : defaultHotkeys;
|
|
if (!hotkeys || hotkeys.length === 0) return null;
|
|
return hotkeys.map(formatHotkey).join(", ");
|
|
}
|
|
var ClaudianSettingTab = class extends import_obsidian26.PluginSettingTab {
|
|
constructor(app, plugin) {
|
|
super(app, plugin);
|
|
this.plugin = plugin;
|
|
}
|
|
display() {
|
|
const { containerEl } = this;
|
|
containerEl.empty();
|
|
containerEl.addClass("claudian-settings");
|
|
new import_obsidian26.Setting(containerEl).setName("Customization").setHeading();
|
|
new import_obsidian26.Setting(containerEl).setName("What should Claudian call you?").setDesc("Your name for personalized greetings (leave empty for generic greetings)").addText(
|
|
(text) => text.setPlaceholder("Enter your name").setValue(this.plugin.settings.userName).onChange(async (value) => {
|
|
this.plugin.settings.userName = value;
|
|
await this.plugin.saveSettings();
|
|
})
|
|
);
|
|
new import_obsidian26.Setting(containerEl).setName("Excluded tags").setDesc("Notes with these tags will not auto-load as context (one per line, without #)").addTextArea((text) => {
|
|
text.setPlaceholder("system\nprivate\ndraft").setValue(this.plugin.settings.excludedTags.join("\n")).onChange(async (value) => {
|
|
this.plugin.settings.excludedTags = value.split(/\r?\n/).map((s) => s.trim().replace(/^#/, "")).filter((s) => s.length > 0);
|
|
await this.plugin.saveSettings();
|
|
});
|
|
text.inputEl.rows = 4;
|
|
text.inputEl.cols = 30;
|
|
});
|
|
new import_obsidian26.Setting(containerEl).setName("Media folder").setDesc("Folder containing attachments/images. When notes use ![[image.jpg]], Claude will look here. Leave empty for vault root.").addText((text) => {
|
|
text.setPlaceholder("attachments").setValue(this.plugin.settings.mediaFolder).onChange(async (value) => {
|
|
this.plugin.settings.mediaFolder = value.trim();
|
|
await this.plugin.saveSettings();
|
|
});
|
|
text.inputEl.addClass("claudian-settings-media-input");
|
|
});
|
|
new import_obsidian26.Setting(containerEl).setName("Custom system prompt").setDesc("Additional instructions appended to the default system prompt").addTextArea((text) => {
|
|
text.setPlaceholder("Add custom instructions here...").setValue(this.plugin.settings.systemPrompt).onChange(async (value) => {
|
|
this.plugin.settings.systemPrompt = value;
|
|
await this.plugin.saveSettings();
|
|
});
|
|
text.inputEl.rows = 6;
|
|
text.inputEl.cols = 50;
|
|
});
|
|
new import_obsidian26.Setting(containerEl).setName("Auto-generate conversation titles").setDesc("Automatically generate conversation titles after the first exchange.").addToggle(
|
|
(toggle) => toggle.setValue(this.plugin.settings.enableAutoTitleGeneration).onChange(async (value) => {
|
|
this.plugin.settings.enableAutoTitleGeneration = value;
|
|
await this.plugin.saveSettings();
|
|
this.display();
|
|
})
|
|
);
|
|
if (this.plugin.settings.enableAutoTitleGeneration) {
|
|
new import_obsidian26.Setting(containerEl).setName("Title generation model").setDesc("Model used for auto-generating conversation titles.").addDropdown((dropdown) => {
|
|
dropdown.addOption("", "Auto (Haiku)");
|
|
const envVars = parseEnvironmentVariables(this.plugin.settings.environmentVariables);
|
|
const customModels = getModelsFromEnvironment(envVars);
|
|
const models = customModels.length > 0 ? customModels : DEFAULT_CLAUDE_MODELS;
|
|
for (const model of models) {
|
|
dropdown.addOption(model.value, model.label);
|
|
}
|
|
dropdown.setValue(this.plugin.settings.titleGenerationModel || "").onChange(async (value) => {
|
|
this.plugin.settings.titleGenerationModel = value;
|
|
await this.plugin.saveSettings();
|
|
});
|
|
});
|
|
}
|
|
new import_obsidian26.Setting(containerEl).setName("Vim-style navigation mappings").setDesc('One mapping per line. Format: "map <key> <action>" (actions: scrollUp, scrollDown, focusInput).').addTextArea((text) => {
|
|
let pendingValue = buildNavMappingText(this.plugin.settings.keyboardNavigation);
|
|
let saveTimeout = null;
|
|
const commitValue = async (showError) => {
|
|
if (saveTimeout !== null) {
|
|
window.clearTimeout(saveTimeout);
|
|
saveTimeout = null;
|
|
}
|
|
const result = parseNavMappings(pendingValue);
|
|
if (!result.settings) {
|
|
if (showError) {
|
|
new import_obsidian26.Notice(`Invalid navigation mappings: ${result.error}`);
|
|
pendingValue = buildNavMappingText(this.plugin.settings.keyboardNavigation);
|
|
text.setValue(pendingValue);
|
|
}
|
|
return;
|
|
}
|
|
this.plugin.settings.keyboardNavigation.scrollUpKey = result.settings.scrollUp;
|
|
this.plugin.settings.keyboardNavigation.scrollDownKey = result.settings.scrollDown;
|
|
this.plugin.settings.keyboardNavigation.focusInputKey = result.settings.focusInput;
|
|
await this.plugin.saveSettings();
|
|
pendingValue = buildNavMappingText(this.plugin.settings.keyboardNavigation);
|
|
text.setValue(pendingValue);
|
|
};
|
|
const scheduleSave = () => {
|
|
if (saveTimeout !== null) {
|
|
window.clearTimeout(saveTimeout);
|
|
}
|
|
saveTimeout = window.setTimeout(() => {
|
|
void commitValue(false);
|
|
}, 500);
|
|
};
|
|
text.setPlaceholder("map w scrollUp\nmap s scrollDown\nmap i focusInput").setValue(pendingValue).onChange((value) => {
|
|
pendingValue = value;
|
|
scheduleSave();
|
|
});
|
|
text.inputEl.rows = 3;
|
|
text.inputEl.addEventListener("blur", async () => {
|
|
await commitValue(true);
|
|
});
|
|
});
|
|
new import_obsidian26.Setting(containerEl).setName("Hotkeys").setHeading();
|
|
const inlineEditCommandId = "claudian:inline-edit";
|
|
const inlineEditHotkey = getHotkeyForCommand(this.app, inlineEditCommandId);
|
|
new import_obsidian26.Setting(containerEl).setName("Inline edit hotkey").setDesc(inlineEditHotkey ? `Current: ${inlineEditHotkey}` : "No hotkey set. Click to configure.").addButton(
|
|
(button) => button.setButtonText(inlineEditHotkey ? "Change" : "Set hotkey").onClick(() => openHotkeySettings(this.app))
|
|
);
|
|
const openChatCommandId = "claudian:open-chat";
|
|
const openChatHotkey = getHotkeyForCommand(this.app, openChatCommandId);
|
|
new import_obsidian26.Setting(containerEl).setName("Open chat hotkey").setDesc(openChatHotkey ? `Current: ${openChatHotkey}` : "No hotkey set. Click to configure.").addButton(
|
|
(button) => button.setButtonText(openChatHotkey ? "Change" : "Set hotkey").onClick(() => openHotkeySettings(this.app))
|
|
);
|
|
new import_obsidian26.Setting(containerEl).setName("Slash Commands").setHeading();
|
|
const slashCommandsDesc = containerEl.createDiv({ cls: "claudian-slash-settings-desc" });
|
|
slashCommandsDesc.createEl("p", {
|
|
text: "Create custom prompt templates triggered by /command. Use $ARGUMENTS for all arguments, $1/$2 for positional args, @file for file content, and !`bash` for command output.",
|
|
cls: "setting-item-description"
|
|
});
|
|
const slashCommandsContainer = containerEl.createDiv({ cls: "claudian-slash-commands-container" });
|
|
new SlashCommandSettings(slashCommandsContainer, this.plugin);
|
|
new import_obsidian26.Setting(containerEl).setName("MCP Servers").setHeading();
|
|
const mcpDesc = containerEl.createDiv({ cls: "claudian-mcp-settings-desc" });
|
|
mcpDesc.createEl("p", {
|
|
text: "Configure Model Context Protocol servers to extend Claude's capabilities with external tools and data sources. Servers with context-saving mode require @mention to activate.",
|
|
cls: "setting-item-description"
|
|
});
|
|
const mcpContainer = containerEl.createDiv({ cls: "claudian-mcp-container" });
|
|
new McpSettingsManager(mcpContainer, this.plugin);
|
|
new import_obsidian26.Setting(containerEl).setName("Safety").setHeading();
|
|
new import_obsidian26.Setting(containerEl).setName("Enable command blocklist").setDesc("Block potentially dangerous bash commands").addToggle(
|
|
(toggle) => toggle.setValue(this.plugin.settings.enableBlocklist).onChange(async (value) => {
|
|
this.plugin.settings.enableBlocklist = value;
|
|
await this.plugin.saveSettings();
|
|
})
|
|
);
|
|
const platformKey = getCurrentPlatformKey();
|
|
const isWindows2 = platformKey === "windows";
|
|
const platformLabel = isWindows2 ? "Windows" : "Unix";
|
|
new import_obsidian26.Setting(containerEl).setName(`Blocked commands (${platformLabel})`).setDesc(`Patterns to block on ${platformLabel} (one per line). Supports regex.`).addTextArea((text) => {
|
|
const placeholder = isWindows2 ? "del /s /q\nrd /s /q\nRemove-Item -Recurse -Force" : "rm -rf\nchmod 777\nmkfs";
|
|
text.setPlaceholder(placeholder).setValue(this.plugin.settings.blockedCommands[platformKey].join("\n")).onChange(async (value) => {
|
|
this.plugin.settings.blockedCommands[platformKey] = value.split(/\r?\n/).map((s) => s.trim()).filter((s) => s.length > 0);
|
|
await this.plugin.saveSettings();
|
|
});
|
|
text.inputEl.rows = 6;
|
|
text.inputEl.cols = 40;
|
|
});
|
|
if (isWindows2) {
|
|
new import_obsidian26.Setting(containerEl).setName("Blocked commands (Unix/Git Bash)").setDesc("Unix patterns also blocked on Windows because Git Bash can invoke them.").addTextArea((text) => {
|
|
text.setPlaceholder("rm -rf\nchmod 777\nmkfs").setValue(this.plugin.settings.blockedCommands.unix.join("\n")).onChange(async (value) => {
|
|
this.plugin.settings.blockedCommands.unix = value.split(/\r?\n/).map((s) => s.trim()).filter((s) => s.length > 0);
|
|
await this.plugin.saveSettings();
|
|
});
|
|
text.inputEl.rows = 4;
|
|
text.inputEl.cols = 40;
|
|
});
|
|
}
|
|
new import_obsidian26.Setting(containerEl).setName("Allowed export paths").setDesc("Paths outside the vault where files can be exported (one per line). Supports ~ for home directory.").addTextArea((text) => {
|
|
const placeholder = process.platform === "win32" ? "~/Desktop\n~/Downloads\n%TEMP%" : "~/Desktop\n~/Downloads\n/tmp";
|
|
text.setPlaceholder(placeholder).setValue(this.plugin.settings.allowedExportPaths.join("\n")).onChange(async (value) => {
|
|
this.plugin.settings.allowedExportPaths = value.split(/\r?\n/).map((s) => s.trim()).filter((s) => s.length > 0);
|
|
await this.plugin.saveSettings();
|
|
});
|
|
text.inputEl.rows = 4;
|
|
text.inputEl.cols = 40;
|
|
});
|
|
const approvedDesc = containerEl.createDiv({ cls: "claudian-approved-desc" });
|
|
approvedDesc.createEl("p", {
|
|
text: 'Actions that have been permanently approved (via "Always Allow"). These will not require approval in Safe mode.',
|
|
cls: "setting-item-description"
|
|
});
|
|
const permissions = this.plugin.settings.permissions;
|
|
if (permissions.length === 0) {
|
|
const emptyEl = containerEl.createDiv({ cls: "claudian-approved-empty" });
|
|
emptyEl.setText('No approved actions yet. When you click "Always Allow" in the approval dialog, actions will appear here.');
|
|
} else {
|
|
const listEl = containerEl.createDiv({ cls: "claudian-approved-list" });
|
|
for (const action of permissions) {
|
|
const itemEl = listEl.createDiv({ cls: "claudian-approved-item" });
|
|
const infoEl = itemEl.createDiv({ cls: "claudian-approved-item-info" });
|
|
const toolEl = infoEl.createSpan({ cls: "claudian-approved-item-tool" });
|
|
toolEl.setText(action.toolName);
|
|
const patternEl = infoEl.createDiv({ cls: "claudian-approved-item-pattern" });
|
|
patternEl.setText(action.pattern);
|
|
const dateEl = infoEl.createSpan({ cls: "claudian-approved-item-date" });
|
|
dateEl.setText(new Date(action.approvedAt).toLocaleDateString());
|
|
const removeBtn = itemEl.createEl("button", {
|
|
text: "Remove",
|
|
cls: "claudian-approved-remove-btn"
|
|
});
|
|
removeBtn.addEventListener("click", async () => {
|
|
this.plugin.settings.permissions = this.plugin.settings.permissions.filter((a) => a !== action);
|
|
await this.plugin.saveSettings();
|
|
this.display();
|
|
});
|
|
}
|
|
new import_obsidian26.Setting(containerEl).setName("Clear all approved actions").setDesc("Remove all permanently approved actions").addButton(
|
|
(button) => button.setButtonText("Clear all").setWarning().onClick(async () => {
|
|
this.plugin.settings.permissions = [];
|
|
await this.plugin.saveSettings();
|
|
this.display();
|
|
})
|
|
);
|
|
}
|
|
new import_obsidian26.Setting(containerEl).setName("Environment").setHeading();
|
|
new import_obsidian26.Setting(containerEl).setName("Custom variables").setDesc("Environment variables for Claude SDK (KEY=VALUE format, one per line)").addTextArea((text) => {
|
|
text.setPlaceholder("ANTHROPIC_API_KEY=your-key\nANTHROPIC_BASE_URL=https://api.example.com\nANTHROPIC_MODEL=custom-model").setValue(this.plugin.settings.environmentVariables).onChange(async (value) => {
|
|
await this.plugin.applyEnvironmentVariables(value);
|
|
});
|
|
text.inputEl.rows = 6;
|
|
text.inputEl.cols = 50;
|
|
text.inputEl.addClass("claudian-settings-env-textarea");
|
|
});
|
|
const envSnippetsContainer = containerEl.createDiv({ cls: "claudian-env-snippets-container" });
|
|
new EnvSnippetManager(envSnippetsContainer, this.plugin);
|
|
new import_obsidian26.Setting(containerEl).setName("Advanced").setHeading();
|
|
const cliPathSetting = new import_obsidian26.Setting(containerEl).setName("Claude CLI path").setDesc("Custom path to Claude Code CLI. Leave empty for auto-detection. Use cli.js path on Windows for npm installations.");
|
|
const validationEl = containerEl.createDiv({ cls: "claudian-cli-path-validation" });
|
|
validationEl.style.color = "var(--text-error)";
|
|
validationEl.style.fontSize = "0.85em";
|
|
validationEl.style.marginTop = "-0.5em";
|
|
validationEl.style.marginBottom = "0.5em";
|
|
validationEl.style.display = "none";
|
|
const validatePath = (value) => {
|
|
const trimmed = value.trim();
|
|
if (!trimmed) return null;
|
|
const expandedPath = expandHomePath(trimmed);
|
|
if (!fs9.existsSync(expandedPath)) {
|
|
return "Path does not exist";
|
|
}
|
|
const stat = fs9.statSync(expandedPath);
|
|
if (!stat.isFile()) {
|
|
return "Path is a directory, not a file";
|
|
}
|
|
return null;
|
|
};
|
|
cliPathSetting.addText((text) => {
|
|
const placeholder = process.platform === "win32" ? "D:\\nodejs\\node_global\\node_modules\\@anthropic-ai\\claude-code\\cli.js" : "/usr/local/lib/node_modules/@anthropic-ai/claude-code/cli.js";
|
|
text.setPlaceholder(placeholder).setValue(this.plugin.settings.claudeCliPath || "").onChange(async (value) => {
|
|
var _a;
|
|
const error2 = validatePath(value);
|
|
if (error2) {
|
|
validationEl.setText(error2);
|
|
validationEl.style.display = "block";
|
|
text.inputEl.style.borderColor = "var(--text-error)";
|
|
} else {
|
|
validationEl.style.display = "none";
|
|
text.inputEl.style.borderColor = "";
|
|
}
|
|
this.plugin.settings.claudeCliPath = value.trim();
|
|
await this.plugin.saveSettings();
|
|
(_a = this.plugin.agentService) == null ? void 0 : _a.cleanup();
|
|
});
|
|
text.inputEl.addClass("claudian-settings-cli-path-input");
|
|
text.inputEl.style.width = "100%";
|
|
const initialError = validatePath(this.plugin.settings.claudeCliPath || "");
|
|
if (initialError) {
|
|
validationEl.setText(initialError);
|
|
validationEl.style.display = "block";
|
|
text.inputEl.style.borderColor = "var(--text-error)";
|
|
}
|
|
});
|
|
}
|
|
};
|
|
|
|
// src/main.ts
|
|
var ClaudianPlugin = class extends import_obsidian27.Plugin {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.conversations = [];
|
|
this.activeConversationId = null;
|
|
this.runtimeEnvironmentVariables = "";
|
|
this.hasNotifiedEnvChange = false;
|
|
}
|
|
async onload() {
|
|
await this.loadSettings();
|
|
this.mcpService = new McpService(this);
|
|
await this.mcpService.loadServers();
|
|
this.agentService = new ClaudianService(this, this.mcpService.getManager());
|
|
this.registerView(
|
|
VIEW_TYPE_CLAUDIAN,
|
|
(leaf) => new ClaudianView(leaf, this)
|
|
);
|
|
this.addRibbonIcon("bot", "Open Claudian", () => {
|
|
this.activateView();
|
|
});
|
|
this.addCommand({
|
|
id: "open-view",
|
|
name: "Open chat view",
|
|
callback: () => {
|
|
this.activateView();
|
|
}
|
|
});
|
|
this.addCommand({
|
|
id: "inline-edit",
|
|
name: "Inline edit",
|
|
editorCallback: async (editor, view) => {
|
|
var _a;
|
|
const selectedText = editor.getSelection();
|
|
const notePath = ((_a = view.file) == null ? void 0 : _a.path) || "unknown";
|
|
let editContext;
|
|
if (selectedText.trim()) {
|
|
editContext = { mode: "selection", selectedText };
|
|
} else {
|
|
const cursor = editor.getCursor();
|
|
const cursorContext = buildCursorContext(
|
|
(line) => editor.getLine(line),
|
|
editor.lineCount(),
|
|
cursor.line,
|
|
cursor.ch
|
|
);
|
|
editContext = { mode: "cursor", cursorContext };
|
|
}
|
|
const modal = new InlineEditModal(this.app, this, editContext, notePath);
|
|
const result = await modal.openAndWait();
|
|
if (result.decision === "accept" && result.editedText !== void 0) {
|
|
new import_obsidian27.Notice(editContext.mode === "cursor" ? "Inserted" : "Edit applied");
|
|
}
|
|
}
|
|
});
|
|
this.addSettingTab(new ClaudianSettingTab(this.app, this));
|
|
}
|
|
onunload() {
|
|
this.agentService.cleanup();
|
|
}
|
|
/** Opens the Claudian sidebar view, creating it if necessary. */
|
|
async activateView() {
|
|
const { workspace } = this.app;
|
|
let leaf = workspace.getLeavesOfType(VIEW_TYPE_CLAUDIAN)[0];
|
|
if (!leaf) {
|
|
const rightLeaf = workspace.getRightLeaf(false);
|
|
if (rightLeaf) {
|
|
await rightLeaf.setViewState({
|
|
type: VIEW_TYPE_CLAUDIAN,
|
|
active: true
|
|
});
|
|
leaf = rightLeaf;
|
|
}
|
|
}
|
|
if (leaf) {
|
|
workspace.revealLeaf(leaf);
|
|
}
|
|
}
|
|
/** Loads settings and conversations from persistent storage. */
|
|
async loadSettings() {
|
|
this.storage = new StorageService(this);
|
|
const { settings, state } = await this.storage.initialize();
|
|
const slashCommands = await this.storage.commands.loadAll();
|
|
this.settings = {
|
|
...DEFAULT_SETTINGS,
|
|
...settings,
|
|
// State fields from data.json
|
|
lastEnvHash: state.lastEnvHash,
|
|
lastClaudeModel: state.lastClaudeModel,
|
|
lastCustomModel: state.lastCustomModel,
|
|
slashCommands
|
|
};
|
|
this.conversations = await this.storage.sessions.loadAllConversations();
|
|
this.activeConversationId = state.activeConversationId;
|
|
if (this.activeConversationId && !this.conversations.find((c) => c.id === this.activeConversationId)) {
|
|
this.activeConversationId = null;
|
|
}
|
|
const backfilledConversations = this.backfillConversationResponseTimestamps();
|
|
this.runtimeEnvironmentVariables = this.settings.environmentVariables || "";
|
|
const { changed, invalidatedConversations } = this.reconcileModelWithEnvironment(this.runtimeEnvironmentVariables);
|
|
if (changed) {
|
|
await this.saveSettings();
|
|
}
|
|
const conversationsToSave = /* @__PURE__ */ new Set([...backfilledConversations, ...invalidatedConversations]);
|
|
for (const conv of conversationsToSave) {
|
|
await this.storage.sessions.saveConversation(conv);
|
|
}
|
|
}
|
|
backfillConversationResponseTimestamps() {
|
|
const updated = [];
|
|
for (const conv of this.conversations) {
|
|
if (conv.lastResponseAt != null) continue;
|
|
if (!conv.messages || conv.messages.length === 0) continue;
|
|
for (let i = conv.messages.length - 1; i >= 0; i--) {
|
|
const msg = conv.messages[i];
|
|
if (msg.role === "assistant") {
|
|
conv.lastResponseAt = msg.timestamp;
|
|
updated.push(conv);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
return updated;
|
|
}
|
|
/** Persists settings to storage. */
|
|
async saveSettings() {
|
|
const {
|
|
slashCommands: _,
|
|
lastEnvHash: __,
|
|
lastClaudeModel: ___,
|
|
lastCustomModel: ____,
|
|
...settingsToSave
|
|
} = this.settings;
|
|
await this.storage.settings.save(settingsToSave);
|
|
await this.storage.saveState({
|
|
activeConversationId: this.activeConversationId,
|
|
lastEnvHash: this.settings.lastEnvHash || "",
|
|
lastClaudeModel: this.settings.lastClaudeModel || "haiku",
|
|
lastCustomModel: this.settings.lastCustomModel || ""
|
|
});
|
|
}
|
|
/** Updates and persists environment variables, notifying if restart is needed. */
|
|
async applyEnvironmentVariables(envText) {
|
|
this.settings.environmentVariables = envText;
|
|
await this.saveSettings();
|
|
if (envText !== this.runtimeEnvironmentVariables) {
|
|
if (!this.hasNotifiedEnvChange) {
|
|
new import_obsidian27.Notice("Environment variables changed. Restart the plugin for changes to take effect.");
|
|
this.hasNotifiedEnvChange = true;
|
|
}
|
|
} else {
|
|
this.hasNotifiedEnvChange = false;
|
|
}
|
|
}
|
|
/** Returns the runtime environment variables (fixed at plugin load). */
|
|
getActiveEnvironmentVariables() {
|
|
return this.runtimeEnvironmentVariables;
|
|
}
|
|
getDefaultModelValues() {
|
|
return DEFAULT_CLAUDE_MODELS.map((m) => m.value);
|
|
}
|
|
getPreferredCustomModel(envVars, customModels) {
|
|
const envPreferred = getCurrentModelFromEnvironment(envVars);
|
|
if (envPreferred && customModels.some((m) => m.value === envPreferred)) {
|
|
return envPreferred;
|
|
}
|
|
return customModels[0].value;
|
|
}
|
|
/** Computes a hash of model and provider base URL environment variables for change detection. */
|
|
computeEnvHash(envText) {
|
|
const envVars = parseEnvironmentVariables(envText || "");
|
|
const modelKeys = [
|
|
"ANTHROPIC_MODEL",
|
|
"ANTHROPIC_DEFAULT_OPUS_MODEL",
|
|
"ANTHROPIC_DEFAULT_SONNET_MODEL",
|
|
"ANTHROPIC_DEFAULT_HAIKU_MODEL"
|
|
];
|
|
const providerKeys = [
|
|
"ANTHROPIC_BASE_URL"
|
|
];
|
|
const allKeys = [...modelKeys, ...providerKeys];
|
|
const relevantPairs = allKeys.filter((key) => envVars[key]).map((key) => `${key}=${envVars[key]}`).sort().join("|");
|
|
return relevantPairs;
|
|
}
|
|
/**
|
|
* Reconciles model with environment.
|
|
* Returns { changed, invalidatedConversations } where changed indicates if
|
|
* settings were modified (requiring save), and invalidatedConversations lists
|
|
* conversations that had their sessionId cleared (also requiring save).
|
|
*/
|
|
reconcileModelWithEnvironment(envText) {
|
|
var _a;
|
|
const currentHash = this.computeEnvHash(envText);
|
|
const savedHash = this.settings.lastEnvHash || "";
|
|
if (currentHash === savedHash) {
|
|
return { changed: false, invalidatedConversations: [] };
|
|
}
|
|
(_a = this.agentService) == null ? void 0 : _a.resetSession();
|
|
const invalidatedConversations = [];
|
|
for (const conv of this.conversations) {
|
|
if (conv.sessionId) {
|
|
conv.sessionId = null;
|
|
invalidatedConversations.push(conv);
|
|
}
|
|
}
|
|
const envVars = parseEnvironmentVariables(envText || "");
|
|
const customModels = getModelsFromEnvironment(envVars);
|
|
if (customModels.length > 0) {
|
|
this.settings.model = this.getPreferredCustomModel(envVars, customModels);
|
|
} else {
|
|
this.settings.model = DEFAULT_CLAUDE_MODELS[0].value;
|
|
}
|
|
this.settings.lastEnvHash = currentHash;
|
|
return { changed: true, invalidatedConversations };
|
|
}
|
|
/** Removes cached images associated with a conversation if not used elsewhere. */
|
|
cleanupConversationImages(conversation) {
|
|
const cachePaths = /* @__PURE__ */ new Set();
|
|
for (const message of conversation.messages || []) {
|
|
if (!message.images) continue;
|
|
for (const img of message.images) {
|
|
if (img.cachePath) {
|
|
cachePaths.add(img.cachePath);
|
|
}
|
|
}
|
|
}
|
|
if (cachePaths.size === 0) return;
|
|
const inUseElsewhere = /* @__PURE__ */ new Set();
|
|
for (const conv of this.conversations) {
|
|
if (conv.id === conversation.id) continue;
|
|
for (const msg of conv.messages || []) {
|
|
if (!msg.images) continue;
|
|
for (const img of msg.images) {
|
|
if (img.cachePath && cachePaths.has(img.cachePath)) {
|
|
inUseElsewhere.add(img.cachePath);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
const deletable = Array.from(cachePaths).filter((p) => !inUseElsewhere.has(p));
|
|
if (deletable.length > 0) {
|
|
deleteCachedImages(this.app, deletable);
|
|
}
|
|
}
|
|
generateConversationId() {
|
|
return `conv-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;
|
|
}
|
|
generateDefaultTitle() {
|
|
const now = /* @__PURE__ */ new Date();
|
|
return now.toLocaleString(void 0, {
|
|
month: "short",
|
|
day: "numeric",
|
|
hour: "2-digit",
|
|
minute: "2-digit"
|
|
});
|
|
}
|
|
getConversationPreview(conv) {
|
|
const firstUserMsg = conv.messages.find((m) => m.role === "user");
|
|
if (!firstUserMsg) return "New conversation";
|
|
return firstUserMsg.content.substring(0, 50) + (firstUserMsg.content.length > 50 ? "..." : "");
|
|
}
|
|
/** Creates a new conversation and sets it as active. */
|
|
async createConversation() {
|
|
const conversation = {
|
|
id: this.generateConversationId(),
|
|
title: this.generateDefaultTitle(),
|
|
createdAt: Date.now(),
|
|
updatedAt: Date.now(),
|
|
sessionId: null,
|
|
messages: []
|
|
};
|
|
this.conversations.unshift(conversation);
|
|
this.activeConversationId = conversation.id;
|
|
this.agentService.resetSession();
|
|
await this.storage.sessions.saveConversation(conversation);
|
|
await this.storage.updateState({ activeConversationId: this.activeConversationId });
|
|
return conversation;
|
|
}
|
|
/** Switches to an existing conversation by ID. */
|
|
async switchConversation(id) {
|
|
const conversation = this.conversations.find((c) => c.id === id);
|
|
if (!conversation) return null;
|
|
this.activeConversationId = id;
|
|
this.agentService.setSessionId(conversation.sessionId);
|
|
await this.storage.updateState({ activeConversationId: this.activeConversationId });
|
|
return conversation;
|
|
}
|
|
/** Deletes a conversation and switches to another if necessary. */
|
|
async deleteConversation(id) {
|
|
const index = this.conversations.findIndex((c) => c.id === id);
|
|
if (index === -1) return;
|
|
const conversation = this.conversations[index];
|
|
this.cleanupConversationImages(conversation);
|
|
this.conversations.splice(index, 1);
|
|
await this.storage.sessions.deleteConversation(id);
|
|
if (this.activeConversationId === id) {
|
|
if (this.conversations.length > 0) {
|
|
await this.switchConversation(this.conversations[0].id);
|
|
} else {
|
|
await this.createConversation();
|
|
}
|
|
}
|
|
}
|
|
/** Renames a conversation. */
|
|
async renameConversation(id, title) {
|
|
const conversation = this.conversations.find((c) => c.id === id);
|
|
if (!conversation) return;
|
|
conversation.title = title.trim() || this.generateDefaultTitle();
|
|
conversation.updatedAt = Date.now();
|
|
await this.storage.sessions.saveConversation(conversation);
|
|
}
|
|
/** Updates conversation properties (messages, sessionId, etc.). */
|
|
async updateConversation(id, updates) {
|
|
const conversation = this.conversations.find((c) => c.id === id);
|
|
if (!conversation) return;
|
|
Object.assign(conversation, updates, { updatedAt: Date.now() });
|
|
await this.storage.sessions.saveConversation(conversation);
|
|
}
|
|
/** Returns the current active conversation. */
|
|
getActiveConversation() {
|
|
return this.conversations.find((c) => c.id === this.activeConversationId) || null;
|
|
}
|
|
/** Gets a conversation by ID from the in-memory cache. */
|
|
getConversationById(id) {
|
|
return this.conversations.find((c) => c.id === id) || null;
|
|
}
|
|
/** Finds an existing empty conversation (no messages). */
|
|
findEmptyConversation() {
|
|
return this.conversations.find((c) => c.messages.length === 0) || null;
|
|
}
|
|
/** Returns conversation metadata list for the history dropdown. */
|
|
getConversationList() {
|
|
return this.conversations.map((c) => ({
|
|
id: c.id,
|
|
title: c.title,
|
|
createdAt: c.createdAt,
|
|
updatedAt: c.updatedAt,
|
|
lastResponseAt: c.lastResponseAt,
|
|
messageCount: c.messages.length,
|
|
preview: this.getConversationPreview(c),
|
|
titleGenerationStatus: c.titleGenerationStatus
|
|
}));
|
|
}
|
|
/** Returns the active Claudian view from workspace, if open. */
|
|
getView() {
|
|
const leaves = this.app.workspace.getLeavesOfType(VIEW_TYPE_CLAUDIAN);
|
|
if (leaves.length > 0) {
|
|
return leaves[0].view;
|
|
}
|
|
return null;
|
|
}
|
|
};
|