"use strict"; 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 __name = (target, value) => __defProp(target, "name", { value, configurable: true }); 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); // packages/alconna/src/index.ts var src_exports = {}; __export(src_exports, { Action: () => Action, Arg: () => Arg, ArgFlag: () => ArgFlag, Args: () => Args, ArgumentMissing: () => ArgumentMissing, BehaveCancelled: () => BehaveCancelled, Behavior: () => Behavior, Command: () => Command, CommandMeta: () => CommandMeta, CommandNode: () => CommandNode, ExceedMaxCount: () => ExceedMaxCount, ExecuteFailed: () => ExecuteFailed, Field: () => Field, FuzzyMatchSuccess: () => FuzzyMatchSuccess, HeadResult: () => HeadResult, InvalidParam: () => InvalidParam, KeyWordVar: () => KeyWordVar, LruCache: () => LruCache, MultiVar: () => MultiVar, Namespace: () => Namespace, NullMessage: () => NullMessage, Option: () => Option, OptionResult: () => OptionResult, OutBoundsBehave: () => OutBoundsBehave, ParamsUnmatched: () => ParamsUnmatched, ParseResult: () => ParseResult, PauseTriggered: () => PauseTriggered, Sentence: () => Sentence, SpecialOptionTriggered: () => SpecialOptionTriggered, Subcommand: () => Subcommand, SubcommandResult: () => SubcommandResult, TextFormatter: () => TextFormatter, UnexpectedElement: () => UnexpectedElement, config: () => config, execArgs: () => execArgs, execData: () => execData, format: () => format, formatKeys: () => formatKeys, levenshteinNorm: () => levenshteinNorm, load_lang: () => load_lang, manager: () => manager, outputManager: () => outputManager, split: () => split, splitOnce: () => splitOnce, withNamespace: () => withNamespace }); module.exports = __toCommonJS(src_exports); // packages/alconna/src/util.ts function splitOnce(command, sep = [" "], crlf = true) { let result = []; let buffer = []; let quote = null; let escape = false; command = command.trimStart(); for (let i = 0; i < command.length; i++) { let char = command[i]; if (escape) { escape = false; buffer.push(char); } else if (char === "\\") { escape = true; } else if (quote) { if (char === quote) { quote = null; } else { buffer.push(char); } } else if (char === "'" || char === '"' || char === "`" || char === "“" || char === "”") { quote = char; } else if (sep.includes(char)) { if (buffer.length > 0) { result.push(buffer.join("")); buffer = []; } return [result.join(" "), command.substring(i + 1)]; } else if (crlf && (char === "\r" || char === "\n")) { if (buffer.length > 0) { result.push(buffer.join("")); buffer = []; } return [result.join(" "), command.substring(i + 1)]; } else { buffer.push(char); } } if (buffer.length > 0) { result.push(buffer.join("")); } return [result.join(" "), ""]; } __name(splitOnce, "splitOnce"); function split(command, sep = [" "], crlf = true) { let result = []; let buffer = []; let quote = null; let escape = false; for (let i = 0; i < command.length; i++) { let char = command[i]; if (escape) { escape = false; buffer.push(char); } else if (char === "\\") { escape = true; } else if (quote) { if (char === quote) { quote = null; } else { buffer.push(char); } } else if (char === "'" || char === '"' || char === "`" || char === "“" || char === "”") { quote = char; } else if (sep.includes(char) || crlf && (char === "\r" || char === "\n")) { if (buffer.length > 0) { result.push(buffer.join("")); buffer = []; } } else { buffer.push(char); } } if (buffer.length > 0) { result.push(buffer.join("")); } return result; } __name(split, "split"); function levenshteinNorm(source, target) { let distance = levenshtein(source, target); return 1 - distance / Math.max(source.length, target.length); } __name(levenshteinNorm, "levenshteinNorm"); function levenshtein(source, target) { let matrix = []; for (let i = 0; i <= source.length; i++) { matrix[i] = [i]; } for (let j = 0; j <= target.length; j++) { matrix[0][j] = j; } for (let i = 1; i <= source.length; i++) { for (let j = 1; j <= target.length; j++) { if (source[i - 1] === target[j - 1]) { matrix[i][j] = matrix[i - 1][j - 1]; } else { matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j] + 1); } } } return matrix[source.length][target.length]; } __name(levenshtein, "levenshtein"); function format(text, ...args) { let i = 0; return text.replace(`{${i}}`, () => { return args[i++]; }); } __name(format, "format"); function formatKeys(text, keys) { return text.replace(/\{([^\}]+)\}/g, (match, key) => { return keys[key]; }); } __name(formatKeys, "formatKeys"); // packages/alconna/src/collection.ts var DoubleLinkedListNode = class { constructor(key, value) { this.key = key; this.value = value; this.prev = null; this.next = null; } }; __name(DoubleLinkedListNode, "DoubleLinkedListNode"); var DoubleLinkedList = class { constructor() { this.head = new DoubleLinkedListNode(); this.tail = new DoubleLinkedListNode(); this.head.next = this.tail; this.tail.prev = this.head; } toHead(node) { node.next = this.head.next; node.prev = this.head; this.head.next.prev = node; this.head.next = node; } add(node) { let prev = this.tail.prev; prev.next = node; node.prev = prev; node.next = this.tail; this.tail.prev = node; } remove(node) { node.prev.next = node.next; node.next.prev = node.prev; return node.key; } removeTail() { if (this.tail.prev === this.head || this.head.next === this.tail) { return void 0; } return this.remove(this.tail.prev); } }; __name(DoubleLinkedList, "DoubleLinkedList"); var LruCache = class { constructor(capacity = -1) { this.capacity = capacity; this.map = /* @__PURE__ */ new Map(); this.list = new DoubleLinkedList(); } get(key, defaultValue) { let node = this.map.get(key); if (node) { this.set(key, node.value); return node.value; } return defaultValue; } set(key, value) { if (this.map.has(key)) { const node = this.map.get(key); node.value = value; this.list.remove(node); this.list.toHead(node); } else { if (this.capacity >= 0 && this.map.size >= this.capacity) { const k = this.list.removeTail(); if (k) { this.map.delete(k); } } const node = new DoubleLinkedListNode(key, value); this.map.set(key, node); this.list.toHead(node); } } [Symbol.iterator]() { let node = this.list.head.next; let end = this.list.tail; return { next: (...args) => { if (node === end) { return { done: true, value: void 0 }; } else { let value = [node.key, node.value]; node = node.next; return { done: false, value }; } } }; } delete(key) { let node = this.map.get(key); if (node) { this.list.remove(node); this.map.delete(key); } } size() { return this.map.size; } clear() { this.map.clear(); this.list = new DoubleLinkedList(); } has(key) { return this.map.has(key); } get length() { return this.map.size; } get recent() { if (this.list.head.next === this.list.tail) { return null; } return this.list.head.next.value; } keys() { return this.map.keys(); } values() { return this.map.values(); } entries() { return this.map.entries(); } toString() { let str = ""; for (let node = this.list.head.next; node !== this.list.tail; node = node.next) { str += `${node.key} -> ${node.value}, `; } return str; } }; __name(LruCache, "LruCache"); // packages/alconna/src/errors.ts var ParamsUnmatched = class extends Error { constructor(message) { super(message); this.name = "ParamsUnmatched"; } }; __name(ParamsUnmatched, "ParamsUnmatched"); var ArgumentMissing = class extends Error { constructor(message) { super(message); this.name = "ArgumentMissing"; } }; __name(ArgumentMissing, "ArgumentMissing"); var InvalidParam = class extends Error { constructor(message) { super(message); this.name = "InvalidParam"; } }; __name(InvalidParam, "InvalidParam"); var NullMessage = class extends Error { constructor(message) { super(message); this.name = "NullMessage"; } }; __name(NullMessage, "NullMessage"); var UnexpectedElement = class extends Error { constructor(message) { super(message); this.name = "UnexpectedElement"; } }; __name(UnexpectedElement, "UnexpectedElement"); var ExecuteFailed = class extends Error { constructor(message) { super(message); this.name = "ExecuteFailed"; } }; __name(ExecuteFailed, "ExecuteFailed"); var ExceedMaxCount = class extends Error { constructor(message) { super(message); this.name = "ExceedMaxCount"; } }; __name(ExceedMaxCount, "ExceedMaxCount"); var BehaveCancelled = class extends Error { constructor(message) { super(message); this.name = "BehaveCancelled"; } }; __name(BehaveCancelled, "BehaveCancelled"); var OutBoundsBehave = class extends Error { constructor(message) { super(message); this.name = "OutBoundsBehave"; } }; __name(OutBoundsBehave, "OutBoundsBehave"); var FuzzyMatchSuccess = class extends Error { constructor(message) { super(message); this.name = "FuzzyMatchSuccess"; } }; __name(FuzzyMatchSuccess, "FuzzyMatchSuccess"); var PauseTriggered = class extends Error { constructor(ana) { super("PauseTriggered"); this.ana = ana; this.name = "PauseTriggered"; this.ana = ana; } }; __name(PauseTriggered, "PauseTriggered"); var SpecialOptionTriggered = class extends Error { constructor(handler) { super("SpecialOptionTriggered"); this.handler = handler; this.handler = handler; this.name = "SpecialOptionTriggered"; } }; __name(SpecialOptionTriggered, "SpecialOptionTriggered"); // packages/alconna/src/typing.ts var import_nepattern = require("@arcletjs/nepattern"); var KeyWordVar = class extends import_nepattern.Pattern { constructor(value, sep = "=") { let base = value instanceof import_nepattern.Pattern ? value : (0, import_nepattern.parser)(value); super(base.origin, ".+?", import_nepattern.MatchMode.KEEP, null, `@${sep}${base.toString()}`); this.base = base; this.sep = sep; } toString() { return this.alias; } }; __name(KeyWordVar, "KeyWordVar"); var MultiVar = class extends import_nepattern.Pattern { constructor(value, flag = "+") { let base = value instanceof import_nepattern.Pattern ? value : (0, import_nepattern.parser)(value); let origin = base instanceof KeyWordVar ? Map : Array; super(origin, ".+?", import_nepattern.MatchMode.KEEP); this.base = base; if (typeof flag !== "number") { this.alias = `(${this.base.toString()}${flag})`; this.flag = flag; this.length = -1; } else if (flag > 1) { this.alias = `(${this.base.toString()}+)[:${flag}]`; this.flag = "+"; this.length = flag; } else { this.alias = this.base.toString(); this.flag = "+"; this.length = 1; } } toString() { return this.alias; } }; __name(MultiVar, "MultiVar"); // packages/alconna/src/model.ts var import_nepattern2 = require("@arcletjs/nepattern"); var Sentence = class { constructor(name, separators = null) { this.name = name; this.separators = separators || []; } toString() { return `Sentence:${this.name}`; } equals(other) { return this.name === other.name && this.separators === other.separators; } }; __name(Sentence, "Sentence"); var OptionResult = class { constructor(value = import_nepattern2.Ellipsis, args = null) { this.value = value; this.args = args || /* @__PURE__ */ new Map(); } toString() { return `OptionResult:[${this.value}, ${this.args}]`; } }; __name(OptionResult, "OptionResult"); var SubcommandResult = class { constructor(value = import_nepattern2.Ellipsis, args = null, options = null, subcommands = null) { this.value = value; this.args = args || /* @__PURE__ */ new Map(); this.options = options || /* @__PURE__ */ new Map(); this.subcommands = subcommands || /* @__PURE__ */ new Map(); } toString() { return `SubcommandResult:[${this.value}, ${this.args}, ${this.options}, ${this.subcommands}]`; } }; __name(SubcommandResult, "SubcommandResult"); var HeadResult = class { constructor(origin = null, result = null, matched = false, groups = null) { this.origin = origin; this.result = result; this.matched = matched; this.groups = groups || {}; } }; __name(HeadResult, "HeadResult"); // packages/alconna/src/config.ts var Namespace = class { constructor(name, headers = [], separators = [" "], formatterType = null, fuzzyMatch = false, throwError = false, enableMessageCache = true, optionName = { help: ["--help", "-h"], shortcut: ["--shortcut", "-s"], completion: ["--comp", "-c"] }, toText = (unit) => { return typeof unit == "string" ? unit : null; }) { this.name = name; this.headers = headers; this.separators = separators; this.formatterType = formatterType; this.fuzzyMatch = fuzzyMatch; this.throwError = throwError; this.enableMessageCache = enableMessageCache; this.optionName = optionName; this.toText = toText; this.name = name; this.headers = headers; this.separators = separators; this.formatterType = formatterType; this.fuzzyMatch = fuzzyMatch; this.throwError = throwError; this.enableMessageCache = enableMessageCache; this.optionName = optionName; this.toText = toText; } equals(other) { return this.name === other.name; } toString() { return `Namespace(${this.name}, ${this.headers}, ${this.separators}, ${this.fuzzyMatch}, ${this.throwError}, ${this.optionName})`; } }; __name(Namespace, "Namespace"); var Lang = class { constructor() { this.path = `../lang/default.json`; this.file = require(this.path); this.config = this.file[this.file["$default"]]; } get types() { let out = []; for (let key in this.file) { if (key.startsWith("$")) continue; out.push(key); } return out; } replace(key, ...value) { let text = this.config[key]; if (text == void 0) throw new Error(`Key ${key} not found`); for (let i = 0; i < value.length; i++) { text = text.replace(`{${i}}`, value[i].toString()); } return text; } replaceKeys(key, value) { let text = this.config[key]; if (text == void 0) throw new Error(`Key ${key} not found`); for (let k in value) { text = text.replace(`{${k}}`, value[k].toString()); } return text; } changeType(type) { if (type != "$default" && !this.types.includes(type)) { this.config = this.file[type]; this.file["$default"] = type; return void 0; } throw new Error(this.replaceKeys("lang.type_error", { target: type })); } reload(path, lang = null) { let content = require(path); if (lang == null) { for (let key in content) { this.config[key] = content[key]; } } else if (lang in this.file) { for (let key in content) { this.file[lang][key] = content[key]; } this.config = this.file[lang]; } else { this.file[lang] = content; this.config = content; } } require(name) { return this.config[name] || name; } set(key, value) { if (key in this.config) { this.config[key] = value; } else { throw new Error(this.replaceKeys("lang.name_error", { target: key })); } } }; __name(Lang, "Lang"); var AlconnaConfig = class { constructor() { this.lang = new Lang(); this.commandMaxCount = 200; this.messageMaxCount = 100; this.fuzzyThreshold = 0.6; this._default_namespace = "Alconna"; this.namespace = { Alconna: new Namespace("Alconna") }; } get defaultNamespace() { return this.namespace[this._default_namespace]; } set defaultNamespace(ns) { if (typeof ns == "string") { if (!(ns in this.namespace)) { let old = this.namespace[this._default_namespace]; old.name = ns; this.namespace[ns] = old; } this._default_namespace = ns; } else { this.namespace[ns.name] = ns; this._default_namespace = ns.name; } } setdefault(name, default_) { if (!(name in this.namespace)) { this.namespace[name] = default_; return default_; } else { return this.namespace[name]; } } }; __name(AlconnaConfig, "AlconnaConfig"); var config = new AlconnaConfig(); var load_lang = config.lang.reload; function withNamespace(name, callbackFn) { let ns = name instanceof Namespace ? name : new Namespace(name); let nm = ns.name; let old = config.defaultNamespace; config.defaultNamespace = ns; callbackFn(ns); config.defaultNamespace = old; config.namespace[nm] = ns; return ns; } __name(withNamespace, "withNamespace"); // packages/alconna/src/args.ts var import_nepattern3 = require("@arcletjs/nepattern"); var ArgFlag = /* @__PURE__ */ ((ArgFlag2) => { ArgFlag2["OPTIONAL"] = "?"; ArgFlag2["HIDDEN"] = "/"; ArgFlag2["ANTI"] = "!"; return ArgFlag2; })(ArgFlag || {}); var Field = class { constructor(default_ = null, defaultGetter = null, alias = null, completion = null) { this.default_ = default_; this.defaultGetter = defaultGetter; this.alias = alias; this.completion = completion; this.default_ = default_; this.defaultGetter = defaultGetter; this.alias = alias; this.completion = completion; } toString() { return `Field(${this.default_}, ${this.defaultGetter}, ${this.alias}, ${this.completion})`; } get default() { return this.defaultGetter ? this.defaultGetter() : this.default_; } get display() { return this.alias || this.default; } }; __name(Field, "Field"); var Arg = class { constructor(name, value = null, field = null, seps = " ", notice = null, flags = []) { this.notice = null; if (name.startsWith("$")) { throw new InvalidParam(config.lang.require("args.name_error")); } if (name.trim() == "") { throw new InvalidParam(config.lang.require("args.name_empty")); } this.name = name; let _value = (0, import_nepattern3.parser)(value || name); let _default = field instanceof Field ? field : new Field(field); if (_value instanceof import_nepattern3.Union && _value.optional) { _default.default_ = _default.default_ === null ? import_nepattern3.Empty : _default.default_; } if (_default.default_ === "...") { _default.default_ = import_nepattern3.Empty; } if (_value === import_nepattern3.Empty) { throw new InvalidParam(config.lang.replaceKeys("args.value_error", { target: name })); } this.value = _value; this.field = _default; this.notice = notice; this.separators = typeof seps === "string" ? [seps] : Array.from(seps); let _flags = flags || []; let mat1 = name.match("^.+?#([^;?!/#]+)"); if (mat1) { this.notice = mat1[1]; this.name = name.replace(`#${mat1[1]}`, ""); } let mat2 = name.match("^.+?;([?!/]+)"); if (mat2) { this.name = name.replace(`;${mat2[1]}`, ""); _flags = _flags.concat(mat2[1].split("").map((x) => x)); } this.flag = _flags; } toString() { let n = `"${this.name}"`; let v = this.value.toString(); return (n == v ? n : `${n}: ${v}`) + (this.field.display != null ? ` = ${this.field.display}` : ""); } get optional() { return this.flag.includes("?" /* OPTIONAL */); } get hidden() { return this.flag.includes("/" /* HIDDEN */); } }; __name(Arg, "Arg"); var Args = class { static push(...args) { if (args.length < 1) { return new Args(); } if (args[0] instanceof Arg) { return new Args(...args); } return new Args(new Arg(...args)); } constructor(...args) { this.argument = args.filter((x) => x instanceof Arg).map((x) => x); this.varPositional = null; this.varKeyword = null; this.keywordOnly = []; this.optionalCount = 0; this.visited = /* @__PURE__ */ new Set(); this._parse(); this.separate(...args.filter((x) => typeof x === "string" || x instanceof Array).map((x) => x).flat()); } add(name, value, default_ = null, flags = []) { if (this.visited.has(name)) { return this; } this.argument.push(new Arg(name, value, default_, " ", null, flags)); this._parse(); return this; } separate(...sep) { this.argument.forEach((x) => x.separators = sep); return this; } _parse() { let _tmp = []; let _visited = /* @__PURE__ */ new Set(); for (let arg of this.argument) { if (_visited.has(arg.name)) { continue; } _tmp.push(arg); _visited.add(arg.name); if (this.visited.has(arg.name)) { continue; } this.visited.add(arg.name); let _limit = false; if (arg.flag.includes("!" /* ANTI */) && arg.value instanceof import_nepattern3.Pattern && arg.value != import_nepattern3.ANY) { arg.value = Object.assign({}, arg.value).reverse(); } if (arg.value instanceof MultiVar && !_limit) { if (arg.value.base instanceof KeyWordVar) { if (this.varKeyword) { throw new InvalidParam(config.lang.require("args.duplicate_kwargs")); } this.varKeyword = arg.name; } else if (this.varPositional) { throw new InvalidParam(config.lang.require("args.duplicate_varargs")); } else { this.varPositional = arg.name; } _limit = true; } if (arg.value instanceof KeyWordVar) { if (this.varKeyword || this.varPositional) { throw new InvalidParam(config.lang.require("args.exclude_mutable_args")); } this.keywordOnly.push(arg.name); if (arg.separators.includes(arg.value.sep)) { let _arg = new Arg(`_key_${arg.name}`, `-*${arg.name}`); _tmp.splice(-1, 0, _arg); _tmp[_tmp.length - 1].value = arg.value.base; } } if (arg.flag.includes("?" /* OPTIONAL */)) { if (this.varPositional || this.varKeyword) { throw new InvalidParam(config.lang.require("args.exclude_mutable_args")); } this.optionalCount++; } } this.argument = _tmp; _visited.clear(); } get length() { return this.argument.length; } push(...args) { if (args.length < 1) { return this; } if (args[0] instanceof Arg) { this.argument.push(...args); } else { this.argument.push(new Arg(...args)); } this._parse(); return this; } merge(other) { if (other instanceof Args) { this.argument.push(...other.argument); this._parse(); this.keywordOnly = [...new Set(this.keywordOnly.concat(other.keywordOnly))]; } else if (other instanceof Arg) { this.argument.push(other); this._parse(); } else if (other instanceof Array) { this.push(...other); } return this; } toString() { return this.argument.length > 0 ? `Args(${this.argument.filter((x) => !x.name.startsWith("_key_")).map((x) => x.toString()).join(", ")})` : "Empty"; } get empty() { return this.argument.length < 1; } get(name) { return this.argument.find((x) => x.name == name) || null; } }; __name(Args, "Args"); // packages/alconna/src/base.ts var Action = class { constructor(fn) { this.fn = fn; this.fn = fn; } static ensure(action) { if (!action) { return null; } if (action instanceof Action) { return action; } return new Action(action); } exec(params, varargs = null, kwargs = null, raise = false) { let vars = []; for (let key in params) { vars.push(params[key]); } vars.push(...varargs || []); if (kwargs) { for (let key in kwargs) { vars.push(kwargs[key]); } } try { let out = this.fn(...vars); if (out instanceof Promise) { out = out.then((x) => x); } if (!out || !(out instanceof Object)) { return params; } return out; } catch (e) { if (raise) { throw e; } return params; } } }; __name(Action, "Action"); function execArgs(args, func, raise) { let result = new Map(args); let [kwargs, kwonly, varargs, kwKey, varKey] = [/* @__PURE__ */ new Map(), /* @__PURE__ */ new Map(), [], null, null]; if (result.has("$kwargs")) { [kwargs, kwKey] = result.get("$kwargs"); result.delete("$kwargs"); result.delete(kwKey); } if (result.has("$varargs")) { [varargs, varKey] = result.get("$varargs"); result.delete("$varargs"); result.delete(varKey); } if (result.has("$kwonly")) { kwonly = result.get("$kwonly"); for (let key of kwonly.keys()) { result.delete(key); } } let additions = new Map(...kwonly, ...kwargs); let res = func.exec(result, varargs, additions, raise); if (kwKey) { res[kwKey] = kwargs; } if (varKey) { res[varKey] = varargs; } return res; } __name(execArgs, "execArgs"); function execData(data, func, raise) { return Object.keys(data.args).length > 0 ? ["args", execArgs(data.args, func, raise)] : ["value", func.fn()]; } __name(execData, "execData"); var CommandNode = class { constructor(name, args = null, dest = null, action = null, separators = [" "], help = null, requires = []) { if (!name.trim()) { throw new InvalidParam(config.lang.require("node.name_empty")); } let mat = name.match(/^[`~!@#$%^&*()_+=\[\]{}|;:'",<.>/?]+.*$/); if (mat) { throw new InvalidParam(config.lang.require("node.name_error")); } let _parts = name.split(" "); this.name = _parts[_parts.length - 1]; this.requires = Array.from(requires); this.requires.push(..._parts.slice(0, -1)); this.args = new Args().merge(args); this._action = Action.ensure(action); this.separators = typeof separators == "string" ? [separators] : Array.from(separators); this.nargs = this.args.length; this.isCompact = this.separators.length == 1 && this.separators[0] == ""; this._dest = (dest || (this.requires.length > 0 ? this.requires.join("_") + "_" + this.name : this.name)).replace(/^-+/, ""); this.helpText = help || this._dest; } separate(...seps) { this.separators = seps; return this; } toString() { return this._dest + this.args.empty ? "" : `(args=${this.args.toString()})`; } require(...args) { this.requires.push(...args); return this; } help(text) { this.helpText = text; return this; } action(fn) { this._action = Action.ensure(fn); return this; } }; __name(CommandNode, "CommandNode"); var Option = class extends CommandNode { constructor(name, args = null, aliases = [], dest = null, action = null, separators = [" "], help = null, requires = [], priority = 0) { let _name = name.split(" ").at(-1); if (_name.includes("|")) { let _aliases = _name.split("|"); _aliases = _aliases.sort((a, b) => b.length - a.length); name = name.replace(_name, _aliases[0]); _name = _aliases[0]; aliases.push(..._aliases.slice(1)); } aliases.splice(0, 0, _name); super(name, args, dest, action, separators, help, requires); this._priority = priority; this.aliases = aliases; } alias(...args) { args = args.sort((a, b) => b.length - a.length).reverse(); this.aliases = args; this.aliases.splice(0, 0, this.name); return this; } priority(level) { this._priority = level; return this; } }; __name(Option, "Option"); var Subcommand = class extends CommandNode { constructor(name, args = null, options = [], dest = null, action = null, separators = [" "], help = null, requires = []) { super(name, args, dest, action, separators, help, requires); this._options = options; } option(...args) { if (args[0] instanceof Option) { this._options.push(args[0]); return this; } this._options.push(new Option(...args)); return this; } subcommand(...args) { if (args[0] instanceof Subcommand) { this._options.push(args[0]); return this; } this._options.push(new Subcommand(...args)); return this; } push(...args) { this._options.push(...args); return this; } }; __name(Subcommand, "Subcommand"); // packages/alconna/src/output.ts var Sender = class { constructor(fn, generator) { this.fn = fn; this.generator = generator; this.fn = fn; this.generator = generator; } exec() { let res = this.generator(); let data = this.fn(res); return data && data instanceof Object ? data : { output: res }; } }; __name(Sender, "Sender"); var OutputManager = class { constructor(cache2 = /* @__PURE__ */ new Map(), outputs = /* @__PURE__ */ new Map(), send_fn = (data) => console.log(data), out_cache = /* @__PURE__ */ new Map()) { this.cache = cache2; this.outputs = outputs; this.send_fn = send_fn; this.out_cache = out_cache; this.cache = cache2; this.outputs = outputs; this.send_fn = send_fn; this.out_cache = out_cache; } send(command = null, generator = null, raise = false) { let sender = this.getSender(command); if (sender) { if (generator) { sender.generator = generator; } } else if (generator) { sender = this.register(generator, command).getSender(command); } else { throw new Error(`No output registered for command ${command}`); } let out = sender.exec(); if (command) { if (this.out_cache.has(command)) { this.out_cache.set(command, Object.assign(this.out_cache.get(command), out)); } else { this.out_cache.set(command, out); } } return out; } getSender(command = null) { let name = command || "$global"; return this.outputs.get(name); } register(generator, command = null) { let name = command || "$global"; if (this.outputs.has(name)) { this.outputs.get(name).generator = generator; } else if (this.cache.has(name)) { this.outputs.set(name, new Sender(this.cache.get(name), generator)); this.cache.delete(name); } else { this.outputs.set(name, new Sender(this.send_fn, generator)); } return this; } setFn(fn, command = null) { if (!command || command === "$global") { this.send_fn = fn; } else if (this.outputs.has(command)) { this.outputs.get(command).fn = fn; } else { this.cache.set(command, fn); } return this; } capture(command = null, callbackFn) { let name = command || "$global"; let out = this.out_cache.get(name); if (out) { callbackFn(out); } else { throw new Error(`No output registered for command ${name}`); } this.out_cache.delete(name); } }; __name(OutputManager, "OutputManager"); var outputManager = new OutputManager(); // packages/alconna/src/result.ts var import_nepattern4 = require("@arcletjs/nepattern"); function handleOpt(prefix, parts, opts) { if (prefix === "options") { prefix = parts[0]; parts = parts.slice(1); } if (parts.length === 0) { return [opts, prefix]; } let src = opts.get(prefix); if (!src) { return [opts, prefix]; } let end = parts[0]; parts = parts.slice(1); if (end === "value") { return [src, end]; } if (end === "args") { return parts.length > 0 ? [src.args, parts[0]] : [src, end]; } return [src.args, end]; } __name(handleOpt, "handleOpt"); function handleSub(prefix, parts, subs) { if (prefix === "subcommands") { prefix = parts[0]; parts = parts.slice(1); } if (parts.length === 0) { return [subs, prefix]; } let src = subs.get(prefix); if (!src) { return [subs, prefix]; } let end = parts[0]; parts = parts.slice(1); if (end === "args") { return parts.length > 0 ? [src.args, parts[0]] : [src, end]; } if (end === "options" && (src.options.has(end) || parts.length < 1)) { throw new Error(config.lang.replaceKeys("arpamar.ambiguous_name", { target: `${prefix}.${end}` })); } if (end === "options" || src.options.has(end)) { return handleOpt(end, parts, src.options); } if (end === "subcommands" && (src.subcommands.has(end) || parts.length < 1)) { throw new Error(config.lang.replaceKeys("arpamar.ambiguous_name", { target: `${prefix}.${end}` })); } if (end === "subcommands" || src.subcommands.has(end)) { return handleSub(end, parts, src.subcommands); } return [src.args, end]; } __name(handleSub, "handleSub"); var ParseResult = class { constructor(_source, origin, matched = false, head = null, errorInfo = "", errorData = null) { this._source = _source; this.origin = origin; this.matched = matched; this.errorInfo = errorInfo; this.errorData = errorData; this._source = _source; this.origin = origin; this.matched = matched; this.head = head || new HeadResult(); this.errorInfo = errorInfo; this.errorData = errorData; this.mainArgs = /* @__PURE__ */ new Map(); this.otherArgs = /* @__PURE__ */ new Map(); this.options = /* @__PURE__ */ new Map(); this.subcommands = /* @__PURE__ */ new Map(); } clear() { this.mainArgs.clear(); this.otherArgs.clear(); this.options.clear(); this.subcommands.clear(); } get source() { return manager.get(this._source); } get header() { return this.head.groups; } get head_matched() { return this.head.matched; } get head_result() { return this.head.result; } get emptyComponent() { return this.options.size === 0 && this.subcommands.size === 0; } get component() { let res = /* @__PURE__ */ new Map(); for (let [key, value] of this.options) { res.set(key, value); } for (let [key, value] of this.subcommands) { res.set(key, value); } return res; } get allArgs() { let res = /* @__PURE__ */ new Map(); for (let [key, value] of this.mainArgs) { res.set(key, value); } for (let [key, value] of this.otherArgs) { res.set(key, value); } return res; } get token() { return manager.getToken(this); } unpackOpts(data) { for (let value of data.values()) { value.args.forEach((v, k) => { this.otherArgs.set(k, v); }); } } unpackSubs(data) { for (let value of data.values()) { value.args.forEach((v, k) => { this.otherArgs.set(k, v); }); if (value.options.size > 0) { this.unpackOpts(value.options); } if (value.subcommands.size > 0) { this.unpackSubs(value.subcommands); } } } encapsulate(mainArgs, options, subcommands) { this.mainArgs = new Map(mainArgs); this.options = new Map(Object.entries(options)); this.subcommands = new Map(Object.entries(subcommands)); this.unpackOpts(this.options); this.unpackSubs(this.subcommands); } static behaveCancelled() { throw new BehaveCancelled("cancelled"); } static outBoundsBehave() { throw new OutBoundsBehave("out bounds"); } execute(behaviors = []) { let data = this.source._behaviors.slice(1); data.push(...behaviors); if (data.length < 1) { return this; } let excs = []; for (let behavior of data) { excs.push(...requirementHandler(behavior)); } for (let behavior of excs) { behavior.beforeExecute(this); } for (let behavior of excs) { try { behavior.execute(this); } catch (e) { if (e instanceof BehaveCancelled) { continue; } else if (e instanceof OutBoundsBehave) { return this.fail(e); } else { throw e; } } } return this; } fail(errorInfo) { return new ParseResult(this._source, this.origin, false, this.head, errorInfo); } require(parts) { if (parts.length === 1) { let prefix2 = parts[0]; for (let src of [this.mainArgs, this.otherArgs, this.options, this.subcommands]) { if (src.has(prefix2)) { return [src, prefix2]; } } if (["options", "subcommands", "mainArgs", "otherArgs"].includes(prefix2)) { return [this[prefix2], ""]; } return prefix2 === "args" ? [this.allArgs, ""] : [null, prefix2]; } let [prefix, ...rest] = parts; if (["options", "subcommands"].includes(prefix) && this.component.has(prefix)) { throw new Error(config.lang.replaceKeys("arpamar.ambiguous_name", { target: prefix })); } if (prefix === "options" || this.options.has(prefix)) { return handleOpt(prefix, rest, this.options); } if (prefix === "subcommands" || this.subcommands.has(prefix)) { return handleSub(prefix, rest, this.subcommands); } prefix = prefix.replace(/\$main/g, "mainArgs").replace(/\$other/g, "otherArgs"); if (["mainArgs", "otherArgs"].includes(prefix)) { return [this[prefix], rest[0]]; } return [null, prefix]; } query(path, defaultValue = null) { let [src, end] = this.require(path.split(".")); if (src === null) { return defaultValue; } if (src instanceof OptionResult || src instanceof SubcommandResult) { return end && end !== "" ? src[end] || defaultValue : src; } return end && end !== "" ? src.get(end) || defaultValue : new Map(src); } find(path) { return this.query(path, import_nepattern4.Empty) !== import_nepattern4.Empty; } }; __name(ParseResult, "ParseResult"); var Behavior = class { constructor(requires = []) { this.requires = requires; this.record = /* @__PURE__ */ new Map(); this.requires = requires; } beforeExecute(result) { if (this.record.size < 1) { return; } if (!this.record.has(result.token)) { return; } let _record = this.record.get(result.token); for (let [key, value] of _record) { let [past, current] = value; let [src, end] = result.require(key.split(".")); if (src === null) { continue; } if (src instanceof Map) { if (past !== import_nepattern4.Empty) { src.set(end, past); } else if ((src.get(end) || import_nepattern4.Empty) !== current) { src.delete(end); } } else if (past !== import_nepattern4.Empty) { src[end] = past; } else if ((src[end] || import_nepattern4.Empty) !== current) { delete src[end]; } } _record.clear(); } _update(token, src, path, end, value) { if (!this.record.has(token)) { this.record.set(token, /* @__PURE__ */ new Map()); } let _record = this.record.get(token); _record[path] = [src[end], value]; src[end] = value; } update(result, path, value) { let [src, end] = result.require(path.split(".")); if (src === null) { return; } if (end && end !== "") { this._update(result.token, src, path, end, value); } else if (src instanceof Map) { for (let [key, value2] of src) { this._update(result.token, src, path, `${path}.${key}`, value2); } } } }; __name(Behavior, "Behavior"); function requirementHandler(behavior) { let res = []; for (let value of behavior.requires) { res.push(...requirementHandler(value)); } res.push(behavior); return res; } __name(requirementHandler, "requirementHandler"); // packages/alconna/src/manager.ts var Manager = class { constructor() { this.sign = "ALCONNA:"; this.current_count = 0; this.max_count = config.messageMaxCount; this.commands = /* @__PURE__ */ new Map(); this.analysers = /* @__PURE__ */ new Map(); this.abandons = []; this.records = new LruCache(config.messageMaxCount); this.shortcuts = new LruCache(); } get loadedNamespaces() { return Array.from(this.commands.keys()); } commandPart(command) { let parts = command.split(":"); if (parts.length < 2) { parts.splice(0, 0, config.defaultNamespace.name); } return [parts[0], parts[1]]; } getNamespaceConfig(name) { if (this.commands.has(name)) { return config.namespace[name]; } } register(command) { if (this.current_count >= this.max_count) { throw new ExceedMaxCount(""); } this.analysers.delete(command); this.analysers.set(command, command.compile()); let namespace; if (this.commands.has(command.namespace)) { namespace = this.commands.get(command.namespace); } else { namespace = /* @__PURE__ */ new Map(); this.commands.set(command.namespace, namespace); } if (!namespace.has(command.name)) { command.formatter.add(command); namespace.set(command.name, command); this.current_count++; } else { if (namespace.get(command.name) == command) { return; } let _cmd = namespace.get(command.name); _cmd.formatter.add(command); command.formatter = _cmd.formatter; } } require(command) { if (this.analysers.has(command)) { return this.analysers.get(command); } throw new Error(config.lang.replaceKeys("manager.undefined_command", { target: `${command.path}` })); } requires(...path) { let res = []; for (let [k, v] of this.analysers.entries()) { if (path.includes(k.path)) { res.push(v); } } return res; } delete(command) { let [ns, name] = this.commandPart(typeof command == "string" ? command : command.path); if (this.commands.has(ns)) { let base = this.commands.get(ns); if (base.has(name)) { let _cmd = base.get(name); _cmd.formatter.remove(_cmd); this.analysers.delete(_cmd); base.delete(name); this.current_count--; } if (base.size == 0) { this.commands.delete(ns); } } } get(command) { let [ns, name] = this.commandPart(command); if (this.commands.has(ns)) { let base = this.commands.get(ns); if (base.has(name)) { return base.get(name); } } throw new Error(config.lang.replaceKeys("manager.undefined_command", { target: command })); } gets(namespace = "") { if (!namespace) { return Array.from(this.analysers.keys()); } if (namespace instanceof Namespace) { namespace = namespace.name; } if (this.commands.has(namespace)) { return Array.from(this.commands.get(namespace).values()); } return []; } isDisabled(command) { return this.abandons.includes(command); } setEnabled(command, enabled) { let cmd; if (typeof command == "string") { cmd = this.get(command); } else { cmd = command; } if (enabled) { this.abandons = this.abandons.filter((item) => item != cmd); } if (!enabled) { this.abandons.push(cmd); } } addShortcut(target, key, source) { let [ns, name] = this.commandPart(target.path); if (source instanceof ParseResult) { if (source.matched) { this.shortcuts.set(`${ns}.${name}::${key}`, source); } else { throw new Error(config.lang.replaceKeys("manager.incorrect_shortcut", { target: `${key}` })); } } else { source.command = source.command || target.command || target.name; this.shortcuts.set(`${ns}.${name}::${key}`, source); } } findShortcut(target, query) { let [ns, name] = this.commandPart(target.path); if (query) { let res = this.shortcuts.get(`${ns}.${name}::${query}`); if (res) { return [res, null]; } for (let key of this.shortcuts.keys()) { let mat = query.match(key.split("::")[1]); if (mat) { return [this.shortcuts.get(key), mat]; } } throw new Error(config.lang.replaceKeys("manager.target_command_error", { target: `${ns}.${name}` })); } return Array.from(this.shortcuts.keys()).filter((v) => v.includes(`${ns}.${name}`)).map((v) => this.shortcuts.get(v)); } deleteShortcut(target, key) { for (let res of key ? [this.findShortcut(target, key)[0]] : this.findShortcut(target)) { this.shortcuts.delete(Array.from(this.shortcuts.keys()).filter((v) => this.shortcuts.get(v) == res)[0]); } } broadcast(message, namespace = "") { for (let command of this.gets(namespace)) { let res = command.parse(message); if (res) { return res; } } } allCommandHelp(showIndex = false, namespace = "", header = null, footer = null, pages = null, maxLen = -1, page = 1) { pages = pages || config.lang.require("manager.help_pages"); let commands = this.gets(namespace).filter((command) => !command._meta.hide); header = header || config.lang.require("manager.help_header"); let helps; if (maxLen < 1) { maxLen = commands.length; helps = showIndex ? commands.map((command, index) => `${index.toString().padStart(maxLen.toString().length, "0")} ${command.name} : ${command._meta.description}`).join("\n") : commands.map((command) => ` - ${command.name} : ${command._meta.description}`).join("\n"); } else { let maxPage = Math.ceil(commands.length / maxLen); if (page < 1 || page > maxPage) { page = 1; } header += " " + formatKeys(pages, { current: page, total: maxPage }); helps = showIndex ? commands.slice((page - 1) * maxLen, page * maxLen).map((command, index) => `${(index + (page - 1) * maxLen).toString().padStart(maxLen.toString().length, "0")} ${command.name} : ${command._meta.description}`).join("\n") : commands.slice((page - 1) * maxLen, page * maxLen).map((command) => ` - ${command.name} : ${command._meta.description}`).join("\n"); } let names = /* @__PURE__ */ new Set(); for (let command of commands) { command.nsConfig.optionName["help"].forEach((name) => names.add(name)); } footer = footer || config.lang.replaceKeys("manager.help_footer", { help: Array.from(names).join("|") }); return header + "\n" + helps + "\n" + footer; } allCommandRawHelp(namespace = "") { let res = {}; for (let command of this.gets(namespace).filter((command2) => !command2._meta.hide)) { res[command.path] = Object.assign({}, command._meta); } return res; } commandHelp(command) { try { let commandObj = this.get(command); return commandObj.getHelp(); } catch (e) { } } record(token, result) { this.records.set(token, result); } getRecord(token) { return this.records.get(token) || null; } getToken(result) { for (let [token, value] of this.records.entries()) { if (value.value == result) { return token; } } return 0; } get recentMessage() { let rct = this.records.recent; if (rct) { return rct.origin; } } get lastUsing() { let rct = this.records.recent; if (rct) { return rct.source; } } getResult(command) { for (let value of this.records.values()) { if (value.value.source == command) { return value.value; } } return null; } reuse(index = -1) { let values = Array.from(this.records.values()).map((item) => item.value); return values.at(index); } }; __name(Manager, "Manager"); var manager = new Manager(); // packages/alconna/src/formatter.ts var import_nepattern5 = require("@arcletjs/nepattern"); function resolveRequires(opts) { let reqs = /* @__PURE__ */ new Map(); function _update(target, source) { for (let [key, value] of source) { if (!target.has(key) || target[key] instanceof Option || target[key] instanceof Subcommand) { source.forEach((value2, key2) => { target.set(key2, value2); }); break; } _update(target.get(key), value); } } __name(_update, "_update"); for (let opt of opts) { if (!opt.requires) { if (opt instanceof Option) { opt.aliases.forEach((alias) => reqs.set(alias, opt)); } else if (opt instanceof Subcommand) { reqs.set(opt.name, resolveRequires(opt._options)); } } else { let _reqs = /* @__PURE__ */ new Map(); let _cache = _reqs; for (let req of opt.requires) { if (_reqs.size == 0) { _reqs.set(req, /* @__PURE__ */ new Map()); _cache = _reqs.get(req); } else { _cache.set(req, /* @__PURE__ */ new Map()); _cache = _cache.get(req); } } if (opt instanceof Option) { opt.aliases.forEach((alias) => _cache.set(alias, opt)); } else if (opt instanceof Subcommand) { _cache.set(opt.name, resolveRequires(opt._options)); } _update(reqs, _reqs); } } return reqs; } __name(resolveRequires, "resolveRequires"); function ensure_node(target, source) { for (let opt of source) { if (opt instanceof Option && opt.aliases.includes(target)) { return opt; } if (opt instanceof Subcommand) { return target == opt.name ? opt : ensure_node(target, opt._options); } } } __name(ensure_node, "ensure_node"); var Trace = class { constructor(head, args, separators, body) { this.head = head; this.args = args; this.separators = separators; this.body = body; this.head = head; this.args = args; this.separators = separators; this.body = body; } union(others) { if (others.length == 0) { return this; } if (others[0] == this) { return this.union(others.slice(1)); } let hds = Object.assign({}, this.head); hds.header = [.../* @__PURE__ */ new Set([...this.head.header, ...others[0].head.header])]; return new Trace( hds, this.args, this.separators, [...this.body, ...others[0].body] ).union(others.slice(1)); } }; __name(Trace, "Trace"); var TextFormatter = class { constructor() { this.data = /* @__PURE__ */ new Map(); this.ignore = /* @__PURE__ */ new Set(); } add(base) { base.nsConfig.optionName.help.forEach((name) => this.ignore.add(name)); base.nsConfig.optionName.shortcut.forEach((name) => this.ignore.add(name)); base.nsConfig.optionName.completion.forEach((name) => this.ignore.add(name)); let hds = Object.assign([], base.headers); if (hds.includes(base.name)) { hds.splice(hds.indexOf(base.name), 1); } let res = new Trace( { name: base.name, header: hds || [], description: base._meta.description, usage: base._meta.usage, examples: base._meta.examples }, base.args, base.separators, Array.from(base._options) ); if (this.data.has(base.name)) { this.data.get(base.name).push(res); } else { this.data.set(base.name, [res]); } return this; } remove(base) { if (typeof base == "string") { this.data.delete(base); } else { try { let data = this.data.get(base.path); data.splice(data.indexOf(data.find((d) => d.head.name == base.name)), 1); } catch (e) { } } } handle(traces, end = null) { let trace = traces[0].union(traces.slice(1)); if (!end || end.length == 0 || end[0] == "") { return trace; } let _cache = resolveRequires(trace.body); let _parts = []; for (let part of end) { if (_cache instanceof Map && _cache.has(part)) { _cache = _cache.get(part); _parts.push(part); } } if (_parts.length == 0) { return trace; } if (_cache instanceof Map) { let ensure = ensure_node(_parts[_parts.length - 1], trace.body); if (ensure) { _cache = ensure; } else { let _opts = []; let _visited = /* @__PURE__ */ new Set(); for (let [key, value] of _cache) { if (value instanceof Map) { _opts.push(new Option(key).require(..._parts)); } else if (!_visited.has(value)) { _opts.push(value); _visited.add(value); } } return new Trace( { name: _parts.at(-1), header: [], description: _parts.at(-1), usage: null, examples: [] }, new Args(), trace.separators, _opts ); } } if (_cache instanceof Option) { return new Trace( { name: _cache.name, header: [], description: _cache.helpText, usage: null, examples: [] }, _cache.args, _cache.separators, [] ); } if (_cache instanceof Subcommand) { return new Trace( { name: _cache.name, header: [], description: _cache.helpText, usage: null, examples: [] }, _cache.args, _cache.separators, _cache._options ); } return trace; } format(end = null) { let nodes = []; for (let [key, value] of this.data) { nodes.push(this.entry(this.handle(value, end))); } return nodes.join("\n"); } entry(trace) { let header = this.header(trace.head, trace.separators); let param = this.parameters(trace.args); let body = this.body(trace.body); return `${header[0]}${param}${header[1]}${body}${header[2]}`; } param(arg) { let name = arg.name; let argp = arg.optional ? `[${name}` : `<${name}`; if (!arg.hidden) { if (arg.value == import_nepattern5.AllParam) { return `<...${name}>`; } if (!(arg.value instanceof import_nepattern5.Pattern) || arg.value.source != name) { argp += `:${arg.value}`; } if (arg.field.display == import_nepattern5.Empty) { argp += " = null"; } else if (arg.field.display != null) { argp += ` = ${arg.field.display} `; } } return argp + (arg.optional ? "]" : ">"); } parameters(args) { let res = ""; let notice = []; for (let arg of args.argument) { if (arg.name.startsWith("_key_")) continue; let sep; if (arg.separators.length == 1) sep = arg.separators[0] == " " ? " " : ` ${arg.separators[0]} `; else sep = arg.separators.join("|"); res += this.param(arg) + sep; if (arg.notice) notice.push([arg.name, arg.notice]); } return notice.length > 0 ? `${res} ## 注释 ` + notice.map((v) => `${v[0]}: ${v[1]}`).join("\n ") : res; } header(root, seps) { let help_string = root.description ? ` ${root.description}` : ""; let usage_string = root.usage ? ` 用法: ${root.usage}` : ""; let example_string = root.examples.length > 0 ? ` 使用示例: ` + root.examples.join("\n ") : ""; let header_string = root.header.length > 0 ? `[${root.header.map((v) => String(v)).join("")}]` : ""; let cmd = `${header_string}${root.name || ""}`; let command_string = cmd || `${root.name}${seps[0]}`; return [`${command_string} `, `${help_string}${usage_string} `, `${example_string}`]; } part(node) { if (node instanceof Subcommand) { let name = node.requires.join(" ") + (node.requires.length > 0 ? " " : "") + node.name; let option_string = node._options.map((v) => this.part(v).replace(/\n/g, "\n ")).join(""); let option_help = option_string ? "## 该子命令内可用的选项有:\n " : ""; return `# ${node.helpText} ${name}${node.separators[0]}${this.parameters(node.args)} ${option_help}${option_string}`; } if (node instanceof Option) { let alias = node.requires.join(" ") + (node.requires.length > 0 ? " " : "") + node.aliases.join(", "); return `# ${node.helpText} ${alias}${node.separators[0]}${this.parameters(node.args)} `; } throw new Error("Unknown node type"); } body(parts) { let option_string = parts.filter((v) => { return v instanceof Option && !this.ignore.has(v.name); }).map((v) => this.part(v)).join(""); let subcommand_string = parts.filter((v) => { return v instanceof Subcommand && !this.ignore.has(v.name); }).map((v) => this.part(v)).join(""); let option_help = option_string ? "可用的选项有:\n" : ""; let subcommand_help = subcommand_string ? "可用的子命令有:\n" : ""; return `${option_help}${option_string}${subcommand_help}${subcommand_string}`; } }; __name(TextFormatter, "TextFormatter"); // packages/alconna/src/analyser.ts var import_nepattern8 = require("@arcletjs/nepattern"); // packages/alconna/src/header.ts var import_nepattern6 = require("@arcletjs/nepattern"); function handleBracket(command) { let mat = command.split(/(\{.*?\})/g); if (mat.length <= 1) { return command; } let i = 0; let patMap = (0, import_nepattern6.allPatterns)(); while (i < mat.length) { let part = mat[i]; if (part.length < 1) { i++; continue; } if (part.startsWith("{") && part.endsWith("}")) { let content = part.slice(1, part.length - 1).split(":"); if (content.length < 1 || content.length > 1 && !content[0] && !content[1]) { mat[i] = ".+?"; } else if (content.length == 1 || !content[1]) { mat[i] = `(?<${content[0]}>.+?)`; } else if (!content[0]) { mat[i] = patMap.has(content[1]) ? `${patMap.get(content[1]).source}` : `${content[1]}`; } else { mat[i] = patMap.has(content[1]) ? `(?<${content[0]}>${patMap.get(content[1]).source})` : `(?<${content[0]}>${content[1]})`; } } i++; } return mat.join(""); } __name(handleBracket, "handleBracket"); var Pair = class { constructor(prefix, pattern, isPrefixPat = false) { this.prefix = prefix; this.pattern = pattern; this.isPrefixPat = isPrefixPat; this.prefix = prefix; this.pattern = pattern; this.isPrefixPat = prefix instanceof import_nepattern6.Pattern; } match(prefix, command) { let mat = command.match(this.pattern); if (mat) { if (this.isPrefixPat) { let val = this.prefix.exec(prefix, import_nepattern6.Empty); if (val.isSuccess()) { return [[prefix, command], [val.value, command], true, Object.assign({}, mat.groups)]; } } else if (prefix == this.prefix || prefix.constructor === this.prefix) { return [[prefix, command], [prefix, command], true, Object.assign({}, mat.groups)]; } } } }; __name(Pair, "Pair"); var Double = class { constructor(elements, patterns, prefix, command) { this.elements = elements; this.patterns = patterns; this.prefix = prefix; this.command = command; this.elements = elements; this.patterns = patterns; this.prefix = prefix; this.command = command; } match(prefix, command, prefixStr, commandStr, pushbackfn) { if (this.prefix && prefixStr) { if (commandStr) { let pat = new RegExp(`^${this.prefix.source}${this.command.source}$`); let mat2 = command.match(pat); if (mat2) { pushbackfn(command); return [prefix, prefix, true, Object.assign({}, mat2.groups)]; } else { let name = prefix + command; mat2 = name.match(pat); if (mat2) { return [name, name, true, Object.assign({}, mat2.groups)]; } } } let mat = prefix.match(this.prefix); let val = this.command.exec(command, import_nepattern6.Empty); if (mat && val.isSuccess()) { return [[prefix, command], [prefix, val.value], true, Object.assign({}, mat.groups)]; } } let po; let pr; if (this.patterns) { let val = this.patterns.validate(prefix, import_nepattern6.Empty); if (val.isSuccess()) { po = prefix; pr = val.value; } else { return null; } } else if (this.elements.length > 0 && this.elements.filter((e) => e == prefix || e.constructor == prefix).length > 0) { po = prefix; pr = prefix; } else { return null; } if (this.command instanceof RegExp && commandStr) { let mat = command.match(this.command); if (mat) { return [[po, command], [pr, command], true, Object.assign({}, mat.groups)]; } } else if (this.command instanceof import_nepattern6.Pattern) { let val = this.command.exec(command, import_nepattern6.Empty); if (val.isSuccess()) { return [[po, command], [pr, val.value], true, {}]; } } return null; } }; __name(Double, "Double"); function regEscape(str) { return str.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&"); } __name(regEscape, "regEscape"); function handleHeader(command, headers) { if (typeof command == "string") { command = handleBracket(command); } let cmd; let cmdString; if (typeof command == "string") { cmdString = command; cmd = new RegExp(`^${command}$`); } else { cmdString = `${command}`; cmd = (0, import_nepattern6.parser)(command); } if (headers.length == 0) { return cmd; } if (headers[0] instanceof Array && headers[0].length == 2) { let pairs = []; for (let [prefix, command2] of headers) { let pat = new RegExp(`${regEscape(command2)}${cmdString}`); pairs.push(new Pair(prefix, pat)); } return pairs; } let elements = []; let patterns = []; let text = ""; for (let header of headers) { if (typeof header == "string") { text += `${regEscape(header)}|`; } else if (header instanceof import_nepattern6.Pattern) { patterns.push(header); } else { elements.push(header); } } if (elements.length == 0 && patterns.length == 0) { if (cmd instanceof RegExp) { return new RegExp(`(?:${text.slice(0, text.length - 1)})${cmdString}`); } cmd.source = `(?:${text.slice(0, text.length - 1)})${cmd.source}`; cmd.regex = new RegExp(cmd.source); return cmd; } return new Double( elements, patterns.length > 0 ? new import_nepattern6.Union(patterns) : null, text.length > 0 ? new RegExp(`(?:${text.slice(0, text.length - 1)})`) : null, cmd ); } __name(handleHeader, "handleHeader"); // packages/alconna/src/container.ts var crypt = __toESM(require("crypto-browserify")); var cache = /* @__PURE__ */ new Map(); var DataCollectionContainer = class { constructor(preprocessors = /* @__PURE__ */ new Map(), toText = (unit) => { return typeof unit === "string" ? unit : null; }, separators = [" "], filterOut = [], defaultSeparate = true, filterCRLF = true, cacheMessage = true, paramIds = /* @__PURE__ */ new Set()) { this.preprocessors = preprocessors; this.toText = toText; this.separators = separators; this.filterOut = filterOut; this.defaultSeparate = defaultSeparate; this.filterCRLF = filterCRLF; this.cacheMessage = cacheMessage; this.paramIds = paramIds; this.preprocessors = preprocessors; this.toText = toText; this.separators = separators; this.filterOut = filterOut; this.defaultSeparate = defaultSeparate; this.filterCRLF = filterCRLF; this.cacheMessage = cacheMessage; this.paramIds = paramIds; this.context = null; [this.currentIndex, this.nData, this.tempToken] = [0, 0, 0]; [this.bakData, this.rawData] = [[], []]; this.tempData = /* @__PURE__ */ new Map(); if (cache.has(this.constructor.name)) { let cacheMap = cache.get(this.constructor.name); for (let [key, value] of cacheMap.get("preprocessors") || {}) { this.preprocessors.set(key, value); } this.toText = cacheMap.get("toText") || this.toText; this.filterOut.push(...cacheMap.get("filterOut") || []); } } static config(name, preprocessors = /* @__PURE__ */ new Map(), toText = (unit) => { return typeof unit === "string" ? unit : null; }, separators = [" "]) { let cacheMap = cache.get(name) || /* @__PURE__ */ new Map(); cacheMap.set("preprocessors", preprocessors); cacheMap.set("toText", toText); cacheMap.set("separators", separators); cache.set(name, cacheMap); } reset() { this.context = null; [this.currentIndex, this.nData, this.tempToken] = [0, 0, 0]; [this.bakData, this.rawData] = [[], []]; this.tempData = /* @__PURE__ */ new Map(); } generateToken(data) { let stringData = JSON.stringify(data); let hash = crypt.createHash("sha256"); hash.update(stringData, "utf8"); return parseInt(hash.digest("hex"), 16); } get origin() { return this.tempData.get("origin") || "None"; } get done() { return this.currentIndex >= this.nData; } build(data) { this.reset(); this.tempData.set("origin", data); if (typeof data === "string") { data = [data]; } let [i, err, raw] = [0, null, this.rawData]; for (let unit of data) { let uname = unit.constructor.name; if (this.filterOut.includes(uname)) { continue; } if (this.preprocessors.has(uname)) { let proc = this.preprocessors.get(uname); let res = proc(unit); if (res) { unit = res; } } let text = this.toText(unit) || ""; if (text) { let res = text.trim(); if (!res) { continue; } raw.push(res); } else { raw.push(unit); } i++; } if (i < 1) { throw new NullMessage(config.lang.replaceKeys("analyser.handle_null_message", { target: data })); } this.nData = i; this.bakData = Array.from(raw); if (this.cacheMessage) { this.tempToken = this.generateToken(raw); } return this; } rebuild(...data) { this.rawData = Array.from(this.bakData); for (let i = 0; i < data.length; i++) { let d = data[i]; if (!d) { continue; } if (typeof d == "string" && i > 0 && typeof this.rawData.at(-1) == "string") { this.rawData[this.rawData.length - 1] += `${this.separators[0]}${d}`; } else { this.rawData.push(d); this.nData++; } } this.currentIndex = 0; this.bakData = Array.from(this.rawData); if (this.cacheMessage) { this.tempToken = this.generateToken(this.rawData); } return this; } popitem(separate = null, move = true) { if (this.tempData.has("sep")) { this.tempData.delete("sep"); } if (this.currentIndex == this.nData) { return ["", true]; } if (!separate || separate.length < 1) { separate = this.separators; } let currentData = this.rawData[this.currentIndex]; if (typeof currentData === "string") { let [text, rest] = splitOnce(currentData, separate, this.filterCRLF); if (move) { if (rest) { this.tempData.set("sep", separate); this.rawData[this.currentIndex] = rest; } else { this.currentIndex++; } } return [text, true]; } if (move) { this.currentIndex++; } return [currentData, false]; } pushback(data, replace = false) { if (data == null || data == "") { return; } if (this.tempData.has("sep")) { let currentData = this.rawData[this.currentIndex]; this.rawData[this.currentIndex] = `${data}${this.tempData.get("sep")[0]}${currentData}`; return; } if (this.currentIndex >= 1) { this.currentIndex--; } if (replace) { this.rawData[this.currentIndex] = data; } } release(separate = null, recover = false) { let result = []; let data = recover ? this.bakData : this.rawData.slice(this.currentIndex); if (!separate || separate.length < 1) { separate = this.separators; } for (let _data of data) { if (typeof _data == "string") { result.push(...split(_data, separate)); } else { result.push(_data); } } return result; } dataSet() { return [Array.from(this.rawData), this.currentIndex]; } dataReset(data, index) { this.rawData = data; this.currentIndex = index; } }; __name(DataCollectionContainer, "DataCollectionContainer"); // packages/alconna/src/handlers.ts var import_nepattern7 = require("@arcletjs/nepattern"); function handleKeyword(analyser, value, mayArg, seps, result, defaultVal, optional, key = null) { let pat = new RegExp(`^([^${value.sep}]+)${value.sep}(.*?)$`, "s"); let match = pat.exec(mayArg); if (match) { key = key || match[1]; let [_, _key, val] = match; if (_key !== key) { analyser.container.pushback(mayArg); if (analyser.fuzzyMatch && levenshteinNorm(_key, key) >= config.fuzzyThreshold) { throw new FuzzyMatchSuccess(config.lang.replaceKeys("common.fuzzy_matched", { source: _key, target: key })); } if (defaultVal === null || defaultVal === void 0) { throw new ParamsUnmatched(config.lang.replaceKeys("common.fuzzy_matched", { source: _key, target: key })); } result.set(_key, defaultVal == import_nepattern7.Empty ? null : defaultVal); return; } let isStr = false; if (!val) { [mayArg, isStr] = analyser.container.popitem(seps); } let res = value.base.exec(val, defaultVal); if (!res.isSuccess()) { analyser.container.pushback(mayArg); } if (res.isFailed()) { if (optional) { return; } throw new ParamsUnmatched(res.error.message); } result.set(key, res.value); return; } analyser.container.pushback(mayArg); throw new ParamsUnmatched(config.lang.replaceKeys("args.key_missing", { "target": mayArg, "key": key })); } __name(handleKeyword, "handleKeyword"); function loopKw(analyser, loop, restArg, seps, value, defaultVal) { let result = /* @__PURE__ */ new Map(); for (let i = 0; i < loop; i++) { let [mayArg, isStr] = analyser.container.popitem(seps); if (!mayArg) { continue; } if (isStr && analyser.container.paramIds.has(mayArg)) { analyser.container.pushback(mayArg); let keys = Array.from(result.keys()); for (let j = 0; j < Math.min(result.size, restArg - 1); j++) { let key = keys[result.size - 1]; let arg = result.get(key); result.delete(key); analyser.container.pushback(`{${key}${value.base.sep}${arg}`); } break; } try { handleKeyword(analyser, value.base, mayArg, seps, result, defaultVal, false); } catch (e) { if (e instanceof ParamsUnmatched) { break; } throw e; } } if (result.size < 1) { if (value.flag == "+") { throw new ParamsUnmatched("args.missing"); } return defaultVal == import_nepattern7.Empty ? [] : [defaultVal]; } return result; } __name(loopKw, "loopKw"); function loopVar(container, loop, restArg, seps, value, defaultVal) { let result = []; for (let i = 0; i < loop; i++) { let [mayArg, isStr] = container.popitem(seps); if (!mayArg) { continue; } if (isStr && (container.paramIds.has(mayArg) || /^(.+)=\s?$/.test(mayArg))) { container.pushback(mayArg); for (let j = 0; j < Math.min(result.length, restArg - 1); j++) { let arg = result.pop(); container.pushback(arg); } break; } let res = value.base.exec(mayArg); if (!res.isSuccess()) { container.pushback(mayArg); break; } result.push(res.value); } if (result.length < 1) { if (value.flag == "+") { throw new ParamsUnmatched("args.missing"); } return defaultVal == import_nepattern7.Empty ? [] : [defaultVal]; } return result; } __name(loopVar, "loopVar"); function handleMultiArg(analyser, args, arg, result, nargs) { let seps = arg.separators; let value = arg.value; let key = arg.name; let defaultVal = arg.field.default; let kw = value.base instanceof KeyWordVar; let mRestArg = nargs - result.size; let mRestAllParamCount = analyser.container.release(seps).length; let loop; if (!kw && !args.varKeyword || kw && !args.varPositional) { loop = mRestAllParamCount - (mRestArg - (value.flag === "+" ? 1 : 0)); } else if (!kw) { loop = mRestAllParamCount - (mRestArg - (args.get(args.varPositional).value.flag === "*" ? 1 : 0)); } else { loop = mRestAllParamCount - (mRestArg - (args.get(args.varKeyword).value.flag === "*" ? 1 : 0)); } if (value.length > 0) { loop = Math.min(loop, value.length); } result.set( key, kw ? loopKw(analyser, loop, mRestArg, seps, value, defaultVal) : loopVar(analyser.container, loop, mRestArg, seps, value, defaultVal) ); } __name(handleMultiArg, "handleMultiArg"); function analyseArgs(analyser, args, nargs) { let result = /* @__PURE__ */ new Map(); for (let arg of args.argument) { analyser.container.context = arg; let [key, value, defaultVal, optional] = [arg.name, arg.value, arg.field.default, arg.optional]; let seps = arg.separators; let [mayArg, isStr] = analyser.container.popitem(seps); if (isStr && analyser.special.has(mayArg)) { throw new SpecialOptionTriggered(analyser.special.get(mayArg)); } if (!mayArg || isStr && analyser.container.paramIds.has(mayArg)) { analyser.container.pushback(mayArg); if (defaultVal !== null && defaultVal !== void 0) { result.set(key, defaultVal == import_nepattern7.Empty ? null : defaultVal); } else if (!optional) { throw new ArgumentMissing(config.lang.replaceKeys("args.missing", { key })); } continue; } if (value instanceof MultiVar) { analyser.container.pushback(mayArg); handleMultiArg(analyser, args, arg, result, nargs); } else if (value instanceof KeyWordVar) { handleKeyword(analyser, value, mayArg, seps, result, defaultVal, optional, key); } else if (value instanceof import_nepattern7.Pattern) { let res = value.exec(mayArg, defaultVal); if (!res.isSuccess()) { analyser.container.pushback(mayArg); } if (res.isFailed()) { if (optional) { continue; } throw new ParamsUnmatched(res.error.message); } if (!key.startsWith("_key")) { result.set(key, res.value); } } else if (value == import_nepattern7.AllParam) { analyser.container.pushback(mayArg); result.set(key, analyser.container.release(seps)); analyser.container.currentIndex = analyser.container.nData; return result; } else if (mayArg == value) { result.set(key, mayArg); } else if (defaultVal !== null && defaultVal !== void 0) { result.set(key, defaultVal == import_nepattern7.Empty ? null : defaultVal); } else if (!optional) { throw new ParamsUnmatched(config.lang.replaceKeys("args.error", { target: mayArg })); } } if (args.varKeyword) { let kwargs = result.get(args.varKeyword); if (!(kwargs instanceof Map)) { kwargs = /* @__PURE__ */ new Map([[args.varKeyword, kwargs]]); } result.set("$kwargs", [kwargs, args.varKeyword]); } if (args.varPositional) { let varargs = result.get(args.varPositional); if (!(varargs instanceof Array)) { varargs = [varargs]; } result.set("$varargs", [varargs, args.varPositional]); } if (args.keywordOnly.length > 0) { let res = /* @__PURE__ */ new Map(); for (let [key, val] of result.entries()) { if (args.keywordOnly.includes(key)) { res.set(key, val); } } result.set("$kwonly", res); } return result; } __name(analyseArgs, "analyseArgs"); function analyseUnmatchParams(analyser, text) { for (let param of analyser.compileParams.values()) { if (param instanceof Array) { let res = []; for (let opt of param) { let mayParam = splitOnce(text, opt.separators)[0]; if (opt.aliases.includes(mayParam) || opt.aliases.some((alias) => mayParam.startsWith(alias))) { res.push(opt); continue; } if (analyser.fuzzyMatch && levenshteinNorm(mayParam, opt.name) >= config.fuzzyThreshold) { throw new FuzzyMatchSuccess(config.lang.replaceKeys("common.fuzzy_matched", { source: mayParam, target: opt.name })); } } if (res.length > 0) { return res; } } else if (param instanceof Sentence) { let mayParam = splitOnce(text, param.separators)[0]; if (mayParam == param.name) { return param; } if (analyser.fuzzyMatch && levenshteinNorm(mayParam, param.name) >= config.fuzzyThreshold) { throw new FuzzyMatchSuccess(config.lang.replaceKeys("common.fuzzy_matched", { source: mayParam, target: param.name })); } } else { let mayParam = splitOnce(text, param.command.separators)[0]; if (mayParam == param.command.name || mayParam.startsWith(param.command.name)) { return param; } if (analyser.fuzzyMatch && levenshteinNorm(mayParam, param.command.name) >= config.fuzzyThreshold) { throw new FuzzyMatchSuccess(config.lang.replaceKeys("common.fuzzy_matched", { source: mayParam, target: param.command.name })); } } } return null; } __name(analyseUnmatchParams, "analyseUnmatchParams"); function analyseOption(analyser, param) { analyser.container.context = param; if (param.requires.length > 0 && !param.requires.every((r) => analyser.sentences.includes(r))) { throw new ParamsUnmatched(`${param.name}'s requires not satisfied ${analyser.sentences.join(" ")}`); } analyser.sentences = []; if (param.isCompact) { let name2 = analyser.container.popitem()[0]; let match = false; for (let al of param.aliases) { let mat = name2.match(new RegExp(`${al}(?.*)`)); if (mat) { analyser.container.pushback(mat.groups["rest"], true); match = true; break; } } if (!match) { throw new ParamsUnmatched(`${name2} does not match with ${param.name}`); } } else { let [name2, _] = analyser.container.popitem(param.separators); if (!param.aliases.includes(name2)) { throw new ParamsUnmatched(`${name2} does not match with ${param.name}`); } } let name = param._dest; if (param.nargs == 0) { return [name, new OptionResult()]; } return [name, new OptionResult(null, analyseArgs(analyser, param.args, param.nargs))]; } __name(analyseOption, "analyseOption"); function analyseParam(analyser, text, isStr) { if (isStr && analyser.special.has(text)) { throw new SpecialOptionTriggered(analyser.special.get(text)); } let param; if (!isStr || !text) { param = import_nepattern7.Ellipsis; } else if (analyser.compileParams.has(text)) { param = analyser.compileParams.get(text); } else { param = analyser.container.defaultSeparate ? null : analyseUnmatchParams(analyser, text); } if ((!param || param == import_nepattern7.Ellipsis) && analyser.argsResult.size < 1) { analyser.argsResult = analyseArgs(analyser, analyser.selfArgs, analyser.command.nargs); } else if (param instanceof Array) { let match = false; let err = new Error("null"); for (let opt of param) { let sets = analyser.container.dataSet(); try { let [optN, optV] = analyseOption(analyser, opt); analyser.optionResults.set(optN, optV); match = true; break; } catch (e) { err = e; analyser.container.dataReset(...sets); continue; } } if (!match) { throw err; } } else if (param instanceof Sentence) { analyser.sentences.push(analyser.container.popitem()[0]); } else if (param !== null && param !== import_nepattern7.Ellipsis) { if (!analyser.subcommandResults.has(param.command._dest)) { analyser.subcommandResults.set(param.command._dest, param.process().export()); } } } __name(analyseParam, "analyseParam"); function analyseHeader(analyser) { let hdr = analyser.commandHeader; let [prefix, isStr] = analyser.container.popitem(); if (hdr instanceof RegExp && isStr) { let mat = hdr.exec(prefix); if (mat) { return new HeadResult(prefix, prefix, true, Object.assign({}, mat.groups)); } } if (hdr instanceof import_nepattern7.Pattern) { let val = hdr.exec(prefix, import_nepattern7.Empty); if (val.isSuccess()) { return new HeadResult(prefix, val.value, true); } } let [command, mStr] = analyser.container.popitem(); if (hdr instanceof Array && mStr) { for (let pair of hdr) { let res = pair.match(prefix, command); if (res) { return new HeadResult(...res); } } } if (hdr instanceof Double) { let res = hdr.match(prefix, command, isStr, mStr, analyser.container.pushback); if (res) { return new HeadResult(...res); } } if (isStr && analyser.fuzzyMatch) { let headerTexts = []; if (analyser.command.headers.length > 0 && analyser.command.headers[0] != "") { analyser.command.headers.forEach((v) => headerTexts.push(`${v}${analyser.command.command}`)); } else if (analyser.command.command) { headerTexts.push(`${analyser.command.command}`); } let source; if (hdr instanceof RegExp || hdr instanceof import_nepattern7.Pattern) { source = prefix; } else { source = prefix + analyser.container.separators[0] + `${command}`; } if (source == analyser.command.command) { analyser.headResult = new HeadResult(source, source, false); throw new ParamsUnmatched(config.lang.replaceKeys("header.error", { target: prefix })); } for (let ht of headerTexts) { if (levenshteinNorm(source, ht) >= config.fuzzyThreshold) { analyser.headResult = new HeadResult(source, ht, true); throw new FuzzyMatchSuccess(config.lang.replaceKeys("common.fuzzy_matched", { target: source, source: ht })); } } } throw new ParamsUnmatched(config.lang.replaceKeys("header.error", { target: prefix })); } __name(analyseHeader, "analyseHeader"); function handleHelp(analyser) { let helpParam = analyser.container.release(null, true).filter((v) => !analyser.special.has(`${v}`)).map((v) => `${v}`); outputManager.send( analyser.command.name, () => analyser.command.formatter.format(helpParam) ); return analyser.export(); } __name(handleHelp, "handleHelp"); function handleShortcut(analyser) { analyser.container.popitem(); let opt = analyseArgs( analyser, Args.push("delete;?", "delete").push("name", String).push("command", String, "_"), 3 ); try { let msg = analyser.command.shortcut( opt.get("name"), opt.get("command") == "_" ? void 0 : { command: analyser.converter(opt.get("command")) }, opt.has("delete") ); outputManager.send(analyser.command.name, () => msg); } catch (e) { outputManager.send(analyser.command.name, () => e.message); } return analyser.export(); } __name(handleShortcut, "handleShortcut"); function handleUnit(analyser, trigger) { let gen = trigger.field.completion; if (gen) { let comp = gen(); if (typeof comp == "string") { return outputManager.send(analyser.command.name, () => comp); } let target = `${analyser.container.release(null, true).at(-2)}`; let includes = comp.filter((v) => v.includes(target)); let out2 = (includes.length > 0 ? includes : comp).join("\n* "); return outputManager.send( analyser.command.name, () => `${config.lang.require("common.completion_arg")} * ${out2}` ); } let defaultVal = trigger.field.default; let out = `[${trigger.name}]${String(trigger.value)}${defaultVal ? ` default:(${defaultVal == import_nepattern7.Empty ? null : defaultVal})` : ""}`; return outputManager.send(analyser.command.name, () => `${config.lang.require("common.completion_arg")} ${out}`); } __name(handleUnit, "handleUnit"); function handleSentence(analyser) { let res = []; for (let opt of analyser.command._options.filter( (v) => v.requires.length >= analyser.sentences.length && v.requires[analyser.sentences.length - 1] == analyser.sentences.at(-1) )) { if (opt.requires.length > analyser.sentences.length) { res.push(opt.requires[analyser.sentences.length]); } else { res.push(...opt instanceof Option ? opt.aliases : [opt.name]); } } return res; } __name(handleSentence, "handleSentence"); function handleNone(ana, got) { let res = []; if (ana.argsResult.size < 1 && ana.selfArgs.length > 0) { let unit = ana.selfArgs.argument.at(0); let gen = unit.field.completion; if (gen) { let comp = gen(); res.push(comp instanceof Array ? comp.join("\n* ") : comp); } else { let defaultVal = unit.field.default; res.push(`[${unit.name}]${String(unit.value)}${defaultVal ? ` default:(${defaultVal == import_nepattern7.Empty ? null : defaultVal})` : ""}`); } } for (let opt of ana.command._options.filter((v) => !ana.completionNames.includes(v.name))) { if (opt.requires.length > 0 && got.every((v) => !opt.requires[0].includes(v))) { res.push(opt.requires[0]); } else if (!got.includes(opt._dest)) { res.push(...opt instanceof Option ? opt.aliases : [opt.name]); } } return res; } __name(handleNone, "handleNone"); function handleCompletion(analyser, trigger = null) { let trig = trigger || analyser.container.context; let got = [...analyser.optionResults.keys()]; got.push(...analyser.subcommandResults.keys()); got.push(...analyser.sentences); if (trig instanceof Arg) { handleUnit(analyser, trig); } else if (trig instanceof Subcommand) { outputManager.send( analyser.command.name, () => `${config.lang.require("common.completion_node")} * ` + [...analyser.getSubAnalyser(trig).compileParams.keys()].join("\n* ") ); } else if (typeof trig == "string") { let res = [...analyser.compileParams.keys()].filter((v) => v.includes(trig)); if (res.length == 0) { return analyser.export( new ParamsUnmatched(config.lang.replaceKeys("analyser.param_unmatched", { target: trig })), true ); } let out = res.filter((v) => !got.includes(v)); outputManager.send( analyser.command.name, () => `${config.lang.require("common.completion_node")} * ` + (out.length > 0 ? out : res).join("\n* ") ); } else { let target = `${analyser.container.release(null, true).at(-1)}`; let res = [...analyser.compileParams.keys()].filter((v) => v.includes(target) && v != target); if (res.length > 0) { let out = res.filter((v) => !got.includes(v)); outputManager.send( analyser.command.name, () => `${config.lang.require("common.completion_node")} * ` + (out.length > 0 ? out : res).join("\n* ") ); } else { let _res = analyser.sentences.length > 0 ? handleSentence(analyser) : handleNone(analyser, got); outputManager.send( analyser.command.name, () => `${config.lang.require("common.completion_node")} * ` + [...new Set(_res).keys()].join("\n* ") ); } } return analyser.export(new Error("completion"), true); } __name(handleCompletion, "handleCompletion"); // packages/alconna/src/analyser.ts function compileOpts(option, data) { for (let alias of option.aliases) { let li = data.get(alias); if (li && li instanceof Array) { li.push(option); li.sort((a, b) => a._priority - b._priority); } else { data.set(alias, [option]); } } } __name(compileOpts, "compileOpts"); function defaultCompiler(analyser, ns) { let requireLength = 0; for (let opts of analyser.command._options) { if (opts instanceof Option) { compileOpts(opts, analyser.compileParams); opts.aliases.forEach((alias) => { analyser.container.paramIds.add(alias); }); } else if (opts instanceof Subcommand) { let sub = new SubAnalyser(opts, analyser.container, ns, analyser.fuzzyMatch); analyser.compileParams.set(opts.name, sub); analyser.container.paramIds.add(opts.name); defaultCompiler(sub, ns); } let separatorSet = new Set(analyser.container.separators); if (opts.separators.some((s) => !separatorSet.has(s))) { analyser.container.defaultSeparate = false; } if (opts.requires.length > 0) { opts.requires.forEach((r) => { analyser.container.paramIds.add(r); }); requireLength = Math.max(requireLength, opts.requires.length); for (let k of opts.requires) { if (!analyser.compileParams.has(k)) { analyser.compileParams.set(k, new Sentence(k)); } } } } analyser.partLength = requireLength + analyser.command._options.length + (analyser.needMainArgs ? 1 : 0); } __name(defaultCompiler, "defaultCompiler"); var SubAnalyser = class { constructor(command, container, namespace, fuzzyMatch = false, defaultMainOnly = false, partLength = 0, needMainArgs = false, compileParams = /* @__PURE__ */ new Map()) { this.command = command; this.container = container; this.fuzzyMatch = fuzzyMatch; this.defaultMainOnly = defaultMainOnly; this.partLength = partLength; this.needMainArgs = needMainArgs; this.compileParams = compileParams; [this.argsResult, this.optionResults, this.subcommandResults] = [/* @__PURE__ */ new Map(), /* @__PURE__ */ new Map(), /* @__PURE__ */ new Map()]; [this.sentences, this.valueResult, this.headResult] = [[], null, null]; this.container.reset(); this.special = /* @__PURE__ */ new Map(); for (let key of namespace.optionName.help) { this.special.set(key, handleHelp); } for (let key of namespace.optionName.completion) { this.special.set(key, handleCompletion); } for (let key of namespace.optionName.shortcut) { this.special.set(key, handleShortcut); } this.completionNames = namespace.optionName.completion; this.selfArgs = this.command.args; this.handleArgs(); } export() { let res = new SubcommandResult( this.valueResult, new Map(this.argsResult), new Map(this.optionResults), new Map(this.subcommandResults) ); this.reset(); return res; } reset() { [this.argsResult, this.optionResults, this.subcommandResults] = [/* @__PURE__ */ new Map(), /* @__PURE__ */ new Map(), /* @__PURE__ */ new Map()]; [this.sentences, this.valueResult, this.headResult] = [[], null, null]; } handleArgs() { if (this.command.nargs > 0 && this.command.nargs > this.selfArgs.optionalCount) { this.needMainArgs = true; } let defCount = 0; for (let arg of this.selfArgs.argument) { if (arg.field.defaultGetter !== null) { defCount++; } } if (defCount > 0 && defCount === this.command.nargs) { this.defaultMainOnly = true; } } process() { let param = this.command; this.container.context = param; if (param.requires.length > 0 && !param.requires.every((r) => this.sentences.includes(r))) { throw new ParamsUnmatched(`${param.name}'s requires not satisfied ${this.sentences.join(" ")}`); } this.sentences = []; if (param.isCompact) { let [name, _] = this.container.popitem(); if (!name.startsWith(param.name)) { throw new ParamsUnmatched(`${name} does not match with ${param.name}`); } this.container.pushback(name.replace(param.name, ""), true); } else { let [name, _] = this.container.popitem(param.separators); if (name !== param.name) { throw new ParamsUnmatched(`${name} does not match with ${param.name}`); } } if (this.partLength < 1) { this.valueResult = import_nepattern8.Ellipsis; return this; } return this.analyse(); } analyse() { for (let i = 0; i < this.partLength; i++) { analyseParam(this, ...this.container.popitem(this.command.separators, false)); } if (this.defaultMainOnly && this.argsResult.size === 0) { this.argsResult = analyseArgs(this, this.selfArgs, this.command.nargs); } if (this.argsResult.size == 0 && this.needMainArgs) { throw new ArgumentMissing(config.lang.replaceKeys("subcommand.args_missing", { name: this.command._dest })); } return this; } getSubAnalyser(subcommand) { if (subcommand === this.command) { return this; } for (let sub of this.subcommandResults.values()) { if (sub instanceof SubAnalyser) { return sub.getSubAnalyser(subcommand); } } } }; __name(SubAnalyser, "SubAnalyser"); var _Analyser = class extends SubAnalyser { constructor(command, containerType = null) { let construct = containerType || _Analyser.globalContainerType; super( command, new construct( /* @__PURE__ */ new Map(), command.nsConfig.toText, command.separators, [], true, !command._meta.keepCRLF, command.nsConfig.enableMessageCache ), command.nsConfig ); this.command = command; this.fuzzyMatch = command._meta.fuzzyMatch; this.usedTokens = /* @__PURE__ */ new Set(); this.commandHeader = handleHeader(command.command, command.headers); } static defaultContainer(t) { _Analyser.globalContainerType = t; return _Analyser; } converter(command) { return command; } toString() { return `<${this.constructor.name} of ${this.command.path}>`; } static compile(command, compiler = defaultCompiler) { let analyser = new command.analyserType(command); compiler(analyser, command.nsConfig); return analyser; } shortcut(data, short, reg) { if (short instanceof ParseResult) { return short; } this.container.build(short.command); let dataIndex = 0; for (let i = 0; i < this.container.rawData.length; i++) { if (data.length < 1) { break; } let unit = this.container.rawData[i]; if (typeof unit === "string" && unit.includes(`{%${dataIndex}}`)) { this.container.rawData[i] = unit.replace(`{%${dataIndex}}`, `${data.shift()}`); dataIndex++; } else if (unit === `{%${dataIndex}}`) { this.container.rawData[i] = data.shift(); dataIndex++; } } this.container.bakData = Array.from(this.container.rawData); this.container.rebuild(...data).rebuild(...short.args || []); if (reg) { let groups = Array.from(reg).slice(1); let gdict = Object.assign({}, reg.groups || {}); for (let i = 0; i < this.container.rawData.length; i++) { let unit = this.container.rawData[i]; if (typeof unit === "string") { for (let j = 0; j < groups.length; j++) { unit = unit.replace(`{${j}}`, `${groups[j]}`); } for (let key in gdict) { unit = unit.replace(`{${key}}`, `${gdict[key]}`); } this.container.rawData[i] = unit; } } } if (this.container.cacheMessage) { this.container.tempToken = this.container.generateToken(this.container.rawData); } return this.process(null, false); } process(message = null, interrupt = false) { if (manager.isDisabled(this.command)) { return this.export(null, true); } if (this.container.nData == 0) { if (!message) { throw new NullMessage(config.lang.replaceKeys("analyser.handle_null_message", { target: message })); } try { this.container.build(message); } catch (e) { return this.export(e, true); } } if (this.container.cacheMessage && this.usedTokens.has(this.container.tempToken)) { let res = manager.getRecord(this.container.tempToken); if (res) { return res; } } try { this.headResult = analyseHeader(this); } catch (e) { if (e instanceof FuzzyMatchSuccess) { outputManager.send(this.command.name, () => e.message); return this.export(null, true); } if (e instanceof ParamsUnmatched) { this.container.rawData = Array.from(this.container.bakData); this.container.currentIndex = 0; let res; try { res = manager.findShortcut(this.command, this.container.popitem(null, false)[0]); } catch (e2) { if (this.command._meta.throwError) { throw e2; } return this.export(e2, true); } this.container.popitem(); let data = this.container.release(); this.reset(); this.container.reset(); return this.shortcut(data, ...res); } throw e; } let fail = this.analyse(interrupt); if (fail) { return fail; } if (this.container.done && (!this.needMainArgs || this.argsResult.size > 0)) { return this.export(null, false); } let rest = this.container.release(); let err; if (rest.length > 0) { if (typeof rest.at(-1) == "string" && this.completionNames.includes(rest.at(-1))) { return handleCompletion(this, rest.at(-2)); } err = new ParamsUnmatched(config.lang.replaceKeys("analyser.param_unmatched", { target: this.container.popitem(null, false)[0] })); } else { err = new ArgumentMissing(config.lang.require("analyser.param_missing")); } if (interrupt && err instanceof ArgumentMissing) { throw new PauseTriggered(this); } if (this.command._meta.throwError) { throw err; } return this.export(err, true); } analyse(interrupt = false) { for (let i = 0; i < this.partLength; i++) { try { analyseParam(this, ...this.container.popitem(null, false)); } catch (e) { if (e instanceof FuzzyMatchSuccess) { outputManager.send(this.command.name, () => e.message); return this.export(null, true); } if (e instanceof SpecialOptionTriggered) { return e.handler(this); } if (e instanceof ParamsUnmatched || e instanceof ArgumentMissing) { let rest = this.container.release(); if (rest.length > 0 && typeof rest.at(-1) == "string") { if (this.completionNames.includes(rest.at(-1))) { return handleCompletion(this); } if (this.special.has(rest.at(-1))) { return this.special.get(rest.at(-1))(this); } } if (interrupt && e instanceof ArgumentMissing) { throw new PauseTriggered(this); } if (this.command._meta.throwError) { throw e; } return this.export(e, true); } } if (this.container.done) { break; } } if (this.defaultMainOnly && this.argsResult.size < 1) { this.argsResult = analyseArgs(this, this.selfArgs, this.command.nargs); } return null; } export(error = null, fail = false) { let result = new ParseResult(this.command.path, this.container.origin, !fail, this.headResult); if (fail) { result.errorInfo = `${error}`; result.errorData = this.container.release(); } else { result.encapsulate(this.argsResult, this.optionResults, this.subcommandResults); if (this.container.cacheMessage) { manager.record(this.container.tempToken, result); this.usedTokens.add(this.container.tempToken); } } this.reset(); return result; } }; var Analyser = _Analyser; __name(Analyser, "Analyser"); Analyser.globalContainerType = DataCollectionContainer; // packages/alconna/src/core.ts var ActionHandler = class extends Behavior { constructor(source) { super(); this.mainAction = source._action; this.options = /* @__PURE__ */ new Map(); this.step(source); } step(src, prefix = null) { for (let opt of src._options) { if (opt._action) { this.options.set(prefix ? `${prefix}.${opt._dest}` : opt._dest, opt._action); } if ("_options" in opt) { this.step(opt, prefix ? `${prefix}.${opt._dest}` : opt._dest); } } } execute(result) { this.beforeExecute(result); let source = result.source; if (this.mainAction) { this.update(result, "mainArgs", execArgs(result.mainArgs, this.mainAction, source._meta.throwError)); } for (let [key, action] of this.options) { let d = result.query(key, void 0); if (d !== void 0) { let [end, value] = execData(d, action, source._meta.throwError); this.update(result, `${key}.${end}`, value); } } } }; __name(ActionHandler, "ActionHandler"); var CommandMeta = class { constructor(description = "Untitled", usage = null, examples = [], author = null, fuzzyMatch = false, throwError = false, hide = false, keepCRLF = false) { this.description = description; this.usage = usage; this.examples = examples; this.author = author; this.fuzzyMatch = fuzzyMatch; this.throwError = throwError; this.hide = hide; this.keepCRLF = keepCRLF; this.description = description; this.usage = usage; this.examples = examples; this.author = author; this.fuzzyMatch = fuzzyMatch; this.throwError = throwError; this.hide = hide; this.keepCRLF = keepCRLF; } }; __name(CommandMeta, "CommandMeta"); var _Command = class extends Subcommand { constructor(name = null, headers = null, args = new Args(), options = [], action = null, meta = new CommandMeta(), namespace = null, separators = [" "], analyserType = null, formatterType = null, behaviors = null) { if (!namespace) { namespace = config.defaultNamespace; } else if (namespace instanceof Namespace) { namespace = config.setdefault(namespace.name, namespace); } else { namespace = config.setdefault(namespace, new Namespace(namespace)); } let _args = args instanceof Args ? args : new Args(...args); super("ALCONNA::", _args, options, null, action, separators); this.headers = headers || Array.from(namespace.headers); this.command = name || (this.headers.length > 0 ? "" : "Alconna"); this.namespace = namespace.name; this.analyserType = analyserType || _Command.globalAnalyserType; this._meta = meta; this._meta.fuzzyMatch = this._meta.fuzzyMatch || namespace.fuzzyMatch; this._meta.throwError = this._meta.throwError || namespace.throwError; this._options.push( new Option( namespace.optionName.help.join("|") ).help(config.lang.require("builtin.option_help")), new Option( namespace.optionName.shortcut.join("|"), Args.push("delete;?", "delete").push("name", String).push("command", String, "_") ).help(config.lang.require("builtin.option_shortcut")), new Option( namespace.optionName.completion.join("|") ).help(config.lang.require("builtin.option_completion")) ); this._behaviors = behaviors || []; this._behaviors.splice(0, 0, new ActionHandler(this)); this.formatter = new (formatterType || namespace.formatterType || TextFormatter)(); this.name = `${this.command || this.headers[0]}`.replace(/ALCONNA::/g, ""); manager.register(this); this.union = /* @__PURE__ */ new Set(); } static defaultAnalyser(type) { _Command.globalAnalyserType = type; return _Command; } meta(data) { if (data instanceof CommandMeta) { this._meta = data; } else { Object.assign(this._meta, data); } return this; } get path() { return `${this.namespace}:${this.name}`; } get nsConfig() { return config.namespace[this.namespace]; } compile() { return Analyser.compile(this); } resetNamespace(ns, header = true) { manager.delete(this); let namespace; if (typeof ns == "string") { namespace = config.setdefault(ns, new Namespace(ns)); } else { namespace = ns; } this.namespace = namespace.name; if (header) { this.headers.splice(0, this.headers.length); this.headers.push(...namespace.headers); } this._options.splice(this._options.length - 3, 3); this._options.push( new Option( namespace.optionName.help.join("|") ).help(config.lang.require("builtin.option_help")), new Option( namespace.optionName.shortcut.join("|"), Args.push("delete;?", "delete").push("name", String).push("command", String, "_") ).help(config.lang.require("builtin.option_shortcut")), new Option( namespace.optionName.completion.join("|") ).help(config.lang.require("builtin.option_completion")) ); this._meta.fuzzyMatch = namespace.fuzzyMatch || this._meta.fuzzyMatch; this._meta.throwError = namespace.throwError || this._meta.throwError; manager.register(this); return this; } option(...args) { manager.delete(this); let opt = args[0] instanceof Option ? args[0] : new Option(...args); this._options.splice(this._options.length - 3, 0, opt); manager.register(this); return this; } subcommand(...args) { manager.delete(this); let sub = args[0] instanceof Subcommand ? args[0] : new Subcommand(...args); this._options.splice(this._options.length - 3, 0, sub); manager.register(this); return this; } push(...args) { manager.delete(this); this._options.splice(this._options.length - 3, 0, ...args); manager.register(this); return this; } resetBehavior(...behaviors) { this._behaviors.splice(1, this._behaviors.length, ...behaviors); return this; } getHelp() { return this.formatter.format(); } shortcut(key, args, del = false) { try { if (del) { manager.deleteShortcut(this, key); return config.lang.replaceKeys("shortcut.delete_success", { shortcut: key, target: this.path }); } if (args) { manager.addShortcut(this, key, args); return config.lang.replaceKeys("shortcut.add_success", { shortcut: key, target: this.path }); } let cmd = manager.recentMessage; if (cmd) { let alc = manager.lastUsing; if (alc && alc == this) { manager.addShortcut(this, key, { command: cmd }); return config.lang.replaceKeys("shortcut.add_success", { shortcut: key, target: this.path }); } throw new Error(config.lang.replaceKeys( "shortcut.recent_command_error", { target: this.path, source: (alc == null ? void 0 : alc.path) || "Unknown" } )); } throw new Error(config.lang.require("shortcut.no_recent_command")); } catch (e) { if (this._meta.throwError) { throw e; } return e.message; } } unionWith(...commands) { commands.forEach((cmd) => { this.union.add(cmd.path); }); return this; } _parse(message, interrupt = false) { if (this.union.size > 0) { for (let ana of manager.requires(...this.union)) { ana.container.build(message); let res = ana.process(null, interrupt); if (res.matched) { return res; } } } let analyser = manager.require(this); analyser.container.build(message); return analyser.process(null, interrupt); } parse(message, interrupt = false) { let arp; try { arp = this._parse(message, interrupt); } catch (e) { if (e instanceof PauseTriggered) { return e.ana; } throw e; } if (arp.matched) { this._behaviors[0].execute(arp); arp = arp.execute(); } return arp; } }; var Command = _Command; __name(Command, "Command"); Command.globalAnalyserType = Analyser; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { Action, Arg, ArgFlag, Args, ArgumentMissing, BehaveCancelled, Behavior, Command, CommandMeta, CommandNode, ExceedMaxCount, ExecuteFailed, Field, FuzzyMatchSuccess, HeadResult, InvalidParam, KeyWordVar, LruCache, MultiVar, Namespace, NullMessage, Option, OptionResult, OutBoundsBehave, ParamsUnmatched, ParseResult, PauseTriggered, Sentence, SpecialOptionTriggered, Subcommand, SubcommandResult, TextFormatter, UnexpectedElement, config, execArgs, execData, format, formatKeys, levenshteinNorm, load_lang, manager, outputManager, split, splitOnce, withNamespace }); //# sourceMappingURL=index.cjs.map