UNPKG

akm-cli

Version:

akm (Agent Knowledge Manager) — a portable, local-first capability library for AI agents. Discover, load, share, and improve reusable skills, scripts, workflows, and knowledge across any shell-capable coding agent, including Claude Code, OpenCode, and Cur

55,063 lines • 1.82 MB
#!/usr/bin/env bun
// @bun
import { createRequire } from "node:module";
var __create = Object.create;
var __getProtoOf = Object.getPrototypeOf;
var __defProp = Object.defineProperty;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
function __accessProp(key) {
  return this[key];
}
var __toESMCache_node;
var __toESMCache_esm;
var __toESM = (mod, isNodeMode, target) => {
  var canCache = mod != null && typeof mod === "object";
  if (canCache) {
    var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
    var cached = cache.get(mod);
    if (cached)
      return cached;
  }
  target = mod != null ? __create(__getProtoOf(mod)) : {};
  const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
  for (let key of __getOwnPropNames(mod))
    if (!__hasOwnProp.call(to, key))
      __defProp(to, key, {
        get: __accessProp.bind(mod, key),
        enumerable: true
      });
  if (canCache)
    cache.set(mod, to);
  return to;
};
var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
var __returnValue = (v) => v;
function __exportSetter(name, newValue) {
  this[name] = __returnValue.bind(null, newValue);
}
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, {
      get: all[name],
      enumerable: true,
      configurable: true,
      set: __exportSetter.bind(all, name)
    });
};
var __require = /* @__PURE__ */ createRequire(import.meta.url);

// node_modules/yaml/dist/nodes/identity.js
var require_identity = __commonJS((exports) => {
  var ALIAS = Symbol.for("yaml.alias");
  var DOC = Symbol.for("yaml.document");
  var MAP = Symbol.for("yaml.map");
  var PAIR = Symbol.for("yaml.pair");
  var SCALAR = Symbol.for("yaml.scalar");
  var SEQ = Symbol.for("yaml.seq");
  var NODE_TYPE = Symbol.for("yaml.node.type");
  var isAlias = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === ALIAS;
  var isDocument = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === DOC;
  var isMap = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === MAP;
  var isPair = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === PAIR;
  var isScalar = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SCALAR;
  var isSeq = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SEQ;
  function isCollection(node) {
    if (node && typeof node === "object")
      switch (node[NODE_TYPE]) {
        case MAP:
        case SEQ:
          return true;
      }
    return false;
  }
  function isNode(node) {
    if (node && typeof node === "object")
      switch (node[NODE_TYPE]) {
        case ALIAS:
        case MAP:
        case SCALAR:
        case SEQ:
          return true;
      }
    return false;
  }
  var hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor;
  exports.ALIAS = ALIAS;
  exports.DOC = DOC;
  exports.MAP = MAP;
  exports.NODE_TYPE = NODE_TYPE;
  exports.PAIR = PAIR;
  exports.SCALAR = SCALAR;
  exports.SEQ = SEQ;
  exports.hasAnchor = hasAnchor;
  exports.isAlias = isAlias;
  exports.isCollection = isCollection;
  exports.isDocument = isDocument;
  exports.isMap = isMap;
  exports.isNode = isNode;
  exports.isPair = isPair;
  exports.isScalar = isScalar;
  exports.isSeq = isSeq;
});

// node_modules/yaml/dist/visit.js
var require_visit = __commonJS((exports) => {
  var identity = require_identity();
  var BREAK = Symbol("break visit");
  var SKIP = Symbol("skip children");
  var REMOVE = Symbol("remove node");
  function visit(node, visitor) {
    const visitor_ = initVisitor(visitor);
    if (identity.isDocument(node)) {
      const cd = visit_(null, node.contents, visitor_, Object.freeze([node]));
      if (cd === REMOVE)
        node.contents = null;
    } else
      visit_(null, node, visitor_, Object.freeze([]));
  }
  visit.BREAK = BREAK;
  visit.SKIP = SKIP;
  visit.REMOVE = REMOVE;
  function visit_(key, node, visitor, path) {
    const ctrl = callVisitor(key, node, visitor, path);
    if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
      replaceNode(key, path, ctrl);
      return visit_(key, ctrl, visitor, path);
    }
    if (typeof ctrl !== "symbol") {
      if (identity.isCollection(node)) {
        path = Object.freeze(path.concat(node));
        for (let i = 0;i < node.items.length; ++i) {
          const ci = visit_(i, node.items[i], visitor, path);
          if (typeof ci === "number")
            i = ci - 1;
          else if (ci === BREAK)
            return BREAK;
          else if (ci === REMOVE) {
            node.items.splice(i, 1);
            i -= 1;
          }
        }
      } else if (identity.isPair(node)) {
        path = Object.freeze(path.concat(node));
        const ck = visit_("key", node.key, visitor, path);
        if (ck === BREAK)
          return BREAK;
        else if (ck === REMOVE)
          node.key = null;
        const cv = visit_("value", node.value, visitor, path);
        if (cv === BREAK)
          return BREAK;
        else if (cv === REMOVE)
          node.value = null;
      }
    }
    return ctrl;
  }
  async function visitAsync(node, visitor) {
    const visitor_ = initVisitor(visitor);
    if (identity.isDocument(node)) {
      const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node]));
      if (cd === REMOVE)
        node.contents = null;
    } else
      await visitAsync_(null, node, visitor_, Object.freeze([]));
  }
  visitAsync.BREAK = BREAK;
  visitAsync.SKIP = SKIP;
  visitAsync.REMOVE = REMOVE;
  async function visitAsync_(key, node, visitor, path) {
    const ctrl = await callVisitor(key, node, visitor, path);
    if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
      replaceNode(key, path, ctrl);
      return visitAsync_(key, ctrl, visitor, path);
    }
    if (typeof ctrl !== "symbol") {
      if (identity.isCollection(node)) {
        path = Object.freeze(path.concat(node));
        for (let i = 0;i < node.items.length; ++i) {
          const ci = await visitAsync_(i, node.items[i], visitor, path);
          if (typeof ci === "number")
            i = ci - 1;
          else if (ci === BREAK)
            return BREAK;
          else if (ci === REMOVE) {
            node.items.splice(i, 1);
            i -= 1;
          }
        }
      } else if (identity.isPair(node)) {
        path = Object.freeze(path.concat(node));
        const ck = await visitAsync_("key", node.key, visitor, path);
        if (ck === BREAK)
          return BREAK;
        else if (ck === REMOVE)
          node.key = null;
        const cv = await visitAsync_("value", node.value, visitor, path);
        if (cv === BREAK)
          return BREAK;
        else if (cv === REMOVE)
          node.value = null;
      }
    }
    return ctrl;
  }
  function initVisitor(visitor) {
    if (typeof visitor === "object" && (visitor.Collection || visitor.Node || visitor.Value)) {
      return Object.assign({
        Alias: visitor.Node,
        Map: visitor.Node,
        Scalar: visitor.Node,
        Seq: visitor.Node
      }, visitor.Value && {
        Map: visitor.Value,
        Scalar: visitor.Value,
        Seq: visitor.Value
      }, visitor.Collection && {
        Map: visitor.Collection,
        Seq: visitor.Collection
      }, visitor);
    }
    return visitor;
  }
  function callVisitor(key, node, visitor, path) {
    if (typeof visitor === "function")
      return visitor(key, node, path);
    if (identity.isMap(node))
      return visitor.Map?.(key, node, path);
    if (identity.isSeq(node))
      return visitor.Seq?.(key, node, path);
    if (identity.isPair(node))
      return visitor.Pair?.(key, node, path);
    if (identity.isScalar(node))
      return visitor.Scalar?.(key, node, path);
    if (identity.isAlias(node))
      return visitor.Alias?.(key, node, path);
    return;
  }
  function replaceNode(key, path, node) {
    const parent = path[path.length - 1];
    if (identity.isCollection(parent)) {
      parent.items[key] = node;
    } else if (identity.isPair(parent)) {
      if (key === "key")
        parent.key = node;
      else
        parent.value = node;
    } else if (identity.isDocument(parent)) {
      parent.contents = node;
    } else {
      const pt = identity.isAlias(parent) ? "alias" : "scalar";
      throw new Error(`Cannot replace node with ${pt} parent`);
    }
  }
  exports.visit = visit;
  exports.visitAsync = visitAsync;
});

// node_modules/yaml/dist/doc/directives.js
var require_directives = __commonJS((exports) => {
  var identity = require_identity();
  var visit = require_visit();
  var escapeChars = {
    "!": "%21",
    ",": "%2C",
    "[": "%5B",
    "]": "%5D",
    "{": "%7B",
    "}": "%7D"
  };
  var escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, (ch) => escapeChars[ch]);

  class Directives {
    constructor(yaml, tags) {
      this.docStart = null;
      this.docEnd = false;
      this.yaml = Object.assign({}, Directives.defaultYaml, yaml);
      this.tags = Object.assign({}, Directives.defaultTags, tags);
    }
    clone() {
      const copy = new Directives(this.yaml, this.tags);
      copy.docStart = this.docStart;
      return copy;
    }
    atDocument() {
      const res = new Directives(this.yaml, this.tags);
      switch (this.yaml.version) {
        case "1.1":
          this.atNextDocument = true;
          break;
        case "1.2":
          this.atNextDocument = false;
          this.yaml = {
            explicit: Directives.defaultYaml.explicit,
            version: "1.2"
          };
          this.tags = Object.assign({}, Directives.defaultTags);
          break;
      }
      return res;
    }
    add(line, onError) {
      if (this.atNextDocument) {
        this.yaml = { explicit: Directives.defaultYaml.explicit, version: "1.1" };
        this.tags = Object.assign({}, Directives.defaultTags);
        this.atNextDocument = false;
      }
      const parts = line.trim().split(/[ \t]+/);
      const name = parts.shift();
      switch (name) {
        case "%TAG": {
          if (parts.length !== 2) {
            onError(0, "%TAG directive should contain exactly two parts");
            if (parts.length < 2)
              return false;
          }
          const [handle, prefix] = parts;
          this.tags[handle] = prefix;
          return true;
        }
        case "%YAML": {
          this.yaml.explicit = true;
          if (parts.length !== 1) {
            onError(0, "%YAML directive should contain exactly one part");
            return false;
          }
          const [version] = parts;
          if (version === "1.1" || version === "1.2") {
            this.yaml.version = version;
            return true;
          } else {
            const isValid = /^\d+\.\d+$/.test(version);
            onError(6, `Unsupported YAML version ${version}`, isValid);
            return false;
          }
        }
        default:
          onError(0, `Unknown directive ${name}`, true);
          return false;
      }
    }
    tagName(source, onError) {
      if (source === "!")
        return "!";
      if (source[0] !== "!") {
        onError(`Not a valid tag: ${source}`);
        return null;
      }
      if (source[1] === "<") {
        const verbatim = source.slice(2, -1);
        if (verbatim === "!" || verbatim === "!!") {
          onError(`Verbatim tags aren't resolved, so ${source} is invalid.`);
          return null;
        }
        if (source[source.length - 1] !== ">")
          onError("Verbatim tags must end with a >");
        return verbatim;
      }
      const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s);
      if (!suffix)
        onError(`The ${source} tag has no suffix`);
      const prefix = this.tags[handle];
      if (prefix) {
        try {
          return prefix + decodeURIComponent(suffix);
        } catch (error) {
          onError(String(error));
          return null;
        }
      }
      if (handle === "!")
        return source;
      onError(`Could not resolve tag: ${source}`);
      return null;
    }
    tagString(tag) {
      for (const [handle, prefix] of Object.entries(this.tags)) {
        if (tag.startsWith(prefix))
          return handle + escapeTagName(tag.substring(prefix.length));
      }
      return tag[0] === "!" ? tag : `!<${tag}>`;
    }
    toString(doc) {
      const lines = this.yaml.explicit ? [`%YAML ${this.yaml.version || "1.2"}`] : [];
      const tagEntries = Object.entries(this.tags);
      let tagNames;
      if (doc && tagEntries.length > 0 && identity.isNode(doc.contents)) {
        const tags = {};
        visit.visit(doc.contents, (_key, node) => {
          if (identity.isNode(node) && node.tag)
            tags[node.tag] = true;
        });
        tagNames = Object.keys(tags);
      } else
        tagNames = [];
      for (const [handle, prefix] of tagEntries) {
        if (handle === "!!" && prefix === "tag:yaml.org,2002:")
          continue;
        if (!doc || tagNames.some((tn) => tn.startsWith(prefix)))
          lines.push(`%TAG ${handle} ${prefix}`);
      }
      return lines.join(`
`);
    }
  }
  Directives.defaultYaml = { explicit: false, version: "1.2" };
  Directives.defaultTags = { "!!": "tag:yaml.org,2002:" };
  exports.Directives = Directives;
});

// node_modules/yaml/dist/doc/anchors.js
var require_anchors = __commonJS((exports) => {
  var identity = require_identity();
  var visit = require_visit();
  function anchorIsValid(anchor) {
    if (/[\x00-\x19\s,[\]{}]/.test(anchor)) {
      const sa = JSON.stringify(anchor);
      const msg = `Anchor must not contain whitespace or control characters: ${sa}`;
      throw new Error(msg);
    }
    return true;
  }
  function anchorNames(root) {
    const anchors = new Set;
    visit.visit(root, {
      Value(_key, node) {
        if (node.anchor)
          anchors.add(node.anchor);
      }
    });
    return anchors;
  }
  function findNewAnchor(prefix, exclude) {
    for (let i = 1;; ++i) {
      const name = `${prefix}${i}`;
      if (!exclude.has(name))
        return name;
    }
  }
  function createNodeAnchors(doc, prefix) {
    const aliasObjects = [];
    const sourceObjects = new Map;
    let prevAnchors = null;
    return {
      onAnchor: (source) => {
        aliasObjects.push(source);
        prevAnchors ?? (prevAnchors = anchorNames(doc));
        const anchor = findNewAnchor(prefix, prevAnchors);
        prevAnchors.add(anchor);
        return anchor;
      },
      setAnchors: () => {
        for (const source of aliasObjects) {
          const ref = sourceObjects.get(source);
          if (typeof ref === "object" && ref.anchor && (identity.isScalar(ref.node) || identity.isCollection(ref.node))) {
            ref.node.anchor = ref.anchor;
          } else {
            const error = new Error("Failed to resolve repeated object (this should not happen)");
            error.source = source;
            throw error;
          }
        }
      },
      sourceObjects
    };
  }
  exports.anchorIsValid = anchorIsValid;
  exports.anchorNames = anchorNames;
  exports.createNodeAnchors = createNodeAnchors;
  exports.findNewAnchor = findNewAnchor;
});

// node_modules/yaml/dist/doc/applyReviver.js
var require_applyReviver = __commonJS((exports) => {
  function applyReviver(reviver, obj, key, val) {
    if (val && typeof val === "object") {
      if (Array.isArray(val)) {
        for (let i = 0, len = val.length;i < len; ++i) {
          const v0 = val[i];
          const v1 = applyReviver(reviver, val, String(i), v0);
          if (v1 === undefined)
            delete val[i];
          else if (v1 !== v0)
            val[i] = v1;
        }
      } else if (val instanceof Map) {
        for (const k of Array.from(val.keys())) {
          const v0 = val.get(k);
          const v1 = applyReviver(reviver, val, k, v0);
          if (v1 === undefined)
            val.delete(k);
          else if (v1 !== v0)
            val.set(k, v1);
        }
      } else if (val instanceof Set) {
        for (const v0 of Array.from(val)) {
          const v1 = applyReviver(reviver, val, v0, v0);
          if (v1 === undefined)
            val.delete(v0);
          else if (v1 !== v0) {
            val.delete(v0);
            val.add(v1);
          }
        }
      } else {
        for (const [k, v0] of Object.entries(val)) {
          const v1 = applyReviver(reviver, val, k, v0);
          if (v1 === undefined)
            delete val[k];
          else if (v1 !== v0)
            val[k] = v1;
        }
      }
    }
    return reviver.call(obj, key, val);
  }
  exports.applyReviver = applyReviver;
});

// node_modules/yaml/dist/nodes/toJS.js
var require_toJS = __commonJS((exports) => {
  var identity = require_identity();
  function toJS(value, arg, ctx) {
    if (Array.isArray(value))
      return value.map((v, i) => toJS(v, String(i), ctx));
    if (value && typeof value.toJSON === "function") {
      if (!ctx || !identity.hasAnchor(value))
        return value.toJSON(arg, ctx);
      const data = { aliasCount: 0, count: 1, res: undefined };
      ctx.anchors.set(value, data);
      ctx.onCreate = (res2) => {
        data.res = res2;
        delete ctx.onCreate;
      };
      const res = value.toJSON(arg, ctx);
      if (ctx.onCreate)
        ctx.onCreate(res);
      return res;
    }
    if (typeof value === "bigint" && !ctx?.keep)
      return Number(value);
    return value;
  }
  exports.toJS = toJS;
});

// node_modules/yaml/dist/nodes/Node.js
var require_Node = __commonJS((exports) => {
  var applyReviver = require_applyReviver();
  var identity = require_identity();
  var toJS = require_toJS();

  class NodeBase {
    constructor(type) {
      Object.defineProperty(this, identity.NODE_TYPE, { value: type });
    }
    clone() {
      const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
      if (this.range)
        copy.range = this.range.slice();
      return copy;
    }
    toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
      if (!identity.isDocument(doc))
        throw new TypeError("A document argument is required");
      const ctx = {
        anchors: new Map,
        doc,
        keep: true,
        mapAsMap: mapAsMap === true,
        mapKeyWarned: false,
        maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100
      };
      const res = toJS.toJS(this, "", ctx);
      if (typeof onAnchor === "function")
        for (const { count, res: res2 } of ctx.anchors.values())
          onAnchor(res2, count);
      return typeof reviver === "function" ? applyReviver.applyReviver(reviver, { "": res }, "", res) : res;
    }
  }
  exports.NodeBase = NodeBase;
});

// node_modules/yaml/dist/nodes/Alias.js
var require_Alias = __commonJS((exports) => {
  var anchors = require_anchors();
  var visit = require_visit();
  var identity = require_identity();
  var Node = require_Node();
  var toJS = require_toJS();

  class Alias extends Node.NodeBase {
    constructor(source) {
      super(identity.ALIAS);
      this.source = source;
      Object.defineProperty(this, "tag", {
        set() {
          throw new Error("Alias nodes cannot have tags");
        }
      });
    }
    resolve(doc, ctx) {
      if (ctx?.maxAliasCount === 0)
        throw new ReferenceError("Alias resolution is disabled");
      let nodes;
      if (ctx?.aliasResolveCache) {
        nodes = ctx.aliasResolveCache;
      } else {
        nodes = [];
        visit.visit(doc, {
          Node: (_key, node) => {
            if (identity.isAlias(node) || identity.hasAnchor(node))
              nodes.push(node);
          }
        });
        if (ctx)
          ctx.aliasResolveCache = nodes;
      }
      let found = undefined;
      for (const node of nodes) {
        if (node === this)
          break;
        if (node.anchor === this.source)
          found = node;
      }
      return found;
    }
    toJSON(_arg, ctx) {
      if (!ctx)
        return { source: this.source };
      const { anchors: anchors2, doc, maxAliasCount } = ctx;
      const source = this.resolve(doc, ctx);
      if (!source) {
        const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
        throw new ReferenceError(msg);
      }
      let data = anchors2.get(source);
      if (!data) {
        toJS.toJS(source, null, ctx);
        data = anchors2.get(source);
      }
      if (data?.res === undefined) {
        const msg = "This should not happen: Alias anchor was not resolved?";
        throw new ReferenceError(msg);
      }
      if (maxAliasCount >= 0) {
        data.count += 1;
        if (data.aliasCount === 0)
          data.aliasCount = getAliasCount(doc, source, anchors2);
        if (data.count * data.aliasCount > maxAliasCount) {
          const msg = "Excessive alias count indicates a resource exhaustion attack";
          throw new ReferenceError(msg);
        }
      }
      return data.res;
    }
    toString(ctx, _onComment, _onChompKeep) {
      const src = `*${this.source}`;
      if (ctx) {
        anchors.anchorIsValid(this.source);
        if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) {
          const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
          throw new Error(msg);
        }
        if (ctx.implicitKey)
          return `${src} `;
      }
      return src;
    }
  }
  function getAliasCount(doc, node, anchors2) {
    if (identity.isAlias(node)) {
      const source = node.resolve(doc);
      const anchor = anchors2 && source && anchors2.get(source);
      return anchor ? anchor.count * anchor.aliasCount : 0;
    } else if (identity.isCollection(node)) {
      let count = 0;
      for (const item of node.items) {
        const c = getAliasCount(doc, item, anchors2);
        if (c > count)
          count = c;
      }
      return count;
    } else if (identity.isPair(node)) {
      const kc = getAliasCount(doc, node.key, anchors2);
      const vc = getAliasCount(doc, node.value, anchors2);
      return Math.max(kc, vc);
    }
    return 1;
  }
  exports.Alias = Alias;
});

// node_modules/yaml/dist/nodes/Scalar.js
var require_Scalar = __commonJS((exports) => {
  var identity = require_identity();
  var Node = require_Node();
  var toJS = require_toJS();
  var isScalarValue = (value) => !value || typeof value !== "function" && typeof value !== "object";

  class Scalar extends Node.NodeBase {
    constructor(value) {
      super(identity.SCALAR);
      this.value = value;
    }
    toJSON(arg, ctx) {
      return ctx?.keep ? this.value : toJS.toJS(this.value, arg, ctx);
    }
    toString() {
      return String(this.value);
    }
  }
  Scalar.BLOCK_FOLDED = "BLOCK_FOLDED";
  Scalar.BLOCK_LITERAL = "BLOCK_LITERAL";
  Scalar.PLAIN = "PLAIN";
  Scalar.QUOTE_DOUBLE = "QUOTE_DOUBLE";
  Scalar.QUOTE_SINGLE = "QUOTE_SINGLE";
  exports.Scalar = Scalar;
  exports.isScalarValue = isScalarValue;
});

// node_modules/yaml/dist/doc/createNode.js
var require_createNode = __commonJS((exports) => {
  var Alias = require_Alias();
  var identity = require_identity();
  var Scalar = require_Scalar();
  var defaultTagPrefix = "tag:yaml.org,2002:";
  function findTagObject(value, tagName, tags) {
    if (tagName) {
      const match = tags.filter((t) => t.tag === tagName);
      const tagObj = match.find((t) => !t.format) ?? match[0];
      if (!tagObj)
        throw new Error(`Tag ${tagName} not found`);
      return tagObj;
    }
    return tags.find((t) => t.identify?.(value) && !t.format);
  }
  function createNode(value, tagName, ctx) {
    if (identity.isDocument(value))
      value = value.contents;
    if (identity.isNode(value))
      return value;
    if (identity.isPair(value)) {
      const map = ctx.schema[identity.MAP].createNode?.(ctx.schema, null, ctx);
      map.items.push(value);
      return map;
    }
    if (value instanceof String || value instanceof Number || value instanceof Boolean || typeof BigInt !== "undefined" && value instanceof BigInt) {
      value = value.valueOf();
    }
    const { aliasDuplicateObjects, onAnchor, onTagObj, schema, sourceObjects } = ctx;
    let ref = undefined;
    if (aliasDuplicateObjects && value && typeof value === "object") {
      ref = sourceObjects.get(value);
      if (ref) {
        ref.anchor ?? (ref.anchor = onAnchor(value));
        return new Alias.Alias(ref.anchor);
      } else {
        ref = { anchor: null, node: null };
        sourceObjects.set(value, ref);
      }
    }
    if (tagName?.startsWith("!!"))
      tagName = defaultTagPrefix + tagName.slice(2);
    let tagObj = findTagObject(value, tagName, schema.tags);
    if (!tagObj) {
      if (value && typeof value.toJSON === "function") {
        value = value.toJSON();
      }
      if (!value || typeof value !== "object") {
        const node2 = new Scalar.Scalar(value);
        if (ref)
          ref.node = node2;
        return node2;
      }
      tagObj = value instanceof Map ? schema[identity.MAP] : (Symbol.iterator in Object(value)) ? schema[identity.SEQ] : schema[identity.MAP];
    }
    if (onTagObj) {
      onTagObj(tagObj);
      delete ctx.onTagObj;
    }
    const node = tagObj?.createNode ? tagObj.createNode(ctx.schema, value, ctx) : typeof tagObj?.nodeClass?.from === "function" ? tagObj.nodeClass.from(ctx.schema, value, ctx) : new Scalar.Scalar(value);
    if (tagName)
      node.tag = tagName;
    else if (!tagObj.default)
      node.tag = tagObj.tag;
    if (ref)
      ref.node = node;
    return node;
  }
  exports.createNode = createNode;
});

// node_modules/yaml/dist/nodes/Collection.js
var require_Collection = __commonJS((exports) => {
  var createNode = require_createNode();
  var identity = require_identity();
  var Node = require_Node();
  function collectionFromPath(schema, path, value) {
    let v = value;
    for (let i = path.length - 1;i >= 0; --i) {
      const k = path[i];
      if (typeof k === "number" && Number.isInteger(k) && k >= 0) {
        const a = [];
        a[k] = v;
        v = a;
      } else {
        v = new Map([[k, v]]);
      }
    }
    return createNode.createNode(v, undefined, {
      aliasDuplicateObjects: false,
      keepUndefined: false,
      onAnchor: () => {
        throw new Error("This should not happen, please report a bug.");
      },
      schema,
      sourceObjects: new Map
    });
  }
  var isEmptyPath = (path) => path == null || typeof path === "object" && !!path[Symbol.iterator]().next().done;

  class Collection extends Node.NodeBase {
    constructor(type, schema) {
      super(type);
      Object.defineProperty(this, "schema", {
        value: schema,
        configurable: true,
        enumerable: false,
        writable: true
      });
    }
    clone(schema) {
      const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
      if (schema)
        copy.schema = schema;
      copy.items = copy.items.map((it) => identity.isNode(it) || identity.isPair(it) ? it.clone(schema) : it);
      if (this.range)
        copy.range = this.range.slice();
      return copy;
    }
    addIn(path, value) {
      if (isEmptyPath(path))
        this.add(value);
      else {
        const [key, ...rest] = path;
        const node = this.get(key, true);
        if (identity.isCollection(node))
          node.addIn(rest, value);
        else if (node === undefined && this.schema)
          this.set(key, collectionFromPath(this.schema, rest, value));
        else
          throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
      }
    }
    deleteIn(path) {
      const [key, ...rest] = path;
      if (rest.length === 0)
        return this.delete(key);
      const node = this.get(key, true);
      if (identity.isCollection(node))
        return node.deleteIn(rest);
      else
        throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
    }
    getIn(path, keepScalar) {
      const [key, ...rest] = path;
      const node = this.get(key, true);
      if (rest.length === 0)
        return !keepScalar && identity.isScalar(node) ? node.value : node;
      else
        return identity.isCollection(node) ? node.getIn(rest, keepScalar) : undefined;
    }
    hasAllNullValues(allowScalar) {
      return this.items.every((node) => {
        if (!identity.isPair(node))
          return false;
        const n = node.value;
        return n == null || allowScalar && identity.isScalar(n) && n.value == null && !n.commentBefore && !n.comment && !n.tag;
      });
    }
    hasIn(path) {
      const [key, ...rest] = path;
      if (rest.length === 0)
        return this.has(key);
      const node = this.get(key, true);
      return identity.isCollection(node) ? node.hasIn(rest) : false;
    }
    setIn(path, value) {
      const [key, ...rest] = path;
      if (rest.length === 0) {
        this.set(key, value);
      } else {
        const node = this.get(key, true);
        if (identity.isCollection(node))
          node.setIn(rest, value);
        else if (node === undefined && this.schema)
          this.set(key, collectionFromPath(this.schema, rest, value));
        else
          throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
      }
    }
  }
  exports.Collection = Collection;
  exports.collectionFromPath = collectionFromPath;
  exports.isEmptyPath = isEmptyPath;
});

// node_modules/yaml/dist/stringify/stringifyComment.js
var require_stringifyComment = __commonJS((exports) => {
  var stringifyComment = (str) => str.replace(/^(?!$)(?: $)?/gm, "#");
  function indentComment(comment, indent) {
    if (/^\n+$/.test(comment))
      return comment.substring(1);
    return indent ? comment.replace(/^(?! *$)/gm, indent) : comment;
  }
  var lineComment = (str, indent, comment) => str.endsWith(`
`) ? indentComment(comment, indent) : comment.includes(`
`) ? `
` + indentComment(comment, indent) : (str.endsWith(" ") ? "" : " ") + comment;
  exports.indentComment = indentComment;
  exports.lineComment = lineComment;
  exports.stringifyComment = stringifyComment;
});

// node_modules/yaml/dist/stringify/foldFlowLines.js
var require_foldFlowLines = __commonJS((exports) => {
  var FOLD_FLOW = "flow";
  var FOLD_BLOCK = "block";
  var FOLD_QUOTED = "quoted";
  function foldFlowLines(text, indent, mode = "flow", { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) {
    if (!lineWidth || lineWidth < 0)
      return text;
    if (lineWidth < minContentWidth)
      minContentWidth = 0;
    const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length);
    if (text.length <= endStep)
      return text;
    const folds = [];
    const escapedFolds = {};
    let end = lineWidth - indent.length;
    if (typeof indentAtStart === "number") {
      if (indentAtStart > lineWidth - Math.max(2, minContentWidth))
        folds.push(0);
      else
        end = lineWidth - indentAtStart;
    }
    let split = undefined;
    let prev = undefined;
    let overflow = false;
    let i = -1;
    let escStart = -1;
    let escEnd = -1;
    if (mode === FOLD_BLOCK) {
      i = consumeMoreIndentedLines(text, i, indent.length);
      if (i !== -1)
        end = i + endStep;
    }
    for (let ch;ch = text[i += 1]; ) {
      if (mode === FOLD_QUOTED && ch === "\\") {
        escStart = i;
        switch (text[i + 1]) {
          case "x":
            i += 3;
            break;
          case "u":
            i += 5;
            break;
          case "U":
            i += 9;
            break;
          default:
            i += 1;
        }
        escEnd = i;
      }
      if (ch === `
`) {
        if (mode === FOLD_BLOCK)
          i = consumeMoreIndentedLines(text, i, indent.length);
        end = i + indent.length + endStep;
        split = undefined;
      } else {
        if (ch === " " && prev && prev !== " " && prev !== `
` && prev !== "\t") {
          const next = text[i + 1];
          if (next && next !== " " && next !== `
` && next !== "\t")
            split = i;
        }
        if (i >= end) {
          if (split) {
            folds.push(split);
            end = split + endStep;
            split = undefined;
          } else if (mode === FOLD_QUOTED) {
            while (prev === " " || prev === "\t") {
              prev = ch;
              ch = text[i += 1];
              overflow = true;
            }
            const j = i > escEnd + 1 ? i - 2 : escStart - 1;
            if (escapedFolds[j])
              return text;
            folds.push(j);
            escapedFolds[j] = true;
            end = j + endStep;
            split = undefined;
          } else {
            overflow = true;
          }
        }
      }
      prev = ch;
    }
    if (overflow && onOverflow)
      onOverflow();
    if (folds.length === 0)
      return text;
    if (onFold)
      onFold();
    let res = text.slice(0, folds[0]);
    for (let i2 = 0;i2 < folds.length; ++i2) {
      const fold = folds[i2];
      const end2 = folds[i2 + 1] || text.length;
      if (fold === 0)
        res = `
${indent}${text.slice(0, end2)}`;
      else {
        if (mode === FOLD_QUOTED && escapedFolds[fold])
          res += `${text[fold]}\\`;
        res += `
${indent}${text.slice(fold + 1, end2)}`;
      }
    }
    return res;
  }
  function consumeMoreIndentedLines(text, i, indent) {
    let end = i;
    let start = i + 1;
    let ch = text[start];
    while (ch === " " || ch === "\t") {
      if (i < start + indent) {
        ch = text[++i];
      } else {
        do {
          ch = text[++i];
        } while (ch && ch !== `
`);
        end = i;
        start = i + 1;
        ch = text[start];
      }
    }
    return end;
  }
  exports.FOLD_BLOCK = FOLD_BLOCK;
  exports.FOLD_FLOW = FOLD_FLOW;
  exports.FOLD_QUOTED = FOLD_QUOTED;
  exports.foldFlowLines = foldFlowLines;
});

// node_modules/yaml/dist/stringify/stringifyString.js
var require_stringifyString = __commonJS((exports) => {
  var Scalar = require_Scalar();
  var foldFlowLines = require_foldFlowLines();
  var getFoldOptions = (ctx, isBlock) => ({
    indentAtStart: isBlock ? ctx.indent.length : ctx.indentAtStart,
    lineWidth: ctx.options.lineWidth,
    minContentWidth: ctx.options.minContentWidth
  });
  var containsDocumentMarker = (str) => /^(%|---|\.\.\.)/m.test(str);
  function lineLengthOverLimit(str, lineWidth, indentLength) {
    if (!lineWidth || lineWidth < 0)
      return false;
    const limit = lineWidth - indentLength;
    const strLen = str.length;
    if (strLen <= limit)
      return false;
    for (let i = 0, start = 0;i < strLen; ++i) {
      if (str[i] === `
`) {
        if (i - start > limit)
          return true;
        start = i + 1;
        if (strLen - start <= limit)
          return false;
      }
    }
    return true;
  }
  function doubleQuotedString(value, ctx) {
    const json = JSON.stringify(value);
    if (ctx.options.doubleQuotedAsJSON)
      return json;
    const { implicitKey } = ctx;
    const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength;
    const indent = ctx.indent || (containsDocumentMarker(value) ? "  " : "");
    let str = "";
    let start = 0;
    for (let i = 0, ch = json[i];ch; ch = json[++i]) {
      if (ch === " " && json[i + 1] === "\\" && json[i + 2] === "n") {
        str += json.slice(start, i) + "\\ ";
        i += 1;
        start = i;
        ch = "\\";
      }
      if (ch === "\\")
        switch (json[i + 1]) {
          case "u":
            {
              str += json.slice(start, i);
              const code = json.substr(i + 2, 4);
              switch (code) {
                case "0000":
                  str += "\\0";
                  break;
                case "0007":
                  str += "\\a";
                  break;
                case "000b":
                  str += "\\v";
                  break;
                case "001b":
                  str += "\\e";
                  break;
                case "0085":
                  str += "\\N";
                  break;
                case "00a0":
                  str += "\\_";
                  break;
                case "2028":
                  str += "\\L";
                  break;
                case "2029":
                  str += "\\P";
                  break;
                default:
                  if (code.substr(0, 2) === "00")
                    str += "\\x" + code.substr(2);
                  else
                    str += json.substr(i, 6);
              }
              i += 5;
              start = i + 1;
            }
            break;
          case "n":
            if (implicitKey || json[i + 2] === '"' || json.length < minMultiLineLength) {
              i += 1;
            } else {
              str += json.slice(start, i) + `

`;
              while (json[i + 2] === "\\" && json[i + 3] === "n" && json[i + 4] !== '"') {
                str += `
`;
                i += 2;
              }
              str += indent;
              if (json[i + 2] === " ")
                str += "\\";
              i += 1;
              start = i + 1;
            }
            break;
          default:
            i += 1;
        }
    }
    str = start ? str + json.slice(start) : json;
    return implicitKey ? str : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_QUOTED, getFoldOptions(ctx, false));
  }
  function singleQuotedString(value, ctx) {
    if (ctx.options.singleQuote === false || ctx.implicitKey && value.includes(`
`) || /[ \t]\n|\n[ \t]/.test(value))
      return doubleQuotedString(value, ctx);
    const indent = ctx.indent || (containsDocumentMarker(value) ? "  " : "");
    const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$&
${indent}`) + "'";
    return ctx.implicitKey ? res : foldFlowLines.foldFlowLines(res, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false));
  }
  function quotedString(value, ctx) {
    const { singleQuote } = ctx.options;
    let qs;
    if (singleQuote === false)
      qs = doubleQuotedString;
    else {
      const hasDouble = value.includes('"');
      const hasSingle = value.includes("'");
      if (hasDouble && !hasSingle)
        qs = singleQuotedString;
      else if (hasSingle && !hasDouble)
        qs = doubleQuotedString;
      else
        qs = singleQuote ? singleQuotedString : doubleQuotedString;
    }
    return qs(value, ctx);
  }
  var blockEndNewlines;
  try {
    blockEndNewlines = new RegExp(`(^|(?<!
))
+(?!
|$)`, "g");
  } catch {
    blockEndNewlines = /\n+(?!\n|$)/g;
  }
  function blockString({ comment, type, value }, ctx, onComment, onChompKeep) {
    const { blockQuote, commentString, lineWidth } = ctx.options;
    if (!blockQuote || /\n[\t ]+$/.test(value)) {
      return quotedString(value, ctx);
    }
    const indent = ctx.indent || (ctx.forceBlockIndent || containsDocumentMarker(value) ? "  " : "");
    const literal = blockQuote === "literal" ? true : blockQuote === "folded" || type === Scalar.Scalar.BLOCK_FOLDED ? false : type === Scalar.Scalar.BLOCK_LITERAL ? true : !lineLengthOverLimit(value, lineWidth, indent.length);
    if (!value)
      return literal ? `|
` : `>
`;
    let chomp;
    let endStart;
    for (endStart = value.length;endStart > 0; --endStart) {
      const ch = value[endStart - 1];
      if (ch !== `
` && ch !== "\t" && ch !== " ")
        break;
    }
    let end = value.substring(endStart);
    const endNlPos = end.indexOf(`
`);
    if (endNlPos === -1) {
      chomp = "-";
    } else if (value === end || endNlPos !== end.length - 1) {
      chomp = "+";
      if (onChompKeep)
        onChompKeep();
    } else {
      chomp = "";
    }
    if (end) {
      value = value.slice(0, -end.length);
      if (end[end.length - 1] === `
`)
        end = end.slice(0, -1);
      end = end.replace(blockEndNewlines, `$&${indent}`);
    }
    let startWithSpace = false;
    let startEnd;
    let startNlPos = -1;
    for (startEnd = 0;startEnd < value.length; ++startEnd) {
      const ch = value[startEnd];
      if (ch === " ")
        startWithSpace = true;
      else if (ch === `
`)
        startNlPos = startEnd;
      else
        break;
    }
    let start = value.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd);
    if (start) {
      value = value.substring(start.length);
      start = start.replace(/\n+/g, `$&${indent}`);
    }
    const indentSize = indent ? "2" : "1";
    let header = (startWithSpace ? indentSize : "") + chomp;
    if (comment) {
      header += " " + commentString(comment.replace(/ ?[\r\n]+/g, " "));
      if (onComment)
        onComment();
    }
    if (!literal) {
      const foldedValue = value.replace(/\n+/g, `
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`);
      let literalFallback = false;
      const foldOptions = getFoldOptions(ctx, true);
      if (blockQuote !== "folded" && type !== Scalar.Scalar.BLOCK_FOLDED) {
        foldOptions.onOverflow = () => {
          literalFallback = true;
        };
      }
      const body = foldFlowLines.foldFlowLines(`${start}${foldedValue}${end}`, indent, foldFlowLines.FOLD_BLOCK, foldOptions);
      if (!literalFallback)
        return `>${header}
${indent}${body}`;
    }
    value = value.replace(/\n+/g, `$&${indent}`);
    return `|${header}
${indent}${start}${value}${end}`;
  }
  function plainString(item, ctx, onComment, onChompKeep) {
    const { type, value } = item;
    const { actualString, implicitKey, indent, indentStep, inFlow } = ctx;
    if (implicitKey && value.includes(`
`) || inFlow && /[[\]{},]/.test(value)) {
      return quotedString(value, ctx);
    }
    if (/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) {
      return implicitKey || inFlow || !value.includes(`
`) ? quotedString(value, ctx) : blockString(item, ctx, onComment, onChompKeep);
    }
    if (!implicitKey && !inFlow && type !== Scalar.Scalar.PLAIN && value.includes(`
`)) {
      return blockString(item, ctx, onComment, onChompKeep);
    }
    if (containsDocumentMarker(value)) {
      if (indent === "") {
        ctx.forceBlockIndent = true;
        return blockString(item, ctx, onComment, onChompKeep);
      } else if (implicitKey && indent === indentStep) {
        return quotedString(value, ctx);
      }
    }
    const str = value.replace(/\n+/g, `$&
${indent}`);
    if (actualString) {
      const test = (tag) => tag.default && tag.tag !== "tag:yaml.org,2002:str" && tag.test?.test(str);
      const { compat, tags } = ctx.doc.schema;
      if (tags.some(test) || compat?.some(test))
        return quotedString(value, ctx);
    }
    return implicitKey ? str : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false));
  }
  function stringifyString(item, ctx, onComment, onChompKeep) {
    const { implicitKey, inFlow } = ctx;
    const ss = typeof item.value === "string" ? item : Object.assign({}, item, { value: String(item.value) });
    let { type } = item;
    if (type !== Scalar.Scalar.QUOTE_DOUBLE) {
      if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value))
        type = Scalar.Scalar.QUOTE_DOUBLE;
    }
    const _stringify = (_type) => {
      switch (_type) {
        case Scalar.Scalar.BLOCK_FOLDED:
        case Scalar.Scalar.BLOCK_LITERAL:
          return implicitKey || inFlow ? quotedString(ss.value, ctx) : blockString(ss, ctx, onComment, onChompKeep);
        case Scalar.Scalar.QUOTE_DOUBLE:
          return doubleQuotedString(ss.value, ctx);
        case Scalar.Scalar.QUOTE_SINGLE:
          return singleQuotedString(ss.value, ctx);
        case Scalar.Scalar.PLAIN:
          return plainString(ss, ctx, onComment, onChompKeep);
        default:
          return null;
      }
    };
    let res = _stringify(type);
    if (res === null) {
      const { defaultKeyType, defaultStringType } = ctx.options;
      const t = implicitKey && defaultKeyType || defaultStringType;
      res = _stringify(t);
      if (res === null)
        throw new Error(`Unsupported default string type ${t}`);
    }
    return res;
  }
  exports.stringifyString = stringifyString;
});

// node_modules/yaml/dist/stringify/stringify.js
var require_stringify = __commonJS((exports) => {
  var anchors = require_anchors();
  var identity = require_identity();
  var stringifyComment = require_stringifyComment();
  var stringifyString = require_stringifyString();
  function createStringifyContext(doc, options) {
    const opt = Object.assign({
      blockQuote: true,
      commentString: stringifyComment.stringifyComment,
      defaultKeyType: null,
      defaultStringType: "PLAIN",
      directives: null,
      doubleQuotedAsJSON: false,
      doubleQuotedMinMultiLineLength: 40,
      falseStr: "false",
      flowCollectionPadding: true,
      indentSeq: true,
      lineWidth: 80,
      minContentWidth: 20,
      nullStr: "null",
      simpleKeys: false,
      singleQuote: null,
      trailingComma: false,
      trueStr: "true",
      verifyAliasOrder: true
    }, doc.schema.toStringOptions, options);
    let inFlow;
    switch (opt.collectionStyle) {
      case "block":
        inFlow = false;
        break;
      case "flow":
        inFlow = true;
        break;
      default:
        inFlow = null;
    }
    return {
      anchors: new Set,
      doc,
      flowCollectionPadding: opt.flowCollectionPadding ? " " : "",
      indent: "",
      indentStep: typeof opt.indent === "number" ? " ".repeat(opt.indent) : "  ",
      inFlow,
      options: opt
    };
  }
  function getTagObject(tags, item) {
    if (item.tag) {
      const match = tags.filter((t) => t.tag === item.tag);
      if (match.length > 0)
        return match.find((t) => t.format === item.format) ?? match[0];
    }
    let tagObj = undefined;
    let obj;
    if (identity.isScalar(item)) {
      obj = item.value;
      let match = tags.filter((t) => t.identify?.(obj));
      if (match.length > 1) {
        const testMatch = match.filter((t) => t.test);
        if (testMatch.length > 0)
          match = testMatch;
      }
      tagObj = match.find((t) => t.format === item.format) ?? match.find((t) => !t.format);
    } else {
      obj = item;
      tagObj = tags.find((t) => t.nodeClass && obj instanceof t.nodeClass);
    }
    if (!tagObj) {
      const name = obj?.constructor?.name ?? (obj === null ? "null" : typeof obj);
      throw new Error(`Tag not resolved for ${name} value`);
    }
    return tagObj;
  }
  function stringifyProps(node, tagObj, { anchors: anchors$1, doc }) {
    if (!doc.directives)
      return "";
    const props = [];
    const anchor = (identity.isScalar(node) || identity.isCollection(node)) && node.anchor;
    if (anchor && anchors.anchorIsValid(anchor)) {
      anchors$1.add(anchor);
      props.push(`&${anchor}`);
    }
    const tag = node.tag ?? (tagObj.default ? null : tagObj.tag);
    if (tag)
      props.push(doc.directives.tagString(tag));
    return props.join(" ");
  }
  function stringify(item, ctx, onComment, onChompKeep) {
    if (identity.isPair(item))
      return item.toString(ctx, onComment, onChompKeep);
    if (identity.isAlias(item)) {
      if (ctx.doc.directives)
        return item.toString(ctx);
      if (ctx.resolvedAliases?.has(item)) {
        throw new TypeError(`Cannot stringify circular structure without alias nodes`);
      } else {
        if (ctx.resolvedAliases)
          ctx.resolvedAliases.add(item);
        else
          ctx.resolvedAliases = new Set([item]);
        item = item.resolve(ctx.doc);
      }
    }
    let tagObj = undefined;
    const node = identity.isNode(item) ? item : ctx.doc.createNode(item, { onTagObj: (o) => tagObj = o });
    tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node));
    const props = stringifyProps(node, tagObj, ctx);
    if (props.length > 0)
      ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1;
    const str = typeof tagObj.stringify === "function" ? tagObj.stringify(node, ctx, onComment, onChompKeep) : identity.isScalar(node) ? stringifyString.stringifyString(node, ctx, onComment, onChompKeep) : node.toString(ctx, onComment, onChompKeep);
    if (!props)
      return str;
    return identity.isScalar(node) || str[0] === "{" || str[0] === "[" ? `${props} ${str}` : `${props}
${ctx.indent}${str}`;
  }
  exports.createStringifyContext = createStringifyContext;
  exports.stringify = stringify;
});

// node_modules/yaml/dist/stringify/stringifyPair.js
var require_stringifyPair = __commonJS((exports) => {
  var identity = require_identity();
  var Scalar = require_Scalar();
  var stringify = require_stringify();
  var stringifyComment = require_stringifyComment();
  function stringifyPair({ key, value }, ctx, onComment, onChompKeep) {
    const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx;
    let keyComment = identity.isNode(key) && key.comment || null;
    if (simpleKeys) {
      if (keyComment) {
        throw new Error("With simple keys, key nodes cannot have comments");
      }
      if (identity.isCollection(key) || !identity.isNode(key) && typeof key === "object") {
        const msg = "With simple keys, collection cannot be used as a key value";
        throw new Error(msg);
      }
    }
    let explicitKey = !simpleKeys && (!key || keyComment && value == null && !ctx.inFlow || identity.isCollection(key) || (identity.isScalar(key) ? key.type === Scalar.Scalar.BLOCK_FOLDED || key.type === Scalar.Scalar.BLOCK_LITERAL : typeof key === "object"));
    ctx = Object.assign({}, ctx, {
      allNullValues: false,
      implicitKey: !explicitKey && (simpleKeys || !allNullValues),
      indent: indent + indentStep
    });
    let keyCommentDone = false;
    let chompKeep = false;
    let str = stringify.stringify(key, ctx, () => keyCommentDone = true, () => chompKeep = true);
    if (!explicitKey && !ctx.inFlow && str.length > 1024) {
      if (simpleKeys)
        throw new Error("With simple keys, single line scalar must not span more than 1024 characters");
      explicitKey = true;
    }
    if (ctx.inFlow) {
      if (allNullValues || value == null) {
        if (keyCommentDone && onComment)
          onComment();
        return str === "" ? "?" : explicitKey ? `? ${str}` : str;
      }
    } else if (allNullValues && !simpleKeys || value == null && explicitKey) {
      str = `? ${str}`;
      if (keyComment && !keyCommentDone) {
        str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));
      } else if (chompKeep && onChompKeep)
        onChompKeep();
      return str;
    }
    if (keyCommentDone)
      keyComment = null;
    if (explicitKey) {
      if (keyComment)
        str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));
      str = `? ${str}
${indent}:`;
    } else {
      str = `${str}:`;
      if (keyComment)
        str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));
    }
    let vsb, vcb, valueComment;
    if (identity.isNode(value)) {
      vsb = !!value.spaceBefore;
      vcb = value.commentBefore;
      valueComment = value.comment;
    } else {
      vsb = false;
      vcb = null;
      valueComment = null;
      if (value && typeof value === "object")
        value = doc.createNode(value);
    }
    ctx.implicitKey = false;
    if (!explicitKey && !keyComment && identity.isScalar(value))
      ctx.indentAtStart = str.length + 1;
    chompKeep = false;
    if (!indentSeq && indentStep.length >= 2 && !ctx.inFlow && !explicitKey && identity.isSeq(value) && !value.flow && !value.tag && !value.anchor) {
      ctx.indent = ctx.indent.substring(2);
    }
    let valueCommentDone = false;
    const valueStr = stringify.stringify(value, ctx, () => valueCommentDone = true, () => chompKeep = true);
    let ws = " ";
    if (keyComment || vsb || vcb) {
      ws = vsb ? `
` : "";
      if (vcb) {
        const cs = commentString(vcb);
        ws += `
${stringifyComment.indentComment(cs, ctx.indent)}`;
      }
      if (valueStr === "" && !ctx.inFlow) {
        if (ws === `
` && valueComment)
          ws = `

`;
      } else {
        ws += `
${ctx.indent}`;
      }
    } else if (!explicitKey && identity.isCollection(value)) {
      const vs0 = valueStr[0];
      const nl0 = valueStr.indexOf(`
`);
      const hasNewline = nl0 !== -1;
      const flow = ctx.inFlow ?? value.flow ?? value.items.length === 0;
      if (hasNewline || !flow) {
        let hasPropsLine = false;
        if (hasNewline && (vs0 === "&" || vs0 === "!")) {
          let sp0 = valueStr.indexOf(" ");
          if (vs0 === "&" && sp0 !== -1 && sp0 < nl0 && valueStr[sp0 + 1] === "!") {
            sp0 = valueStr.indexOf(" ", sp0 + 1);
          }
          if (sp0 === -1 || nl0 < sp0)
            hasPropsLine = true;
        }
        if (!hasPropsLine)
          ws = `
${ctx.indent}`;
      }
    } else if (valueStr === "" || valueStr[0] === `
`) {
      ws = "";
    }
    str += ws + valueStr;
    if (ctx.inFlow) {
      if (valueCommentDone && onComment)
        onComment();
    } else if (valueComment && !valueCommentDone) {
      str += stringifyComment.lineComment(str, ctx.indent, commentString(valueComment));
    } else if (chompKeep && onChompKeep) {
      onChompKeep();
    }
    return str;
  }
  exports.stringifyPair = stringifyPair;
});

// node_modules/yaml/dist/log.js
var require_log = __commonJS((exports) => {
  var node_process = __require("process");
  function debug(logLevel, ...messages) {
    if (logLevel === "debug")
      console.log(...messages);
  }
  function warn(logLevel, warning) {
    if (logLevel === "debug" || logLevel === "warn") {
      if (typeof node_process.emitWarning === "function")
        node_process.emitWarning(warning);
      else
        console.warn(warning);
    }
  }
  exports.debug = debug;
  exports.warn = warn;
});

// node_modules/yaml/dist/schema/yaml-1.1/merge.js
var require_merge = __commonJS((exports) => {
  var identity = require_identity();
  var Scalar = require_Scalar();
  var MERGE_KEY = "<<";
  var merge = {
    identify: (value) => value === MERGE_KEY || typeof value === "symbol" && value.description === MERGE_KEY,
    default: "key",
    tag: "tag:yaml.org,2002:merge",
    test: /^<<$/,
    resolve: () => Object.assign(new Scalar.Scalar(Symbol(MERGE_KEY)), {
      addToJSMap: addMergeToJSMap
    }),
    stringify: () => MERGE_KEY
  };
  var isMergeKey = (ctx, key) => (merge.identify(key) || identity.isScalar(key) && (!key.type || key.type === Scalar.Scalar.PLAIN) && merge.identify(key.value)) && ctx?.doc.schema.tags.some((tag) => tag.tag === merge.tag && tag.default);
  function addMergeToJSMap(ctx, map, value) {
    const source = resolveAliasValue(ctx, value);
    if (identity.isSeq(source))
      for (const it of source.items)
        mergeValue(ctx, map, it);
    else if (Array.isArray(source))
      for (const it of source)
        mergeValue(ctx, map, it);
    else
      mergeValue(ctx, map, source);
  }
  function mergeValue(ctx, map, value) {
    const source = resolveAliasValue(ctx, value);
    if (!identity.isMap(source))
      throw new Error("Merge sources must be maps or map aliases");
    const srcMap = source.toJSON(null, ctx, Map);
    for (const [key, value2] of srcMap) {
      if (map instanceof Map) {
        if (!map.has(key))
          map.set(key, value2);
      } else if (map instanceof Set) {
        map.add(key);
      } else if (!Object.prototype.hasOwnProperty.call(map, key)) {
        Object.defineProperty(map, key, {
          value: value2,
          writable: true,
          enumerable: true,
          configurable: true
        });
      }
    }
    return map;
  }
  function resolveAliasValue(ctx, value) {
    return ctx && identity.isAlias(value) ? value.resolve(ctx.doc, ctx) : value;
  }
  exports.addMergeToJSMap = addMergeToJSMap;
  exports.isMergeKey = isMergeKey;
  exports.merge = merge;
});

// node_modules/yaml/dist/nodes/addPairToJSMap.js
var require_addPairToJSMap = __commonJS((exports) => {
  var log = require_log();
  var merge = require_merge();
  var stringify = require_stringify();
  var identity = require_identity();
  var toJS = require_toJS();
  function addPairToJSMap(ctx, map, { key, value }) {
    if (identity.isNode(key) && key.addToJSMap)
      key.addToJSMap(ctx, map, value);
    else if (merge.isMergeKey(ctx, key))
      merge.addMergeToJSMap(ctx, map, value);
    else {
      const jsKey = toJS.toJS(key, "", ctx);
      if (map instanceof Map) {
        map.set(jsKey, toJS.toJS(value, jsKey, ctx));
      } else if (map instanceof Set) {
        map.add(jsKey);
      } else {
        const stringKey = stringifyKey(key, jsKey, ctx);
        const jsValue = toJS.toJS(value, stringKey, ctx);
        if (stringKey in map)
          Object.defineProperty(map, stringKey, {
            value: jsValue,
            writable: true,
            enumerable: true,
            configurable: true
          });
        else
          map[stringKey] = jsValue;
      }
    }
    return map;
  }
  function stringifyKey(key, jsKey, ctx) {
    if (jsKey === null)
      return "";
    if (typeof jsKey !== "object")
      return String(jsKey);
    if (identity.isNode(key) && ctx?.doc) {
      const strCtx = stringify.createStringifyContext(ctx.doc, {});
      strCtx.anchors = new Set;
      for (const node of ctx.anchors.keys())
        strCtx.anchors.add(node.anchor);
      strCtx.inFlow = true;
      strCtx.inStringifyKey = true;
      const strKey = key.toString(strCtx);
      if (!ctx.mapKeyWarned) {
        let jsonStr = JSON.stringify(strKey);
        if (jsonStr.length > 40)
          jsonStr = jsonStr.substring(0, 36) + '..."';
        log.warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`);
        ctx.mapKeyWarned = true;
      }
      return strKey;
    }
    return JSON.stringify(jsKey);
  }
  exports.addPairToJSMap = addPairToJSMap;
});

// node_modules/yaml/dist/nodes/Pair.js
var require_Pair = __commonJS((exports) => {
  var createNode = require_createNode();
  var stringifyPair = require_stringifyPair();
  var addPairToJSMap = require_addPairToJSMap();
  var identity = require_identity();
  function createPair(key, value, ctx) {
    const k = createNode.createNode(key, undefined, ctx);
    const v = createNode.createNode(value, undefined, ctx);
    return new Pair(k, v);
  }

  class Pair {
    constructor(key, value = null) {
      Object.defineProperty(this, identity.NODE_TYPE, { value: identity.PAIR });
      this.key = key;
      this.value = value;
    }
    clone(schema) {
      let { key, value } = this;
      if (identity.isNode(key))
        key = key.clone(schema);
      if (identity.isNode(value))
        value = value.clone(schema);
      return new Pair(key, value);
    }
    toJSON(_, ctx) {
      const pair = ctx?.mapAsMap ? new Map : {};
      return addPairToJSMap.addPairToJSMap(ctx, pair, this);
    }
    toString(ctx, onComment, onChompKeep) {
      return ctx?.doc ? stringifyPair.stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this);
    }
  }
  exports.Pair = Pair;
  exports.createPair = createPair;
});

// node_modules/yaml/dist/stringify/stringifyCollection.js
var require_stringifyCollection = __commonJS((exports) => {
  var identity = require_identity();
  var stringify = require_stringify();
  var stringifyComment = require_stringifyComment();
  function stringifyCollection(collection, ctx, options) {
    const flow = ctx.inFlow ?? collection.flow;
    const stringify2 = flow ? stringifyFlowCollection : stringifyBlockCollection;
    return stringify2(collection, ctx, options);
  }
  function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) {
    const { indent, options: { commentString } } = ctx;
    const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null });
    let chompKeep = false;
    const lines = [];
    for (let i = 0;i < items.length; ++i) {
      const item = items[i];
      let comment2 = null;
      if (identity.isNode(item)) {
        if (!chompKeep && item.spaceBefore)
          lines.push("");
        addCommentBefore(ctx, lines, item.commentBefore, chompKeep);
        if (item.comment)
          comment2 = item.comment;
      } else if (identity.isPair(item)) {
        const ik = identity.isNode(item.key) ? item.key : null;
        if (ik) {
          if (!chompKeep && ik.spaceBefore)
            lines.push("");
          addCommentBefore(ctx, lines, ik.commentBefore, chompKeep);
        }
      }
      chompKeep = false;
      let str2 = stringify.stringify(item, itemCtx, () => comment2 = null, () => chompKeep = true);
      if (comment2)
        str2 += stringifyComment.lineComment(str2, itemIndent, commentString(comment2));
      if (chompKeep && comment2)
        chompKeep = false;
      lines.push(blockItemPrefix + str2);
    }
    let str;
    if (lines.length === 0) {
      str = flowChars.start + flowChars.end;
    } else {
      str = lines[0];
      for (let i = 1;i < lines.length; ++i) {
        const line = lines[i];
        str += line ? `
${indent}${line}` : `
`;
      }
    }
    if (comment) {
      str += `
` + stringifyComment.indentComment(commentString(comment), indent);
      if (onComment)
        onComment();
    } else if (chompKeep && onChompKeep)
      onChompKeep();
    return str;
  }
  function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) {
    const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx;
    itemIndent += indentStep;
    const itemCtx = Object.assign({}, ctx, {
      indent: itemIndent,
      inFlow: true,
      type: null
    });
    let reqNewline = false;
    let linesAtValue = 0;
    const lines = [];
    for (let i = 0;i < items.length; ++i) {
      const item = items[i];
      let comment = null;
      if (identity.isNode(item)) {
        if (item.spaceBefore)
          lines.push("");
        addCommentBefore(ctx, lines, item.commentBefore, false);
        if (item.comment)
          comment = item.comment;
      } else if (identity.isPair(item)) {
        const ik = identity.isNode(item.key) ? item.key : null;
        if (ik) {
          if (ik.spaceBefore)
            lines.push("");
          addCommentBefore(ctx, lines, ik.commentBefore, false);
          if (ik.comment)
            reqNewline = true;
        }
        const iv = identity.isNode(item.value) ? item.value : null;
        if (iv) {
          if (iv.comment)
            comment = iv.comment;
          if (iv.commentBefore)
            reqNewline = true;
        } else if (item.value == null && ik?.comment) {
          comment = ik.comment;
        }
      }
      if (comment)
        reqNewline = true;
      let str = stringify.stringify(item, itemCtx, () => comment = null);
      reqNewline || (reqNewline = lines.length > linesAtValue || str.includes(`
`));
      if (i < items.length - 1) {
        str += ",";
      } else if (ctx.options.trailingComma) {
        if (ctx.options.lineWidth > 0) {
          reqNewline || (reqNewline = lines.reduce((sum, line) => sum + line.length + 2, 2) + (str.length + 2) > ctx.options.lineWidth);
        }
        if (reqNewline) {
          str += ",";
        }
      }
      if (comment)
        str += stringifyComment.lineComment(str, itemIndent, commentString(comment));
      lines.push(str);
      linesAtValue = lines.length;
    }
    const { start, end } = flowChars;
    if (lines.length === 0) {
      return start + end;
    } else {
      if (!reqNewline) {
        const len = lines.reduce((sum, line) => sum + line.length + 2, 2);
        reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth;
      }
      if (reqNewline) {
        let str = start;
        for (const line of lines)
          str += line ? `
${indentStep}${indent}${line}` : `
`;
        return `${str}
${indent}${end}`;
      } else {
        return `${start}${fcPadding}${lines.join(" ")}${fcPadding}${end}`;
      }
    }
  }
  function addCommentBefore({ indent, options: { commentString } }, lines, comment, chompKeep) {
    if (comment && chompKeep)
      comment = comment.replace(/^\n+/, "");
    if (comment) {
      const ic = stringifyComment.indentComment(commentString(comment), indent);
      lines.push(ic.trimStart());
    }
  }
  exports.stringifyCollection = stringifyCollection;
});

// node_modules/yaml/dist/nodes/YAMLMap.js
var require_YAMLMap = __commonJS((exports) => {
  var stringifyCollection = require_stringifyCollection();
  var addPairToJSMap = require_addPairToJSMap();
  var Collection = require_Collection();
  var identity = require_identity();
  var Pair = require_Pair();
  var Scalar = require_Scalar();
  function findPair(items, key) {
    const k = identity.isScalar(key) ? key.value : key;
    for (const it of items) {
      if (identity.isPair(it)) {
        if (it.key === key || it.key === k)
          return it;
        if (identity.isScalar(it.key) && it.key.value === k)
          return it;
      }
    }
    return;
  }

  class YAMLMap extends Collection.Collection {
    static get tagName() {
      return "tag:yaml.org,2002:map";
    }
    constructor(schema) {
      super(identity.MAP, schema);
      this.items = [];
    }
    static from(schema, obj, ctx) {
      const { keepUndefined, replacer } = ctx;
      const map = new this(schema);
      const add = (key, value) => {
        if (typeof replacer === "function")
          value = replacer.call(obj, key, value);
        else if (Array.isArray(replacer) && !replacer.includes(key))
          return;
        if (value !== undefined || keepUndefined)
          map.items.push(Pair.createPair(key, value, ctx));
      };
      if (obj instanceof Map) {
        for (const [key, value] of obj)
          add(key, value);
      } else if (obj && typeof obj === "object") {
        for (const key of Object.keys(obj))
          add(key, obj[key]);
      }
      if (typeof schema.sortMapEntries === "function") {
        map.items.sort(schema.sortMapEntries);
      }
      return map;
    }
    add(pair, overwrite) {
      let _pair;
      if (identity.isPair(pair))
        _pair = pair;
      else if (!pair || typeof pair !== "object" || !("key" in pair)) {
        _pair = new Pair.Pair(pair, pair?.value);
      } else
        _pair = new Pair.Pair(pair.key, pair.value);
      const prev = findPair(this.items, _pair.key);
      const sortEntries = this.schema?.sortMapEntries;
      if (prev) {
        if (!overwrite)
          throw new Error(`Key ${_pair.key} already set`);
        if (identity.isScalar(prev.value) && Scalar.isScalarValue(_pair.value))
          prev.value.value = _pair.value;
        else
          prev.value = _pair.value;
      } else if (sortEntries) {
        const i = this.items.findIndex((item) => sortEntries(_pair, item) < 0);
        if (i === -1)
          this.items.push(_pair);
        else
          this.items.splice(i, 0, _pair);
      } else {
        this.items.push(_pair);
      }
    }
    delete(key) {
      const it = findPair(this.items, key);
      if (!it)
        return false;
      const del = this.items.splice(this.items.indexOf(it), 1);
      return del.length > 0;
    }
    get(key, keepScalar) {
      const it = findPair(this.items, key);
      const node = it?.value;
      return (!keepScalar && identity.isScalar(node) ? node.value : node) ?? undefined;
    }
    has(key) {
      return !!findPair(this.items, key);
    }
    set(key, value) {
      this.add(new Pair.Pair(key, value), true);
    }
    toJSON(_, ctx, Type) {
      const map = Type ? new Type : ctx?.mapAsMap ? new Map : {};
      if (ctx?.onCreate)
        ctx.onCreate(map);
      for (const item of this.items)
        addPairToJSMap.addPairToJSMap(ctx, map, item);
      return map;
    }
    toString(ctx, onComment, onChompKeep) {
      if (!ctx)
        return JSON.stringify(this);
      for (const item of this.items) {
        if (!identity.isPair(item))
          throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`);
      }
      if (!ctx.allNullValues && this.hasAllNullValues(false))
        ctx = Object.assign({}, ctx, { allNullValues: true });
      return stringifyCollection.stringifyCollection(this, ctx, {
        blockItemPrefix: "",
        flowChars: { start: "{", end: "}" },
        itemIndent: ctx.indent || "",
        onChompKeep,
        onComment
      });
    }
  }
  exports.YAMLMap = YAMLMap;
  exports.findPair = findPair;
});

// node_modules/yaml/dist/schema/common/map.js
var require_map = __commonJS((exports) => {
  var identity = require_identity();
  var YAMLMap = require_YAMLMap();
  var map = {
    collection: "map",
    default: true,
    nodeClass: YAMLMap.YAMLMap,
    tag: "tag:yaml.org,2002:map",
    resolve(map2, onError) {
      if (!identity.isMap(map2))
        onError("Expected a mapping for this tag");
      return map2;
    },
    createNode: (schema, obj, ctx) => YAMLMap.YAMLMap.from(schema, obj, ctx)
  };
  exports.map = map;
});

// node_modules/yaml/dist/nodes/YAMLSeq.js
var require_YAMLSeq = __commonJS((exports) => {
  var createNode = require_createNode();
  var stringifyCollection = require_stringifyCollection();
  var Collection = require_Collection();
  var identity = require_identity();
  var Scalar = require_Scalar();
  var toJS = require_toJS();

  class YAMLSeq extends Collection.Collection {
    static get tagName() {
      return "tag:yaml.org,2002:seq";
    }
    constructor(schema) {
      super(identity.SEQ, schema);
      this.items = [];
    }
    add(value) {
      this.items.push(value);
    }
    delete(key) {
      const idx = asItemIndex(key);
      if (typeof idx !== "number")
        return false;
      const del = this.items.splice(idx, 1);
      return del.length > 0;
    }
    get(key, keepScalar) {
      const idx = asItemIndex(key);
      if (typeof idx !== "number")
        return;
      const it = this.items[idx];
      return !keepScalar && identity.isScalar(it) ? it.value : it;
    }
    has(key) {
      const idx = asItemIndex(key);
      return typeof idx === "number" && idx < this.items.length;
    }
    set(key, value) {
      const idx = asItemIndex(key);
      if (typeof idx !== "number")
        throw new Error(`Expected a valid index, not ${key}.`);
      const prev = this.items[idx];
      if (identity.isScalar(prev) && Scalar.isScalarValue(value))
        prev.value = value;
      else
        this.items[idx] = value;
    }
    toJSON(_, ctx) {
      const seq = [];
      if (ctx?.onCreate)
        ctx.onCreate(seq);
      let i = 0;
      for (const item of this.items)
        seq.push(toJS.toJS(item, String(i++), ctx));
      return seq;
    }
    toString(ctx, onComment, onChompKeep) {
      if (!ctx)
        return JSON.stringify(this);
      return stringifyCollection.stringifyCollection(this, ctx, {
        blockItemPrefix: "- ",
        flowChars: { start: "[", end: "]" },
        itemIndent: (ctx.indent || "") + "  ",
        onChompKeep,
        onComment
      });
    }
    static from(schema, obj, ctx) {
      const { replacer } = ctx;
      const seq = new this(schema);
      if (obj && Symbol.iterator in Object(obj)) {
        let i = 0;
        for (let it of obj) {
          if (typeof replacer === "function") {
            const key = obj instanceof Set ? it : String(i++);
            it = replacer.call(obj, key, it);
          }
          seq.items.push(createNode.createNode(it, undefined, ctx));
        }
      }
      return seq;
    }
  }
  function asItemIndex(key) {
    let idx = identity.isScalar(key) ? key.value : key;
    if (idx && typeof idx === "string")
      idx = Number(idx);
    return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null;
  }
  exports.YAMLSeq = YAMLSeq;
});

// node_modules/yaml/dist/schema/common/seq.js
var require_seq = __commonJS((exports) => {
  var identity = require_identity();
  var YAMLSeq = require_YAMLSeq();
  var seq = {
    collection: "seq",
    default: true,
    nodeClass: YAMLSeq.YAMLSeq,
    tag: "tag:yaml.org,2002:seq",
    resolve(seq2, onError) {
      if (!identity.isSeq(seq2))
        onError("Expected a sequence for this tag");
      return seq2;
    },
    createNode: (schema, obj, ctx) => YAMLSeq.YAMLSeq.from(schema, obj, ctx)
  };
  exports.seq = seq;
});

// node_modules/yaml/dist/schema/common/string.js
var require_string = __commonJS((exports) => {
  var stringifyString = require_stringifyString();
  var string = {
    identify: (value) => typeof value === "string",
    default: true,
    tag: "tag:yaml.org,2002:str",
    resolve: (str) => str,
    stringify(item, ctx, onComment, onChompKeep) {
      ctx = Object.assign({ actualString: true }, ctx);
      return stringifyString.stringifyString(item, ctx, onComment, onChompKeep);
    }
  };
  exports.string = string;
});

// node_modules/yaml/dist/schema/common/null.js
var require_null = __commonJS((exports) => {
  var Scalar = require_Scalar();
  var nullTag = {
    identify: (value) => value == null,
    createNode: () => new Scalar.Scalar(null),
    default: true,
    tag: "tag:yaml.org,2002:null",
    test: /^(?:~|[Nn]ull|NULL)?$/,
    resolve: () => new Scalar.Scalar(null),
    stringify: ({ source }, ctx) => typeof source === "string" && nullTag.test.test(source) ? source : ctx.options.nullStr
  };
  exports.nullTag = nullTag;
});

// node_modules/yaml/dist/schema/core/bool.js
var require_bool = __commonJS((exports) => {
  var Scalar = require_Scalar();
  var boolTag = {
    identify: (value) => typeof value === "boolean",
    default: true,
    tag: "tag:yaml.org,2002:bool",
    test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,
    resolve: (str) => new Scalar.Scalar(str[0] === "t" || str[0] === "T"),
    stringify({ source, value }, ctx) {
      if (source && boolTag.test.test(source)) {
        const sv = source[0] === "t" || source[0] === "T";
        if (value === sv)
          return source;
      }
      return value ? ctx.options.trueStr : ctx.options.falseStr;
    }
  };
  exports.boolTag = boolTag;
});

// node_modules/yaml/dist/stringify/stringifyNumber.js
var require_stringifyNumber = __commonJS((exports) => {
  function stringifyNumber({ format, minFractionDigits, tag, value }) {
    if (typeof value === "bigint")
      return String(value);
    const num = typeof value === "number" ? value : Number(value);
    if (!isFinite(num))
      return isNaN(num) ? ".nan" : num < 0 ? "-.inf" : ".inf";
    let n = Object.is(value, -0) ? "-0" : JSON.stringify(value);
    if (!format && minFractionDigits && (!tag || tag === "tag:yaml.org,2002:float") && /^-?\d/.test(n) && !n.includes("e")) {
      let i = n.indexOf(".");
      if (i < 0) {
        i = n.length;
        n += ".";
      }
      let d = minFractionDigits - (n.length - i - 1);
      while (d-- > 0)
        n += "0";
    }
    return n;
  }
  exports.stringifyNumber = stringifyNumber;
});

// node_modules/yaml/dist/schema/core/float.js
var require_float = __commonJS((exports) => {
  var Scalar = require_Scalar();
  var stringifyNumber = require_stringifyNumber();
  var floatNaN = {
    identify: (value) => typeof value === "number",
    default: true,
    tag: "tag:yaml.org,2002:float",
    test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,
    resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
    stringify: stringifyNumber.stringifyNumber
  };
  var floatExp = {
    identify: (value) => typeof value === "number",
    default: true,
    tag: "tag:yaml.org,2002:float",
    format: "EXP",
    test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,
    resolve: (str) => parseFloat(str),
    stringify(node) {
      const num = Number(node.value);
      return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node);
    }
  };
  var float = {
    identify: (value) => typeof value === "number",
    default: true,
    tag: "tag:yaml.org,2002:float",
    test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,
    resolve(str) {
      const node = new Scalar.Scalar(parseFloat(str));
      const dot = str.indexOf(".");
      if (dot !== -1 && str[str.length - 1] === "0")
        node.minFractionDigits = str.length - dot - 1;
      return node;
    },
    stringify: stringifyNumber.stringifyNumber
  };
  exports.float = float;
  exports.floatExp = floatExp;
  exports.floatNaN = floatNaN;
});

// node_modules/yaml/dist/schema/core/int.js
var require_int = __commonJS((exports) => {
  var stringifyNumber = require_stringifyNumber();
  var intIdentify = (value) => typeof value === "bigint" || Number.isInteger(value);
  var intResolve = (str, offset, radix, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str.substring(offset), radix);
  function intStringify(node, radix, prefix) {
    const { value } = node;
    if (intIdentify(value) && value >= 0)
      return prefix + value.toString(radix);
    return stringifyNumber.stringifyNumber(node);
  }
  var intOct = {
    identify: (value) => intIdentify(value) && value >= 0,
    default: true,
    tag: "tag:yaml.org,2002:int",
    format: "OCT",
    test: /^0o[0-7]+$/,
    resolve: (str, _onError, opt) => intResolve(str, 2, 8, opt),
    stringify: (node) => intStringify(node, 8, "0o")
  };
  var int = {
    identify: intIdentify,
    default: true,
    tag: "tag:yaml.org,2002:int",
    test: /^[-+]?[0-9]+$/,
    resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),
    stringify: stringifyNumber.stringifyNumber
  };
  var intHex = {
    identify: (value) => intIdentify(value) && value >= 0,
    default: true,
    tag: "tag:yaml.org,2002:int",
    format: "HEX",
    test: /^0x[0-9a-fA-F]+$/,
    resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),
    stringify: (node) => intStringify(node, 16, "0x")
  };
  exports.int = int;
  exports.intHex = intHex;
  exports.intOct = intOct;
});

// node_modules/yaml/dist/schema/core/schema.js
var require_schema = __commonJS((exports) => {
  var map = require_map();
  var _null = require_null();
  var seq = require_seq();
  var string = require_string();
  var bool = require_bool();
  var float = require_float();
  var int = require_int();
  var schema = [
    map.map,
    seq.seq,
    string.string,
    _null.nullTag,
    bool.boolTag,
    int.intOct,
    int.int,
    int.intHex,
    float.floatNaN,
    float.floatExp,
    float.float
  ];
  exports.schema = schema;
});

// node_modules/yaml/dist/schema/json/schema.js
var require_schema2 = __commonJS((exports) => {
  var Scalar = require_Scalar();
  var map = require_map();
  var seq = require_seq();
  function intIdentify(value) {
    return typeof value === "bigint" || Number.isInteger(value);
  }
  var stringifyJSON = ({ value }) => JSON.stringify(value);
  var jsonScalars = [
    {
      identify: (value) => typeof value === "string",
      default: true,
      tag: "tag:yaml.org,2002:str",
      resolve: (str) => str,
      stringify: stringifyJSON
    },
    {
      identify: (value) => value == null,
      createNode: () => new Scalar.Scalar(null),
      default: true,
      tag: "tag:yaml.org,2002:null",
      test: /^null$/,
      resolve: () => null,
      stringify: stringifyJSON
    },
    {
      identify: (value) => typeof value === "boolean",
      default: true,
      tag: "tag:yaml.org,2002:bool",
      test: /^true$|^false$/,
      resolve: (str) => str === "true",
      stringify: stringifyJSON
    },
    {
      identify: intIdentify,
      default: true,
      tag: "tag:yaml.org,2002:int",
      test: /^-?(?:0|[1-9][0-9]*)$/,
      resolve: (str, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str, 10),
      stringify: ({ value }) => intIdentify(value) ? value.toString() : JSON.stringify(value)
    },
    {
      identify: (value) => typeof value === "number",
      default: true,
      tag: "tag:yaml.org,2002:float",
      test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,
      resolve: (str) => parseFloat(str),
      stringify: stringifyJSON
    }
  ];
  var jsonError = {
    default: true,
    tag: "",
    test: /^/,
    resolve(str, onError) {
      onError(`Unresolved plain scalar ${JSON.stringify(str)}`);
      return str;
    }
  };
  var schema = [map.map, seq.seq].concat(jsonScalars, jsonError);
  exports.schema = schema;
});

// node_modules/yaml/dist/schema/yaml-1.1/binary.js
var require_binary = __commonJS((exports) => {
  var node_buffer = __require("buffer");
  var Scalar = require_Scalar();
  var stringifyString = require_stringifyString();
  var binary = {
    identify: (value) => value instanceof Uint8Array,
    default: false,
    tag: "tag:yaml.org,2002:binary",
    resolve(src, onError) {
      if (typeof node_buffer.Buffer === "function") {
        return node_buffer.Buffer.from(src, "base64");
      } else if (typeof atob === "function") {
        const str = atob(src.replace(/[\n\r]/g, ""));
        const buffer = new Uint8Array(str.length);
        for (let i = 0;i < str.length; ++i)
          buffer[i] = str.charCodeAt(i);
        return buffer;
      } else {
        onError("This environment does not support reading binary tags; either Buffer or atob is required");
        return src;
      }
    },
    stringify({ comment, type, value }, ctx, onComment, onChompKeep) {
      if (!value)
        return "";
      const buf = value;
      let str;
      if (typeof node_buffer.Buffer === "function") {
        str = buf instanceof node_buffer.Buffer ? buf.toString("base64") : node_buffer.Buffer.from(buf.buffer).toString("base64");
      } else if (typeof btoa === "function") {
        let s = "";
        for (let i = 0;i < buf.length; ++i)
          s += String.fromCharCode(buf[i]);
        str = btoa(s);
      } else {
        throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");
      }
      type ?? (type = Scalar.Scalar.BLOCK_LITERAL);
      if (type !== Scalar.Scalar.QUOTE_DOUBLE) {
        const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth);
        const n = Math.ceil(str.length / lineWidth);
        const lines = new Array(n);
        for (let i = 0, o = 0;i < n; ++i, o += lineWidth) {
          lines[i] = str.substr(o, lineWidth);
        }
        str = lines.join(type === Scalar.Scalar.BLOCK_LITERAL ? `
` : " ");
      }
      return stringifyString.stringifyString({ comment, type, value: str }, ctx, onComment, onChompKeep);
    }
  };
  exports.binary = binary;
});

// node_modules/yaml/dist/schema/yaml-1.1/pairs.js
var require_pairs = __commonJS((exports) => {
  var identity = require_identity();
  var Pair = require_Pair();
  var Scalar = require_Scalar();
  var YAMLSeq = require_YAMLSeq();
  function resolvePairs(seq, onError) {
    if (identity.isSeq(seq)) {
      for (let i = 0;i < seq.items.length; ++i) {
        let item = seq.items[i];
        if (identity.isPair(item))
          continue;
        else if (identity.isMap(item)) {
          if (item.items.length > 1)
            onError("Each pair must have its own sequence indicator");
          const pair = item.items[0] || new Pair.Pair(new Scalar.Scalar(null));
          if (item.commentBefore)
            pair.key.commentBefore = pair.key.commentBefore ? `${item.commentBefore}
${pair.key.commentBefore}` : item.commentBefore;
          if (item.comment) {
            const cn = pair.value ?? pair.key;
            cn.comment = cn.comment ? `${item.comment}
${cn.comment}` : item.comment;
          }
          item = pair;
        }
        seq.items[i] = identity.isPair(item) ? item : new Pair.Pair(item);
      }
    } else
      onError("Expected a sequence for this tag");
    return seq;
  }
  function createPairs(schema, iterable, ctx) {
    const { replacer } = ctx;
    const pairs2 = new YAMLSeq.YAMLSeq(schema);
    pairs2.tag = "tag:yaml.org,2002:pairs";
    let i = 0;
    if (iterable && Symbol.iterator in Object(iterable))
      for (let it of iterable) {
        if (typeof replacer === "function")
          it = replacer.call(iterable, String(i++), it);
        let key, value;
        if (Array.isArray(it)) {
          if (it.length === 2) {
            key = it[0];
            value = it[1];
          } else
            throw new TypeError(`Expected [key, value] tuple: ${it}`);
        } else if (it && it instanceof Object) {
          const keys = Object.keys(it);
          if (keys.length === 1) {
            key = keys[0];
            value = it[key];
          } else {
            throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`);
          }
        } else {
          key = it;
        }
        pairs2.items.push(Pair.createPair(key, value, ctx));
      }
    return pairs2;
  }
  var pairs = {
    collection: "seq",
    default: false,
    tag: "tag:yaml.org,2002:pairs",
    resolve: resolvePairs,
    createNode: createPairs
  };
  exports.createPairs = createPairs;
  exports.pairs = pairs;
  exports.resolvePairs = resolvePairs;
});

// node_modules/yaml/dist/schema/yaml-1.1/omap.js
var require_omap = __commonJS((exports) => {
  var identity = require_identity();
  var toJS = require_toJS();
  var YAMLMap = require_YAMLMap();
  var YAMLSeq = require_YAMLSeq();
  var pairs = require_pairs();

  class YAMLOMap extends YAMLSeq.YAMLSeq {
    constructor() {
      super();
      this.add = YAMLMap.YAMLMap.prototype.add.bind(this);
      this.delete = YAMLMap.YAMLMap.prototype.delete.bind(this);
      this.get = YAMLMap.YAMLMap.prototype.get.bind(this);
      this.has = YAMLMap.YAMLMap.prototype.has.bind(this);
      this.set = YAMLMap.YAMLMap.prototype.set.bind(this);
      this.tag = YAMLOMap.tag;
    }
    toJSON(_, ctx) {
      if (!ctx)
        return super.toJSON(_);
      const map = new Map;
      if (ctx?.onCreate)
        ctx.onCreate(map);
      for (const pair of this.items) {
        let key, value;
        if (identity.isPair(pair)) {
          key = toJS.toJS(pair.key, "", ctx);
          value = toJS.toJS(pair.value, key, ctx);
        } else {
          key = toJS.toJS(pair, "", ctx);
        }
        if (map.has(key))
          throw new Error("Ordered maps must not include duplicate keys");
        map.set(key, value);
      }
      return map;
    }
    static from(schema, iterable, ctx) {
      const pairs$1 = pairs.createPairs(schema, iterable, ctx);
      const omap2 = new this;
      omap2.items = pairs$1.items;
      return omap2;
    }
  }
  YAMLOMap.tag = "tag:yaml.org,2002:omap";
  var omap = {
    collection: "seq",
    identify: (value) => value instanceof Map,
    nodeClass: YAMLOMap,
    default: false,
    tag: "tag:yaml.org,2002:omap",
    resolve(seq, onError) {
      const pairs$1 = pairs.resolvePairs(seq, onError);
      const seenKeys = [];
      for (const { key } of pairs$1.items) {
        if (identity.isScalar(key)) {
          if (seenKeys.includes(key.value)) {
            onError(`Ordered maps must not include duplicate keys: ${key.value}`);
          } else {
            seenKeys.push(key.value);
          }
        }
      }
      return Object.assign(new YAMLOMap, pairs$1);
    },
    createNode: (schema, iterable, ctx) => YAMLOMap.from(schema, iterable, ctx)
  };
  exports.YAMLOMap = YAMLOMap;
  exports.omap = omap;
});

// node_modules/yaml/dist/schema/yaml-1.1/bool.js
var require_bool2 = __commonJS((exports) => {
  var Scalar = require_Scalar();
  function boolStringify({ value, source }, ctx) {
    const boolObj = value ? trueTag : falseTag;
    if (source && boolObj.test.test(source))
      return source;
    return value ? ctx.options.trueStr : ctx.options.falseStr;
  }
  var trueTag = {
    identify: (value) => value === true,
    default: true,
    tag: "tag:yaml.org,2002:bool",
    test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,
    resolve: () => new Scalar.Scalar(true),
    stringify: boolStringify
  };
  var falseTag = {
    identify: (value) => value === false,
    default: true,
    tag: "tag:yaml.org,2002:bool",
    test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,
    resolve: () => new Scalar.Scalar(false),
    stringify: boolStringify
  };
  exports.falseTag = falseTag;
  exports.trueTag = trueTag;
});

// node_modules/yaml/dist/schema/yaml-1.1/float.js
var require_float2 = __commonJS((exports) => {
  var Scalar = require_Scalar();
  var stringifyNumber = require_stringifyNumber();
  var floatNaN = {
    identify: (value) => typeof value === "number",
    default: true,
    tag: "tag:yaml.org,2002:float",
    test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,
    resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
    stringify: stringifyNumber.stringifyNumber
  };
  var floatExp = {
    identify: (value) => typeof value === "number",
    default: true,
    tag: "tag:yaml.org,2002:float",
    format: "EXP",
    test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,
    resolve: (str) => parseFloat(str.replace(/_/g, "")),
    stringify(node) {
      const num = Number(node.value);
      return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node);
    }
  };
  var float = {
    identify: (value) => typeof value === "number",
    default: true,
    tag: "tag:yaml.org,2002:float",
    test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,
    resolve(str) {
      const node = new Scalar.Scalar(parseFloat(str.replace(/_/g, "")));
      const dot = str.indexOf(".");
      if (dot !== -1) {
        const f = str.substring(dot + 1).replace(/_/g, "");
        if (f[f.length - 1] === "0")
          node.minFractionDigits = f.length;
      }
      return node;
    },
    stringify: stringifyNumber.stringifyNumber
  };
  exports.float = float;
  exports.floatExp = floatExp;
  exports.floatNaN = floatNaN;
});

// node_modules/yaml/dist/schema/yaml-1.1/int.js
var require_int2 = __commonJS((exports) => {
  var stringifyNumber = require_stringifyNumber();
  var intIdentify = (value) => typeof value === "bigint" || Number.isInteger(value);
  function intResolve(str, offset, radix, { intAsBigInt }) {
    const sign = str[0];
    if (sign === "-" || sign === "+")
      offset += 1;
    str = str.substring(offset).replace(/_/g, "");
    if (intAsBigInt) {
      switch (radix) {
        case 2:
          str = `0b${str}`;
          break;
        case 8:
          str = `0o${str}`;
          break;
        case 16:
          str = `0x${str}`;
          break;
      }
      const n2 = BigInt(str);
      return sign === "-" ? BigInt(-1) * n2 : n2;
    }
    const n = parseInt(str, radix);
    return sign === "-" ? -1 * n : n;
  }
  function intStringify(node, radix, prefix) {
    const { value } = node;
    if (intIdentify(value)) {
      const str = value.toString(radix);
      return value < 0 ? "-" + prefix + str.substr(1) : prefix + str;
    }
    return stringifyNumber.stringifyNumber(node);
  }
  var intBin = {
    identify: intIdentify,
    default: true,
    tag: "tag:yaml.org,2002:int",
    format: "BIN",
    test: /^[-+]?0b[0-1_]+$/,
    resolve: (str, _onError, opt) => intResolve(str, 2, 2, opt),
    stringify: (node) => intStringify(node, 2, "0b")
  };
  var intOct = {
    identify: intIdentify,
    default: true,
    tag: "tag:yaml.org,2002:int",
    format: "OCT",
    test: /^[-+]?0[0-7_]+$/,
    resolve: (str, _onError, opt) => intResolve(str, 1, 8, opt),
    stringify: (node) => intStringify(node, 8, "0")
  };
  var int = {
    identify: intIdentify,
    default: true,
    tag: "tag:yaml.org,2002:int",
    test: /^[-+]?[0-9][0-9_]*$/,
    resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),
    stringify: stringifyNumber.stringifyNumber
  };
  var intHex = {
    identify: intIdentify,
    default: true,
    tag: "tag:yaml.org,2002:int",
    format: "HEX",
    test: /^[-+]?0x[0-9a-fA-F_]+$/,
    resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),
    stringify: (node) => intStringify(node, 16, "0x")
  };
  exports.int = int;
  exports.intBin = intBin;
  exports.intHex = intHex;
  exports.intOct = intOct;
});

// node_modules/yaml/dist/schema/yaml-1.1/set.js
var require_set = __commonJS((exports) => {
  var identity = require_identity();
  var Pair = require_Pair();
  var YAMLMap = require_YAMLMap();

  class YAMLSet extends YAMLMap.YAMLMap {
    constructor(schema) {
      super(schema);
      this.tag = YAMLSet.tag;
    }
    add(key) {
      let pair;
      if (identity.isPair(key))
        pair = key;
      else if (key && typeof key === "object" && "key" in key && "value" in key && key.value === null)
        pair = new Pair.Pair(key.key, null);
      else
        pair = new Pair.Pair(key, null);
      const prev = YAMLMap.findPair(this.items, pair.key);
      if (!prev)
        this.items.push(pair);
    }
    get(key, keepPair) {
      const pair = YAMLMap.findPair(this.items, key);
      return !keepPair && identity.isPair(pair) ? identity.isScalar(pair.key) ? pair.key.value : pair.key : pair;
    }
    set(key, value) {
      if (typeof value !== "boolean")
        throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`);
      const prev = YAMLMap.findPair(this.items, key);
      if (prev && !value) {
        this.items.splice(this.items.indexOf(prev), 1);
      } else if (!prev && value) {
        this.items.push(new Pair.Pair(key));
      }
    }
    toJSON(_, ctx) {
      return super.toJSON(_, ctx, Set);
    }
    toString(ctx, onComment, onChompKeep) {
      if (!ctx)
        return JSON.stringify(this);
      if (this.hasAllNullValues(true))
        return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep);
      else
        throw new Error("Set items must all have null values");
    }
    static from(schema, iterable, ctx) {
      const { replacer } = ctx;
      const set2 = new this(schema);
      if (iterable && Symbol.iterator in Object(iterable))
        for (let value of iterable) {
          if (typeof replacer === "function")
            value = replacer.call(iterable, value, value);
          set2.items.push(Pair.createPair(value, null, ctx));
        }
      return set2;
    }
  }
  YAMLSet.tag = "tag:yaml.org,2002:set";
  var set = {
    collection: "map",
    identify: (value) => value instanceof Set,
    nodeClass: YAMLSet,
    default: false,
    tag: "tag:yaml.org,2002:set",
    createNode: (schema, iterable, ctx) => YAMLSet.from(schema, iterable, ctx),
    resolve(map, onError) {
      if (identity.isMap(map)) {
        if (map.hasAllNullValues(true))
          return Object.assign(new YAMLSet, map);
        else
          onError("Set items must all have null values");
      } else
        onError("Expected a mapping for this tag");
      return map;
    }
  };
  exports.YAMLSet = YAMLSet;
  exports.set = set;
});

// node_modules/yaml/dist/schema/yaml-1.1/timestamp.js
var require_timestamp = __commonJS((exports) => {
  var stringifyNumber = require_stringifyNumber();
  function parseSexagesimal(str, asBigInt) {
    const sign = str[0];
    const parts = sign === "-" || sign === "+" ? str.substring(1) : str;
    const num = (n) => asBigInt ? BigInt(n) : Number(n);
    const res = parts.replace(/_/g, "").split(":").reduce((res2, p) => res2 * num(60) + num(p), num(0));
    return sign === "-" ? num(-1) * res : res;
  }
  function stringifySexagesimal(node) {
    let { value } = node;
    let num = (n) => n;
    if (typeof value === "bigint")
      num = (n) => BigInt(n);
    else if (isNaN(value) || !isFinite(value))
      return stringifyNumber.stringifyNumber(node);
    let sign = "";
    if (value < 0) {
      sign = "-";
      value *= num(-1);
    }
    const _60 = num(60);
    const parts = [value % _60];
    if (value < 60) {
      parts.unshift(0);
    } else {
      value = (value - parts[0]) / _60;
      parts.unshift(value % _60);
      if (value >= 60) {
        value = (value - parts[0]) / _60;
        parts.unshift(value);
      }
    }
    return sign + parts.map((n) => String(n).padStart(2, "0")).join(":").replace(/000000\d*$/, "");
  }
  var intTime = {
    identify: (value) => typeof value === "bigint" || Number.isInteger(value),
    default: true,
    tag: "tag:yaml.org,2002:int",
    format: "TIME",
    test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,
    resolve: (str, _onError, { intAsBigInt }) => parseSexagesimal(str, intAsBigInt),
    stringify: stringifySexagesimal
  };
  var floatTime = {
    identify: (value) => typeof value === "number",
    default: true,
    tag: "tag:yaml.org,2002:float",
    format: "TIME",
    test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,
    resolve: (str) => parseSexagesimal(str, false),
    stringify: stringifySexagesimal
  };
  var timestamp = {
    identify: (value) => value instanceof Date,
    default: true,
    tag: "tag:yaml.org,2002:timestamp",
    test: RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})" + "(?:" + "(?:t|T|[ \\t]+)" + "([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)" + "(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?" + ")?$"),
    resolve(str) {
      const match = str.match(timestamp.test);
      if (!match)
        throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");
      const [, year, month, day, hour, minute, second] = match.map(Number);
      const millisec = match[7] ? Number((match[7] + "00").substr(1, 3)) : 0;
      let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec);
      const tz = match[8];
      if (tz && tz !== "Z") {
        let d = parseSexagesimal(tz, false);
        if (Math.abs(d) < 30)
          d *= 60;
        date -= 60000 * d;
      }
      return new Date(date);
    },
    stringify: ({ value }) => value?.toISOString().replace(/(T00:00:00)?\.000Z$/, "") ?? ""
  };
  exports.floatTime = floatTime;
  exports.intTime = intTime;
  exports.timestamp = timestamp;
});

// node_modules/yaml/dist/schema/yaml-1.1/schema.js
var require_schema3 = __commonJS((exports) => {
  var map = require_map();
  var _null = require_null();
  var seq = require_seq();
  var string = require_string();
  var binary = require_binary();
  var bool = require_bool2();
  var float = require_float2();
  var int = require_int2();
  var merge = require_merge();
  var omap = require_omap();
  var pairs = require_pairs();
  var set = require_set();
  var timestamp = require_timestamp();
  var schema = [
    map.map,
    seq.seq,
    string.string,
    _null.nullTag,
    bool.trueTag,
    bool.falseTag,
    int.intBin,
    int.intOct,
    int.int,
    int.intHex,
    float.floatNaN,
    float.floatExp,
    float.float,
    binary.binary,
    merge.merge,
    omap.omap,
    pairs.pairs,
    set.set,
    timestamp.intTime,
    timestamp.floatTime,
    timestamp.timestamp
  ];
  exports.schema = schema;
});

// node_modules/yaml/dist/schema/tags.js
var require_tags = __commonJS((exports) => {
  var map = require_map();
  var _null = require_null();
  var seq = require_seq();
  var string = require_string();
  var bool = require_bool();
  var float = require_float();
  var int = require_int();
  var schema = require_schema();
  var schema$1 = require_schema2();
  var binary = require_binary();
  var merge = require_merge();
  var omap = require_omap();
  var pairs = require_pairs();
  var schema$2 = require_schema3();
  var set = require_set();
  var timestamp = require_timestamp();
  var schemas = new Map([
    ["core", schema.schema],
    ["failsafe", [map.map, seq.seq, string.string]],
    ["json", schema$1.schema],
    ["yaml11", schema$2.schema],
    ["yaml-1.1", schema$2.schema]
  ]);
  var tagsByName = {
    binary: binary.binary,
    bool: bool.boolTag,
    float: float.float,
    floatExp: float.floatExp,
    floatNaN: float.floatNaN,
    floatTime: timestamp.floatTime,
    int: int.int,
    intHex: int.intHex,
    intOct: int.intOct,
    intTime: timestamp.intTime,
    map: map.map,
    merge: merge.merge,
    null: _null.nullTag,
    omap: omap.omap,
    pairs: pairs.pairs,
    seq: seq.seq,
    set: set.set,
    timestamp: timestamp.timestamp
  };
  var coreKnownTags = {
    "tag:yaml.org,2002:binary": binary.binary,
    "tag:yaml.org,2002:merge": merge.merge,
    "tag:yaml.org,2002:omap": omap.omap,
    "tag:yaml.org,2002:pairs": pairs.pairs,
    "tag:yaml.org,2002:set": set.set,
    "tag:yaml.org,2002:timestamp": timestamp.timestamp
  };
  function getTags(customTags, schemaName, addMergeTag) {
    const schemaTags = schemas.get(schemaName);
    if (schemaTags && !customTags) {
      return addMergeTag && !schemaTags.includes(merge.merge) ? schemaTags.concat(merge.merge) : schemaTags.slice();
    }
    let tags = schemaTags;
    if (!tags) {
      if (Array.isArray(customTags))
        tags = [];
      else {
        const keys = Array.from(schemas.keys()).filter((key) => key !== "yaml11").map((key) => JSON.stringify(key)).join(", ");
        throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`);
      }
    }
    if (Array.isArray(customTags)) {
      for (const tag of customTags)
        tags = tags.concat(tag);
    } else if (typeof customTags === "function") {
      tags = customTags(tags.slice());
    }
    if (addMergeTag)
      tags = tags.concat(merge.merge);
    return tags.reduce((tags2, tag) => {
      const tagObj = typeof tag === "string" ? tagsByName[tag] : tag;
      if (!tagObj) {
        const tagName = JSON.stringify(tag);
        const keys = Object.keys(tagsByName).map((key) => JSON.stringify(key)).join(", ");
        throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`);
      }
      if (!tags2.includes(tagObj))
        tags2.push(tagObj);
      return tags2;
    }, []);
  }
  exports.coreKnownTags = coreKnownTags;
  exports.getTags = getTags;
});

// node_modules/yaml/dist/schema/Schema.js
var require_Schema = __commonJS((exports) => {
  var identity = require_identity();
  var map = require_map();
  var seq = require_seq();
  var string = require_string();
  var tags = require_tags();
  var sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0;

  class Schema {
    constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults }) {
      this.compat = Array.isArray(compat) ? tags.getTags(compat, "compat") : compat ? tags.getTags(null, compat) : null;
      this.name = typeof schema === "string" && schema || "core";
      this.knownTags = resolveKnownTags ? tags.coreKnownTags : {};
      this.tags = tags.getTags(customTags, this.name, merge);
      this.toStringOptions = toStringDefaults ?? null;
      Object.defineProperty(this, identity.MAP, { value: map.map });
      Object.defineProperty(this, identity.SCALAR, { value: string.string });
      Object.defineProperty(this, identity.SEQ, { value: seq.seq });
      this.sortMapEntries = typeof sortMapEntries === "function" ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null;
    }
    clone() {
      const copy = Object.create(Schema.prototype, Object.getOwnPropertyDescriptors(this));
      copy.tags = this.tags.slice();
      return copy;
    }
  }
  exports.Schema = Schema;
});

// node_modules/yaml/dist/stringify/stringifyDocument.js
var require_stringifyDocument = __commonJS((exports) => {
  var identity = require_identity();
  var stringify = require_stringify();
  var stringifyComment = require_stringifyComment();
  function stringifyDocument(doc, options) {
    const lines = [];
    let hasDirectives = options.directives === true;
    if (options.directives !== false && doc.directives) {
      const dir = doc.directives.toString(doc);
      if (dir) {
        lines.push(dir);
        hasDirectives = true;
      } else if (doc.directives.docStart)
        hasDirectives = true;
    }
    if (hasDirectives)
      lines.push("---");
    const ctx = stringify.createStringifyContext(doc, options);
    const { commentString } = ctx.options;
    if (doc.commentBefore) {
      if (lines.length !== 1)
        lines.unshift("");
      const cs = commentString(doc.commentBefore);
      lines.unshift(stringifyComment.indentComment(cs, ""));
    }
    let chompKeep = false;
    let contentComment = null;
    if (doc.contents) {
      if (identity.isNode(doc.contents)) {
        if (doc.contents.spaceBefore && hasDirectives)
          lines.push("");
        if (doc.contents.commentBefore) {
          const cs = commentString(doc.contents.commentBefore);
          lines.push(stringifyComment.indentComment(cs, ""));
        }
        ctx.forceBlockIndent = !!doc.comment;
        contentComment = doc.contents.comment;
      }
      const onChompKeep = contentComment ? undefined : () => chompKeep = true;
      let body = stringify.stringify(doc.contents, ctx, () => contentComment = null, onChompKeep);
      if (contentComment)
        body += stringifyComment.lineComment(body, "", commentString(contentComment));
      if ((body[0] === "|" || body[0] === ">") && lines[lines.length - 1] === "---") {
        lines[lines.length - 1] = `--- ${body}`;
      } else
        lines.push(body);
    } else {
      lines.push(stringify.stringify(doc.contents, ctx));
    }
    if (doc.directives?.docEnd) {
      if (doc.comment) {
        const cs = commentString(doc.comment);
        if (cs.includes(`
`)) {
          lines.push("...");
          lines.push(stringifyComment.indentComment(cs, ""));
        } else {
          lines.push(`... ${cs}`);
        }
      } else {
        lines.push("...");
      }
    } else {
      let dc = doc.comment;
      if (dc && chompKeep)
        dc = dc.replace(/^\n+/, "");
      if (dc) {
        if ((!chompKeep || contentComment) && lines[lines.length - 1] !== "")
          lines.push("");
        lines.push(stringifyComment.indentComment(commentString(dc), ""));
      }
    }
    return lines.join(`
`) + `
`;
  }
  exports.stringifyDocument = stringifyDocument;
});

// node_modules/yaml/dist/doc/Document.js
var require_Document = __commonJS((exports) => {
  var Alias = require_Alias();
  var Collection = require_Collection();
  var identity = require_identity();
  var Pair = require_Pair();
  var toJS = require_toJS();
  var Schema = require_Schema();
  var stringifyDocument = require_stringifyDocument();
  var anchors = require_anchors();
  var applyReviver = require_applyReviver();
  var createNode = require_createNode();
  var directives = require_directives();

  class Document {
    constructor(value, replacer, options) {
      this.commentBefore = null;
      this.comment = null;
      this.errors = [];
      this.warnings = [];
      Object.defineProperty(this, identity.NODE_TYPE, { value: identity.DOC });
      let _replacer = null;
      if (typeof replacer === "function" || Array.isArray(replacer)) {
        _replacer = replacer;
      } else if (options === undefined && replacer) {
        options = replacer;
        replacer = undefined;
      }
      const opt = Object.assign({
        intAsBigInt: false,
        keepSourceTokens: false,
        logLevel: "warn",
        prettyErrors: true,
        strict: true,
        stringKeys: false,
        uniqueKeys: true,
        version: "1.2"
      }, options);
      this.options = opt;
      let { version } = opt;
      if (options?._directives) {
        this.directives = options._directives.atDocument();
        if (this.directives.yaml.explicit)
          version = this.directives.yaml.version;
      } else
        this.directives = new directives.Directives({ version });
      this.setSchema(version, options);
      this.contents = value === undefined ? null : this.createNode(value, _replacer, options);
    }
    clone() {
      const copy = Object.create(Document.prototype, {
        [identity.NODE_TYPE]: { value: identity.DOC }
      });
      copy.commentBefore = this.commentBefore;
      copy.comment = this.comment;
      copy.errors = this.errors.slice();
      copy.warnings = this.warnings.slice();
      copy.options = Object.assign({}, this.options);
      if (this.directives)
        copy.directives = this.directives.clone();
      copy.schema = this.schema.clone();
      copy.contents = identity.isNode(this.contents) ? this.contents.clone(copy.schema) : this.contents;
      if (this.range)
        copy.range = this.range.slice();
      return copy;
    }
    add(value) {
      if (assertCollection(this.contents))
        this.contents.add(value);
    }
    addIn(path, value) {
      if (assertCollection(this.contents))
        this.contents.addIn(path, value);
    }
    createAlias(node, name) {
      if (!node.anchor) {
        const prev = anchors.anchorNames(this);
        node.anchor = !name || prev.has(name) ? anchors.findNewAnchor(name || "a", prev) : name;
      }
      return new Alias.Alias(node.anchor);
    }
    createNode(value, replacer, options) {
      let _replacer = undefined;
      if (typeof replacer === "function") {
        value = replacer.call({ "": value }, "", value);
        _replacer = replacer;
      } else if (Array.isArray(replacer)) {
        const keyToStr = (v) => typeof v === "number" || v instanceof String || v instanceof Number;
        const asStr = replacer.filter(keyToStr).map(String);
        if (asStr.length > 0)
          replacer = replacer.concat(asStr);
        _replacer = replacer;
      } else if (options === undefined && replacer) {
        options = replacer;
        replacer = undefined;
      }
      const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {};
      const { onAnchor, setAnchors, sourceObjects } = anchors.createNodeAnchors(this, anchorPrefix || "a");
      const ctx = {
        aliasDuplicateObjects: aliasDuplicateObjects ?? true,
        keepUndefined: keepUndefined ?? false,
        onAnchor,
        onTagObj,
        replacer: _replacer,
        schema: this.schema,
        sourceObjects
      };
      const node = createNode.createNode(value, tag, ctx);
      if (flow && identity.isCollection(node))
        node.flow = true;
      setAnchors();
      return node;
    }
    createPair(key, value, options = {}) {
      const k = this.createNode(key, null, options);
      const v = this.createNode(value, null, options);
      return new Pair.Pair(k, v);
    }
    delete(key) {
      return assertCollection(this.contents) ? this.contents.delete(key) : false;
    }
    deleteIn(path) {
      if (Collection.isEmptyPath(path)) {
        if (this.contents == null)
          return false;
        this.contents = null;
        return true;
      }
      return assertCollection(this.contents) ? this.contents.deleteIn(path) : false;
    }
    get(key, keepScalar) {
      return identity.isCollection(this.contents) ? this.contents.get(key, keepScalar) : undefined;
    }
    getIn(path, keepScalar) {
      if (Collection.isEmptyPath(path))
        return !keepScalar && identity.isScalar(this.contents) ? this.contents.value : this.contents;
      return identity.isCollection(this.contents) ? this.contents.getIn(path, keepScalar) : undefined;
    }
    has(key) {
      return identity.isCollection(this.contents) ? this.contents.has(key) : false;
    }
    hasIn(path) {
      if (Collection.isEmptyPath(path))
        return this.contents !== undefined;
      return identity.isCollection(this.contents) ? this.contents.hasIn(path) : false;
    }
    set(key, value) {
      if (this.contents == null) {
        this.contents = Collection.collectionFromPath(this.schema, [key], value);
      } else if (assertCollection(this.contents)) {
        this.contents.set(key, value);
      }
    }
    setIn(path, value) {
      if (Collection.isEmptyPath(path)) {
        this.contents = value;
      } else if (this.contents == null) {
        this.contents = Collection.collectionFromPath(this.schema, Array.from(path), value);
      } else if (assertCollection(this.contents)) {
        this.contents.setIn(path, value);
      }
    }
    setSchema(version, options = {}) {
      if (typeof version === "number")
        version = String(version);
      let opt;
      switch (version) {
        case "1.1":
          if (this.directives)
            this.directives.yaml.version = "1.1";
          else
            this.directives = new directives.Directives({ version: "1.1" });
          opt = { resolveKnownTags: false, schema: "yaml-1.1" };
          break;
        case "1.2":
        case "next":
          if (this.directives)
            this.directives.yaml.version = version;
          else
            this.directives = new directives.Directives({ version });
          opt = { resolveKnownTags: true, schema: "core" };
          break;
        case null:
          if (this.directives)
            delete this.directives;
          opt = null;
          break;
        default: {
          const sv = JSON.stringify(version);
          throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`);
        }
      }
      if (options.schema instanceof Object)
        this.schema = options.schema;
      else if (opt)
        this.schema = new Schema.Schema(Object.assign(opt, options));
      else
        throw new Error(`With a null YAML version, the { schema: Schema } option is required`);
    }
    toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
      const ctx = {
        anchors: new Map,
        doc: this,
        keep: !json,
        mapAsMap: mapAsMap === true,
        mapKeyWarned: false,
        maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100
      };
      const res = toJS.toJS(this.contents, jsonArg ?? "", ctx);
      if (typeof onAnchor === "function")
        for (const { count, res: res2 } of ctx.anchors.values())
          onAnchor(res2, count);
      return typeof reviver === "function" ? applyReviver.applyReviver(reviver, { "": res }, "", res) : res;
    }
    toJSON(jsonArg, onAnchor) {
      return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor });
    }
    toString(options = {}) {
      if (this.errors.length > 0)
        throw new Error("Document with errors cannot be stringified");
      if ("indent" in options && (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) {
        const s = JSON.stringify(options.indent);
        throw new Error(`"indent" option must be a positive integer, not ${s}`);
      }
      return stringifyDocument.stringifyDocument(this, options);
    }
  }
  function assertCollection(contents) {
    if (identity.isCollection(contents))
      return true;
    throw new Error("Expected a YAML collection as document contents");
  }
  exports.Document = Document;
});

// node_modules/yaml/dist/errors.js
var require_errors = __commonJS((exports) => {
  class YAMLError extends Error {
    constructor(name, pos, code, message) {
      super();
      this.name = name;
      this.code = code;
      this.message = message;
      this.pos = pos;
    }
  }

  class YAMLParseError extends YAMLError {
    constructor(pos, code, message) {
      super("YAMLParseError", pos, code, message);
    }
  }

  class YAMLWarning extends YAMLError {
    constructor(pos, code, message) {
      super("YAMLWarning", pos, code, message);
    }
  }
  var prettifyError = (src, lc) => (error) => {
    if (error.pos[0] === -1)
      return;
    error.linePos = error.pos.map((pos) => lc.linePos(pos));
    const { line, col } = error.linePos[0];
    error.message += ` at line ${line}, column ${col}`;
    let ci = col - 1;
    let lineStr = src.substring(lc.lineStarts[line - 1], lc.lineStarts[line]).replace(/[\n\r]+$/, "");
    if (ci >= 60 && lineStr.length > 80) {
      const trimStart = Math.min(ci - 39, lineStr.length - 79);
      lineStr = "…" + lineStr.substring(trimStart);
      ci -= trimStart - 1;
    }
    if (lineStr.length > 80)
      lineStr = lineStr.substring(0, 79) + "…";
    if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) {
      let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]);
      if (prev.length > 80)
        prev = prev.substring(0, 79) + `…
`;
      lineStr = prev + lineStr;
    }
    if (/[^ ]/.test(lineStr)) {
      let count = 1;
      const end = error.linePos[1];
      if (end?.line === line && end.col > col) {
        count = Math.max(1, Math.min(end.col - col, 80 - ci));
      }
      const pointer = " ".repeat(ci) + "^".repeat(count);
      error.message += `:

${lineStr}
${pointer}
`;
    }
  };
  exports.YAMLError = YAMLError;
  exports.YAMLParseError = YAMLParseError;
  exports.YAMLWarning = YAMLWarning;
  exports.prettifyError = prettifyError;
});

// node_modules/yaml/dist/compose/resolve-props.js
var require_resolve_props = __commonJS((exports) => {
  function resolveProps(tokens, { flow, indicator, next, offset, onError, parentIndent, startOnNewline }) {
    let spaceBefore = false;
    let atNewline = startOnNewline;
    let hasSpace = startOnNewline;
    let comment = "";
    let commentSep = "";
    let hasNewline = false;
    let reqSpace = false;
    let tab = null;
    let anchor = null;
    let tag = null;
    let newlineAfterProp = null;
    let comma = null;
    let found = null;
    let start = null;
    for (const token of tokens) {
      if (reqSpace) {
        if (token.type !== "space" && token.type !== "newline" && token.type !== "comma")
          onError(token.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space");
        reqSpace = false;
      }
      if (tab) {
        if (atNewline && token.type !== "comment" && token.type !== "newline") {
          onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation");
        }
        tab = null;
      }
      switch (token.type) {
        case "space":
          if (!flow && (indicator !== "doc-start" || next?.type !== "flow-collection") && token.source.includes("\t")) {
            tab = token;
          }
          hasSpace = true;
          break;
        case "comment": {
          if (!hasSpace)
            onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters");
          const cb = token.source.substring(1) || " ";
          if (!comment)
            comment = cb;
          else
            comment += commentSep + cb;
          commentSep = "";
          atNewline = false;
          break;
        }
        case "newline":
          if (atNewline) {
            if (comment)
              comment += token.source;
            else if (!found || indicator !== "seq-item-ind")
              spaceBefore = true;
          } else
            commentSep += token.source;
          atNewline = true;
          hasNewline = true;
          if (anchor || tag)
            newlineAfterProp = token;
          hasSpace = true;
          break;
        case "anchor":
          if (anchor)
            onError(token, "MULTIPLE_ANCHORS", "A node can have at most one anchor");
          if (token.source.endsWith(":"))
            onError(token.offset + token.source.length - 1, "BAD_ALIAS", "Anchor ending in : is ambiguous", true);
          anchor = token;
          start ?? (start = token.offset);
          atNewline = false;
          hasSpace = false;
          reqSpace = true;
          break;
        case "tag": {
          if (tag)
            onError(token, "MULTIPLE_TAGS", "A node can have at most one tag");
          tag = token;
          start ?? (start = token.offset);
          atNewline = false;
          hasSpace = false;
          reqSpace = true;
          break;
        }
        case indicator:
          if (anchor || tag)
            onError(token, "BAD_PROP_ORDER", `Anchors and tags must be after the ${token.source} indicator`);
          if (found)
            onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.source} in ${flow ?? "collection"}`);
          found = token;
          atNewline = indicator === "seq-item-ind" || indicator === "explicit-key-ind";
          hasSpace = false;
          break;
        case "comma":
          if (flow) {
            if (comma)
              onError(token, "UNEXPECTED_TOKEN", `Unexpected , in ${flow}`);
            comma = token;
            atNewline = false;
            hasSpace = false;
            break;
          }
        default:
          onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.type} token`);
          atNewline = false;
          hasSpace = false;
      }
    }
    const last = tokens[tokens.length - 1];
    const end = last ? last.offset + last.source.length : offset;
    if (reqSpace && next && next.type !== "space" && next.type !== "newline" && next.type !== "comma" && (next.type !== "scalar" || next.source !== "")) {
      onError(next.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space");
    }
    if (tab && (atNewline && tab.indent <= parentIndent || next?.type === "block-map" || next?.type === "block-seq"))
      onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation");
    return {
      comma,
      found,
      spaceBefore,
      comment,
      hasNewline,
      anchor,
      tag,
      newlineAfterProp,
      end,
      start: start ?? end
    };
  }
  exports.resolveProps = resolveProps;
});

// node_modules/yaml/dist/compose/util-contains-newline.js
var require_util_contains_newline = __commonJS((exports) => {
  function containsNewline(key) {
    if (!key)
      return null;
    switch (key.type) {
      case "alias":
      case "scalar":
      case "double-quoted-scalar":
      case "single-quoted-scalar":
        if (key.source.includes(`
`))
          return true;
        if (key.end) {
          for (const st of key.end)
            if (st.type === "newline")
              return true;
        }
        return false;
      case "flow-collection":
        for (const it of key.items) {
          for (const st of it.start)
            if (st.type === "newline")
              return true;
          if (it.sep) {
            for (const st of it.sep)
              if (st.type === "newline")
                return true;
          }
          if (containsNewline(it.key) || containsNewline(it.value))
            return true;
        }
        return false;
      default:
        return true;
    }
  }
  exports.containsNewline = containsNewline;
});

// node_modules/yaml/dist/compose/util-flow-indent-check.js
var require_util_flow_indent_check = __commonJS((exports) => {
  var utilContainsNewline = require_util_contains_newline();
  function flowIndentCheck(indent, fc, onError) {
    if (fc?.type === "flow-collection") {
      const end = fc.end[0];
      if (end.indent === indent && (end.source === "]" || end.source === "}") && utilContainsNewline.containsNewline(fc)) {
        const msg = "Flow end indicator should be more indented than parent";
        onError(end, "BAD_INDENT", msg, true);
      }
    }
  }
  exports.flowIndentCheck = flowIndentCheck;
});

// node_modules/yaml/dist/compose/util-map-includes.js
var require_util_map_includes = __commonJS((exports) => {
  var identity = require_identity();
  function mapIncludes(ctx, items, search) {
    const { uniqueKeys } = ctx.options;
    if (uniqueKeys === false)
      return false;
    const isEqual = typeof uniqueKeys === "function" ? uniqueKeys : (a, b) => a === b || identity.isScalar(a) && identity.isScalar(b) && a.value === b.value;
    return items.some((pair) => isEqual(pair.key, search));
  }
  exports.mapIncludes = mapIncludes;
});

// node_modules/yaml/dist/compose/resolve-block-map.js
var require_resolve_block_map = __commonJS((exports) => {
  var Pair = require_Pair();
  var YAMLMap = require_YAMLMap();
  var resolveProps = require_resolve_props();
  var utilContainsNewline = require_util_contains_newline();
  var utilFlowIndentCheck = require_util_flow_indent_check();
  var utilMapIncludes = require_util_map_includes();
  var startColMsg = "All mapping items must start at the same column";
  function resolveBlockMap({ composeNode, composeEmptyNode }, ctx, bm, onError, tag) {
    const NodeClass = tag?.nodeClass ?? YAMLMap.YAMLMap;
    const map = new NodeClass(ctx.schema);
    if (ctx.atRoot)
      ctx.atRoot = false;
    let offset = bm.offset;
    let commentEnd = null;
    for (const collItem of bm.items) {
      const { start, key, sep, value } = collItem;
      const keyProps = resolveProps.resolveProps(start, {
        indicator: "explicit-key-ind",
        next: key ?? sep?.[0],
        offset,
        onError,
        parentIndent: bm.indent,
        startOnNewline: true
      });
      const implicitKey = !keyProps.found;
      if (implicitKey) {
        if (key) {
          if (key.type === "block-seq")
            onError(offset, "BLOCK_AS_IMPLICIT_KEY", "A block sequence may not be used as an implicit map key");
          else if ("indent" in key && key.indent !== bm.indent)
            onError(offset, "BAD_INDENT", startColMsg);
        }
        if (!keyProps.anchor && !keyProps.tag && !sep) {
          commentEnd = keyProps.end;
          if (keyProps.comment) {
            if (map.comment)
              map.comment += `
` + keyProps.comment;
            else
              map.comment = keyProps.comment;
          }
          continue;
        }
        if (keyProps.newlineAfterProp || utilContainsNewline.containsNewline(key)) {
          onError(key ?? start[start.length - 1], "MULTILINE_IMPLICIT_KEY", "Implicit keys need to be on a single line");
        }
      } else if (keyProps.found?.indent !== bm.indent) {
        onError(offset, "BAD_INDENT", startColMsg);
      }
      ctx.atKey = true;
      const keyStart = keyProps.end;
      const keyNode = key ? composeNode(ctx, key, keyProps, onError) : composeEmptyNode(ctx, keyStart, start, null, keyProps, onError);
      if (ctx.schema.compat)
        utilFlowIndentCheck.flowIndentCheck(bm.indent, key, onError);
      ctx.atKey = false;
      if (utilMapIncludes.mapIncludes(ctx, map.items, keyNode))
        onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique");
      const valueProps = resolveProps.resolveProps(sep ?? [], {
        indicator: "map-value-ind",
        next: value,
        offset: keyNode.range[2],
        onError,
        parentIndent: bm.indent,
        startOnNewline: !key || key.type === "block-scalar"
      });
      offset = valueProps.end;
      if (valueProps.found) {
        if (implicitKey) {
          if (value?.type === "block-map" && !valueProps.hasNewline)
            onError(offset, "BLOCK_AS_IMPLICIT_KEY", "Nested mappings are not allowed in compact mappings");
          if (ctx.options.strict && keyProps.start < valueProps.found.offset - 1024)
            onError(keyNode.range, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit block mapping key");
        }
        const valueNode = value ? composeNode(ctx, value, valueProps, onError) : composeEmptyNode(ctx, offset, sep, null, valueProps, onError);
        if (ctx.schema.compat)
          utilFlowIndentCheck.flowIndentCheck(bm.indent, value, onError);
        offset = valueNode.range[2];
        const pair = new Pair.Pair(keyNode, valueNode);
        if (ctx.options.keepSourceTokens)
          pair.srcToken = collItem;
        map.items.push(pair);
      } else {
        if (implicitKey)
          onError(keyNode.range, "MISSING_CHAR", "Implicit map keys need to be followed by map values");
        if (valueProps.comment) {
          if (keyNode.comment)
            keyNode.comment += `
` + valueProps.comment;
          else
            keyNode.comment = valueProps.comment;
        }
        const pair = new Pair.Pair(keyNode);
        if (ctx.options.keepSourceTokens)
          pair.srcToken = collItem;
        map.items.push(pair);
      }
    }
    if (commentEnd && commentEnd < offset)
      onError(commentEnd, "IMPOSSIBLE", "Map comment with trailing content");
    map.range = [bm.offset, offset, commentEnd ?? offset];
    return map;
  }
  exports.resolveBlockMap = resolveBlockMap;
});

// node_modules/yaml/dist/compose/resolve-block-seq.js
var require_resolve_block_seq = __commonJS((exports) => {
  var YAMLSeq = require_YAMLSeq();
  var resolveProps = require_resolve_props();
  var utilFlowIndentCheck = require_util_flow_indent_check();
  function resolveBlockSeq({ composeNode, composeEmptyNode }, ctx, bs, onError, tag) {
    const NodeClass = tag?.nodeClass ?? YAMLSeq.YAMLSeq;
    const seq = new NodeClass(ctx.schema);
    if (ctx.atRoot)
      ctx.atRoot = false;
    if (ctx.atKey)
      ctx.atKey = false;
    let offset = bs.offset;
    let commentEnd = null;
    for (const { start, value } of bs.items) {
      const props = resolveProps.resolveProps(start, {
        indicator: "seq-item-ind",
        next: value,
        offset,
        onError,
        parentIndent: bs.indent,
        startOnNewline: true
      });
      if (!props.found) {
        if (props.anchor || props.tag || value) {
          if (value?.type === "block-seq")
            onError(props.end, "BAD_INDENT", "All sequence items must start at the same column");
          else
            onError(offset, "MISSING_CHAR", "Sequence item without - indicator");
        } else {
          commentEnd = props.end;
          if (props.comment)
            seq.comment = props.comment;
          continue;
        }
      }
      const node = value ? composeNode(ctx, value, props, onError) : composeEmptyNode(ctx, props.end, start, null, props, onError);
      if (ctx.schema.compat)
        utilFlowIndentCheck.flowIndentCheck(bs.indent, value, onError);
      offset = node.range[2];
      seq.items.push(node);
    }
    seq.range = [bs.offset, offset, commentEnd ?? offset];
    return seq;
  }
  exports.resolveBlockSeq = resolveBlockSeq;
});

// node_modules/yaml/dist/compose/resolve-end.js
var require_resolve_end = __commonJS((exports) => {
  function resolveEnd(end, offset, reqSpace, onError) {
    let comment = "";
    if (end) {
      let hasSpace = false;
      let sep = "";
      for (const token of end) {
        const { source, type } = token;
        switch (type) {
          case "space":
            hasSpace = true;
            break;
          case "comment": {
            if (reqSpace && !hasSpace)
              onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters");
            const cb = source.substring(1) || " ";
            if (!comment)
              comment = cb;
            else
              comment += sep + cb;
            sep = "";
            break;
          }
          case "newline":
            if (comment)
              sep += source;
            hasSpace = true;
            break;
          default:
            onError(token, "UNEXPECTED_TOKEN", `Unexpected ${type} at node end`);
        }
        offset += source.length;
      }
    }
    return { comment, offset };
  }
  exports.resolveEnd = resolveEnd;
});

// node_modules/yaml/dist/compose/resolve-flow-collection.js
var require_resolve_flow_collection = __commonJS((exports) => {
  var identity = require_identity();
  var Pair = require_Pair();
  var YAMLMap = require_YAMLMap();
  var YAMLSeq = require_YAMLSeq();
  var resolveEnd = require_resolve_end();
  var resolveProps = require_resolve_props();
  var utilContainsNewline = require_util_contains_newline();
  var utilMapIncludes = require_util_map_includes();
  var blockMsg = "Block collections are not allowed within flow collections";
  var isBlock = (token) => token && (token.type === "block-map" || token.type === "block-seq");
  function resolveFlowCollection({ composeNode, composeEmptyNode }, ctx, fc, onError, tag) {
    const isMap = fc.start.source === "{";
    const fcName = isMap ? "flow map" : "flow sequence";
    const NodeClass = tag?.nodeClass ?? (isMap ? YAMLMap.YAMLMap : YAMLSeq.YAMLSeq);
    const coll = new NodeClass(ctx.schema);
    coll.flow = true;
    const atRoot = ctx.atRoot;
    if (atRoot)
      ctx.atRoot = false;
    if (ctx.atKey)
      ctx.atKey = false;
    let offset = fc.offset + fc.start.source.length;
    for (let i = 0;i < fc.items.length; ++i) {
      const collItem = fc.items[i];
      const { start, key, sep, value } = collItem;
      const props = resolveProps.resolveProps(start, {
        flow: fcName,
        indicator: "explicit-key-ind",
        next: key ?? sep?.[0],
        offset,
        onError,
        parentIndent: fc.indent,
        startOnNewline: false
      });
      if (!props.found) {
        if (!props.anchor && !props.tag && !sep && !value) {
          if (i === 0 && props.comma)
            onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`);
          else if (i < fc.items.length - 1)
            onError(props.start, "UNEXPECTED_TOKEN", `Unexpected empty item in ${fcName}`);
          if (props.comment) {
            if (coll.comment)
              coll.comment += `
` + props.comment;
            else
              coll.comment = props.comment;
          }
          offset = props.end;
          continue;
        }
        if (!isMap && ctx.options.strict && utilContainsNewline.containsNewline(key))
          onError(key, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line");
      }
      if (i === 0) {
        if (props.comma)
          onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`);
      } else {
        if (!props.comma)
          onError(props.start, "MISSING_CHAR", `Missing , between ${fcName} items`);
        if (props.comment) {
          let prevItemComment = "";
          loop:
            for (const st of start) {
              switch (st.type) {
                case "comma":
                case "space":
                  break;
                case "comment":
                  prevItemComment = st.source.substring(1);
                  break loop;
                default:
                  break loop;
              }
            }
          if (prevItemComment) {
            let prev = coll.items[coll.items.length - 1];
            if (identity.isPair(prev))
              prev = prev.value ?? prev.key;
            if (prev.comment)
              prev.comment += `
` + prevItemComment;
            else
              prev.comment = prevItemComment;
            props.comment = props.comment.substring(prevItemComment.length + 1);
          }
        }
      }
      if (!isMap && !sep && !props.found) {
        const valueNode = value ? composeNode(ctx, value, props, onError) : composeEmptyNode(ctx, props.end, sep, null, props, onError);
        coll.items.push(valueNode);
        offset = valueNode.range[2];
        if (isBlock(value))
          onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg);
      } else {
        ctx.atKey = true;
        const keyStart = props.end;
        const keyNode = key ? composeNode(ctx, key, props, onError) : composeEmptyNode(ctx, keyStart, start, null, props, onError);
        if (isBlock(key))
          onError(keyNode.range, "BLOCK_IN_FLOW", blockMsg);
        ctx.atKey = false;
        const valueProps = resolveProps.resolveProps(sep ?? [], {
          flow: fcName,
          indicator: "map-value-ind",
          next: value,
          offset: keyNode.range[2],
          onError,
          parentIndent: fc.indent,
          startOnNewline: false
        });
        if (valueProps.found) {
          if (!isMap && !props.found && ctx.options.strict) {
            if (sep)
              for (const st of sep) {
                if (st === valueProps.found)
                  break;
                if (st.type === "newline") {
                  onError(st, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line");
                  break;
                }
              }
            if (props.start < valueProps.found.offset - 1024)
              onError(valueProps.found, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit flow sequence key");
          }
        } else if (value) {
          if ("source" in value && value.source?.[0] === ":")
            onError(value, "MISSING_CHAR", `Missing space after : in ${fcName}`);
          else
            onError(valueProps.start, "MISSING_CHAR", `Missing , or : between ${fcName} items`);
        }
        const valueNode = value ? composeNode(ctx, value, valueProps, onError) : valueProps.found ? composeEmptyNode(ctx, valueProps.end, sep, null, valueProps, onError) : null;
        if (valueNode) {
          if (isBlock(value))
            onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg);
        } else if (valueProps.comment) {
          if (keyNode.comment)
            keyNode.comment += `
` + valueProps.comment;
          else
            keyNode.comment = valueProps.comment;
        }
        const pair = new Pair.Pair(keyNode, valueNode);
        if (ctx.options.keepSourceTokens)
          pair.srcToken = collItem;
        if (isMap) {
          const map = coll;
          if (utilMapIncludes.mapIncludes(ctx, map.items, keyNode))
            onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique");
          map.items.push(pair);
        } else {
          const map = new YAMLMap.YAMLMap(ctx.schema);
          map.flow = true;
          map.items.push(pair);
          const endRange = (valueNode ?? keyNode).range;
          map.range = [keyNode.range[0], endRange[1], endRange[2]];
          coll.items.push(map);
        }
        offset = valueNode ? valueNode.range[2] : valueProps.end;
      }
    }
    const expectedEnd = isMap ? "}" : "]";
    const [ce, ...ee] = fc.end;
    let cePos = offset;
    if (ce?.source === expectedEnd)
      cePos = ce.offset + ce.source.length;
    else {
      const name = fcName[0].toUpperCase() + fcName.substring(1);
      const msg = atRoot ? `${name} must end with a ${expectedEnd}` : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`;
      onError(offset, atRoot ? "MISSING_CHAR" : "BAD_INDENT", msg);
      if (ce && ce.source.length !== 1)
        ee.unshift(ce);
    }
    if (ee.length > 0) {
      const end = resolveEnd.resolveEnd(ee, cePos, ctx.options.strict, onError);
      if (end.comment) {
        if (coll.comment)
          coll.comment += `
` + end.comment;
        else
          coll.comment = end.comment;
      }
      coll.range = [fc.offset, cePos, end.offset];
    } else {
      coll.range = [fc.offset, cePos, cePos];
    }
    return coll;
  }
  exports.resolveFlowCollection = resolveFlowCollection;
});

// node_modules/yaml/dist/compose/compose-collection.js
var require_compose_collection = __commonJS((exports) => {
  var identity = require_identity();
  var Scalar = require_Scalar();
  var YAMLMap = require_YAMLMap();
  var YAMLSeq = require_YAMLSeq();
  var resolveBlockMap = require_resolve_block_map();
  var resolveBlockSeq = require_resolve_block_seq();
  var resolveFlowCollection = require_resolve_flow_collection();
  function resolveCollection(CN, ctx, token, onError, tagName, tag) {
    const coll = token.type === "block-map" ? resolveBlockMap.resolveBlockMap(CN, ctx, token, onError, tag) : token.type === "block-seq" ? resolveBlockSeq.resolveBlockSeq(CN, ctx, token, onError, tag) : resolveFlowCollection.resolveFlowCollection(CN, ctx, token, onError, tag);
    const Coll = coll.constructor;
    if (tagName === "!" || tagName === Coll.tagName) {
      coll.tag = Coll.tagName;
      return coll;
    }
    if (tagName)
      coll.tag = tagName;
    return coll;
  }
  function composeCollection(CN, ctx, token, props, onError) {
    const tagToken = props.tag;
    const tagName = !tagToken ? null : ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg));
    if (token.type === "block-seq") {
      const { anchor, newlineAfterProp: nl } = props;
      const lastProp = anchor && tagToken ? anchor.offset > tagToken.offset ? anchor : tagToken : anchor ?? tagToken;
      if (lastProp && (!nl || nl.offset < lastProp.offset)) {
        const message = "Missing newline after block sequence props";
        onError(lastProp, "MISSING_CHAR", message);
      }
    }
    const expType = token.type === "block-map" ? "map" : token.type === "block-seq" ? "seq" : token.start.source === "{" ? "map" : "seq";
    if (!tagToken || !tagName || tagName === "!" || tagName === YAMLMap.YAMLMap.tagName && expType === "map" || tagName === YAMLSeq.YAMLSeq.tagName && expType === "seq") {
      return resolveCollection(CN, ctx, token, onError, tagName);
    }
    let tag = ctx.schema.tags.find((t) => t.tag === tagName && t.collection === expType);
    if (!tag) {
      const kt = ctx.schema.knownTags[tagName];
      if (kt?.collection === expType) {
        ctx.schema.tags.push(Object.assign({}, kt, { default: false }));
        tag = kt;
      } else {
        if (kt) {
          onError(tagToken, "BAD_COLLECTION_TYPE", `${kt.tag} used for ${expType} collection, but expects ${kt.collection ?? "scalar"}`, true);
        } else {
          onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, true);
        }
        return resolveCollection(CN, ctx, token, onError, tagName);
      }
    }
    const coll = resolveCollection(CN, ctx, token, onError, tagName, tag);
    const res = tag.resolve?.(coll, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg), ctx.options) ?? coll;
    const node = identity.isNode(res) ? res : new Scalar.Scalar(res);
    node.range = coll.range;
    node.tag = tagName;
    if (tag?.format)
      node.format = tag.format;
    return node;
  }
  exports.composeCollection = composeCollection;
});

// node_modules/yaml/dist/compose/resolve-block-scalar.js
var require_resolve_block_scalar = __commonJS((exports) => {
  var Scalar = require_Scalar();
  function resolveBlockScalar(ctx, scalar, onError) {
    const start = scalar.offset;
    const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError);
    if (!header)
      return { value: "", type: null, comment: "", range: [start, start, start] };
    const type = header.mode === ">" ? Scalar.Scalar.BLOCK_FOLDED : Scalar.Scalar.BLOCK_LITERAL;
    const lines = scalar.source ? splitLines(scalar.source) : [];
    let chompStart = lines.length;
    for (let i = lines.length - 1;i >= 0; --i) {
      const content = lines[i][1];
      if (content === "" || content === "\r")
        chompStart = i;
      else
        break;
    }
    if (chompStart === 0) {
      const value2 = header.chomp === "+" && lines.length > 0 ? `
`.repeat(Math.max(1, lines.length - 1)) : "";
      let end2 = start + header.length;
      if (scalar.source)
        end2 += scalar.source.length;
      return { value: value2, type, comment: header.comment, range: [start, end2, end2] };
    }
    let trimIndent = scalar.indent + header.indent;
    let offset = scalar.offset + header.length;
    let contentStart = 0;
    for (let i = 0;i < chompStart; ++i) {
      const [indent, content] = lines[i];
      if (content === "" || content === "\r") {
        if (header.indent === 0 && indent.length > trimIndent)
          trimIndent = indent.length;
      } else {
        if (indent.length < trimIndent) {
          const message = "Block scalars with more-indented leading empty lines must use an explicit indentation indicator";
          onError(offset + indent.length, "MISSING_CHAR", message);
        }
        if (header.indent === 0)
          trimIndent = indent.length;
        contentStart = i;
        if (trimIndent === 0 && !ctx.atRoot) {
          const message = "Block scalar values in collections must be indented";
          onError(offset, "BAD_INDENT", message);
        }
        break;
      }
      offset += indent.length + content.length + 1;
    }
    for (let i = lines.length - 1;i >= chompStart; --i) {
      if (lines[i][0].length > trimIndent)
        chompStart = i + 1;
    }
    let value = "";
    let sep = "";
    let prevMoreIndented = false;
    for (let i = 0;i < contentStart; ++i)
      value += lines[i][0].slice(trimIndent) + `
`;
    for (let i = contentStart;i < chompStart; ++i) {
      let [indent, content] = lines[i];
      offset += indent.length + content.length + 1;
      const crlf = content[content.length - 1] === "\r";
      if (crlf)
        content = content.slice(0, -1);
      if (content && indent.length < trimIndent) {
        const src = header.indent ? "explicit indentation indicator" : "first line";
        const message = `Block scalar lines must not be less indented than their ${src}`;
        onError(offset - content.length - (crlf ? 2 : 1), "BAD_INDENT", message);
        indent = "";
      }
      if (type === Scalar.Scalar.BLOCK_LITERAL) {
        value += sep + indent.slice(trimIndent) + content;
        sep = `
`;
      } else if (indent.length > trimIndent || content[0] === "\t") {
        if (sep === " ")
          sep = `
`;
        else if (!prevMoreIndented && sep === `
`)
          sep = `

`;
        value += sep + indent.slice(trimIndent) + content;
        sep = `
`;
        prevMoreIndented = true;
      } else if (content === "") {
        if (sep === `
`)
          value += `
`;
        else
          sep = `
`;
      } else {
        value += sep + content;
        sep = " ";
        prevMoreIndented = false;
      }
    }
    switch (header.chomp) {
      case "-":
        break;
      case "+":
        for (let i = chompStart;i < lines.length; ++i)
          value += `
` + lines[i][0].slice(trimIndent);
        if (value[value.length - 1] !== `
`)
          value += `
`;
        break;
      default:
        value += `
`;
    }
    const end = start + header.length + scalar.source.length;
    return { value, type, comment: header.comment, range: [start, end, end] };
  }
  function parseBlockScalarHeader({ offset, props }, strict, onError) {
    if (props[0].type !== "block-scalar-header") {
      onError(props[0], "IMPOSSIBLE", "Block scalar header not found");
      return null;
    }
    const { source } = props[0];
    const mode = source[0];
    let indent = 0;
    let chomp = "";
    let error = -1;
    for (let i = 1;i < source.length; ++i) {
      const ch = source[i];
      if (!chomp && (ch === "-" || ch === "+"))
        chomp = ch;
      else {
        const n = Number(ch);
        if (!indent && n)
          indent = n;
        else if (error === -1)
          error = offset + i;
      }
    }
    if (error !== -1)
      onError(error, "UNEXPECTED_TOKEN", `Block scalar header includes extra characters: ${source}`);
    let hasSpace = false;
    let comment = "";
    let length = source.length;
    for (let i = 1;i < props.length; ++i) {
      const token = props[i];
      switch (token.type) {
        case "space":
          hasSpace = true;
        case "newline":
          length += token.source.length;
          break;
        case "comment":
          if (strict && !hasSpace) {
            const message = "Comments must be separated from other tokens by white space characters";
            onError(token, "MISSING_CHAR", message);
          }
          length += token.source.length;
          comment = token.source.substring(1);
          break;
        case "error":
          onError(token, "UNEXPECTED_TOKEN", token.message);
          length += token.source.length;
          break;
        default: {
          const message = `Unexpected token in block scalar header: ${token.type}`;
          onError(token, "UNEXPECTED_TOKEN", message);
          const ts = token.source;
          if (ts && typeof ts === "string")
            length += ts.length;
        }
      }
    }
    return { mode, indent, chomp, comment, length };
  }
  function splitLines(source) {
    const split = source.split(/\n( *)/);
    const first = split[0];
    const m = first.match(/^( *)/);
    const line0 = m?.[1] ? [m[1], first.slice(m[1].length)] : ["", first];
    const lines = [line0];
    for (let i = 1;i < split.length; i += 2)
      lines.push([split[i], split[i + 1]]);
    return lines;
  }
  exports.resolveBlockScalar = resolveBlockScalar;
});

// node_modules/yaml/dist/compose/resolve-flow-scalar.js
var require_resolve_flow_scalar = __commonJS((exports) => {
  var Scalar = require_Scalar();
  var resolveEnd = require_resolve_end();
  function resolveFlowScalar(scalar, strict, onError) {
    const { offset, type, source, end } = scalar;
    let _type;
    let value;
    const _onError = (rel, code, msg) => onError(offset + rel, code, msg);
    switch (type) {
      case "scalar":
        _type = Scalar.Scalar.PLAIN;
        value = plainValue(source, _onError);
        break;
      case "single-quoted-scalar":
        _type = Scalar.Scalar.QUOTE_SINGLE;
        value = singleQuotedValue(source, _onError);
        break;
      case "double-quoted-scalar":
        _type = Scalar.Scalar.QUOTE_DOUBLE;
        value = doubleQuotedValue(source, _onError);
        break;
      default:
        onError(scalar, "UNEXPECTED_TOKEN", `Expected a flow scalar value, but found: ${type}`);
        return {
          value: "",
          type: null,
          comment: "",
          range: [offset, offset + source.length, offset + source.length]
        };
    }
    const valueEnd = offset + source.length;
    const re = resolveEnd.resolveEnd(end, valueEnd, strict, onError);
    return {
      value,
      type: _type,
      comment: re.comment,
      range: [offset, valueEnd, re.offset]
    };
  }
  function plainValue(source, onError) {
    let badChar = "";
    switch (source[0]) {
      case "\t":
        badChar = "a tab character";
        break;
      case ",":
        badChar = "flow indicator character ,";
        break;
      case "%":
        badChar = "directive indicator character %";
        break;
      case "|":
      case ">": {
        badChar = `block scalar indicator ${source[0]}`;
        break;
      }
      case "@":
      case "`": {
        badChar = `reserved character ${source[0]}`;
        break;
      }
    }
    if (badChar)
      onError(0, "BAD_SCALAR_START", `Plain value cannot start with ${badChar}`);
    return foldLines(source);
  }
  function singleQuotedValue(source, onError) {
    if (source[source.length - 1] !== "'" || source.length === 1)
      onError(source.length, "MISSING_CHAR", "Missing closing 'quote");
    return foldLines(source.slice(1, -1)).replace(/''/g, "'");
  }
  function foldLines(source) {
    let first, line;
    try {
      first = new RegExp(`(.*?)(?<![ 	])[ 	]*\r?
`, "sy");
      line = new RegExp(`[ 	]*(.*?)(?:(?<![ 	])[ 	]*)?\r?
`, "sy");
    } catch {
      first = /(.*?)[ \t]*\r?\n/sy;
      line = /[ \t]*(.*?)[ \t]*\r?\n/sy;
    }
    let match = first.exec(source);
    if (!match)
      return source;
    let res = match[1];
    let sep = " ";
    let pos = first.lastIndex;
    line.lastIndex = pos;
    while (match = line.exec(source)) {
      if (match[1] === "") {
        if (sep === `
`)
          res += sep;
        else
          sep = `
`;
      } else {
        res += sep + match[1];
        sep = " ";
      }
      pos = line.lastIndex;
    }
    const last = /[ \t]*(.*)/sy;
    last.lastIndex = pos;
    match = last.exec(source);
    return res + sep + (match?.[1] ?? "");
  }
  function doubleQuotedValue(source, onError) {
    let res = "";
    for (let i = 1;i < source.length - 1; ++i) {
      const ch = source[i];
      if (ch === "\r" && source[i + 1] === `
`)
        continue;
      if (ch === `
`) {
        const { fold, offset } = foldNewline(source, i);
        res += fold;
        i = offset;
      } else if (ch === "\\") {
        let next = source[++i];
        const cc = escapeCodes[next];
        if (cc)
          res += cc;
        else if (next === `
`) {
          next = source[i + 1];
          while (next === " " || next === "\t")
            next = source[++i + 1];
        } else if (next === "\r" && source[i + 1] === `
`) {
          next = source[++i + 1];
          while (next === " " || next === "\t")
            next = source[++i + 1];
        } else if (next === "x" || next === "u" || next === "U") {
          const length = next === "x" ? 2 : next === "u" ? 4 : 8;
          res += parseCharCode(source, i + 1, length, onError);
          i += length;
        } else {
          const raw = source.substr(i - 1, 2);
          onError(i - 1, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw}`);
          res += raw;
        }
      } else if (ch === " " || ch === "\t") {
        const wsStart = i;
        let next = source[i + 1];
        while (next === " " || next === "\t")
          next = source[++i + 1];
        if (next !== `
` && !(next === "\r" && source[i + 2] === `
`))
          res += i > wsStart ? source.slice(wsStart, i + 1) : ch;
      } else {
        res += ch;
      }
    }
    if (source[source.length - 1] !== '"' || source.length === 1)
      onError(source.length, "MISSING_CHAR", 'Missing closing "quote');
    return res;
  }
  function foldNewline(source, offset) {
    let fold = "";
    let ch = source[offset + 1];
    while (ch === " " || ch === "\t" || ch === `
` || ch === "\r") {
      if (ch === "\r" && source[offset + 2] !== `
`)
        break;
      if (ch === `
`)
        fold += `
`;
      offset += 1;
      ch = source[offset + 1];
    }
    if (!fold)
      fold = " ";
    return { fold, offset };
  }
  var escapeCodes = {
    "0": "\x00",
    a: "\x07",
    b: "\b",
    e: "\x1B",
    f: "\f",
    n: `
`,
    r: "\r",
    t: "\t",
    v: "\v",
    N: "…",
    _: " ",
    L: "\u2028",
    P: "\u2029",
    " ": " ",
    '"': '"',
    "/": "/",
    "\\": "\\",
    "\t": "\t"
  };
  function parseCharCode(source, offset, length, onError) {
    const cc = source.substr(offset, length);
    const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc);
    const code = ok ? parseInt(cc, 16) : NaN;
    try {
      return String.fromCodePoint(code);
    } catch {
      const raw = source.substr(offset - 2, length + 2);
      onError(offset - 2, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw}`);
      return raw;
    }
  }
  exports.resolveFlowScalar = resolveFlowScalar;
});

// node_modules/yaml/dist/compose/compose-scalar.js
var require_compose_scalar = __commonJS((exports) => {
  var identity = require_identity();
  var Scalar = require_Scalar();
  var resolveBlockScalar = require_resolve_block_scalar();
  var resolveFlowScalar = require_resolve_flow_scalar();
  function composeScalar(ctx, token, tagToken, onError) {
    const { value, type, comment, range } = token.type === "block-scalar" ? resolveBlockScalar.resolveBlockScalar(ctx, token, onError) : resolveFlowScalar.resolveFlowScalar(token, ctx.options.strict, onError);
    const tagName = tagToken ? ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)) : null;
    let tag;
    if (ctx.options.stringKeys && ctx.atKey) {
      tag = ctx.schema[identity.SCALAR];
    } else if (tagName)
      tag = findScalarTagByName(ctx.schema, value, tagName, tagToken, onError);
    else if (token.type === "scalar")
      tag = findScalarTagByTest(ctx, value, token, onError);
    else
      tag = ctx.schema[identity.SCALAR];
    let scalar;
    try {
      const res = tag.resolve(value, (msg) => onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg), ctx.options);
      scalar = identity.isScalar(res) ? res : new Scalar.Scalar(res);
    } catch (error) {
      const msg = error instanceof Error ? error.message : String(error);
      onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg);
      scalar = new Scalar.Scalar(value);
    }
    scalar.range = range;
    scalar.source = value;
    if (type)
      scalar.type = type;
    if (tagName)
      scalar.tag = tagName;
    if (tag.format)
      scalar.format = tag.format;
    if (comment)
      scalar.comment = comment;
    return scalar;
  }
  function findScalarTagByName(schema, value, tagName, tagToken, onError) {
    if (tagName === "!")
      return schema[identity.SCALAR];
    const matchWithTest = [];
    for (const tag of schema.tags) {
      if (!tag.collection && tag.tag === tagName) {
        if (tag.default && tag.test)
          matchWithTest.push(tag);
        else
          return tag;
      }
    }
    for (const tag of matchWithTest)
      if (tag.test?.test(value))
        return tag;
    const kt = schema.knownTags[tagName];
    if (kt && !kt.collection) {
      schema.tags.push(Object.assign({}, kt, { default: false, test: undefined }));
      return kt;
    }
    onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, tagName !== "tag:yaml.org,2002:str");
    return schema[identity.SCALAR];
  }
  function findScalarTagByTest({ atKey, directives, schema }, value, token, onError) {
    const tag = schema.tags.find((tag2) => (tag2.default === true || atKey && tag2.default === "key") && tag2.test?.test(value)) || schema[identity.SCALAR];
    if (schema.compat) {
      const compat = schema.compat.find((tag2) => tag2.default && tag2.test?.test(value)) ?? schema[identity.SCALAR];
      if (tag.tag !== compat.tag) {
        const ts = directives.tagString(tag.tag);
        const cs = directives.tagString(compat.tag);
        const msg = `Value may be parsed as either ${ts} or ${cs}`;
        onError(token, "TAG_RESOLVE_FAILED", msg, true);
      }
    }
    return tag;
  }
  exports.composeScalar = composeScalar;
});

// node_modules/yaml/dist/compose/util-empty-scalar-position.js
var require_util_empty_scalar_position = __commonJS((exports) => {
  function emptyScalarPosition(offset, before, pos) {
    if (before) {
      pos ?? (pos = before.length);
      for (let i = pos - 1;i >= 0; --i) {
        let st = before[i];
        switch (st.type) {
          case "space":
          case "comment":
          case "newline":
            offset -= st.source.length;
            continue;
        }
        st = before[++i];
        while (st?.type === "space") {
          offset += st.source.length;
          st = before[++i];
        }
        break;
      }
    }
    return offset;
  }
  exports.emptyScalarPosition = emptyScalarPosition;
});

// node_modules/yaml/dist/compose/compose-node.js
var require_compose_node = __commonJS((exports) => {
  var Alias = require_Alias();
  var identity = require_identity();
  var composeCollection = require_compose_collection();
  var composeScalar = require_compose_scalar();
  var resolveEnd = require_resolve_end();
  var utilEmptyScalarPosition = require_util_empty_scalar_position();
  var CN = { composeNode, composeEmptyNode };
  function composeNode(ctx, token, props, onError) {
    const atKey = ctx.atKey;
    const { spaceBefore, comment, anchor, tag } = props;
    let node;
    let isSrcToken = true;
    switch (token.type) {
      case "alias":
        node = composeAlias(ctx, token, onError);
        if (anchor || tag)
          onError(token, "ALIAS_PROPS", "An alias node must not specify any properties");
        break;
      case "scalar":
      case "single-quoted-scalar":
      case "double-quoted-scalar":
      case "block-scalar":
        node = composeScalar.composeScalar(ctx, token, tag, onError);
        if (anchor)
          node.anchor = anchor.source.substring(1);
        break;
      case "block-map":
      case "block-seq":
      case "flow-collection":
        try {
          node = composeCollection.composeCollection(CN, ctx, token, props, onError);
          if (anchor)
            node.anchor = anchor.source.substring(1);
        } catch (error) {
          const message = error instanceof Error ? error.message : String(error);
          onError(token, "RESOURCE_EXHAUSTION", message);
        }
        break;
      default: {
        const message = token.type === "error" ? token.message : `Unsupported token (type: ${token.type})`;
        onError(token, "UNEXPECTED_TOKEN", message);
        isSrcToken = false;
      }
    }
    node ?? (node = composeEmptyNode(ctx, token.offset, undefined, null, props, onError));
    if (anchor && node.anchor === "")
      onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string");
    if (atKey && ctx.options.stringKeys && (!identity.isScalar(node) || typeof node.value !== "string" || node.tag && node.tag !== "tag:yaml.org,2002:str")) {
      const msg = "With stringKeys, all keys must be strings";
      onError(tag ?? token, "NON_STRING_KEY", msg);
    }
    if (spaceBefore)
      node.spaceBefore = true;
    if (comment) {
      if (token.type === "scalar" && token.source === "")
        node.comment = comment;
      else
        node.commentBefore = comment;
    }
    if (ctx.options.keepSourceTokens && isSrcToken)
      node.srcToken = token;
    return node;
  }
  function composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError) {
    const token = {
      type: "scalar",
      offset: utilEmptyScalarPosition.emptyScalarPosition(offset, before, pos),
      indent: -1,
      source: ""
    };
    const node = composeScalar.composeScalar(ctx, token, tag, onError);
    if (anchor) {
      node.anchor = anchor.source.substring(1);
      if (node.anchor === "")
        onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string");
    }
    if (spaceBefore)
      node.spaceBefore = true;
    if (comment) {
      node.comment = comment;
      node.range[2] = end;
    }
    return node;
  }
  function composeAlias({ options }, { offset, source, end }, onError) {
    const alias = new Alias.Alias(source.substring(1));
    if (alias.source === "")
      onError(offset, "BAD_ALIAS", "Alias cannot be an empty string");
    if (alias.source.endsWith(":"))
      onError(offset + source.length - 1, "BAD_ALIAS", "Alias ending in : is ambiguous", true);
    const valueEnd = offset + source.length;
    const re = resolveEnd.resolveEnd(end, valueEnd, options.strict, onError);
    alias.range = [offset, valueEnd, re.offset];
    if (re.comment)
      alias.comment = re.comment;
    return alias;
  }
  exports.composeEmptyNode = composeEmptyNode;
  exports.composeNode = composeNode;
});

// node_modules/yaml/dist/compose/compose-doc.js
var require_compose_doc = __commonJS((exports) => {
  var Document = require_Document();
  var composeNode = require_compose_node();
  var resolveEnd = require_resolve_end();
  var resolveProps = require_resolve_props();
  function composeDoc(options, directives, { offset, start, value, end }, onError) {
    const opts = Object.assign({ _directives: directives }, options);
    const doc = new Document.Document(undefined, opts);
    const ctx = {
      atKey: false,
      atRoot: true,
      directives: doc.directives,
      options: doc.options,
      schema: doc.schema
    };
    const props = resolveProps.resolveProps(start, {
      indicator: "doc-start",
      next: value ?? end?.[0],
      offset,
      onError,
      parentIndent: 0,
      startOnNewline: true
    });
    if (props.found) {
      doc.directives.docStart = true;
      if (value && (value.type === "block-map" || value.type === "block-seq") && !props.hasNewline)
        onError(props.end, "MISSING_CHAR", "Block collection cannot start on same line with directives-end marker");
    }
    doc.contents = value ? composeNode.composeNode(ctx, value, props, onError) : composeNode.composeEmptyNode(ctx, props.end, start, null, props, onError);
    const contentEnd = doc.contents.range[2];
    const re = resolveEnd.resolveEnd(end, contentEnd, false, onError);
    if (re.comment)
      doc.comment = re.comment;
    doc.range = [offset, contentEnd, re.offset];
    return doc;
  }
  exports.composeDoc = composeDoc;
});

// node_modules/yaml/dist/compose/composer.js
var require_composer = __commonJS((exports) => {
  var node_process = __require("process");
  var directives = require_directives();
  var Document = require_Document();
  var errors = require_errors();
  var identity = require_identity();
  var composeDoc = require_compose_doc();
  var resolveEnd = require_resolve_end();
  function getErrorPos(src) {
    if (typeof src === "number")
      return [src, src + 1];
    if (Array.isArray(src))
      return src.length === 2 ? src : [src[0], src[1]];
    const { offset, source } = src;
    return [offset, offset + (typeof source === "string" ? source.length : 1)];
  }
  function parsePrelude(prelude) {
    let comment = "";
    let atComment = false;
    let afterEmptyLine = false;
    for (let i = 0;i < prelude.length; ++i) {
      const source = prelude[i];
      switch (source[0]) {
        case "#":
          comment += (comment === "" ? "" : afterEmptyLine ? `

` : `
`) + (source.substring(1) || " ");
          atComment = true;
          afterEmptyLine = false;
          break;
        case "%":
          if (prelude[i + 1]?.[0] !== "#")
            i += 1;
          atComment = false;
          break;
        default:
          if (!atComment)
            afterEmptyLine = true;
          atComment = false;
      }
    }
    return { comment, afterEmptyLine };
  }

  class Composer {
    constructor(options = {}) {
      this.doc = null;
      this.atDirectives = false;
      this.prelude = [];
      this.errors = [];
      this.warnings = [];
      this.onError = (source, code, message, warning) => {
        const pos = getErrorPos(source);
        if (warning)
          this.warnings.push(new errors.YAMLWarning(pos, code, message));
        else
          this.errors.push(new errors.YAMLParseError(pos, code, message));
      };
      this.directives = new directives.Directives({ version: options.version || "1.2" });
      this.options = options;
    }
    decorate(doc, afterDoc) {
      const { comment, afterEmptyLine } = parsePrelude(this.prelude);
      if (comment) {
        const dc = doc.contents;
        if (afterDoc) {
          doc.comment = doc.comment ? `${doc.comment}
${comment}` : comment;
        } else if (afterEmptyLine || doc.directives.docStart || !dc) {
          doc.commentBefore = comment;
        } else if (identity.isCollection(dc) && !dc.flow && dc.items.length > 0) {
          let it = dc.items[0];
          if (identity.isPair(it))
            it = it.key;
          const cb = it.commentBefore;
          it.commentBefore = cb ? `${comment}
${cb}` : comment;
        } else {
          const cb = dc.commentBefore;
          dc.commentBefore = cb ? `${comment}
${cb}` : comment;
        }
      }
      if (afterDoc) {
        Array.prototype.push.apply(doc.errors, this.errors);
        Array.prototype.push.apply(doc.warnings, this.warnings);
      } else {
        doc.errors = this.errors;
        doc.warnings = this.warnings;
      }
      this.prelude = [];
      this.errors = [];
      this.warnings = [];
    }
    streamInfo() {
      return {
        comment: parsePrelude(this.prelude).comment,
        directives: this.directives,
        errors: this.errors,
        warnings: this.warnings
      };
    }
    *compose(tokens, forceDoc = false, endOffset = -1) {
      for (const token of tokens)
        yield* this.next(token);
      yield* this.end(forceDoc, endOffset);
    }
    *next(token) {
      if (node_process.env.LOG_STREAM)
        console.dir(token, { depth: null });
      switch (token.type) {
        case "directive":
          this.directives.add(token.source, (offset, message, warning) => {
            const pos = getErrorPos(token);
            pos[0] += offset;
            this.onError(pos, "BAD_DIRECTIVE", message, warning);
          });
          this.prelude.push(token.source);
          this.atDirectives = true;
          break;
        case "document": {
          const doc = composeDoc.composeDoc(this.options, this.directives, token, this.onError);
          if (this.atDirectives && !doc.directives.docStart)
            this.onError(token, "MISSING_CHAR", "Missing directives-end/doc-start indicator line");
          this.decorate(doc, false);
          if (this.doc)
            yield this.doc;
          this.doc = doc;
          this.atDirectives = false;
          break;
        }
        case "byte-order-mark":
        case "space":
          break;
        case "comment":
        case "newline":
          this.prelude.push(token.source);
          break;
        case "error": {
          const msg = token.source ? `${token.message}: ${JSON.stringify(token.source)}` : token.message;
          const error = new errors.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg);
          if (this.atDirectives || !this.doc)
            this.errors.push(error);
          else
            this.doc.errors.push(error);
          break;
        }
        case "doc-end": {
          if (!this.doc) {
            const msg = "Unexpected doc-end without preceding document";
            this.errors.push(new errors.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg));
            break;
          }
          this.doc.directives.docEnd = true;
          const end = resolveEnd.resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError);
          this.decorate(this.doc, true);
          if (end.comment) {
            const dc = this.doc.comment;
            this.doc.comment = dc ? `${dc}
${end.comment}` : end.comment;
          }
          this.doc.range[2] = end.offset;
          break;
        }
        default:
          this.errors.push(new errors.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", `Unsupported token ${token.type}`));
      }
    }
    *end(forceDoc = false, endOffset = -1) {
      if (this.doc) {
        this.decorate(this.doc, true);
        yield this.doc;
        this.doc = null;
      } else if (forceDoc) {
        const opts = Object.assign({ _directives: this.directives }, this.options);
        const doc = new Document.Document(undefined, opts);
        if (this.atDirectives)
          this.onError(endOffset, "MISSING_CHAR", "Missing directives-end indicator line");
        doc.range = [0, endOffset, endOffset];
        this.decorate(doc, false);
        yield doc;
      }
    }
  }
  exports.Composer = Composer;
});

// node_modules/yaml/dist/parse/cst-scalar.js
var require_cst_scalar = __commonJS((exports) => {
  var resolveBlockScalar = require_resolve_block_scalar();
  var resolveFlowScalar = require_resolve_flow_scalar();
  var errors = require_errors();
  var stringifyString = require_stringifyString();
  function resolveAsScalar(token, strict = true, onError) {
    if (token) {
      const _onError = (pos, code, message) => {
        const offset = typeof pos === "number" ? pos : Array.isArray(pos) ? pos[0] : pos.offset;
        if (onError)
          onError(offset, code, message);
        else
          throw new errors.YAMLParseError([offset, offset + 1], code, message);
      };
      switch (token.type) {
        case "scalar":
        case "single-quoted-scalar":
        case "double-quoted-scalar":
          return resolveFlowScalar.resolveFlowScalar(token, strict, _onError);
        case "block-scalar":
          return resolveBlockScalar.resolveBlockScalar({ options: { strict } }, token, _onError);
      }
    }
    return null;
  }
  function createScalarToken(value, context) {
    const { implicitKey = false, indent, inFlow = false, offset = -1, type = "PLAIN" } = context;
    const source = stringifyString.stringifyString({ type, value }, {
      implicitKey,
      indent: indent > 0 ? " ".repeat(indent) : "",
      inFlow,
      options: { blockQuote: true, lineWidth: -1 }
    });
    const end = context.end ?? [
      { type: "newline", offset: -1, indent, source: `
` }
    ];
    switch (source[0]) {
      case "|":
      case ">": {
        const he = source.indexOf(`
`);
        const head = source.substring(0, he);
        const body = source.substring(he + 1) + `
`;
        const props = [
          { type: "block-scalar-header", offset, indent, source: head }
        ];
        if (!addEndtoBlockProps(props, end))
          props.push({ type: "newline", offset: -1, indent, source: `
` });
        return { type: "block-scalar", offset, indent, props, source: body };
      }
      case '"':
        return { type: "double-quoted-scalar", offset, indent, source, end };
      case "'":
        return { type: "single-quoted-scalar", offset, indent, source, end };
      default:
        return { type: "scalar", offset, indent, source, end };
    }
  }
  function setScalarValue(token, value, context = {}) {
    let { afterKey = false, implicitKey = false, inFlow = false, type } = context;
    let indent = "indent" in token ? token.indent : null;
    if (afterKey && typeof indent === "number")
      indent += 2;
    if (!type)
      switch (token.type) {
        case "single-quoted-scalar":
          type = "QUOTE_SINGLE";
          break;
        case "double-quoted-scalar":
          type = "QUOTE_DOUBLE";
          break;
        case "block-scalar": {
          const header = token.props[0];
          if (header.type !== "block-scalar-header")
            throw new Error("Invalid block scalar header");
          type = header.source[0] === ">" ? "BLOCK_FOLDED" : "BLOCK_LITERAL";
          break;
        }
        default:
          type = "PLAIN";
      }
    const source = stringifyString.stringifyString({ type, value }, {
      implicitKey: implicitKey || indent === null,
      indent: indent !== null && indent > 0 ? " ".repeat(indent) : "",
      inFlow,
      options: { blockQuote: true, lineWidth: -1 }
    });
    switch (source[0]) {
      case "|":
      case ">":
        setBlockScalarValue(token, source);
        break;
      case '"':
        setFlowScalarValue(token, source, "double-quoted-scalar");
        break;
      case "'":
        setFlowScalarValue(token, source, "single-quoted-scalar");
        break;
      default:
        setFlowScalarValue(token, source, "scalar");
    }
  }
  function setBlockScalarValue(token, source) {
    const he = source.indexOf(`
`);
    const head = source.substring(0, he);
    const body = source.substring(he + 1) + `
`;
    if (token.type === "block-scalar") {
      const header = token.props[0];
      if (header.type !== "block-scalar-header")
        throw new Error("Invalid block scalar header");
      header.source = head;
      token.source = body;
    } else {
      const { offset } = token;
      const indent = "indent" in token ? token.indent : -1;
      const props = [
        { type: "block-scalar-header", offset, indent, source: head }
      ];
      if (!addEndtoBlockProps(props, "end" in token ? token.end : undefined))
        props.push({ type: "newline", offset: -1, indent, source: `
` });
      for (const key of Object.keys(token))
        if (key !== "type" && key !== "offset")
          delete token[key];
      Object.assign(token, { type: "block-scalar", indent, props, source: body });
    }
  }
  function addEndtoBlockProps(props, end) {
    if (end)
      for (const st of end)
        switch (st.type) {
          case "space":
          case "comment":
            props.push(st);
            break;
          case "newline":
            props.push(st);
            return true;
        }
    return false;
  }
  function setFlowScalarValue(token, source, type) {
    switch (token.type) {
      case "scalar":
      case "double-quoted-scalar":
      case "single-quoted-scalar":
        token.type = type;
        token.source = source;
        break;
      case "block-scalar": {
        const end = token.props.slice(1);
        let oa = source.length;
        if (token.props[0].type === "block-scalar-header")
          oa -= token.props[0].source.length;
        for (const tok of end)
          tok.offset += oa;
        delete token.props;
        Object.assign(token, { type, source, end });
        break;
      }
      case "block-map":
      case "block-seq": {
        const offset = token.offset + source.length;
        const nl = { type: "newline", offset, indent: token.indent, source: `
` };
        delete token.items;
        Object.assign(token, { type, source, end: [nl] });
        break;
      }
      default: {
        const indent = "indent" in token ? token.indent : -1;
        const end = "end" in token && Array.isArray(token.end) ? token.end.filter((st) => st.type === "space" || st.type === "comment" || st.type === "newline") : [];
        for (const key of Object.keys(token))
          if (key !== "type" && key !== "offset")
            delete token[key];
        Object.assign(token, { type, indent, source, end });
      }
    }
  }
  exports.createScalarToken = createScalarToken;
  exports.resolveAsScalar = resolveAsScalar;
  exports.setScalarValue = setScalarValue;
});

// node_modules/yaml/dist/parse/cst-stringify.js
var require_cst_stringify = __commonJS((exports) => {
  var stringify = (cst) => ("type" in cst) ? stringifyToken(cst) : stringifyItem(cst);
  function stringifyToken(token) {
    switch (token.type) {
      case "block-scalar": {
        let res = "";
        for (const tok of token.props)
          res += stringifyToken(tok);
        return res + token.source;
      }
      case "block-map":
      case "block-seq": {
        let res = "";
        for (const item of token.items)
          res += stringifyItem(item);
        return res;
      }
      case "flow-collection": {
        let res = token.start.source;
        for (const item of token.items)
          res += stringifyItem(item);
        for (const st of token.end)
          res += st.source;
        return res;
      }
      case "document": {
        let res = stringifyItem(token);
        if (token.end)
          for (const st of token.end)
            res += st.source;
        return res;
      }
      default: {
        let res = token.source;
        if ("end" in token && token.end)
          for (const st of token.end)
            res += st.source;
        return res;
      }
    }
  }
  function stringifyItem({ start, key, sep, value }) {
    let res = "";
    for (const st of start)
      res += st.source;
    if (key)
      res += stringifyToken(key);
    if (sep)
      for (const st of sep)
        res += st.source;
    if (value)
      res += stringifyToken(value);
    return res;
  }
  exports.stringify = stringify;
});

// node_modules/yaml/dist/parse/cst-visit.js
var require_cst_visit = __commonJS((exports) => {
  var BREAK = Symbol("break visit");
  var SKIP = Symbol("skip children");
  var REMOVE = Symbol("remove item");
  function visit(cst, visitor) {
    if ("type" in cst && cst.type === "document")
      cst = { start: cst.start, value: cst.value };
    _visit(Object.freeze([]), cst, visitor);
  }
  visit.BREAK = BREAK;
  visit.SKIP = SKIP;
  visit.REMOVE = REMOVE;
  visit.itemAtPath = (cst, path) => {
    let item = cst;
    for (const [field, index] of path) {
      const tok = item?.[field];
      if (tok && "items" in tok) {
        item = tok.items[index];
      } else
        return;
    }
    return item;
  };
  visit.parentCollection = (cst, path) => {
    const parent = visit.itemAtPath(cst, path.slice(0, -1));
    const field = path[path.length - 1][0];
    const coll = parent?.[field];
    if (coll && "items" in coll)
      return coll;
    throw new Error("Parent collection not found");
  };
  function _visit(path, item, visitor) {
    let ctrl = visitor(item, path);
    if (typeof ctrl === "symbol")
      return ctrl;
    for (const field of ["key", "value"]) {
      const token = item[field];
      if (token && "items" in token) {
        for (let i = 0;i < token.items.length; ++i) {
          const ci = _visit(Object.freeze(path.concat([[field, i]])), token.items[i], visitor);
          if (typeof ci === "number")
            i = ci - 1;
          else if (ci === BREAK)
            return BREAK;
          else if (ci === REMOVE) {
            token.items.splice(i, 1);
            i -= 1;
          }
        }
        if (typeof ctrl === "function" && field === "key")
          ctrl = ctrl(item, path);
      }
    }
    return typeof ctrl === "function" ? ctrl(item, path) : ctrl;
  }
  exports.visit = visit;
});

// node_modules/yaml/dist/parse/cst.js
var require_cst = __commonJS((exports) => {
  var cstScalar = require_cst_scalar();
  var cstStringify = require_cst_stringify();
  var cstVisit = require_cst_visit();
  var BOM = "\uFEFF";
  var DOCUMENT = "\x02";
  var FLOW_END = "\x18";
  var SCALAR = "\x1F";
  var isCollection = (token) => !!token && ("items" in token);
  var isScalar = (token) => !!token && (token.type === "scalar" || token.type === "single-quoted-scalar" || token.type === "double-quoted-scalar" || token.type === "block-scalar");
  function prettyToken(token) {
    switch (token) {
      case BOM:
        return "<BOM>";
      case DOCUMENT:
        return "<DOC>";
      case FLOW_END:
        return "<FLOW_END>";
      case SCALAR:
        return "<SCALAR>";
      default:
        return JSON.stringify(token);
    }
  }
  function tokenType(source) {
    switch (source) {
      case BOM:
        return "byte-order-mark";
      case DOCUMENT:
        return "doc-mode";
      case FLOW_END:
        return "flow-error-end";
      case SCALAR:
        return "scalar";
      case "---":
        return "doc-start";
      case "...":
        return "doc-end";
      case "":
      case `
`:
      case `\r
`:
        return "newline";
      case "-":
        return "seq-item-ind";
      case "?":
        return "explicit-key-ind";
      case ":":
        return "map-value-ind";
      case "{":
        return "flow-map-start";
      case "}":
        return "flow-map-end";
      case "[":
        return "flow-seq-start";
      case "]":
        return "flow-seq-end";
      case ",":
        return "comma";
    }
    switch (source[0]) {
      case " ":
      case "\t":
        return "space";
      case "#":
        return "comment";
      case "%":
        return "directive-line";
      case "*":
        return "alias";
      case "&":
        return "anchor";
      case "!":
        return "tag";
      case "'":
        return "single-quoted-scalar";
      case '"':
        return "double-quoted-scalar";
      case "|":
      case ">":
        return "block-scalar-header";
    }
    return null;
  }
  exports.createScalarToken = cstScalar.createScalarToken;
  exports.resolveAsScalar = cstScalar.resolveAsScalar;
  exports.setScalarValue = cstScalar.setScalarValue;
  exports.stringify = cstStringify.stringify;
  exports.visit = cstVisit.visit;
  exports.BOM = BOM;
  exports.DOCUMENT = DOCUMENT;
  exports.FLOW_END = FLOW_END;
  exports.SCALAR = SCALAR;
  exports.isCollection = isCollection;
  exports.isScalar = isScalar;
  exports.prettyToken = prettyToken;
  exports.tokenType = tokenType;
});

// node_modules/yaml/dist/parse/lexer.js
var require_lexer = __commonJS((exports) => {
  var cst = require_cst();
  function isEmpty(ch) {
    switch (ch) {
      case undefined:
      case " ":
      case `
`:
      case "\r":
      case "\t":
        return true;
      default:
        return false;
    }
  }
  var hexDigits = new Set("0123456789ABCDEFabcdef");
  var tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()");
  var flowIndicatorChars = new Set(",[]{}");
  var invalidAnchorChars = new Set(` ,[]{}
\r	`);
  var isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch);

  class Lexer {
    constructor() {
      this.atEnd = false;
      this.blockScalarIndent = -1;
      this.blockScalarKeep = false;
      this.buffer = "";
      this.flowKey = false;
      this.flowLevel = 0;
      this.indentNext = 0;
      this.indentValue = 0;
      this.lineEndPos = null;
      this.next = null;
      this.pos = 0;
    }
    *lex(source, incomplete = false) {
      if (source) {
        if (typeof source !== "string")
          throw TypeError("source is not a string");
        this.buffer = this.buffer ? this.buffer + source : source;
        this.lineEndPos = null;
      }
      this.atEnd = !incomplete;
      let next = this.next ?? "stream";
      while (next && (incomplete || this.hasChars(1)))
        next = yield* this.parseNext(next);
    }
    atLineEnd() {
      let i = this.pos;
      let ch = this.buffer[i];
      while (ch === " " || ch === "\t")
        ch = this.buffer[++i];
      if (!ch || ch === "#" || ch === `
`)
        return true;
      if (ch === "\r")
        return this.buffer[i + 1] === `
`;
      return false;
    }
    charAt(n) {
      return this.buffer[this.pos + n];
    }
    continueScalar(offset) {
      let ch = this.buffer[offset];
      if (this.indentNext > 0) {
        let indent = 0;
        while (ch === " ")
          ch = this.buffer[++indent + offset];
        if (ch === "\r") {
          const next = this.buffer[indent + offset + 1];
          if (next === `
` || !next && !this.atEnd)
            return offset + indent + 1;
        }
        return ch === `
` || indent >= this.indentNext || !ch && !this.atEnd ? offset + indent : -1;
      }
      if (ch === "-" || ch === ".") {
        const dt = this.buffer.substr(offset, 3);
        if ((dt === "---" || dt === "...") && isEmpty(this.buffer[offset + 3]))
          return -1;
      }
      return offset;
    }
    getLine() {
      let end = this.lineEndPos;
      if (typeof end !== "number" || end !== -1 && end < this.pos) {
        end = this.buffer.indexOf(`
`, this.pos);
        this.lineEndPos = end;
      }
      if (end === -1)
        return this.atEnd ? this.buffer.substring(this.pos) : null;
      if (this.buffer[end - 1] === "\r")
        end -= 1;
      return this.buffer.substring(this.pos, end);
    }
    hasChars(n) {
      return this.pos + n <= this.buffer.length;
    }
    setNext(state) {
      this.buffer = this.buffer.substring(this.pos);
      this.pos = 0;
      this.lineEndPos = null;
      this.next = state;
      return null;
    }
    peek(n) {
      return this.buffer.substr(this.pos, n);
    }
    *parseNext(next) {
      switch (next) {
        case "stream":
          return yield* this.parseStream();
        case "line-start":
          return yield* this.parseLineStart();
        case "block-start":
          return yield* this.parseBlockStart();
        case "doc":
          return yield* this.parseDocument();
        case "flow":
          return yield* this.parseFlowCollection();
        case "quoted-scalar":
          return yield* this.parseQuotedScalar();
        case "block-scalar":
          return yield* this.parseBlockScalar();
        case "plain-scalar":
          return yield* this.parsePlainScalar();
      }
    }
    *parseStream() {
      let line = this.getLine();
      if (line === null)
        return this.setNext("stream");
      if (line[0] === cst.BOM) {
        yield* this.pushCount(1);
        line = line.substring(1);
      }
      if (line[0] === "%") {
        let dirEnd = line.length;
        let cs = line.indexOf("#");
        while (cs !== -1) {
          const ch = line[cs - 1];
          if (ch === " " || ch === "\t") {
            dirEnd = cs - 1;
            break;
          } else {
            cs = line.indexOf("#", cs + 1);
          }
        }
        while (true) {
          const ch = line[dirEnd - 1];
          if (ch === " " || ch === "\t")
            dirEnd -= 1;
          else
            break;
        }
        const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true));
        yield* this.pushCount(line.length - n);
        this.pushNewline();
        return "stream";
      }
      if (this.atLineEnd()) {
        const sp = yield* this.pushSpaces(true);
        yield* this.pushCount(line.length - sp);
        yield* this.pushNewline();
        return "stream";
      }
      yield cst.DOCUMENT;
      return yield* this.parseLineStart();
    }
    *parseLineStart() {
      const ch = this.charAt(0);
      if (!ch && !this.atEnd)
        return this.setNext("line-start");
      if (ch === "-" || ch === ".") {
        if (!this.atEnd && !this.hasChars(4))
          return this.setNext("line-start");
        const s = this.peek(3);
        if ((s === "---" || s === "...") && isEmpty(this.charAt(3))) {
          yield* this.pushCount(3);
          this.indentValue = 0;
          this.indentNext = 0;
          return s === "---" ? "doc" : "stream";
        }
      }
      this.indentValue = yield* this.pushSpaces(false);
      if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1)))
        this.indentNext = this.indentValue;
      return yield* this.parseBlockStart();
    }
    *parseBlockStart() {
      const [ch0, ch1] = this.peek(2);
      if (!ch1 && !this.atEnd)
        return this.setNext("block-start");
      if ((ch0 === "-" || ch0 === "?" || ch0 === ":") && isEmpty(ch1)) {
        const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true));
        this.indentNext = this.indentValue + 1;
        this.indentValue += n;
        return yield* this.parseBlockStart();
      }
      return "doc";
    }
    *parseDocument() {
      yield* this.pushSpaces(true);
      const line = this.getLine();
      if (line === null)
        return this.setNext("doc");
      let n = yield* this.pushIndicators();
      switch (line[n]) {
        case "#":
          yield* this.pushCount(line.length - n);
        case undefined:
          yield* this.pushNewline();
          return yield* this.parseLineStart();
        case "{":
        case "[":
          yield* this.pushCount(1);
          this.flowKey = false;
          this.flowLevel = 1;
          return "flow";
        case "}":
        case "]":
          yield* this.pushCount(1);
          return "doc";
        case "*":
          yield* this.pushUntil(isNotAnchorChar);
          return "doc";
        case '"':
        case "'":
          return yield* this.parseQuotedScalar();
        case "|":
        case ">":
          n += yield* this.parseBlockScalarHeader();
          n += yield* this.pushSpaces(true);
          yield* this.pushCount(line.length - n);
          yield* this.pushNewline();
          return yield* this.parseBlockScalar();
        default:
          return yield* this.parsePlainScalar();
      }
    }
    *parseFlowCollection() {
      let nl, sp;
      let indent = -1;
      do {
        nl = yield* this.pushNewline();
        if (nl > 0) {
          sp = yield* this.pushSpaces(false);
          this.indentValue = indent = sp;
        } else {
          sp = 0;
        }
        sp += yield* this.pushSpaces(true);
      } while (nl + sp > 0);
      const line = this.getLine();
      if (line === null)
        return this.setNext("flow");
      if (indent !== -1 && indent < this.indentNext && line[0] !== "#" || indent === 0 && (line.startsWith("---") || line.startsWith("...")) && isEmpty(line[3])) {
        const atFlowEndMarker = indent === this.indentNext - 1 && this.flowLevel === 1 && (line[0] === "]" || line[0] === "}");
        if (!atFlowEndMarker) {
          this.flowLevel = 0;
          yield cst.FLOW_END;
          return yield* this.parseLineStart();
        }
      }
      let n = 0;
      while (line[n] === ",") {
        n += yield* this.pushCount(1);
        n += yield* this.pushSpaces(true);
        this.flowKey = false;
      }
      n += yield* this.pushIndicators();
      switch (line[n]) {
        case undefined:
          return "flow";
        case "#":
          yield* this.pushCount(line.length - n);
          return "flow";
        case "{":
        case "[":
          yield* this.pushCount(1);
          this.flowKey = false;
          this.flowLevel += 1;
          return "flow";
        case "}":
        case "]":
          yield* this.pushCount(1);
          this.flowKey = true;
          this.flowLevel -= 1;
          return this.flowLevel ? "flow" : "doc";
        case "*":
          yield* this.pushUntil(isNotAnchorChar);
          return "flow";
        case '"':
        case "'":
          this.flowKey = true;
          return yield* this.parseQuotedScalar();
        case ":": {
          const next = this.charAt(1);
          if (this.flowKey || isEmpty(next) || next === ",") {
            this.flowKey = false;
            yield* this.pushCount(1);
            yield* this.pushSpaces(true);
            return "flow";
          }
        }
        default:
          this.flowKey = false;
          return yield* this.parsePlainScalar();
      }
    }
    *parseQuotedScalar() {
      const quote = this.charAt(0);
      let end = this.buffer.indexOf(quote, this.pos + 1);
      if (quote === "'") {
        while (end !== -1 && this.buffer[end + 1] === "'")
          end = this.buffer.indexOf("'", end + 2);
      } else {
        while (end !== -1) {
          let n = 0;
          while (this.buffer[end - 1 - n] === "\\")
            n += 1;
          if (n % 2 === 0)
            break;
          end = this.buffer.indexOf('"', end + 1);
        }
      }
      const qb = this.buffer.substring(0, end);
      let nl = qb.indexOf(`
`, this.pos);
      if (nl !== -1) {
        while (nl !== -1) {
          const cs = this.continueScalar(nl + 1);
          if (cs === -1)
            break;
          nl = qb.indexOf(`
`, cs);
        }
        if (nl !== -1) {
          end = nl - (qb[nl - 1] === "\r" ? 2 : 1);
        }
      }
      if (end === -1) {
        if (!this.atEnd)
          return this.setNext("quoted-scalar");
        end = this.buffer.length;
      }
      yield* this.pushToIndex(end + 1, false);
      return this.flowLevel ? "flow" : "doc";
    }
    *parseBlockScalarHeader() {
      this.blockScalarIndent = -1;
      this.blockScalarKeep = false;
      let i = this.pos;
      while (true) {
        const ch = this.buffer[++i];
        if (ch === "+")
          this.blockScalarKeep = true;
        else if (ch > "0" && ch <= "9")
          this.blockScalarIndent = Number(ch) - 1;
        else if (ch !== "-")
          break;
      }
      return yield* this.pushUntil((ch) => isEmpty(ch) || ch === "#");
    }
    *parseBlockScalar() {
      let nl = this.pos - 1;
      let indent = 0;
      let ch;
      loop:
        for (let i2 = this.pos;ch = this.buffer[i2]; ++i2) {
          switch (ch) {
            case " ":
              indent += 1;
              break;
            case `
`:
              nl = i2;
              indent = 0;
              break;
            case "\r": {
              const next = this.buffer[i2 + 1];
              if (!next && !this.atEnd)
                return this.setNext("block-scalar");
              if (next === `
`)
                break;
            }
            default:
              break loop;
          }
        }
      if (!ch && !this.atEnd)
        return this.setNext("block-scalar");
      if (indent >= this.indentNext) {
        if (this.blockScalarIndent === -1)
          this.indentNext = indent;
        else {
          this.indentNext = this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext);
        }
        do {
          const cs = this.continueScalar(nl + 1);
          if (cs === -1)
            break;
          nl = this.buffer.indexOf(`
`, cs);
        } while (nl !== -1);
        if (nl === -1) {
          if (!this.atEnd)
            return this.setNext("block-scalar");
          nl = this.buffer.length;
        }
      }
      let i = nl + 1;
      ch = this.buffer[i];
      while (ch === " ")
        ch = this.buffer[++i];
      if (ch === "\t") {
        while (ch === "\t" || ch === " " || ch === "\r" || ch === `
`)
          ch = this.buffer[++i];
        nl = i - 1;
      } else if (!this.blockScalarKeep) {
        do {
          let i2 = nl - 1;
          let ch2 = this.buffer[i2];
          if (ch2 === "\r")
            ch2 = this.buffer[--i2];
          const lastChar = i2;
          while (ch2 === " ")
            ch2 = this.buffer[--i2];
          if (ch2 === `
` && i2 >= this.pos && i2 + 1 + indent > lastChar)
            nl = i2;
          else
            break;
        } while (true);
      }
      yield cst.SCALAR;
      yield* this.pushToIndex(nl + 1, true);
      return yield* this.parseLineStart();
    }
    *parsePlainScalar() {
      const inFlow = this.flowLevel > 0;
      let end = this.pos - 1;
      let i = this.pos - 1;
      let ch;
      while (ch = this.buffer[++i]) {
        if (ch === ":") {
          const next = this.buffer[i + 1];
          if (isEmpty(next) || inFlow && flowIndicatorChars.has(next))
            break;
          end = i;
        } else if (isEmpty(ch)) {
          let next = this.buffer[i + 1];
          if (ch === "\r") {
            if (next === `
`) {
              i += 1;
              ch = `
`;
              next = this.buffer[i + 1];
            } else
              end = i;
          }
          if (next === "#" || inFlow && flowIndicatorChars.has(next))
            break;
          if (ch === `
`) {
            const cs = this.continueScalar(i + 1);
            if (cs === -1)
              break;
            i = Math.max(i, cs - 2);
          }
        } else {
          if (inFlow && flowIndicatorChars.has(ch))
            break;
          end = i;
        }
      }
      if (!ch && !this.atEnd)
        return this.setNext("plain-scalar");
      yield cst.SCALAR;
      yield* this.pushToIndex(end + 1, true);
      return inFlow ? "flow" : "doc";
    }
    *pushCount(n) {
      if (n > 0) {
        yield this.buffer.substr(this.pos, n);
        this.pos += n;
        return n;
      }
      return 0;
    }
    *pushToIndex(i, allowEmpty) {
      const s = this.buffer.slice(this.pos, i);
      if (s) {
        yield s;
        this.pos += s.length;
        return s.length;
      } else if (allowEmpty)
        yield "";
      return 0;
    }
    *pushIndicators() {
      switch (this.charAt(0)) {
        case "!":
          return (yield* this.pushTag()) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators());
        case "&":
          return (yield* this.pushUntil(isNotAnchorChar)) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators());
        case "-":
        case "?":
        case ":": {
          const inFlow = this.flowLevel > 0;
          const ch1 = this.charAt(1);
          if (isEmpty(ch1) || inFlow && flowIndicatorChars.has(ch1)) {
            if (!inFlow)
              this.indentNext = this.indentValue + 1;
            else if (this.flowKey)
              this.flowKey = false;
            return (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators());
          }
        }
      }
      return 0;
    }
    *pushTag() {
      if (this.charAt(1) === "<") {
        let i = this.pos + 2;
        let ch = this.buffer[i];
        while (!isEmpty(ch) && ch !== ">")
          ch = this.buffer[++i];
        return yield* this.pushToIndex(ch === ">" ? i + 1 : i, false);
      } else {
        let i = this.pos + 1;
        let ch = this.buffer[i];
        while (ch) {
          if (tagChars.has(ch))
            ch = this.buffer[++i];
          else if (ch === "%" && hexDigits.has(this.buffer[i + 1]) && hexDigits.has(this.buffer[i + 2])) {
            ch = this.buffer[i += 3];
          } else
            break;
        }
        return yield* this.pushToIndex(i, false);
      }
    }
    *pushNewline() {
      const ch = this.buffer[this.pos];
      if (ch === `
`)
        return yield* this.pushCount(1);
      else if (ch === "\r" && this.charAt(1) === `
`)
        return yield* this.pushCount(2);
      else
        return 0;
    }
    *pushSpaces(allowTabs) {
      let i = this.pos - 1;
      let ch;
      do {
        ch = this.buffer[++i];
      } while (ch === " " || allowTabs && ch === "\t");
      const n = i - this.pos;
      if (n > 0) {
        yield this.buffer.substr(this.pos, n);
        this.pos = i;
      }
      return n;
    }
    *pushUntil(test) {
      let i = this.pos;
      let ch = this.buffer[i];
      while (!test(ch))
        ch = this.buffer[++i];
      return yield* this.pushToIndex(i, false);
    }
  }
  exports.Lexer = Lexer;
});

// node_modules/yaml/dist/parse/line-counter.js
var require_line_counter = __commonJS((exports) => {
  class LineCounter {
    constructor() {
      this.lineStarts = [];
      this.addNewLine = (offset) => this.lineStarts.push(offset);
      this.linePos = (offset) => {
        let low = 0;
        let high = this.lineStarts.length;
        while (low < high) {
          const mid = low + high >> 1;
          if (this.lineStarts[mid] < offset)
            low = mid + 1;
          else
            high = mid;
        }
        if (this.lineStarts[low] === offset)
          return { line: low + 1, col: 1 };
        if (low === 0)
          return { line: 0, col: offset };
        const start = this.lineStarts[low - 1];
        return { line: low, col: offset - start + 1 };
      };
    }
  }
  exports.LineCounter = LineCounter;
});

// node_modules/yaml/dist/parse/parser.js
var require_parser = __commonJS((exports) => {
  var node_process = __require("process");
  var cst = require_cst();
  var lexer = require_lexer();
  function includesToken(list, type) {
    for (let i = 0;i < list.length; ++i)
      if (list[i].type === type)
        return true;
    return false;
  }
  function findNonEmptyIndex(list) {
    for (let i = 0;i < list.length; ++i) {
      switch (list[i].type) {
        case "space":
        case "comment":
        case "newline":
          break;
        default:
          return i;
      }
    }
    return -1;
  }
  function isFlowToken(token) {
    switch (token?.type) {
      case "alias":
      case "scalar":
      case "single-quoted-scalar":
      case "double-quoted-scalar":
      case "flow-collection":
        return true;
      default:
        return false;
    }
  }
  function getPrevProps(parent) {
    switch (parent.type) {
      case "document":
        return parent.start;
      case "block-map": {
        const it = parent.items[parent.items.length - 1];
        return it.sep ?? it.start;
      }
      case "block-seq":
        return parent.items[parent.items.length - 1].start;
      default:
        return [];
    }
  }
  function getFirstKeyStartProps(prev) {
    if (prev.length === 0)
      return [];
    let i = prev.length;
    loop:
      while (--i >= 0) {
        switch (prev[i].type) {
          case "doc-start":
          case "explicit-key-ind":
          case "map-value-ind":
          case "seq-item-ind":
          case "newline":
            break loop;
        }
      }
    while (prev[++i]?.type === "space") {}
    return prev.splice(i, prev.length);
  }
  function fixFlowSeqItems(fc) {
    if (fc.start.type === "flow-seq-start") {
      for (const it of fc.items) {
        if (it.sep && !it.value && !includesToken(it.start, "explicit-key-ind") && !includesToken(it.sep, "map-value-ind")) {
          if (it.key)
            it.value = it.key;
          delete it.key;
          if (isFlowToken(it.value)) {
            if (it.value.end)
              Array.prototype.push.apply(it.value.end, it.sep);
            else
              it.value.end = it.sep;
          } else
            Array.prototype.push.apply(it.start, it.sep);
          delete it.sep;
        }
      }
    }
  }

  class Parser {
    constructor(onNewLine) {
      this.atNewLine = true;
      this.atScalar = false;
      this.indent = 0;
      this.offset = 0;
      this.onKeyLine = false;
      this.stack = [];
      this.source = "";
      this.type = "";
      this.lexer = new lexer.Lexer;
      this.onNewLine = onNewLine;
    }
    *parse(source, incomplete = false) {
      if (this.onNewLine && this.offset === 0)
        this.onNewLine(0);
      for (const lexeme of this.lexer.lex(source, incomplete))
        yield* this.next(lexeme);
      if (!incomplete)
        yield* this.end();
    }
    *next(source) {
      this.source = source;
      if (node_process.env.LOG_TOKENS)
        console.log("|", cst.prettyToken(source));
      if (this.atScalar) {
        this.atScalar = false;
        yield* this.step();
        this.offset += source.length;
        return;
      }
      const type = cst.tokenType(source);
      if (!type) {
        const message = `Not a YAML token: ${source}`;
        yield* this.pop({ type: "error", offset: this.offset, message, source });
        this.offset += source.length;
      } else if (type === "scalar") {
        this.atNewLine = false;
        this.atScalar = true;
        this.type = "scalar";
      } else {
        this.type = type;
        yield* this.step();
        switch (type) {
          case "newline":
            this.atNewLine = true;
            this.indent = 0;
            if (this.onNewLine)
              this.onNewLine(this.offset + source.length);
            break;
          case "space":
            if (this.atNewLine && source[0] === " ")
              this.indent += source.length;
            break;
          case "explicit-key-ind":
          case "map-value-ind":
          case "seq-item-ind":
            if (this.atNewLine)
              this.indent += source.length;
            break;
          case "doc-mode":
          case "flow-error-end":
            return;
          default:
            this.atNewLine = false;
        }
        this.offset += source.length;
      }
    }
    *end() {
      while (this.stack.length > 0)
        yield* this.pop();
    }
    get sourceToken() {
      const st = {
        type: this.type,
        offset: this.offset,
        indent: this.indent,
        source: this.source
      };
      return st;
    }
    *step() {
      const top = this.peek(1);
      if (this.type === "doc-end" && top?.type !== "doc-end") {
        while (this.stack.length > 0)
          yield* this.pop();
        this.stack.push({
          type: "doc-end",
          offset: this.offset,
          source: this.source
        });
        return;
      }
      if (!top)
        return yield* this.stream();
      switch (top.type) {
        case "document":
          return yield* this.document(top);
        case "alias":
        case "scalar":
        case "single-quoted-scalar":
        case "double-quoted-scalar":
          return yield* this.scalar(top);
        case "block-scalar":
          return yield* this.blockScalar(top);
        case "block-map":
          return yield* this.blockMap(top);
        case "block-seq":
          return yield* this.blockSequence(top);
        case "flow-collection":
          return yield* this.flowCollection(top);
        case "doc-end":
          return yield* this.documentEnd(top);
      }
      yield* this.pop();
    }
    peek(n) {
      return this.stack[this.stack.length - n];
    }
    *pop(error) {
      const token = error ?? this.stack.pop();
      if (!token) {
        const message = "Tried to pop an empty stack";
        yield { type: "error", offset: this.offset, source: "", message };
      } else if (this.stack.length === 0) {
        yield token;
      } else {
        const top = this.peek(1);
        if (token.type === "block-scalar") {
          token.indent = "indent" in top ? top.indent : 0;
        } else if (token.type === "flow-collection" && top.type === "document") {
          token.indent = 0;
        }
        if (token.type === "flow-collection")
          fixFlowSeqItems(token);
        switch (top.type) {
          case "document":
            top.value = token;
            break;
          case "block-scalar":
            top.props.push(token);
            break;
          case "block-map": {
            const it = top.items[top.items.length - 1];
            if (it.value) {
              top.items.push({ start: [], key: token, sep: [] });
              this.onKeyLine = true;
              return;
            } else if (it.sep) {
              it.value = token;
            } else {
              Object.assign(it, { key: token, sep: [] });
              this.onKeyLine = !it.explicitKey;
              return;
            }
            break;
          }
          case "block-seq": {
            const it = top.items[top.items.length - 1];
            if (it.value)
              top.items.push({ start: [], value: token });
            else
              it.value = token;
            break;
          }
          case "flow-collection": {
            const it = top.items[top.items.length - 1];
            if (!it || it.value)
              top.items.push({ start: [], key: token, sep: [] });
            else if (it.sep)
              it.value = token;
            else
              Object.assign(it, { key: token, sep: [] });
            return;
          }
          default:
            yield* this.pop();
            yield* this.pop(token);
        }
        if ((top.type === "document" || top.type === "block-map" || top.type === "block-seq") && (token.type === "block-map" || token.type === "block-seq")) {
          const last = token.items[token.items.length - 1];
          if (last && !last.sep && !last.value && last.start.length > 0 && findNonEmptyIndex(last.start) === -1 && (token.indent === 0 || last.start.every((st) => st.type !== "comment" || st.indent < token.indent))) {
            if (top.type === "document")
              top.end = last.start;
            else
              top.items.push({ start: last.start });
            token.items.splice(-1, 1);
          }
        }
      }
    }
    *stream() {
      switch (this.type) {
        case "directive-line":
          yield { type: "directive", offset: this.offset, source: this.source };
          return;
        case "byte-order-mark":
        case "space":
        case "comment":
        case "newline":
          yield this.sourceToken;
          return;
        case "doc-mode":
        case "doc-start": {
          const doc = {
            type: "document",
            offset: this.offset,
            start: []
          };
          if (this.type === "doc-start")
            doc.start.push(this.sourceToken);
          this.stack.push(doc);
          return;
        }
      }
      yield {
        type: "error",
        offset: this.offset,
        message: `Unexpected ${this.type} token in YAML stream`,
        source: this.source
      };
    }
    *document(doc) {
      if (doc.value)
        return yield* this.lineEnd(doc);
      switch (this.type) {
        case "doc-start": {
          if (findNonEmptyIndex(doc.start) !== -1) {
            yield* this.pop();
            yield* this.step();
          } else
            doc.start.push(this.sourceToken);
          return;
        }
        case "anchor":
        case "tag":
        case "space":
        case "comment":
        case "newline":
          doc.start.push(this.sourceToken);
          return;
      }
      const bv = this.startBlockValue(doc);
      if (bv)
        this.stack.push(bv);
      else {
        yield {
          type: "error",
          offset: this.offset,
          message: `Unexpected ${this.type} token in YAML document`,
          source: this.source
        };
      }
    }
    *scalar(scalar) {
      if (this.type === "map-value-ind") {
        const prev = getPrevProps(this.peek(2));
        const start = getFirstKeyStartProps(prev);
        let sep;
        if (scalar.end) {
          sep = scalar.end;
          sep.push(this.sourceToken);
          delete scalar.end;
        } else
          sep = [this.sourceToken];
        const map = {
          type: "block-map",
          offset: scalar.offset,
          indent: scalar.indent,
          items: [{ start, key: scalar, sep }]
        };
        this.onKeyLine = true;
        this.stack[this.stack.length - 1] = map;
      } else
        yield* this.lineEnd(scalar);
    }
    *blockScalar(scalar) {
      switch (this.type) {
        case "space":
        case "comment":
        case "newline":
          scalar.props.push(this.sourceToken);
          return;
        case "scalar":
          scalar.source = this.source;
          this.atNewLine = true;
          this.indent = 0;
          if (this.onNewLine) {
            let nl = this.source.indexOf(`
`) + 1;
            while (nl !== 0) {
              this.onNewLine(this.offset + nl);
              nl = this.source.indexOf(`
`, nl) + 1;
            }
          }
          yield* this.pop();
          break;
        default:
          yield* this.pop();
          yield* this.step();
      }
    }
    *blockMap(map) {
      const it = map.items[map.items.length - 1];
      switch (this.type) {
        case "newline":
          this.onKeyLine = false;
          if (it.value) {
            const end = "end" in it.value ? it.value.end : undefined;
            const last = Array.isArray(end) ? end[end.length - 1] : undefined;
            if (last?.type === "comment")
              end?.push(this.sourceToken);
            else
              map.items.push({ start: [this.sourceToken] });
          } else if (it.sep) {
            it.sep.push(this.sourceToken);
          } else {
            it.start.push(this.sourceToken);
          }
          return;
        case "space":
        case "comment":
          if (it.value) {
            map.items.push({ start: [this.sourceToken] });
          } else if (it.sep) {
            it.sep.push(this.sourceToken);
          } else {
            if (this.atIndentedComment(it.start, map.indent)) {
              const prev = map.items[map.items.length - 2];
              const end = prev?.value?.end;
              if (Array.isArray(end)) {
                Array.prototype.push.apply(end, it.start);
                end.push(this.sourceToken);
                map.items.pop();
                return;
              }
            }
            it.start.push(this.sourceToken);
          }
          return;
      }
      if (this.indent >= map.indent) {
        const atMapIndent = !this.onKeyLine && this.indent === map.indent;
        const atNextItem = atMapIndent && (it.sep || it.explicitKey) && this.type !== "seq-item-ind";
        let start = [];
        if (atNextItem && it.sep && !it.value) {
          const nl = [];
          for (let i = 0;i < it.sep.length; ++i) {
            const st = it.sep[i];
            switch (st.type) {
              case "newline":
                nl.push(i);
                break;
              case "space":
                break;
              case "comment":
                if (st.indent > map.indent)
                  nl.length = 0;
                break;
              default:
                nl.length = 0;
            }
          }
          if (nl.length >= 2)
            start = it.sep.splice(nl[1]);
        }
        switch (this.type) {
          case "anchor":
          case "tag":
            if (atNextItem || it.value) {
              start.push(this.sourceToken);
              map.items.push({ start });
              this.onKeyLine = true;
            } else if (it.sep) {
              it.sep.push(this.sourceToken);
            } else {
              it.start.push(this.sourceToken);
            }
            return;
          case "explicit-key-ind":
            if (!it.sep && !it.explicitKey) {
              it.start.push(this.sourceToken);
              it.explicitKey = true;
            } else if (atNextItem || it.value) {
              start.push(this.sourceToken);
              map.items.push({ start, explicitKey: true });
            } else {
              this.stack.push({
                type: "block-map",
                offset: this.offset,
                indent: this.indent,
                items: [{ start: [this.sourceToken], explicitKey: true }]
              });
            }
            this.onKeyLine = true;
            return;
          case "map-value-ind":
            if (it.explicitKey) {
              if (!it.sep) {
                if (includesToken(it.start, "newline")) {
                  Object.assign(it, { key: null, sep: [this.sourceToken] });
                } else {
                  const start2 = getFirstKeyStartProps(it.start);
                  this.stack.push({
                    type: "block-map",
                    offset: this.offset,
                    indent: this.indent,
                    items: [{ start: start2, key: null, sep: [this.sourceToken] }]
                  });
                }
              } else if (it.value) {
                map.items.push({ start: [], key: null, sep: [this.sourceToken] });
              } else if (includesToken(it.sep, "map-value-ind")) {
                this.stack.push({
                  type: "block-map",
                  offset: this.offset,
                  indent: this.indent,
                  items: [{ start, key: null, sep: [this.sourceToken] }]
                });
              } else if (isFlowToken(it.key) && !includesToken(it.sep, "newline")) {
                const start2 = getFirstKeyStartProps(it.start);
                const key = it.key;
                const sep = it.sep;
                sep.push(this.sourceToken);
                delete it.key;
                delete it.sep;
                this.stack.push({
                  type: "block-map",
                  offset: this.offset,
                  indent: this.indent,
                  items: [{ start: start2, key, sep }]
                });
              } else if (start.length > 0) {
                it.sep = it.sep.concat(start, this.sourceToken);
              } else {
                it.sep.push(this.sourceToken);
              }
            } else {
              if (!it.sep) {
                Object.assign(it, { key: null, sep: [this.sourceToken] });
              } else if (it.value || atNextItem) {
                map.items.push({ start, key: null, sep: [this.sourceToken] });
              } else if (includesToken(it.sep, "map-value-ind")) {
                this.stack.push({
                  type: "block-map",
                  offset: this.offset,
                  indent: this.indent,
                  items: [{ start: [], key: null, sep: [this.sourceToken] }]
                });
              } else {
                it.sep.push(this.sourceToken);
              }
            }
            this.onKeyLine = true;
            return;
          case "alias":
          case "scalar":
          case "single-quoted-scalar":
          case "double-quoted-scalar": {
            const fs = this.flowScalar(this.type);
            if (atNextItem || it.value) {
              map.items.push({ start, key: fs, sep: [] });
              this.onKeyLine = true;
            } else if (it.sep) {
              this.stack.push(fs);
            } else {
              Object.assign(it, { key: fs, sep: [] });
              this.onKeyLine = true;
            }
            return;
          }
          default: {
            const bv = this.startBlockValue(map);
            if (bv) {
              if (bv.type === "block-seq") {
                if (!it.explicitKey && it.sep && !includesToken(it.sep, "newline")) {
                  yield* this.pop({
                    type: "error",
                    offset: this.offset,
                    message: "Unexpected block-seq-ind on same line with key",
                    source: this.source
                  });
                  return;
                }
              } else if (atMapIndent) {
                map.items.push({ start });
              }
              this.stack.push(bv);
              return;
            }
          }
        }
      }
      yield* this.pop();
      yield* this.step();
    }
    *blockSequence(seq) {
      const it = seq.items[seq.items.length - 1];
      switch (this.type) {
        case "newline":
          if (it.value) {
            const end = "end" in it.value ? it.value.end : undefined;
            const last = Array.isArray(end) ? end[end.length - 1] : undefined;
            if (last?.type === "comment")
              end?.push(this.sourceToken);
            else
              seq.items.push({ start: [this.sourceToken] });
          } else
            it.start.push(this.sourceToken);
          return;
        case "space":
        case "comment":
          if (it.value)
            seq.items.push({ start: [this.sourceToken] });
          else {
            if (this.atIndentedComment(it.start, seq.indent)) {
              const prev = seq.items[seq.items.length - 2];
              const end = prev?.value?.end;
              if (Array.isArray(end)) {
                Array.prototype.push.apply(end, it.start);
                end.push(this.sourceToken);
                seq.items.pop();
                return;
              }
            }
            it.start.push(this.sourceToken);
          }
          return;
        case "anchor":
        case "tag":
          if (it.value || this.indent <= seq.indent)
            break;
          it.start.push(this.sourceToken);
          return;
        case "seq-item-ind":
          if (this.indent !== seq.indent)
            break;
          if (it.value || includesToken(it.start, "seq-item-ind"))
            seq.items.push({ start: [this.sourceToken] });
          else
            it.start.push(this.sourceToken);
          return;
      }
      if (this.indent > seq.indent) {
        const bv = this.startBlockValue(seq);
        if (bv) {
          this.stack.push(bv);
          return;
        }
      }
      yield* this.pop();
      yield* this.step();
    }
    *flowCollection(fc) {
      const it = fc.items[fc.items.length - 1];
      if (this.type === "flow-error-end") {
        let top;
        do {
          yield* this.pop();
          top = this.peek(1);
        } while (top?.type === "flow-collection");
      } else if (fc.end.length === 0) {
        switch (this.type) {
          case "comma":
          case "explicit-key-ind":
            if (!it || it.sep)
              fc.items.push({ start: [this.sourceToken] });
            else
              it.start.push(this.sourceToken);
            return;
          case "map-value-ind":
            if (!it || it.value)
              fc.items.push({ start: [], key: null, sep: [this.sourceToken] });
            else if (it.sep)
              it.sep.push(this.sourceToken);
            else
              Object.assign(it, { key: null, sep: [this.sourceToken] });
            return;
          case "space":
          case "comment":
          case "newline":
          case "anchor":
          case "tag":
            if (!it || it.value)
              fc.items.push({ start: [this.sourceToken] });
            else if (it.sep)
              it.sep.push(this.sourceToken);
            else
              it.start.push(this.sourceToken);
            return;
          case "alias":
          case "scalar":
          case "single-quoted-scalar":
          case "double-quoted-scalar": {
            const fs = this.flowScalar(this.type);
            if (!it || it.value)
              fc.items.push({ start: [], key: fs, sep: [] });
            else if (it.sep)
              this.stack.push(fs);
            else
              Object.assign(it, { key: fs, sep: [] });
            return;
          }
          case "flow-map-end":
          case "flow-seq-end":
            fc.end.push(this.sourceToken);
            return;
        }
        const bv = this.startBlockValue(fc);
        if (bv)
          this.stack.push(bv);
        else {
          yield* this.pop();
          yield* this.step();
        }
      } else {
        const parent = this.peek(2);
        if (parent.type === "block-map" && (this.type === "map-value-ind" && parent.indent === fc.indent || this.type === "newline" && !parent.items[parent.items.length - 1].sep)) {
          yield* this.pop();
          yield* this.step();
        } else if (this.type === "map-value-ind" && parent.type !== "flow-collection") {
          const prev = getPrevProps(parent);
          const start = getFirstKeyStartProps(prev);
          fixFlowSeqItems(fc);
          const sep = fc.end.splice(1, fc.end.length);
          sep.push(this.sourceToken);
          const map = {
            type: "block-map",
            offset: fc.offset,
            indent: fc.indent,
            items: [{ start, key: fc, sep }]
          };
          this.onKeyLine = true;
          this.stack[this.stack.length - 1] = map;
        } else {
          yield* this.lineEnd(fc);
        }
      }
    }
    flowScalar(type) {
      if (this.onNewLine) {
        let nl = this.source.indexOf(`
`) + 1;
        while (nl !== 0) {
          this.onNewLine(this.offset + nl);
          nl = this.source.indexOf(`
`, nl) + 1;
        }
      }
      return {
        type,
        offset: this.offset,
        indent: this.indent,
        source: this.source
      };
    }
    startBlockValue(parent) {
      switch (this.type) {
        case "alias":
        case "scalar":
        case "single-quoted-scalar":
        case "double-quoted-scalar":
          return this.flowScalar(this.type);
        case "block-scalar-header":
          return {
            type: "block-scalar",
            offset: this.offset,
            indent: this.indent,
            props: [this.sourceToken],
            source: ""
          };
        case "flow-map-start":
        case "flow-seq-start":
          return {
            type: "flow-collection",
            offset: this.offset,
            indent: this.indent,
            start: this.sourceToken,
            items: [],
            end: []
          };
        case "seq-item-ind":
          return {
            type: "block-seq",
            offset: this.offset,
            indent: this.indent,
            items: [{ start: [this.sourceToken] }]
          };
        case "explicit-key-ind": {
          this.onKeyLine = true;
          const prev = getPrevProps(parent);
          const start = getFirstKeyStartProps(prev);
          start.push(this.sourceToken);
          return {
            type: "block-map",
            offset: this.offset,
            indent: this.indent,
            items: [{ start, explicitKey: true }]
          };
        }
        case "map-value-ind": {
          this.onKeyLine = true;
          const prev = getPrevProps(parent);
          const start = getFirstKeyStartProps(prev);
          return {
            type: "block-map",
            offset: this.offset,
            indent: this.indent,
            items: [{ start, key: null, sep: [this.sourceToken] }]
          };
        }
      }
      return null;
    }
    atIndentedComment(start, indent) {
      if (this.type !== "comment")
        return false;
      if (this.indent <= indent)
        return false;
      return start.every((st) => st.type === "newline" || st.type === "space");
    }
    *documentEnd(docEnd) {
      if (this.type !== "doc-mode") {
        if (docEnd.end)
          docEnd.end.push(this.sourceToken);
        else
          docEnd.end = [this.sourceToken];
        if (this.type === "newline")
          yield* this.pop();
      }
    }
    *lineEnd(token) {
      switch (this.type) {
        case "comma":
        case "doc-start":
        case "doc-end":
        case "flow-seq-end":
        case "flow-map-end":
        case "map-value-ind":
          yield* this.pop();
          yield* this.step();
          break;
        case "newline":
          this.onKeyLine = false;
        case "space":
        case "comment":
        default:
          if (token.end)
            token.end.push(this.sourceToken);
          else
            token.end = [this.sourceToken];
          if (this.type === "newline")
            yield* this.pop();
      }
    }
  }
  exports.Parser = Parser;
});

// node_modules/yaml/dist/public-api.js
var require_public_api = __commonJS((exports) => {
  var composer = require_composer();
  var Document = require_Document();
  var errors = require_errors();
  var log = require_log();
  var identity = require_identity();
  var lineCounter = require_line_counter();
  var parser = require_parser();
  function parseOptions(options) {
    const prettyErrors = options.prettyErrors !== false;
    const lineCounter$1 = options.lineCounter || prettyErrors && new lineCounter.LineCounter || null;
    return { lineCounter: lineCounter$1, prettyErrors };
  }
  function parseAllDocuments(source, options = {}) {
    const { lineCounter: lineCounter2, prettyErrors } = parseOptions(options);
    const parser$1 = new parser.Parser(lineCounter2?.addNewLine);
    const composer$1 = new composer.Composer(options);
    const docs = Array.from(composer$1.compose(parser$1.parse(source)));
    if (prettyErrors && lineCounter2)
      for (const doc of docs) {
        doc.errors.forEach(errors.prettifyError(source, lineCounter2));
        doc.warnings.forEach(errors.prettifyError(source, lineCounter2));
      }
    if (docs.length > 0)
      return docs;
    return Object.assign([], { empty: true }, composer$1.streamInfo());
  }
  function parseDocument(source, options = {}) {
    const { lineCounter: lineCounter2, prettyErrors } = parseOptions(options);
    const parser$1 = new parser.Parser(lineCounter2?.addNewLine);
    const composer$1 = new composer.Composer(options);
    let doc = null;
    for (const _doc of composer$1.compose(parser$1.parse(source), true, source.length)) {
      if (!doc)
        doc = _doc;
      else if (doc.options.logLevel !== "silent") {
        doc.errors.push(new errors.YAMLParseError(_doc.range.slice(0, 2), "MULTIPLE_DOCS", "Source contains multiple documents; please use YAML.parseAllDocuments()"));
        break;
      }
    }
    if (prettyErrors && lineCounter2) {
      doc.errors.forEach(errors.prettifyError(source, lineCounter2));
      doc.warnings.forEach(errors.prettifyError(source, lineCounter2));
    }
    return doc;
  }
  function parse(src, reviver, options) {
    let _reviver = undefined;
    if (typeof reviver === "function") {
      _reviver = reviver;
    } else if (options === undefined && reviver && typeof reviver === "object") {
      options = reviver;
    }
    const doc = parseDocument(src, options);
    if (!doc)
      return null;
    doc.warnings.forEach((warning) => log.warn(doc.options.logLevel, warning));
    if (doc.errors.length > 0) {
      if (doc.options.logLevel !== "silent")
        throw doc.errors[0];
      else
        doc.errors = [];
    }
    return doc.toJS(Object.assign({ reviver: _reviver }, options));
  }
  function stringify(value, replacer, options) {
    let _replacer = null;
    if (typeof replacer === "function" || Array.isArray(replacer)) {
      _replacer = replacer;
    } else if (options === undefined && replacer) {
      options = replacer;
    }
    if (typeof options === "string")
      options = options.length;
    if (typeof options === "number") {
      const indent = Math.round(options);
      options = indent < 1 ? undefined : indent > 8 ? { indent: 8 } : { indent };
    }
    if (value === undefined) {
      const { keepUndefined } = options ?? replacer ?? {};
      if (!keepUndefined)
        return;
    }
    if (identity.isDocument(value) && !_replacer)
      return value.toString(options);
    return new Document.Document(value, _replacer, options).toString(options);
  }
  exports.parse = parse;
  exports.parseAllDocuments = parseAllDocuments;
  exports.parseDocument = parseDocument;
  exports.stringify = stringify;
});

// node_modules/semver/internal/constants.js
var require_constants = __commonJS((exports, module) => {
  var SEMVER_SPEC_VERSION = "2.0.0";
  var MAX_LENGTH = 256;
  var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
  var MAX_SAFE_COMPONENT_LENGTH = 16;
  var MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6;
  var RELEASE_TYPES = [
    "major",
    "premajor",
    "minor",
    "preminor",
    "patch",
    "prepatch",
    "prerelease"
  ];
  module.exports = {
    MAX_LENGTH,
    MAX_SAFE_COMPONENT_LENGTH,
    MAX_SAFE_BUILD_LENGTH,
    MAX_SAFE_INTEGER,
    RELEASE_TYPES,
    SEMVER_SPEC_VERSION,
    FLAG_INCLUDE_PRERELEASE: 1,
    FLAG_LOOSE: 2
  };
});

// node_modules/semver/internal/debug.js
var require_debug = __commonJS((exports, module) => {
  var debug = typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error("SEMVER", ...args) : () => {};
  module.exports = debug;
});

// node_modules/semver/internal/re.js
var require_re = __commonJS((exports, module) => {
  var {
    MAX_SAFE_COMPONENT_LENGTH,
    MAX_SAFE_BUILD_LENGTH,
    MAX_LENGTH
  } = require_constants();
  var debug = require_debug();
  exports = module.exports = {};
  var re = exports.re = [];
  var safeRe = exports.safeRe = [];
  var src = exports.src = [];
  var safeSrc = exports.safeSrc = [];
  var t = exports.t = {};
  var R = 0;
  var LETTERDASHNUMBER = "[a-zA-Z0-9-]";
  var safeRegexReplacements = [
    ["\\s", 1],
    ["\\d", MAX_LENGTH],
    [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH]
  ];
  var makeSafeRegex = (value) => {
    for (const [token, max] of safeRegexReplacements) {
      value = value.split(`${token}*`).join(`${token}{0,${max}}`).split(`${token}+`).join(`${token}{1,${max}}`);
    }
    return value;
  };
  var createToken = (name, value, isGlobal) => {
    const safe = makeSafeRegex(value);
    const index = R++;
    debug(name, index, value);
    t[name] = index;
    src[index] = value;
    safeSrc[index] = safe;
    re[index] = new RegExp(value, isGlobal ? "g" : undefined);
    safeRe[index] = new RegExp(safe, isGlobal ? "g" : undefined);
  };
  createToken("NUMERICIDENTIFIER", "0|[1-9]\\d*");
  createToken("NUMERICIDENTIFIERLOOSE", "\\d+");
  createToken("NONNUMERICIDENTIFIER", `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`);
  createToken("MAINVERSION", `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})`);
  createToken("MAINVERSIONLOOSE", `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})`);
  createToken("PRERELEASEIDENTIFIER", `(?:${src[t.NONNUMERICIDENTIFIER]}|${src[t.NUMERICIDENTIFIER]})`);
  createToken("PRERELEASEIDENTIFIERLOOSE", `(?:${src[t.NONNUMERICIDENTIFIER]}|${src[t.NUMERICIDENTIFIERLOOSE]})`);
  createToken("PRERELEASE", `(?:-(${src[t.PRERELEASEIDENTIFIER]}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`);
  createToken("PRERELEASELOOSE", `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`);
  createToken("BUILDIDENTIFIER", `${LETTERDASHNUMBER}+`);
  createToken("BUILD", `(?:\\+(${src[t.BUILDIDENTIFIER]}(?:\\.${src[t.BUILDIDENTIFIER]})*))`);
  createToken("FULLPLAIN", `v?${src[t.MAINVERSION]}${src[t.PRERELEASE]}?${src[t.BUILD]}?`);
  createToken("FULL", `^${src[t.FULLPLAIN]}$`);
  createToken("LOOSEPLAIN", `[v=\\s]*${src[t.MAINVERSIONLOOSE]}${src[t.PRERELEASELOOSE]}?${src[t.BUILD]}?`);
  createToken("LOOSE", `^${src[t.LOOSEPLAIN]}$`);
  createToken("GTLT", "((?:<|>)?=?)");
  createToken("XRANGEIDENTIFIERLOOSE", `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);
  createToken("XRANGEIDENTIFIER", `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`);
  createToken("XRANGEPLAIN", `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:${src[t.PRERELEASE]})?${src[t.BUILD]}?` + `)?)?`);
  createToken("XRANGEPLAINLOOSE", `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:${src[t.PRERELEASELOOSE]})?${src[t.BUILD]}?` + `)?)?`);
  createToken("XRANGE", `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`);
  createToken("XRANGELOOSE", `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`);
  createToken("COERCEPLAIN", `${"(^|[^\\d])" + "(\\d{1,"}${MAX_SAFE_COMPONENT_LENGTH}})` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`);
  createToken("COERCE", `${src[t.COERCEPLAIN]}(?:$|[^\\d])`);
  createToken("COERCEFULL", src[t.COERCEPLAIN] + `(?:${src[t.PRERELEASE]})?` + `(?:${src[t.BUILD]})?` + `(?:$|[^\\d])`);
  createToken("COERCERTL", src[t.COERCE], true);
  createToken("COERCERTLFULL", src[t.COERCEFULL], true);
  createToken("LONETILDE", "(?:~>?)");
  createToken("TILDETRIM", `(\\s*)${src[t.LONETILDE]}\\s+`, true);
  exports.tildeTrimReplace = "$1~";
  createToken("TILDE", `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`);
  createToken("TILDELOOSE", `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`);
  createToken("LONECARET", "(?:\\^)");
  createToken("CARETTRIM", `(\\s*)${src[t.LONECARET]}\\s+`, true);
  exports.caretTrimReplace = "$1^";
  createToken("CARET", `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`);
  createToken("CARETLOOSE", `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`);
  createToken("COMPARATORLOOSE", `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`);
  createToken("COMPARATOR", `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`);
  createToken("COMPARATORTRIM", `(\\s*)${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true);
  exports.comparatorTrimReplace = "$1$2$3";
  createToken("HYPHENRANGE", `^\\s*(${src[t.XRANGEPLAIN]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAIN]})` + `\\s*$`);
  createToken("HYPHENRANGELOOSE", `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAINLOOSE]})` + `\\s*$`);
  createToken("STAR", "(<|>)?=?\\s*\\*");
  createToken("GTE0", "^\\s*>=\\s*0\\.0\\.0\\s*$");
  createToken("GTE0PRE", "^\\s*>=\\s*0\\.0\\.0-0\\s*$");
});

// node_modules/semver/internal/parse-options.js
var require_parse_options = __commonJS((exports, module) => {
  var looseOption = Object.freeze({ loose: true });
  var emptyOpts = Object.freeze({});
  var parseOptions = (options) => {
    if (!options) {
      return emptyOpts;
    }
    if (typeof options !== "object") {
      return looseOption;
    }
    return options;
  };
  module.exports = parseOptions;
});

// node_modules/semver/internal/identifiers.js
var require_identifiers = __commonJS((exports, module) => {
  var numeric = /^[0-9]+$/;
  var compareIdentifiers = (a, b) => {
    if (typeof a === "number" && typeof b === "number") {
      return a === b ? 0 : a < b ? -1 : 1;
    }
    const anum = numeric.test(a);
    const bnum = numeric.test(b);
    if (anum && bnum) {
      a = +a;
      b = +b;
    }
    return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1;
  };
  var rcompareIdentifiers = (a, b) => compareIdentifiers(b, a);
  module.exports = {
    compareIdentifiers,
    rcompareIdentifiers
  };
});

// node_modules/semver/classes/semver.js
var require_semver = __commonJS((exports, module) => {
  var debug = require_debug();
  var { MAX_LENGTH, MAX_SAFE_INTEGER } = require_constants();
  var { safeRe: re, t } = require_re();
  var parseOptions = require_parse_options();
  var { compareIdentifiers } = require_identifiers();

  class SemVer {
    constructor(version, options) {
      options = parseOptions(options);
      if (version instanceof SemVer) {
        if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) {
          return version;
        } else {
          version = version.version;
        }
      } else if (typeof version !== "string") {
        throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`);
      }
      if (version.length > MAX_LENGTH) {
        throw new TypeError(`version is longer than ${MAX_LENGTH} characters`);
      }
      debug("SemVer", version, options);
      this.options = options;
      this.loose = !!options.loose;
      this.includePrerelease = !!options.includePrerelease;
      const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]);
      if (!m) {
        throw new TypeError(`Invalid Version: ${version}`);
      }
      this.raw = version;
      this.major = +m[1];
      this.minor = +m[2];
      this.patch = +m[3];
      if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
        throw new TypeError("Invalid major version");
      }
      if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
        throw new TypeError("Invalid minor version");
      }
      if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
        throw new TypeError("Invalid patch version");
      }
      if (!m[4]) {
        this.prerelease = [];
      } else {
        this.prerelease = m[4].split(".").map((id) => {
          if (/^[0-9]+$/.test(id)) {
            const num2 = +id;
            if (num2 >= 0 && num2 < MAX_SAFE_INTEGER) {
              return num2;
            }
          }
          return id;
        });
      }
      this.build = m[5] ? m[5].split(".") : [];
      this.format();
    }
    format() {
      this.version = `${this.major}.${this.minor}.${this.patch}`;
      if (this.prerelease.length) {
        this.version += `-${this.prerelease.join(".")}`;
      }
      return this.version;
    }
    toString() {
      return this.version;
    }
    compare(other) {
      debug("SemVer.compare", this.version, this.options, other);
      if (!(other instanceof SemVer)) {
        if (typeof other === "string" && other === this.version) {
          return 0;
        }
        other = new SemVer(other, this.options);
      }
      if (other.version === this.version) {
        return 0;
      }
      return this.compareMain(other) || this.comparePre(other);
    }
    compareMain(other) {
      if (!(other instanceof SemVer)) {
        other = new SemVer(other, this.options);
      }
      if (this.major < other.major) {
        return -1;
      }
      if (this.major > other.major) {
        return 1;
      }
      if (this.minor < other.minor) {
        return -1;
      }
      if (this.minor > other.minor) {
        return 1;
      }
      if (this.patch < other.patch) {
        return -1;
      }
      if (this.patch > other.patch) {
        return 1;
      }
      return 0;
    }
    comparePre(other) {
      if (!(other instanceof SemVer)) {
        other = new SemVer(other, this.options);
      }
      if (this.prerelease.length && !other.prerelease.length) {
        return -1;
      } else if (!this.prerelease.length && other.prerelease.length) {
        return 1;
      } else if (!this.prerelease.length && !other.prerelease.length) {
        return 0;
      }
      let i = 0;
      do {
        const a = this.prerelease[i];
        const b = other.prerelease[i];
        debug("prerelease compare", i, a, b);
        if (a === undefined && b === undefined) {
          return 0;
        } else if (b === undefined) {
          return 1;
        } else if (a === undefined) {
          return -1;
        } else if (a === b) {
          continue;
        } else {
          return compareIdentifiers(a, b);
        }
      } while (++i);
    }
    compareBuild(other) {
      if (!(other instanceof SemVer)) {
        other = new SemVer(other, this.options);
      }
      let i = 0;
      do {
        const a = this.build[i];
        const b = other.build[i];
        debug("build compare", i, a, b);
        if (a === undefined && b === undefined) {
          return 0;
        } else if (b === undefined) {
          return 1;
        } else if (a === undefined) {
          return -1;
        } else if (a === b) {
          continue;
        } else {
          return compareIdentifiers(a, b);
        }
      } while (++i);
    }
    inc(release, identifier, identifierBase) {
      if (release.startsWith("pre")) {
        if (!identifier && identifierBase === false) {
          throw new Error("invalid increment argument: identifier is empty");
        }
        if (identifier) {
          const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE]);
          if (!match || match[1] !== identifier) {
            throw new Error(`invalid identifier: ${identifier}`);
          }
        }
      }
      switch (release) {
        case "premajor":
          this.prerelease.length = 0;
          this.patch = 0;
          this.minor = 0;
          this.major++;
          this.inc("pre", identifier, identifierBase);
          break;
        case "preminor":
          this.prerelease.length = 0;
          this.patch = 0;
          this.minor++;
          this.inc("pre", identifier, identifierBase);
          break;
        case "prepatch":
          this.prerelease.length = 0;
          this.inc("patch", identifier, identifierBase);
          this.inc("pre", identifier, identifierBase);
          break;
        case "prerelease":
          if (this.prerelease.length === 0) {
            this.inc("patch", identifier, identifierBase);
          }
          this.inc("pre", identifier, identifierBase);
          break;
        case "release":
          if (this.prerelease.length === 0) {
            throw new Error(`version ${this.raw} is not a prerelease`);
          }
          this.prerelease.length = 0;
          break;
        case "major":
          if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) {
            this.major++;
          }
          this.minor = 0;
          this.patch = 0;
          this.prerelease = [];
          break;
        case "minor":
          if (this.patch !== 0 || this.prerelease.length === 0) {
            this.minor++;
          }
          this.patch = 0;
          this.prerelease = [];
          break;
        case "patch":
          if (this.prerelease.length === 0) {
            this.patch++;
          }
          this.prerelease = [];
          break;
        case "pre": {
          const base = Number(identifierBase) ? 1 : 0;
          if (this.prerelease.length === 0) {
            this.prerelease = [base];
          } else {
            let i = this.prerelease.length;
            while (--i >= 0) {
              if (typeof this.prerelease[i] === "number") {
                this.prerelease[i]++;
                i = -2;
              }
            }
            if (i === -1) {
              if (identifier === this.prerelease.join(".") && identifierBase === false) {
                throw new Error("invalid increment argument: identifier already exists");
              }
              this.prerelease.push(base);
            }
          }
          if (identifier) {
            let prerelease = [identifier, base];
            if (identifierBase === false) {
              prerelease = [identifier];
            }
            if (compareIdentifiers(this.prerelease[0], identifier) === 0) {
              if (isNaN(this.prerelease[1])) {
                this.prerelease = prerelease;
              }
            } else {
              this.prerelease = prerelease;
            }
          }
          break;
        }
        default:
          throw new Error(`invalid increment argument: ${release}`);
      }
      this.raw = this.format();
      if (this.build.length) {
        this.raw += `+${this.build.join(".")}`;
      }
      return this;
    }
  }
  module.exports = SemVer;
});

// node_modules/semver/functions/parse.js
var require_parse = __commonJS((exports, module) => {
  var SemVer = require_semver();
  var parse = (version, options, throwErrors = false) => {
    if (version instanceof SemVer) {
      return version;
    }
    try {
      return new SemVer(version, options);
    } catch (er) {
      if (!throwErrors) {
        return null;
      }
      throw er;
    }
  };
  module.exports = parse;
});

// node_modules/semver/functions/valid.js
var require_valid = __commonJS((exports, module) => {
  var parse = require_parse();
  var valid = (version, options) => {
    const v = parse(version, options);
    return v ? v.version : null;
  };
  module.exports = valid;
});

// node_modules/semver/functions/clean.js
var require_clean = __commonJS((exports, module) => {
  var parse = require_parse();
  var clean = (version, options) => {
    const s = parse(version.trim().replace(/^[=v]+/, ""), options);
    return s ? s.version : null;
  };
  module.exports = clean;
});

// node_modules/semver/functions/inc.js
var require_inc = __commonJS((exports, module) => {
  var SemVer = require_semver();
  var inc = (version, release, options, identifier, identifierBase) => {
    if (typeof options === "string") {
      identifierBase = identifier;
      identifier = options;
      options = undefined;
    }
    try {
      return new SemVer(version instanceof SemVer ? version.version : version, options).inc(release, identifier, identifierBase).version;
    } catch (er) {
      return null;
    }
  };
  module.exports = inc;
});

// node_modules/semver/functions/diff.js
var require_diff = __commonJS((exports, module) => {
  var parse = require_parse();
  var diff = (version1, version2) => {
    const v1 = parse(version1, null, true);
    const v2 = parse(version2, null, true);
    const comparison = v1.compare(v2);
    if (comparison === 0) {
      return null;
    }
    const v1Higher = comparison > 0;
    const highVersion = v1Higher ? v1 : v2;
    const lowVersion = v1Higher ? v2 : v1;
    const highHasPre = !!highVersion.prerelease.length;
    const lowHasPre = !!lowVersion.prerelease.length;
    if (lowHasPre && !highHasPre) {
      if (!lowVersion.patch && !lowVersion.minor) {
        return "major";
      }
      if (lowVersion.compareMain(highVersion) === 0) {
        if (lowVersion.minor && !lowVersion.patch) {
          return "minor";
        }
        return "patch";
      }
    }
    const prefix = highHasPre ? "pre" : "";
    if (v1.major !== v2.major) {
      return prefix + "major";
    }
    if (v1.minor !== v2.minor) {
      return prefix + "minor";
    }
    if (v1.patch !== v2.patch) {
      return prefix + "patch";
    }
    return "prerelease";
  };
  module.exports = diff;
});

// node_modules/semver/functions/major.js
var require_major = __commonJS((exports, module) => {
  var SemVer = require_semver();
  var major = (a, loose) => new SemVer(a, loose).major;
  module.exports = major;
});

// node_modules/semver/functions/minor.js
var require_minor = __commonJS((exports, module) => {
  var SemVer = require_semver();
  var minor = (a, loose) => new SemVer(a, loose).minor;
  module.exports = minor;
});

// node_modules/semver/functions/patch.js
var require_patch = __commonJS((exports, module) => {
  var SemVer = require_semver();
  var patch = (a, loose) => new SemVer(a, loose).patch;
  module.exports = patch;
});

// node_modules/semver/functions/prerelease.js
var require_prerelease = __commonJS((exports, module) => {
  var parse = require_parse();
  var prerelease = (version, options) => {
    const parsed = parse(version, options);
    return parsed && parsed.prerelease.length ? parsed.prerelease : null;
  };
  module.exports = prerelease;
});

// node_modules/semver/functions/compare.js
var require_compare = __commonJS((exports, module) => {
  var SemVer = require_semver();
  var compare = (a, b, loose) => new SemVer(a, loose).compare(new SemVer(b, loose));
  module.exports = compare;
});

// node_modules/semver/functions/rcompare.js
var require_rcompare = __commonJS((exports, module) => {
  var compare = require_compare();
  var rcompare = (a, b, loose) => compare(b, a, loose);
  module.exports = rcompare;
});

// node_modules/semver/functions/compare-loose.js
var require_compare_loose = __commonJS((exports, module) => {
  var compare = require_compare();
  var compareLoose = (a, b) => compare(a, b, true);
  module.exports = compareLoose;
});

// node_modules/semver/functions/compare-build.js
var require_compare_build = __commonJS((exports, module) => {
  var SemVer = require_semver();
  var compareBuild = (a, b, loose) => {
    const versionA = new SemVer(a, loose);
    const versionB = new SemVer(b, loose);
    return versionA.compare(versionB) || versionA.compareBuild(versionB);
  };
  module.exports = compareBuild;
});

// node_modules/semver/functions/sort.js
var require_sort = __commonJS((exports, module) => {
  var compareBuild = require_compare_build();
  var sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose));
  module.exports = sort;
});

// node_modules/semver/functions/rsort.js
var require_rsort = __commonJS((exports, module) => {
  var compareBuild = require_compare_build();
  var rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose));
  module.exports = rsort;
});

// node_modules/semver/functions/gt.js
var require_gt = __commonJS((exports, module) => {
  var compare = require_compare();
  var gt = (a, b, loose) => compare(a, b, loose) > 0;
  module.exports = gt;
});

// node_modules/semver/functions/lt.js
var require_lt = __commonJS((exports, module) => {
  var compare = require_compare();
  var lt = (a, b, loose) => compare(a, b, loose) < 0;
  module.exports = lt;
});

// node_modules/semver/functions/eq.js
var require_eq = __commonJS((exports, module) => {
  var compare = require_compare();
  var eq = (a, b, loose) => compare(a, b, loose) === 0;
  module.exports = eq;
});

// node_modules/semver/functions/neq.js
var require_neq = __commonJS((exports, module) => {
  var compare = require_compare();
  var neq = (a, b, loose) => compare(a, b, loose) !== 0;
  module.exports = neq;
});

// node_modules/semver/functions/gte.js
var require_gte = __commonJS((exports, module) => {
  var compare = require_compare();
  var gte = (a, b, loose) => compare(a, b, loose) >= 0;
  module.exports = gte;
});

// node_modules/semver/functions/lte.js
var require_lte = __commonJS((exports, module) => {
  var compare = require_compare();
  var lte = (a, b, loose) => compare(a, b, loose) <= 0;
  module.exports = lte;
});

// node_modules/semver/functions/cmp.js
var require_cmp = __commonJS((exports, module) => {
  var eq = require_eq();
  var neq = require_neq();
  var gt = require_gt();
  var gte = require_gte();
  var lt = require_lt();
  var lte = require_lte();
  var cmp = (a, op, b, loose) => {
    switch (op) {
      case "===":
        if (typeof a === "object") {
          a = a.version;
        }
        if (typeof b === "object") {
          b = b.version;
        }
        return a === b;
      case "!==":
        if (typeof a === "object") {
          a = a.version;
        }
        if (typeof b === "object") {
          b = b.version;
        }
        return a !== b;
      case "":
      case "=":
      case "==":
        return eq(a, b, loose);
      case "!=":
        return neq(a, b, loose);
      case ">":
        return gt(a, b, loose);
      case ">=":
        return gte(a, b, loose);
      case "<":
        return lt(a, b, loose);
      case "<=":
        return lte(a, b, loose);
      default:
        throw new TypeError(`Invalid operator: ${op}`);
    }
  };
  module.exports = cmp;
});

// node_modules/semver/functions/coerce.js
var require_coerce = __commonJS((exports, module) => {
  var SemVer = require_semver();
  var parse = require_parse();
  var { safeRe: re, t } = require_re();
  var coerce2 = (version, options) => {
    if (version instanceof SemVer) {
      return version;
    }
    if (typeof version === "number") {
      version = String(version);
    }
    if (typeof version !== "string") {
      return null;
    }
    options = options || {};
    let match = null;
    if (!options.rtl) {
      match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE]);
    } else {
      const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL];
      let next;
      while ((next = coerceRtlRegex.exec(version)) && (!match || match.index + match[0].length !== version.length)) {
        if (!match || next.index + next[0].length !== match.index + match[0].length) {
          match = next;
        }
        coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length;
      }
      coerceRtlRegex.lastIndex = -1;
    }
    if (match === null) {
      return null;
    }
    const major = match[2];
    const minor = match[3] || "0";
    const patch = match[4] || "0";
    const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : "";
    const build = options.includePrerelease && match[6] ? `+${match[6]}` : "";
    return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options);
  };
  module.exports = coerce2;
});

// node_modules/semver/internal/lrucache.js
var require_lrucache = __commonJS((exports, module) => {
  class LRUCache {
    constructor() {
      this.max = 1000;
      this.map = new Map;
    }
    get(key) {
      const value = this.map.get(key);
      if (value === undefined) {
        return;
      } else {
        this.map.delete(key);
        this.map.set(key, value);
        return value;
      }
    }
    delete(key) {
      return this.map.delete(key);
    }
    set(key, value) {
      const deleted = this.delete(key);
      if (!deleted && value !== undefined) {
        if (this.map.size >= this.max) {
          const firstKey = this.map.keys().next().value;
          this.delete(firstKey);
        }
        this.map.set(key, value);
      }
      return this;
    }
  }
  module.exports = LRUCache;
});

// node_modules/semver/classes/range.js
var require_range = __commonJS((exports, module) => {
  var SPACE_CHARACTERS = /\s+/g;

  class Range {
    constructor(range, options) {
      options = parseOptions(options);
      if (range instanceof Range) {
        if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) {
          return range;
        } else {
          return new Range(range.raw, options);
        }
      }
      if (range instanceof Comparator) {
        this.raw = range.value;
        this.set = [[range]];
        this.formatted = undefined;
        return this;
      }
      this.options = options;
      this.loose = !!options.loose;
      this.includePrerelease = !!options.includePrerelease;
      this.raw = range.trim().replace(SPACE_CHARACTERS, " ");
      this.set = this.raw.split("||").map((r) => this.parseRange(r.trim())).filter((c) => c.length);
      if (!this.set.length) {
        throw new TypeError(`Invalid SemVer Range: ${this.raw}`);
      }
      if (this.set.length > 1) {
        const first = this.set[0];
        this.set = this.set.filter((c) => !isNullSet(c[0]));
        if (this.set.length === 0) {
          this.set = [first];
        } else if (this.set.length > 1) {
          for (const c of this.set) {
            if (c.length === 1 && isAny(c[0])) {
              this.set = [c];
              break;
            }
          }
        }
      }
      this.formatted = undefined;
    }
    get range() {
      if (this.formatted === undefined) {
        this.formatted = "";
        for (let i = 0;i < this.set.length; i++) {
          if (i > 0) {
            this.formatted += "||";
          }
          const comps = this.set[i];
          for (let k = 0;k < comps.length; k++) {
            if (k > 0) {
              this.formatted += " ";
            }
            this.formatted += comps[k].toString().trim();
          }
        }
      }
      return this.formatted;
    }
    format() {
      return this.range;
    }
    toString() {
      return this.range;
    }
    parseRange(range) {
      const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE);
      const memoKey = memoOpts + ":" + range;
      const cached = cache.get(memoKey);
      if (cached) {
        return cached;
      }
      const loose = this.options.loose;
      const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE];
      range = range.replace(hr, hyphenReplace(this.options.includePrerelease));
      debug("hyphen replace", range);
      range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace);
      debug("comparator trim", range);
      range = range.replace(re[t.TILDETRIM], tildeTrimReplace);
      debug("tilde trim", range);
      range = range.replace(re[t.CARETTRIM], caretTrimReplace);
      debug("caret trim", range);
      let rangeList = range.split(" ").map((comp) => parseComparator(comp, this.options)).join(" ").split(/\s+/).map((comp) => replaceGTE0(comp, this.options));
      if (loose) {
        rangeList = rangeList.filter((comp) => {
          debug("loose invalid filter", comp, this.options);
          return !!comp.match(re[t.COMPARATORLOOSE]);
        });
      }
      debug("range list", rangeList);
      const rangeMap = new Map;
      const comparators = rangeList.map((comp) => new Comparator(comp, this.options));
      for (const comp of comparators) {
        if (isNullSet(comp)) {
          return [comp];
        }
        rangeMap.set(comp.value, comp);
      }
      if (rangeMap.size > 1 && rangeMap.has("")) {
        rangeMap.delete("");
      }
      const result = [...rangeMap.values()];
      cache.set(memoKey, result);
      return result;
    }
    intersects(range, options) {
      if (!(range instanceof Range)) {
        throw new TypeError("a Range is required");
      }
      return this.set.some((thisComparators) => {
        return isSatisfiable(thisComparators, options) && range.set.some((rangeComparators) => {
          return isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => {
            return rangeComparators.every((rangeComparator) => {
              return thisComparator.intersects(rangeComparator, options);
            });
          });
        });
      });
    }
    test(version) {
      if (!version) {
        return false;
      }
      if (typeof version === "string") {
        try {
          version = new SemVer(version, this.options);
        } catch (er) {
          return false;
        }
      }
      for (let i = 0;i < this.set.length; i++) {
        if (testSet(this.set[i], version, this.options)) {
          return true;
        }
      }
      return false;
    }
  }
  module.exports = Range;
  var LRU = require_lrucache();
  var cache = new LRU;
  var parseOptions = require_parse_options();
  var Comparator = require_comparator();
  var debug = require_debug();
  var SemVer = require_semver();
  var {
    safeRe: re,
    t,
    comparatorTrimReplace,
    tildeTrimReplace,
    caretTrimReplace
  } = require_re();
  var { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require_constants();
  var isNullSet = (c) => c.value === "<0.0.0-0";
  var isAny = (c) => c.value === "";
  var isSatisfiable = (comparators, options) => {
    let result = true;
    const remainingComparators = comparators.slice();
    let testComparator = remainingComparators.pop();
    while (result && remainingComparators.length) {
      result = remainingComparators.every((otherComparator) => {
        return testComparator.intersects(otherComparator, options);
      });
      testComparator = remainingComparators.pop();
    }
    return result;
  };
  var parseComparator = (comp, options) => {
    comp = comp.replace(re[t.BUILD], "");
    debug("comp", comp, options);
    comp = replaceCarets(comp, options);
    debug("caret", comp);
    comp = replaceTildes(comp, options);
    debug("tildes", comp);
    comp = replaceXRanges(comp, options);
    debug("xrange", comp);
    comp = replaceStars(comp, options);
    debug("stars", comp);
    return comp;
  };
  var isX = (id) => !id || id.toLowerCase() === "x" || id === "*";
  var replaceTildes = (comp, options) => {
    return comp.trim().split(/\s+/).map((c) => replaceTilde(c, options)).join(" ");
  };
  var replaceTilde = (comp, options) => {
    const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE];
    return comp.replace(r, (_, M, m, p, pr) => {
      debug("tilde", comp, _, M, m, p, pr);
      let ret;
      if (isX(M)) {
        ret = "";
      } else if (isX(m)) {
        ret = `>=${M}.0.0 <${+M + 1}.0.0-0`;
      } else if (isX(p)) {
        ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`;
      } else if (pr) {
        debug("replaceTilde pr", pr);
        ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`;
      } else {
        ret = `>=${M}.${m}.${p} <${M}.${+m + 1}.0-0`;
      }
      debug("tilde return", ret);
      return ret;
    });
  };
  var replaceCarets = (comp, options) => {
    return comp.trim().split(/\s+/).map((c) => replaceCaret(c, options)).join(" ");
  };
  var replaceCaret = (comp, options) => {
    debug("caret", comp, options);
    const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET];
    const z = options.includePrerelease ? "-0" : "";
    return comp.replace(r, (_, M, m, p, pr) => {
      debug("caret", comp, _, M, m, p, pr);
      let ret;
      if (isX(M)) {
        ret = "";
      } else if (isX(m)) {
        ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`;
      } else if (isX(p)) {
        if (M === "0") {
          ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`;
        } else {
          ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`;
        }
      } else if (pr) {
        debug("replaceCaret pr", pr);
        if (M === "0") {
          if (m === "0") {
            ret = `>=${M}.${m}.${p}-${pr} <${M}.${m}.${+p + 1}-0`;
          } else {
            ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`;
          }
        } else {
          ret = `>=${M}.${m}.${p}-${pr} <${+M + 1}.0.0-0`;
        }
      } else {
        debug("no pr");
        if (M === "0") {
          if (m === "0") {
            ret = `>=${M}.${m}.${p}${z} <${M}.${m}.${+p + 1}-0`;
          } else {
            ret = `>=${M}.${m}.${p}${z} <${M}.${+m + 1}.0-0`;
          }
        } else {
          ret = `>=${M}.${m}.${p} <${+M + 1}.0.0-0`;
        }
      }
      debug("caret return", ret);
      return ret;
    });
  };
  var replaceXRanges = (comp, options) => {
    debug("replaceXRanges", comp, options);
    return comp.split(/\s+/).map((c) => replaceXRange(c, options)).join(" ");
  };
  var replaceXRange = (comp, options) => {
    comp = comp.trim();
    const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE];
    return comp.replace(r, (ret, gtlt, M, m, p, pr) => {
      debug("xRange", comp, ret, gtlt, M, m, p, pr);
      const xM = isX(M);
      const xm = xM || isX(m);
      const xp = xm || isX(p);
      const anyX = xp;
      if (gtlt === "=" && anyX) {
        gtlt = "";
      }
      pr = options.includePrerelease ? "-0" : "";
      if (xM) {
        if (gtlt === ">" || gtlt === "<") {
          ret = "<0.0.0-0";
        } else {
          ret = "*";
        }
      } else if (gtlt && anyX) {
        if (xm) {
          m = 0;
        }
        p = 0;
        if (gtlt === ">") {
          gtlt = ">=";
          if (xm) {
            M = +M + 1;
            m = 0;
            p = 0;
          } else {
            m = +m + 1;
            p = 0;
          }
        } else if (gtlt === "<=") {
          gtlt = "<";
          if (xm) {
            M = +M + 1;
          } else {
            m = +m + 1;
          }
        }
        if (gtlt === "<") {
          pr = "-0";
        }
        ret = `${gtlt + M}.${m}.${p}${pr}`;
      } else if (xm) {
        ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`;
      } else if (xp) {
        ret = `>=${M}.${m}.0${pr} <${M}.${+m + 1}.0-0`;
      }
      debug("xRange return", ret);
      return ret;
    });
  };
  var replaceStars = (comp, options) => {
    debug("replaceStars", comp, options);
    return comp.trim().replace(re[t.STAR], "");
  };
  var replaceGTE0 = (comp, options) => {
    debug("replaceGTE0", comp, options);
    return comp.trim().replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], "");
  };
  var hyphenReplace = (incPr) => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr) => {
    if (isX(fM)) {
      from = "";
    } else if (isX(fm)) {
      from = `>=${fM}.0.0${incPr ? "-0" : ""}`;
    } else if (isX(fp)) {
      from = `>=${fM}.${fm}.0${incPr ? "-0" : ""}`;
    } else if (fpr) {
      from = `>=${from}`;
    } else {
      from = `>=${from}${incPr ? "-0" : ""}`;
    }
    if (isX(tM)) {
      to = "";
    } else if (isX(tm)) {
      to = `<${+tM + 1}.0.0-0`;
    } else if (isX(tp)) {
      to = `<${tM}.${+tm + 1}.0-0`;
    } else if (tpr) {
      to = `<=${tM}.${tm}.${tp}-${tpr}`;
    } else if (incPr) {
      to = `<${tM}.${tm}.${+tp + 1}-0`;
    } else {
      to = `<=${to}`;
    }
    return `${from} ${to}`.trim();
  };
  var testSet = (set, version, options) => {
    for (let i = 0;i < set.length; i++) {
      if (!set[i].test(version)) {
        return false;
      }
    }
    if (version.prerelease.length && !options.includePrerelease) {
      for (let i = 0;i < set.length; i++) {
        debug(set[i].semver);
        if (set[i].semver === Comparator.ANY) {
          continue;
        }
        if (set[i].semver.prerelease.length > 0) {
          const allowed = set[i].semver;
          if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) {
            return true;
          }
        }
      }
      return false;
    }
    return true;
  };
});

// node_modules/semver/classes/comparator.js
var require_comparator = __commonJS((exports, module) => {
  var ANY = Symbol("SemVer ANY");

  class Comparator {
    static get ANY() {
      return ANY;
    }
    constructor(comp, options) {
      options = parseOptions(options);
      if (comp instanceof Comparator) {
        if (comp.loose === !!options.loose) {
          return comp;
        } else {
          comp = comp.value;
        }
      }
      comp = comp.trim().split(/\s+/).join(" ");
      debug("comparator", comp, options);
      this.options = options;
      this.loose = !!options.loose;
      this.parse(comp);
      if (this.semver === ANY) {
        this.value = "";
      } else {
        this.value = this.operator + this.semver.version;
      }
      debug("comp", this);
    }
    parse(comp) {
      const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR];
      const m = comp.match(r);
      if (!m) {
        throw new TypeError(`Invalid comparator: ${comp}`);
      }
      this.operator = m[1] !== undefined ? m[1] : "";
      if (this.operator === "=") {
        this.operator = "";
      }
      if (!m[2]) {
        this.semver = ANY;
      } else {
        this.semver = new SemVer(m[2], this.options.loose);
      }
    }
    toString() {
      return this.value;
    }
    test(version) {
      debug("Comparator.test", version, this.options.loose);
      if (this.semver === ANY || version === ANY) {
        return true;
      }
      if (typeof version === "string") {
        try {
          version = new SemVer(version, this.options);
        } catch (er) {
          return false;
        }
      }
      return cmp(version, this.operator, this.semver, this.options);
    }
    intersects(comp, options) {
      if (!(comp instanceof Comparator)) {
        throw new TypeError("a Comparator is required");
      }
      if (this.operator === "") {
        if (this.value === "") {
          return true;
        }
        return new Range(comp.value, options).test(this.value);
      } else if (comp.operator === "") {
        if (comp.value === "") {
          return true;
        }
        return new Range(this.value, options).test(comp.semver);
      }
      options = parseOptions(options);
      if (options.includePrerelease && (this.value === "<0.0.0-0" || comp.value === "<0.0.0-0")) {
        return false;
      }
      if (!options.includePrerelease && (this.value.startsWith("<0.0.0") || comp.value.startsWith("<0.0.0"))) {
        return false;
      }
      if (this.operator.startsWith(">") && comp.operator.startsWith(">")) {
        return true;
      }
      if (this.operator.startsWith("<") && comp.operator.startsWith("<")) {
        return true;
      }
      if (this.semver.version === comp.semver.version && this.operator.includes("=") && comp.operator.includes("=")) {
        return true;
      }
      if (cmp(this.semver, "<", comp.semver, options) && this.operator.startsWith(">") && comp.operator.startsWith("<")) {
        return true;
      }
      if (cmp(this.semver, ">", comp.semver, options) && this.operator.startsWith("<") && comp.operator.startsWith(">")) {
        return true;
      }
      return false;
    }
  }
  module.exports = Comparator;
  var parseOptions = require_parse_options();
  var { safeRe: re, t } = require_re();
  var cmp = require_cmp();
  var debug = require_debug();
  var SemVer = require_semver();
  var Range = require_range();
});

// node_modules/semver/functions/satisfies.js
var require_satisfies = __commonJS((exports, module) => {
  var Range = require_range();
  var satisfies = (version, range, options) => {
    try {
      range = new Range(range, options);
    } catch (er) {
      return false;
    }
    return range.test(version);
  };
  module.exports = satisfies;
});

// node_modules/semver/ranges/to-comparators.js
var require_to_comparators = __commonJS((exports, module) => {
  var Range = require_range();
  var toComparators = (range, options) => new Range(range, options).set.map((comp) => comp.map((c) => c.value).join(" ").trim().split(" "));
  module.exports = toComparators;
});

// node_modules/semver/ranges/max-satisfying.js
var require_max_satisfying = __commonJS((exports, module) => {
  var SemVer = require_semver();
  var Range = require_range();
  var maxSatisfying = (versions, range, options) => {
    let max = null;
    let maxSV = null;
    let rangeObj = null;
    try {
      rangeObj = new Range(range, options);
    } catch (er) {
      return null;
    }
    versions.forEach((v) => {
      if (rangeObj.test(v)) {
        if (!max || maxSV.compare(v) === -1) {
          max = v;
          maxSV = new SemVer(max, options);
        }
      }
    });
    return max;
  };
  module.exports = maxSatisfying;
});

// node_modules/semver/ranges/min-satisfying.js
var require_min_satisfying = __commonJS((exports, module) => {
  var SemVer = require_semver();
  var Range = require_range();
  var minSatisfying = (versions, range, options) => {
    let min = null;
    let minSV = null;
    let rangeObj = null;
    try {
      rangeObj = new Range(range, options);
    } catch (er) {
      return null;
    }
    versions.forEach((v) => {
      if (rangeObj.test(v)) {
        if (!min || minSV.compare(v) === 1) {
          min = v;
          minSV = new SemVer(min, options);
        }
      }
    });
    return min;
  };
  module.exports = minSatisfying;
});

// node_modules/semver/ranges/min-version.js
var require_min_version = __commonJS((exports, module) => {
  var SemVer = require_semver();
  var Range = require_range();
  var gt = require_gt();
  var minVersion = (range, loose) => {
    range = new Range(range, loose);
    let minver = new SemVer("0.0.0");
    if (range.test(minver)) {
      return minver;
    }
    minver = new SemVer("0.0.0-0");
    if (range.test(minver)) {
      return minver;
    }
    minver = null;
    for (let i = 0;i < range.set.length; ++i) {
      const comparators = range.set[i];
      let setMin = null;
      comparators.forEach((comparator) => {
        const compver = new SemVer(comparator.semver.version);
        switch (comparator.operator) {
          case ">":
            if (compver.prerelease.length === 0) {
              compver.patch++;
            } else {
              compver.prerelease.push(0);
            }
            compver.raw = compver.format();
          case "":
          case ">=":
            if (!setMin || gt(compver, setMin)) {
              setMin = compver;
            }
            break;
          case "<":
          case "<=":
            break;
          default:
            throw new Error(`Unexpected operation: ${comparator.operator}`);
        }
      });
      if (setMin && (!minver || gt(minver, setMin))) {
        minver = setMin;
      }
    }
    if (minver && range.test(minver)) {
      return minver;
    }
    return null;
  };
  module.exports = minVersion;
});

// node_modules/semver/ranges/valid.js
var require_valid2 = __commonJS((exports, module) => {
  var Range = require_range();
  var validRange = (range, options) => {
    try {
      return new Range(range, options).range || "*";
    } catch (er) {
      return null;
    }
  };
  module.exports = validRange;
});

// node_modules/semver/ranges/outside.js
var require_outside = __commonJS((exports, module) => {
  var SemVer = require_semver();
  var Comparator = require_comparator();
  var { ANY } = Comparator;
  var Range = require_range();
  var satisfies = require_satisfies();
  var gt = require_gt();
  var lt = require_lt();
  var lte = require_lte();
  var gte = require_gte();
  var outside = (version, range, hilo, options) => {
    version = new SemVer(version, options);
    range = new Range(range, options);
    let gtfn, ltefn, ltfn, comp, ecomp;
    switch (hilo) {
      case ">":
        gtfn = gt;
        ltefn = lte;
        ltfn = lt;
        comp = ">";
        ecomp = ">=";
        break;
      case "<":
        gtfn = lt;
        ltefn = gte;
        ltfn = gt;
        comp = "<";
        ecomp = "<=";
        break;
      default:
        throw new TypeError('Must provide a hilo val of "<" or ">"');
    }
    if (satisfies(version, range, options)) {
      return false;
    }
    for (let i = 0;i < range.set.length; ++i) {
      const comparators = range.set[i];
      let high = null;
      let low = null;
      comparators.forEach((comparator) => {
        if (comparator.semver === ANY) {
          comparator = new Comparator(">=0.0.0");
        }
        high = high || comparator;
        low = low || comparator;
        if (gtfn(comparator.semver, high.semver, options)) {
          high = comparator;
        } else if (ltfn(comparator.semver, low.semver, options)) {
          low = comparator;
        }
      });
      if (high.operator === comp || high.operator === ecomp) {
        return false;
      }
      if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) {
        return false;
      } else if (low.operator === ecomp && ltfn(version, low.semver)) {
        return false;
      }
    }
    return true;
  };
  module.exports = outside;
});

// node_modules/semver/ranges/gtr.js
var require_gtr = __commonJS((exports, module) => {
  var outside = require_outside();
  var gtr = (version, range, options) => outside(version, range, ">", options);
  module.exports = gtr;
});

// node_modules/semver/ranges/ltr.js
var require_ltr = __commonJS((exports, module) => {
  var outside = require_outside();
  var ltr = (version, range, options) => outside(version, range, "<", options);
  module.exports = ltr;
});

// node_modules/semver/ranges/intersects.js
var require_intersects = __commonJS((exports, module) => {
  var Range = require_range();
  var intersects = (r1, r2, options) => {
    r1 = new Range(r1, options);
    r2 = new Range(r2, options);
    return r1.intersects(r2, options);
  };
  module.exports = intersects;
});

// node_modules/semver/ranges/simplify.js
var require_simplify = __commonJS((exports, module) => {
  var satisfies = require_satisfies();
  var compare = require_compare();
  module.exports = (versions, range, options) => {
    const set = [];
    let first = null;
    let prev = null;
    const v = versions.sort((a, b) => compare(a, b, options));
    for (const version of v) {
      const included = satisfies(version, range, options);
      if (included) {
        prev = version;
        if (!first) {
          first = version;
        }
      } else {
        if (prev) {
          set.push([first, prev]);
        }
        prev = null;
        first = null;
      }
    }
    if (first) {
      set.push([first, null]);
    }
    const ranges = [];
    for (const [min, max] of set) {
      if (min === max) {
        ranges.push(min);
      } else if (!max && min === v[0]) {
        ranges.push("*");
      } else if (!max) {
        ranges.push(`>=${min}`);
      } else if (min === v[0]) {
        ranges.push(`<=${max}`);
      } else {
        ranges.push(`${min} - ${max}`);
      }
    }
    const simplified = ranges.join(" || ");
    const original = typeof range.raw === "string" ? range.raw : String(range);
    return simplified.length < original.length ? simplified : range;
  };
});

// node_modules/semver/ranges/subset.js
var require_subset = __commonJS((exports, module) => {
  var Range = require_range();
  var Comparator = require_comparator();
  var { ANY } = Comparator;
  var satisfies = require_satisfies();
  var compare = require_compare();
  var subset = (sub, dom, options = {}) => {
    if (sub === dom) {
      return true;
    }
    sub = new Range(sub, options);
    dom = new Range(dom, options);
    let sawNonNull = false;
    OUTER:
      for (const simpleSub of sub.set) {
        for (const simpleDom of dom.set) {
          const isSub = simpleSubset(simpleSub, simpleDom, options);
          sawNonNull = sawNonNull || isSub !== null;
          if (isSub) {
            continue OUTER;
          }
        }
        if (sawNonNull) {
          return false;
        }
      }
    return true;
  };
  var minimumVersionWithPreRelease = [new Comparator(">=0.0.0-0")];
  var minimumVersion = [new Comparator(">=0.0.0")];
  var simpleSubset = (sub, dom, options) => {
    if (sub === dom) {
      return true;
    }
    if (sub.length === 1 && sub[0].semver === ANY) {
      if (dom.length === 1 && dom[0].semver === ANY) {
        return true;
      } else if (options.includePrerelease) {
        sub = minimumVersionWithPreRelease;
      } else {
        sub = minimumVersion;
      }
    }
    if (dom.length === 1 && dom[0].semver === ANY) {
      if (options.includePrerelease) {
        return true;
      } else {
        dom = minimumVersion;
      }
    }
    const eqSet = new Set;
    let gt, lt;
    for (const c of sub) {
      if (c.operator === ">" || c.operator === ">=") {
        gt = higherGT(gt, c, options);
      } else if (c.operator === "<" || c.operator === "<=") {
        lt = lowerLT(lt, c, options);
      } else {
        eqSet.add(c.semver);
      }
    }
    if (eqSet.size > 1) {
      return null;
    }
    let gtltComp;
    if (gt && lt) {
      gtltComp = compare(gt.semver, lt.semver, options);
      if (gtltComp > 0) {
        return null;
      } else if (gtltComp === 0 && (gt.operator !== ">=" || lt.operator !== "<=")) {
        return null;
      }
    }
    for (const eq of eqSet) {
      if (gt && !satisfies(eq, String(gt), options)) {
        return null;
      }
      if (lt && !satisfies(eq, String(lt), options)) {
        return null;
      }
      for (const c of dom) {
        if (!satisfies(eq, String(c), options)) {
          return false;
        }
      }
      return true;
    }
    let higher, lower;
    let hasDomLT, hasDomGT;
    let needDomLTPre = lt && !options.includePrerelease && lt.semver.prerelease.length ? lt.semver : false;
    let needDomGTPre = gt && !options.includePrerelease && gt.semver.prerelease.length ? gt.semver : false;
    if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === "<" && needDomLTPre.prerelease[0] === 0) {
      needDomLTPre = false;
    }
    for (const c of dom) {
      hasDomGT = hasDomGT || c.operator === ">" || c.operator === ">=";
      hasDomLT = hasDomLT || c.operator === "<" || c.operator === "<=";
      if (gt) {
        if (needDomGTPre) {
          if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomGTPre.major && c.semver.minor === needDomGTPre.minor && c.semver.patch === needDomGTPre.patch) {
            needDomGTPre = false;
          }
        }
        if (c.operator === ">" || c.operator === ">=") {
          higher = higherGT(gt, c, options);
          if (higher === c && higher !== gt) {
            return false;
          }
        } else if (gt.operator === ">=" && !satisfies(gt.semver, String(c), options)) {
          return false;
        }
      }
      if (lt) {
        if (needDomLTPre) {
          if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomLTPre.major && c.semver.minor === needDomLTPre.minor && c.semver.patch === needDomLTPre.patch) {
            needDomLTPre = false;
          }
        }
        if (c.operator === "<" || c.operator === "<=") {
          lower = lowerLT(lt, c, options);
          if (lower === c && lower !== lt) {
            return false;
          }
        } else if (lt.operator === "<=" && !satisfies(lt.semver, String(c), options)) {
          return false;
        }
      }
      if (!c.operator && (lt || gt) && gtltComp !== 0) {
        return false;
      }
    }
    if (gt && hasDomLT && !lt && gtltComp !== 0) {
      return false;
    }
    if (lt && hasDomGT && !gt && gtltComp !== 0) {
      return false;
    }
    if (needDomGTPre || needDomLTPre) {
      return false;
    }
    return true;
  };
  var higherGT = (a, b, options) => {
    if (!a) {
      return b;
    }
    const comp = compare(a.semver, b.semver, options);
    return comp > 0 ? a : comp < 0 ? b : b.operator === ">" && a.operator === ">=" ? b : a;
  };
  var lowerLT = (a, b, options) => {
    if (!a) {
      return b;
    }
    const comp = compare(a.semver, b.semver, options);
    return comp < 0 ? a : comp > 0 ? b : b.operator === "<" && a.operator === "<=" ? b : a;
  };
  module.exports = subset;
});

// node_modules/semver/index.js
var require_semver2 = __commonJS((exports, module) => {
  var internalRe = require_re();
  var constants = require_constants();
  var SemVer = require_semver();
  var identifiers = require_identifiers();
  var parse = require_parse();
  var valid = require_valid();
  var clean = require_clean();
  var inc = require_inc();
  var diff = require_diff();
  var major = require_major();
  var minor = require_minor();
  var patch = require_patch();
  var prerelease = require_prerelease();
  var compare = require_compare();
  var rcompare = require_rcompare();
  var compareLoose = require_compare_loose();
  var compareBuild = require_compare_build();
  var sort = require_sort();
  var rsort = require_rsort();
  var gt = require_gt();
  var lt = require_lt();
  var eq = require_eq();
  var neq = require_neq();
  var gte = require_gte();
  var lte = require_lte();
  var cmp = require_cmp();
  var coerce2 = require_coerce();
  var Comparator = require_comparator();
  var Range = require_range();
  var satisfies = require_satisfies();
  var toComparators = require_to_comparators();
  var maxSatisfying = require_max_satisfying();
  var minSatisfying = require_min_satisfying();
  var minVersion = require_min_version();
  var validRange = require_valid2();
  var outside = require_outside();
  var gtr = require_gtr();
  var ltr = require_ltr();
  var intersects = require_intersects();
  var simplifyRange = require_simplify();
  var subset = require_subset();
  module.exports = {
    parse,
    valid,
    clean,
    inc,
    diff,
    major,
    minor,
    patch,
    prerelease,
    compare,
    rcompare,
    compareLoose,
    compareBuild,
    sort,
    rsort,
    gt,
    lt,
    eq,
    neq,
    gte,
    lte,
    cmp,
    coerce: coerce2,
    Comparator,
    Range,
    satisfies,
    toComparators,
    maxSatisfying,
    minSatisfying,
    minVersion,
    validRange,
    outside,
    gtr,
    ltr,
    intersects,
    simplifyRange,
    subset,
    SemVer,
    re: internalRe.re,
    src: internalRe.src,
    tokens: internalRe.t,
    SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION,
    RELEASE_TYPES: constants.RELEASE_TYPES,
    compareIdentifiers: identifiers.compareIdentifiers,
    rcompareIdentifiers: identifiers.rcompareIdentifiers
  };
});

// node_modules/dotenv/lib/main.js
var require_main = __commonJS((exports, module) => {
  var fs15 = __require("fs");
  var path18 = __require("path");
  var os4 = __require("os");
  var crypto3 = __require("crypto");
  var TIPS = [
    "◈ encrypted .env [www.dotenvx.com]",
    "◈ secrets for agents [www.dotenvx.com]",
    "⌁ auth for agents [www.vestauth.com]",
    "⌘ custom filepath { path: '/custom/path/.env' }",
    "⌘ enable debugging { debug: true }",
    "⌘ override existing { override: true }",
    "⌘ suppress logs { quiet: true }",
    "⌘ multiple files { path: ['.env.local', '.env'] }"
  ];
  function _getRandomTip() {
    return TIPS[Math.floor(Math.random() * TIPS.length)];
  }
  function parseBoolean(value) {
    if (typeof value === "string") {
      return !["false", "0", "no", "off", ""].includes(value.toLowerCase());
    }
    return Boolean(value);
  }
  function supportsAnsi() {
    return process.stdout.isTTY;
  }
  function dim(text) {
    return supportsAnsi() ? `\x1B[2m${text}\x1B[0m` : text;
  }
  var LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;
  function parse(src) {
    const obj = {};
    let lines = src.toString();
    lines = lines.replace(/\r\n?/mg, `
`);
    let match;
    while ((match = LINE.exec(lines)) != null) {
      const key = match[1];
      let value = match[2] || "";
      value = value.trim();
      const maybeQuote = value[0];
      value = value.replace(/^(['"`])([\s\S]*)\1$/mg, "$2");
      if (maybeQuote === '"') {
        value = value.replace(/\\n/g, `
`);
        value = value.replace(/\\r/g, "\r");
      }
      obj[key] = value;
    }
    return obj;
  }
  function _parseVault(options) {
    options = options || {};
    const vaultPath = _vaultPath(options);
    options.path = vaultPath;
    const result = DotenvModule.configDotenv(options);
    if (!result.parsed) {
      const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`);
      err.code = "MISSING_DATA";
      throw err;
    }
    const keys = _dotenvKey(options).split(",");
    const length = keys.length;
    let decrypted;
    for (let i = 0;i < length; i++) {
      try {
        const key = keys[i].trim();
        const attrs = _instructions(result, key);
        decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key);
        break;
      } catch (error2) {
        if (i + 1 >= length) {
          throw error2;
        }
      }
    }
    return DotenvModule.parse(decrypted);
  }
  function _warn(message) {
    console.error(`⚠ ${message}`);
  }
  function _debug(message) {
    console.log(`┆ ${message}`);
  }
  function _log(message) {
    console.log(`◇ ${message}`);
  }
  function _dotenvKey(options) {
    if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) {
      return options.DOTENV_KEY;
    }
    if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) {
      return process.env.DOTENV_KEY;
    }
    return "";
  }
  function _instructions(result, dotenvKey) {
    let uri;
    try {
      uri = new URL(dotenvKey);
    } catch (error2) {
      if (error2.code === "ERR_INVALID_URL") {
        const err = new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");
        err.code = "INVALID_DOTENV_KEY";
        throw err;
      }
      throw error2;
    }
    const key = uri.password;
    if (!key) {
      const err = new Error("INVALID_DOTENV_KEY: Missing key part");
      err.code = "INVALID_DOTENV_KEY";
      throw err;
    }
    const environment = uri.searchParams.get("environment");
    if (!environment) {
      const err = new Error("INVALID_DOTENV_KEY: Missing environment part");
      err.code = "INVALID_DOTENV_KEY";
      throw err;
    }
    const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`;
    const ciphertext = result.parsed[environmentKey];
    if (!ciphertext) {
      const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`);
      err.code = "NOT_FOUND_DOTENV_ENVIRONMENT";
      throw err;
    }
    return { ciphertext, key };
  }
  function _vaultPath(options) {
    let possibleVaultPath = null;
    if (options && options.path && options.path.length > 0) {
      if (Array.isArray(options.path)) {
        for (const filepath of options.path) {
          if (fs15.existsSync(filepath)) {
            possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`;
          }
        }
      } else {
        possibleVaultPath = options.path.endsWith(".vault") ? options.path : `${options.path}.vault`;
      }
    } else {
      possibleVaultPath = path18.resolve(process.cwd(), ".env.vault");
    }
    if (fs15.existsSync(possibleVaultPath)) {
      return possibleVaultPath;
    }
    return null;
  }
  function _resolveHome(envPath) {
    return envPath[0] === "~" ? path18.join(os4.homedir(), envPath.slice(1)) : envPath;
  }
  function _configVault(options) {
    const debug = parseBoolean(process.env.DOTENV_CONFIG_DEBUG || options && options.debug);
    const quiet2 = parseBoolean(process.env.DOTENV_CONFIG_QUIET || options && options.quiet);
    if (debug || !quiet2) {
      _log("loading env from encrypted .env.vault");
    }
    const parsed = DotenvModule._parseVault(options);
    let processEnv = process.env;
    if (options && options.processEnv != null) {
      processEnv = options.processEnv;
    }
    DotenvModule.populate(processEnv, parsed, options);
    return { parsed };
  }
  function configDotenv(options) {
    const dotenvPath = path18.resolve(process.cwd(), ".env");
    let encoding = "utf8";
    let processEnv = process.env;
    if (options && options.processEnv != null) {
      processEnv = options.processEnv;
    }
    let debug = parseBoolean(processEnv.DOTENV_CONFIG_DEBUG || options && options.debug);
    let quiet2 = parseBoolean(processEnv.DOTENV_CONFIG_QUIET || options && options.quiet);
    if (options && options.encoding) {
      encoding = options.encoding;
    } else {
      if (debug) {
        _debug("no encoding is specified (UTF-8 is used by default)");
      }
    }
    let optionPaths = [dotenvPath];
    if (options && options.path) {
      if (!Array.isArray(options.path)) {
        optionPaths = [_resolveHome(options.path)];
      } else {
        optionPaths = [];
        for (const filepath of options.path) {
          optionPaths.push(_resolveHome(filepath));
        }
      }
    }
    let lastError;
    const parsedAll = {};
    for (const path19 of optionPaths) {
      try {
        const parsed = DotenvModule.parse(fs15.readFileSync(path19, { encoding }));
        DotenvModule.populate(parsedAll, parsed, options);
      } catch (e) {
        if (debug) {
          _debug(`failed to load ${path19} ${e.message}`);
        }
        lastError = e;
      }
    }
    const populated = DotenvModule.populate(processEnv, parsedAll, options);
    debug = parseBoolean(processEnv.DOTENV_CONFIG_DEBUG || debug);
    quiet2 = parseBoolean(processEnv.DOTENV_CONFIG_QUIET || quiet2);
    if (debug || !quiet2) {
      const keysCount = Object.keys(populated).length;
      const shortPaths = [];
      for (const filePath of optionPaths) {
        try {
          const relative = path18.relative(process.cwd(), filePath);
          shortPaths.push(relative);
        } catch (e) {
          if (debug) {
            _debug(`failed to load ${filePath} ${e.message}`);
          }
          lastError = e;
        }
      }
      _log(`injected env (${keysCount}) from ${shortPaths.join(",")} ${dim(`// tip: ${_getRandomTip()}`)}`);
    }
    if (lastError) {
      return { parsed: parsedAll, error: lastError };
    } else {
      return { parsed: parsedAll };
    }
  }
  function config(options) {
    if (_dotenvKey(options).length === 0) {
      return DotenvModule.configDotenv(options);
    }
    const vaultPath = _vaultPath(options);
    if (!vaultPath) {
      _warn(`you set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}`);
      return DotenvModule.configDotenv(options);
    }
    return DotenvModule._configVault(options);
  }
  function decrypt(encrypted, keyStr) {
    const key = Buffer.from(keyStr.slice(-64), "hex");
    let ciphertext = Buffer.from(encrypted, "base64");
    const nonce = ciphertext.subarray(0, 12);
    const authTag = ciphertext.subarray(-16);
    ciphertext = ciphertext.subarray(12, -16);
    try {
      const aesgcm = crypto3.createDecipheriv("aes-256-gcm", key, nonce);
      aesgcm.setAuthTag(authTag);
      return `${aesgcm.update(ciphertext)}${aesgcm.final()}`;
    } catch (error2) {
      const isRange = error2 instanceof RangeError;
      const invalidKeyLength = error2.message === "Invalid key length";
      const decryptionFailed = error2.message === "Unsupported state or unable to authenticate data";
      if (isRange || invalidKeyLength) {
        const err = new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");
        err.code = "INVALID_DOTENV_KEY";
        throw err;
      } else if (decryptionFailed) {
        const err = new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");
        err.code = "DECRYPTION_FAILED";
        throw err;
      } else {
        throw error2;
      }
    }
  }
  function populate(processEnv, parsed, options = {}) {
    const debug = Boolean(options && options.debug);
    const override = Boolean(options && options.override);
    const populated = {};
    if (typeof parsed !== "object") {
      const err = new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");
      err.code = "OBJECT_REQUIRED";
      throw err;
    }
    for (const key of Object.keys(parsed)) {
      if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
        if (override === true) {
          processEnv[key] = parsed[key];
          populated[key] = parsed[key];
        }
        if (debug) {
          if (override === true) {
            _debug(`"${key}" is already defined and WAS overwritten`);
          } else {
            _debug(`"${key}" is already defined and was NOT overwritten`);
          }
        }
      } else {
        processEnv[key] = parsed[key];
        populated[key] = parsed[key];
      }
    }
    return populated;
  }
  var DotenvModule = {
    configDotenv,
    _configVault,
    _parseVault,
    config,
    decrypt,
    parse,
    populate
  };
  exports.configDotenv = DotenvModule.configDotenv;
  exports._configVault = DotenvModule._configVault;
  exports._parseVault = DotenvModule._parseVault;
  exports.config = DotenvModule.config;
  exports.decrypt = DotenvModule.decrypt;
  exports.parse = DotenvModule.parse;
  exports.populate = DotenvModule.populate;
  module.exports = DotenvModule;
});

// node_modules/@mixmark-io/domino/lib/Event.js
var require_Event = __commonJS((exports, module) => {
  module.exports = Event;
  Event.CAPTURING_PHASE = 1;
  Event.AT_TARGET = 2;
  Event.BUBBLING_PHASE = 3;
  function Event(type, dictionary) {
    this.type = "";
    this.target = null;
    this.currentTarget = null;
    this.eventPhase = Event.AT_TARGET;
    this.bubbles = false;
    this.cancelable = false;
    this.isTrusted = false;
    this.defaultPrevented = false;
    this.timeStamp = Date.now();
    this._propagationStopped = false;
    this._immediatePropagationStopped = false;
    this._initialized = true;
    this._dispatching = false;
    if (type)
      this.type = type;
    if (dictionary) {
      for (var p in dictionary) {
        this[p] = dictionary[p];
      }
    }
  }
  Event.prototype = Object.create(Object.prototype, {
    constructor: { value: Event },
    stopPropagation: { value: function stopPropagation() {
      this._propagationStopped = true;
    } },
    stopImmediatePropagation: { value: function stopImmediatePropagation() {
      this._propagationStopped = true;
      this._immediatePropagationStopped = true;
    } },
    preventDefault: { value: function preventDefault() {
      if (this.cancelable)
        this.defaultPrevented = true;
    } },
    initEvent: { value: function initEvent(type, bubbles, cancelable) {
      this._initialized = true;
      if (this._dispatching)
        return;
      this._propagationStopped = false;
      this._immediatePropagationStopped = false;
      this.defaultPrevented = false;
      this.isTrusted = false;
      this.target = null;
      this.type = type;
      this.bubbles = bubbles;
      this.cancelable = cancelable;
    } }
  });
});

// node_modules/@mixmark-io/domino/lib/UIEvent.js
var require_UIEvent = __commonJS((exports, module) => {
  var Event = require_Event();
  module.exports = UIEvent;
  function UIEvent() {
    Event.call(this);
    this.view = null;
    this.detail = 0;
  }
  UIEvent.prototype = Object.create(Event.prototype, {
    constructor: { value: UIEvent },
    initUIEvent: { value: function(type, bubbles, cancelable, view, detail) {
      this.initEvent(type, bubbles, cancelable);
      this.view = view;
      this.detail = detail;
    } }
  });
});

// node_modules/@mixmark-io/domino/lib/MouseEvent.js
var require_MouseEvent = __commonJS((exports, module) => {
  var UIEvent = require_UIEvent();
  module.exports = MouseEvent;
  function MouseEvent() {
    UIEvent.call(this);
    this.screenX = this.screenY = this.clientX = this.clientY = 0;
    this.ctrlKey = this.altKey = this.shiftKey = this.metaKey = false;
    this.button = 0;
    this.buttons = 1;
    this.relatedTarget = null;
  }
  MouseEvent.prototype = Object.create(UIEvent.prototype, {
    constructor: { value: MouseEvent },
    initMouseEvent: { value: function(type, bubbles, cancelable, view, detail, screenX, screenY, clientX, clientY, ctrlKey, altKey, shiftKey, metaKey, button, relatedTarget) {
      this.initEvent(type, bubbles, cancelable, view, detail);
      this.screenX = screenX;
      this.screenY = screenY;
      this.clientX = clientX;
      this.clientY = clientY;
      this.ctrlKey = ctrlKey;
      this.altKey = altKey;
      this.shiftKey = shiftKey;
      this.metaKey = metaKey;
      this.button = button;
      switch (button) {
        case 0:
          this.buttons = 1;
          break;
        case 1:
          this.buttons = 4;
          break;
        case 2:
          this.buttons = 2;
          break;
        default:
          this.buttons = 0;
          break;
      }
      this.relatedTarget = relatedTarget;
    } },
    getModifierState: { value: function(key) {
      switch (key) {
        case "Alt":
          return this.altKey;
        case "Control":
          return this.ctrlKey;
        case "Shift":
          return this.shiftKey;
        case "Meta":
          return this.metaKey;
        default:
          return false;
      }
    } }
  });
});

// node_modules/@mixmark-io/domino/lib/DOMException.js
var require_DOMException = __commonJS((exports, module) => {
  module.exports = DOMException2;
  var INDEX_SIZE_ERR = 1;
  var HIERARCHY_REQUEST_ERR = 3;
  var WRONG_DOCUMENT_ERR = 4;
  var INVALID_CHARACTER_ERR = 5;
  var NO_MODIFICATION_ALLOWED_ERR = 7;
  var NOT_FOUND_ERR = 8;
  var NOT_SUPPORTED_ERR = 9;
  var INVALID_STATE_ERR = 11;
  var SYNTAX_ERR = 12;
  var INVALID_MODIFICATION_ERR = 13;
  var NAMESPACE_ERR = 14;
  var INVALID_ACCESS_ERR = 15;
  var TYPE_MISMATCH_ERR = 17;
  var SECURITY_ERR = 18;
  var NETWORK_ERR = 19;
  var ABORT_ERR = 20;
  var URL_MISMATCH_ERR = 21;
  var QUOTA_EXCEEDED_ERR = 22;
  var TIMEOUT_ERR = 23;
  var INVALID_NODE_TYPE_ERR = 24;
  var DATA_CLONE_ERR = 25;
  var names = [
    null,
    "INDEX_SIZE_ERR",
    null,
    "HIERARCHY_REQUEST_ERR",
    "WRONG_DOCUMENT_ERR",
    "INVALID_CHARACTER_ERR",
    null,
    "NO_MODIFICATION_ALLOWED_ERR",
    "NOT_FOUND_ERR",
    "NOT_SUPPORTED_ERR",
    "INUSE_ATTRIBUTE_ERR",
    "INVALID_STATE_ERR",
    "SYNTAX_ERR",
    "INVALID_MODIFICATION_ERR",
    "NAMESPACE_ERR",
    "INVALID_ACCESS_ERR",
    null,
    "TYPE_MISMATCH_ERR",
    "SECURITY_ERR",
    "NETWORK_ERR",
    "ABORT_ERR",
    "URL_MISMATCH_ERR",
    "QUOTA_EXCEEDED_ERR",
    "TIMEOUT_ERR",
    "INVALID_NODE_TYPE_ERR",
    "DATA_CLONE_ERR"
  ];
  var messages = [
    null,
    "INDEX_SIZE_ERR (1): the index is not in the allowed range",
    null,
    "HIERARCHY_REQUEST_ERR (3): the operation would yield an incorrect nodes model",
    "WRONG_DOCUMENT_ERR (4): the object is in the wrong Document, a call to importNode is required",
    "INVALID_CHARACTER_ERR (5): the string contains invalid characters",
    null,
    "NO_MODIFICATION_ALLOWED_ERR (7): the object can not be modified",
    "NOT_FOUND_ERR (8): the object can not be found here",
    "NOT_SUPPORTED_ERR (9): this operation is not supported",
    "INUSE_ATTRIBUTE_ERR (10): setAttributeNode called on owned Attribute",
    "INVALID_STATE_ERR (11): the object is in an invalid state",
    "SYNTAX_ERR (12): the string did not match the expected pattern",
    "INVALID_MODIFICATION_ERR (13): the object can not be modified in this way",
    "NAMESPACE_ERR (14): the operation is not allowed by Namespaces in XML",
    "INVALID_ACCESS_ERR (15): the object does not support the operation or argument",
    null,
    "TYPE_MISMATCH_ERR (17): the type of the object does not match the expected type",
    "SECURITY_ERR (18): the operation is insecure",
    "NETWORK_ERR (19): a network error occurred",
    "ABORT_ERR (20): the user aborted an operation",
    "URL_MISMATCH_ERR (21): the given URL does not match another URL",
    "QUOTA_EXCEEDED_ERR (22): the quota has been exceeded",
    "TIMEOUT_ERR (23): a timeout occurred",
    "INVALID_NODE_TYPE_ERR (24): the supplied node is invalid or has an invalid ancestor for this operation",
    "DATA_CLONE_ERR (25): the object can not be cloned."
  ];
  var constants = {
    INDEX_SIZE_ERR,
    DOMSTRING_SIZE_ERR: 2,
    HIERARCHY_REQUEST_ERR,
    WRONG_DOCUMENT_ERR,
    INVALID_CHARACTER_ERR,
    NO_DATA_ALLOWED_ERR: 6,
    NO_MODIFICATION_ALLOWED_ERR,
    NOT_FOUND_ERR,
    NOT_SUPPORTED_ERR,
    INUSE_ATTRIBUTE_ERR: 10,
    INVALID_STATE_ERR,
    SYNTAX_ERR,
    INVALID_MODIFICATION_ERR,
    NAMESPACE_ERR,
    INVALID_ACCESS_ERR,
    VALIDATION_ERR: 16,
    TYPE_MISMATCH_ERR,
    SECURITY_ERR,
    NETWORK_ERR,
    ABORT_ERR,
    URL_MISMATCH_ERR,
    QUOTA_EXCEEDED_ERR,
    TIMEOUT_ERR,
    INVALID_NODE_TYPE_ERR,
    DATA_CLONE_ERR
  };
  function DOMException2(code) {
    Error.call(this);
    Error.captureStackTrace(this, this.constructor);
    this.code = code;
    this.message = messages[code];
    this.name = names[code];
  }
  DOMException2.prototype.__proto__ = Error.prototype;
  for (c in constants) {
    v = { value: constants[c] };
    Object.defineProperty(DOMException2, c, v);
    Object.defineProperty(DOMException2.prototype, c, v);
  }
  var v;
  var c;
});

// node_modules/@mixmark-io/domino/lib/config.js
var require_config = __commonJS((exports) => {
  exports.isApiWritable = !globalThis.__domino_frozen__;
});

// node_modules/@mixmark-io/domino/lib/utils.js
var require_utils = __commonJS((exports) => {
  var DOMException2 = require_DOMException();
  var ERR = DOMException2;
  var isApiWritable = require_config().isApiWritable;
  exports.NAMESPACE = {
    HTML: "http://www.w3.org/1999/xhtml",
    XML: "http://www.w3.org/XML/1998/namespace",
    XMLNS: "http://www.w3.org/2000/xmlns/",
    MATHML: "http://www.w3.org/1998/Math/MathML",
    SVG: "http://www.w3.org/2000/svg",
    XLINK: "http://www.w3.org/1999/xlink"
  };
  exports.IndexSizeError = function() {
    throw new DOMException2(ERR.INDEX_SIZE_ERR);
  };
  exports.HierarchyRequestError = function() {
    throw new DOMException2(ERR.HIERARCHY_REQUEST_ERR);
  };
  exports.WrongDocumentError = function() {
    throw new DOMException2(ERR.WRONG_DOCUMENT_ERR);
  };
  exports.InvalidCharacterError = function() {
    throw new DOMException2(ERR.INVALID_CHARACTER_ERR);
  };
  exports.NoModificationAllowedError = function() {
    throw new DOMException2(ERR.NO_MODIFICATION_ALLOWED_ERR);
  };
  exports.NotFoundError = function() {
    throw new DOMException2(ERR.NOT_FOUND_ERR);
  };
  exports.NotSupportedError = function() {
    throw new DOMException2(ERR.NOT_SUPPORTED_ERR);
  };
  exports.InvalidStateError = function() {
    throw new DOMException2(ERR.INVALID_STATE_ERR);
  };
  exports.SyntaxError = function() {
    throw new DOMException2(ERR.SYNTAX_ERR);
  };
  exports.InvalidModificationError = function() {
    throw new DOMException2(ERR.INVALID_MODIFICATION_ERR);
  };
  exports.NamespaceError = function() {
    throw new DOMException2(ERR.NAMESPACE_ERR);
  };
  exports.InvalidAccessError = function() {
    throw new DOMException2(ERR.INVALID_ACCESS_ERR);
  };
  exports.TypeMismatchError = function() {
    throw new DOMException2(ERR.TYPE_MISMATCH_ERR);
  };
  exports.SecurityError = function() {
    throw new DOMException2(ERR.SECURITY_ERR);
  };
  exports.NetworkError = function() {
    throw new DOMException2(ERR.NETWORK_ERR);
  };
  exports.AbortError = function() {
    throw new DOMException2(ERR.ABORT_ERR);
  };
  exports.UrlMismatchError = function() {
    throw new DOMException2(ERR.URL_MISMATCH_ERR);
  };
  exports.QuotaExceededError = function() {
    throw new DOMException2(ERR.QUOTA_EXCEEDED_ERR);
  };
  exports.TimeoutError = function() {
    throw new DOMException2(ERR.TIMEOUT_ERR);
  };
  exports.InvalidNodeTypeError = function() {
    throw new DOMException2(ERR.INVALID_NODE_TYPE_ERR);
  };
  exports.DataCloneError = function() {
    throw new DOMException2(ERR.DATA_CLONE_ERR);
  };
  exports.nyi = function() {
    throw new Error("NotYetImplemented");
  };
  exports.shouldOverride = function() {
    throw new Error("Abstract function; should be overriding in subclass.");
  };
  exports.assert = function(expr, msg) {
    if (!expr) {
      throw new Error("Assertion failed: " + (msg || "") + `
` + new Error().stack);
    }
  };
  exports.expose = function(src, c) {
    for (var n in src) {
      Object.defineProperty(c.prototype, n, { value: src[n], writable: isApiWritable });
    }
  };
  exports.merge = function(a, b) {
    for (var n in b) {
      a[n] = b[n];
    }
  };
  exports.documentOrder = function(n, m) {
    return 3 - (n.compareDocumentPosition(m) & 6);
  };
  exports.toASCIILowerCase = function(s) {
    return s.replace(/[A-Z]+/g, function(c) {
      return c.toLowerCase();
    });
  };
  exports.toASCIIUpperCase = function(s) {
    return s.replace(/[a-z]+/g, function(c) {
      return c.toUpperCase();
    });
  };
});

// node_modules/@mixmark-io/domino/lib/EventTarget.js
var require_EventTarget = __commonJS((exports, module) => {
  var Event = require_Event();
  var MouseEvent = require_MouseEvent();
  var utils = require_utils();
  module.exports = EventTarget;
  function EventTarget() {}
  EventTarget.prototype = {
    addEventListener: function addEventListener(type, listener, capture) {
      if (!listener)
        return;
      if (capture === undefined)
        capture = false;
      if (!this._listeners)
        this._listeners = Object.create(null);
      if (!this._listeners[type])
        this._listeners[type] = [];
      var list = this._listeners[type];
      for (var i = 0, n = list.length;i < n; i++) {
        var l = list[i];
        if (l.listener === listener && l.capture === capture)
          return;
      }
      var obj = { listener, capture };
      if (typeof listener === "function")
        obj.f = listener;
      list.push(obj);
    },
    removeEventListener: function removeEventListener(type, listener, capture) {
      if (capture === undefined)
        capture = false;
      if (this._listeners) {
        var list = this._listeners[type];
        if (list) {
          for (var i = 0, n = list.length;i < n; i++) {
            var l = list[i];
            if (l.listener === listener && l.capture === capture) {
              if (list.length === 1) {
                this._listeners[type] = undefined;
              } else {
                list.splice(i, 1);
              }
              return;
            }
          }
        }
      }
    },
    dispatchEvent: function dispatchEvent(event) {
      return this._dispatchEvent(event, false);
    },
    _dispatchEvent: function _dispatchEvent(event, trusted) {
      if (typeof trusted !== "boolean")
        trusted = false;
      function invoke(target, event2) {
        var { type, eventPhase: phase } = event2;
        event2.currentTarget = target;
        if (phase !== Event.CAPTURING_PHASE && target._handlers && target._handlers[type]) {
          var handler3 = target._handlers[type];
          var rv;
          if (typeof handler3 === "function") {
            rv = handler3.call(event2.currentTarget, event2);
          } else {
            var f = handler3.handleEvent;
            if (typeof f !== "function")
              throw new TypeError("handleEvent property of " + "event handler object is" + "not a function.");
            rv = f.call(handler3, event2);
          }
          switch (event2.type) {
            case "mouseover":
              if (rv === true)
                event2.preventDefault();
              break;
            case "beforeunload":
            default:
              if (rv === false)
                event2.preventDefault();
              break;
          }
        }
        var list = target._listeners && target._listeners[type];
        if (!list)
          return;
        list = list.slice();
        for (var i2 = 0, n2 = list.length;i2 < n2; i2++) {
          if (event2._immediatePropagationStopped)
            return;
          var l = list[i2];
          if (phase === Event.CAPTURING_PHASE && !l.capture || phase === Event.BUBBLING_PHASE && l.capture)
            continue;
          if (l.f) {
            l.f.call(event2.currentTarget, event2);
          } else {
            var fn = l.listener.handleEvent;
            if (typeof fn !== "function")
              throw new TypeError("handleEvent property of event listener object is not a function.");
            fn.call(l.listener, event2);
          }
        }
      }
      if (!event._initialized || event._dispatching)
        utils.InvalidStateError();
      event.isTrusted = trusted;
      event._dispatching = true;
      event.target = this;
      var ancestors = [];
      for (var n = this.parentNode;n; n = n.parentNode)
        ancestors.push(n);
      event.eventPhase = Event.CAPTURING_PHASE;
      for (var i = ancestors.length - 1;i >= 0; i--) {
        invoke(ancestors[i], event);
        if (event._propagationStopped)
          break;
      }
      if (!event._propagationStopped) {
        event.eventPhase = Event.AT_TARGET;
        invoke(this, event);
      }
      if (event.bubbles && !event._propagationStopped) {
        event.eventPhase = Event.BUBBLING_PHASE;
        for (var ii = 0, nn = ancestors.length;ii < nn; ii++) {
          invoke(ancestors[ii], event);
          if (event._propagationStopped)
            break;
        }
      }
      event._dispatching = false;
      event.eventPhase = Event.AT_TARGET;
      event.currentTarget = null;
      if (trusted && !event.defaultPrevented && event instanceof MouseEvent) {
        switch (event.type) {
          case "mousedown":
            this._armed = {
              x: event.clientX,
              y: event.clientY,
              t: event.timeStamp
            };
            break;
          case "mouseout":
          case "mouseover":
            this._armed = null;
            break;
          case "mouseup":
            if (this._isClick(event))
              this._doClick(event);
            this._armed = null;
            break;
        }
      }
      return !event.defaultPrevented;
    },
    _isClick: function(event) {
      return this._armed !== null && event.type === "mouseup" && event.isTrusted && event.button === 0 && event.timeStamp - this._armed.t < 1000 && Math.abs(event.clientX - this._armed.x) < 10 && Math.abs(event.clientY - this._armed.Y) < 10;
    },
    _doClick: function(event) {
      if (this._click_in_progress)
        return;
      this._click_in_progress = true;
      var activated = this;
      while (activated && !activated._post_click_activation_steps)
        activated = activated.parentNode;
      if (activated && activated._pre_click_activation_steps) {
        activated._pre_click_activation_steps();
      }
      var click = this.ownerDocument.createEvent("MouseEvent");
      click.initMouseEvent("click", true, true, this.ownerDocument.defaultView, 1, event.screenX, event.screenY, event.clientX, event.clientY, event.ctrlKey, event.altKey, event.shiftKey, event.metaKey, event.button, null);
      var result = this._dispatchEvent(click, true);
      if (activated) {
        if (result) {
          if (activated._post_click_activation_steps)
            activated._post_click_activation_steps(click);
        } else {
          if (activated._cancelled_activation_steps)
            activated._cancelled_activation_steps();
        }
      }
    },
    _setEventHandler: function _setEventHandler(type, handler3) {
      if (!this._handlers)
        this._handlers = Object.create(null);
      this._handlers[type] = handler3;
    },
    _getEventHandler: function _getEventHandler(type) {
      return this._handlers && this._handlers[type] || null;
    }
  };
});

// node_modules/@mixmark-io/domino/lib/LinkedList.js
var require_LinkedList = __commonJS((exports, module) => {
  var utils = require_utils();
  var LinkedList = module.exports = {
    valid: function(a) {
      utils.assert(a, "list falsy");
      utils.assert(a._previousSibling, "previous falsy");
      utils.assert(a._nextSibling, "next falsy");
      return true;
    },
    insertBefore: function(a, b) {
      utils.assert(LinkedList.valid(a) && LinkedList.valid(b));
      var a_first = a, a_last = a._previousSibling;
      var b_first = b, b_last = b._previousSibling;
      a_first._previousSibling = b_last;
      a_last._nextSibling = b_first;
      b_last._nextSibling = a_first;
      b_first._previousSibling = a_last;
      utils.assert(LinkedList.valid(a) && LinkedList.valid(b));
    },
    replace: function(a, b) {
      utils.assert(LinkedList.valid(a) && (b === null || LinkedList.valid(b)));
      if (b !== null) {
        LinkedList.insertBefore(b, a);
      }
      LinkedList.remove(a);
      utils.assert(LinkedList.valid(a) && (b === null || LinkedList.valid(b)));
    },
    remove: function(a) {
      utils.assert(LinkedList.valid(a));
      var prev = a._previousSibling;
      if (prev === a) {
        return;
      }
      var next = a._nextSibling;
      prev._nextSibling = next;
      next._previousSibling = prev;
      a._previousSibling = a._nextSibling = a;
      utils.assert(LinkedList.valid(a));
    }
  };
});

// node_modules/@mixmark-io/domino/lib/NodeUtils.js
var require_NodeUtils = __commonJS((exports, module) => {
  module.exports = {
    serializeOne,
    ɵescapeMatchingClosingTag: escapeMatchingClosingTag,
    ɵescapeClosingCommentTag: escapeClosingCommentTag,
    ɵescapeProcessingInstructionContent: escapeProcessingInstructionContent
  };
  var utils = require_utils();
  var NAMESPACE = utils.NAMESPACE;
  var hasRawContent = {
    STYLE: true,
    SCRIPT: true,
    XMP: true,
    IFRAME: true,
    NOEMBED: true,
    NOFRAMES: true,
    PLAINTEXT: true
  };
  var emptyElements = {
    area: true,
    base: true,
    basefont: true,
    bgsound: true,
    br: true,
    col: true,
    embed: true,
    frame: true,
    hr: true,
    img: true,
    input: true,
    keygen: true,
    link: true,
    meta: true,
    param: true,
    source: true,
    track: true,
    wbr: true
  };
  var extraNewLine = {};
  var ESCAPE_REGEXP = /[&<>\u00A0]/g;
  var ESCAPE_ATTR_REGEXP = /[&"<>\u00A0]/g;
  function escape(s) {
    if (!ESCAPE_REGEXP.test(s)) {
      return s;
    }
    return s.replace(ESCAPE_REGEXP, (c) => {
      switch (c) {
        case "&":
          return "&amp;";
        case "<":
          return "&lt;";
        case ">":
          return "&gt;";
        case " ":
          return "&nbsp;";
      }
    });
  }
  function escapeAttr(s) {
    if (!ESCAPE_ATTR_REGEXP.test(s)) {
      return s;
    }
    return s.replace(ESCAPE_ATTR_REGEXP, (c) => {
      switch (c) {
        case "<":
          return "&lt;";
        case ">":
          return "&gt;";
        case "&":
          return "&amp;";
        case '"':
          return "&quot;";
        case " ":
          return "&nbsp;";
      }
    });
  }
  function attrname(a) {
    var ns = a.namespaceURI;
    if (!ns)
      return a.localName;
    if (ns === NAMESPACE.XML)
      return "xml:" + a.localName;
    if (ns === NAMESPACE.XLINK)
      return "xlink:" + a.localName;
    if (ns === NAMESPACE.XMLNS) {
      if (a.localName === "xmlns")
        return "xmlns";
      else
        return "xmlns:" + a.localName;
    }
    return a.name;
  }
  function escapeMatchingClosingTag(rawText, parentTag) {
    const parentClosingTag = "</" + parentTag;
    if (!rawText.toLowerCase().includes(parentClosingTag)) {
      return rawText;
    }
    const result = [...rawText];
    const matches = rawText.matchAll(new RegExp(parentClosingTag, "ig"));
    for (const match of matches) {
      result[match.index] = "&lt;";
    }
    return result.join("");
  }
  var CLOSING_COMMENT_REGEXP = /--!?>/;
  function escapeClosingCommentTag(rawContent) {
    if (!CLOSING_COMMENT_REGEXP.test(rawContent)) {
      return rawContent;
    }
    return rawContent.replace(/(--\!?)>/g, "$1&gt;");
  }
  function escapeProcessingInstructionContent(rawContent) {
    return rawContent.includes(">") ? rawContent.replaceAll(">", "&gt;") : rawContent;
  }
  function serializeOne(kid, parent) {
    var s = "";
    switch (kid.nodeType) {
      case 1:
        var ns = kid.namespaceURI;
        var html = ns === NAMESPACE.HTML;
        var tagname = html || ns === NAMESPACE.SVG || ns === NAMESPACE.MATHML ? kid.localName : kid.tagName;
        s += "<" + tagname;
        for (var j = 0, k = kid._numattrs;j < k; j++) {
          var a = kid._attr(j);
          s += " " + attrname(a);
          if (a.value !== undefined)
            s += '="' + escapeAttr(a.value) + '"';
        }
        s += ">";
        if (!(html && emptyElements[tagname])) {
          var ss = kid.serialize();
          if (hasRawContent[tagname.toUpperCase()]) {
            ss = escapeMatchingClosingTag(ss, tagname);
          }
          if (html && extraNewLine[tagname] && ss.charAt(0) === `
`)
            s += `
`;
          s += ss;
          s += "</" + tagname + ">";
        }
        break;
      case 3:
      case 4:
        var parenttag;
        if (parent.nodeType === 1 && parent.namespaceURI === NAMESPACE.HTML)
          parenttag = parent.tagName;
        else
          parenttag = "";
        if (hasRawContent[parenttag] || parenttag === "NOSCRIPT" && parent.ownerDocument._scripting_enabled) {
          s += kid.data;
        } else {
          s += escape(kid.data);
        }
        break;
      case 8:
        s += "<!--" + escapeClosingCommentTag(kid.data) + "-->";
        break;
      case 7:
        const content = escapeProcessingInstructionContent(kid.data);
        s += "<?" + kid.target + " " + content + "?>";
        break;
      case 10:
        s += "<!DOCTYPE " + kid.name;
        if (false) {}
        s += ">";
        break;
      default:
        utils.InvalidStateError();
    }
    return s;
  }
});

// node_modules/@mixmark-io/domino/lib/Node.js
var require_Node2 = __commonJS((exports, module) => {
  module.exports = Node;
  var EventTarget = require_EventTarget();
  var LinkedList = require_LinkedList();
  var NodeUtils = require_NodeUtils();
  var utils = require_utils();
  function Node() {
    EventTarget.call(this);
    this.parentNode = null;
    this._nextSibling = this._previousSibling = this;
    this._index = undefined;
  }
  var ELEMENT_NODE = Node.ELEMENT_NODE = 1;
  var ATTRIBUTE_NODE = Node.ATTRIBUTE_NODE = 2;
  var TEXT_NODE = Node.TEXT_NODE = 3;
  var CDATA_SECTION_NODE = Node.CDATA_SECTION_NODE = 4;
  var ENTITY_REFERENCE_NODE = Node.ENTITY_REFERENCE_NODE = 5;
  var ENTITY_NODE = Node.ENTITY_NODE = 6;
  var PROCESSING_INSTRUCTION_NODE = Node.PROCESSING_INSTRUCTION_NODE = 7;
  var COMMENT_NODE = Node.COMMENT_NODE = 8;
  var DOCUMENT_NODE = Node.DOCUMENT_NODE = 9;
  var DOCUMENT_TYPE_NODE = Node.DOCUMENT_TYPE_NODE = 10;
  var DOCUMENT_FRAGMENT_NODE = Node.DOCUMENT_FRAGMENT_NODE = 11;
  var NOTATION_NODE = Node.NOTATION_NODE = 12;
  var DOCUMENT_POSITION_DISCONNECTED = Node.DOCUMENT_POSITION_DISCONNECTED = 1;
  var DOCUMENT_POSITION_PRECEDING = Node.DOCUMENT_POSITION_PRECEDING = 2;
  var DOCUMENT_POSITION_FOLLOWING = Node.DOCUMENT_POSITION_FOLLOWING = 4;
  var DOCUMENT_POSITION_CONTAINS = Node.DOCUMENT_POSITION_CONTAINS = 8;
  var DOCUMENT_POSITION_CONTAINED_BY = Node.DOCUMENT_POSITION_CONTAINED_BY = 16;
  var DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = Node.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = 32;
  Node.prototype = Object.create(EventTarget.prototype, {
    baseURI: { get: utils.nyi },
    parentElement: { get: function() {
      return this.parentNode && this.parentNode.nodeType === ELEMENT_NODE ? this.parentNode : null;
    } },
    hasChildNodes: { value: utils.shouldOverride },
    firstChild: { get: utils.shouldOverride },
    lastChild: { get: utils.shouldOverride },
    isConnected: {
      get: function() {
        let node = this;
        while (node != null) {
          if (node.nodeType === Node.DOCUMENT_NODE) {
            return true;
          }
          node = node.parentNode;
          if (node != null && node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
            node = node.host;
          }
        }
        return false;
      }
    },
    previousSibling: { get: function() {
      var parent = this.parentNode;
      if (!parent)
        return null;
      if (this === parent.firstChild)
        return null;
      return this._previousSibling;
    } },
    nextSibling: { get: function() {
      var parent = this.parentNode, next = this._nextSibling;
      if (!parent)
        return null;
      if (next === parent.firstChild)
        return null;
      return next;
    } },
    textContent: {
      get: function() {
        return null;
      },
      set: function(v) {}
    },
    innerText: {
      get: function() {
        return null;
      },
      set: function(v) {}
    },
    _countChildrenOfType: { value: function(type) {
      var sum = 0;
      for (var kid = this.firstChild;kid !== null; kid = kid.nextSibling) {
        if (kid.nodeType === type)
          sum++;
      }
      return sum;
    } },
    _ensureInsertValid: { value: function _ensureInsertValid(node, child, isPreinsert) {
      var parent = this, i, kid;
      if (!node.nodeType)
        throw new TypeError("not a node");
      switch (parent.nodeType) {
        case DOCUMENT_NODE:
        case DOCUMENT_FRAGMENT_NODE:
        case ELEMENT_NODE:
          break;
        default:
          utils.HierarchyRequestError();
      }
      if (node.isAncestor(parent))
        utils.HierarchyRequestError();
      if (child !== null || !isPreinsert) {
        if (child.parentNode !== parent)
          utils.NotFoundError();
      }
      switch (node.nodeType) {
        case DOCUMENT_FRAGMENT_NODE:
        case DOCUMENT_TYPE_NODE:
        case ELEMENT_NODE:
        case TEXT_NODE:
        case PROCESSING_INSTRUCTION_NODE:
        case COMMENT_NODE:
          break;
        default:
          utils.HierarchyRequestError();
      }
      if (parent.nodeType === DOCUMENT_NODE) {
        switch (node.nodeType) {
          case TEXT_NODE:
            utils.HierarchyRequestError();
            break;
          case DOCUMENT_FRAGMENT_NODE:
            if (node._countChildrenOfType(TEXT_NODE) > 0)
              utils.HierarchyRequestError();
            switch (node._countChildrenOfType(ELEMENT_NODE)) {
              case 0:
                break;
              case 1:
                if (child !== null) {
                  if (isPreinsert && child.nodeType === DOCUMENT_TYPE_NODE)
                    utils.HierarchyRequestError();
                  for (kid = child.nextSibling;kid !== null; kid = kid.nextSibling) {
                    if (kid.nodeType === DOCUMENT_TYPE_NODE)
                      utils.HierarchyRequestError();
                  }
                }
                i = parent._countChildrenOfType(ELEMENT_NODE);
                if (isPreinsert) {
                  if (i > 0)
                    utils.HierarchyRequestError();
                } else {
                  if (i > 1 || i === 1 && child.nodeType !== ELEMENT_NODE)
                    utils.HierarchyRequestError();
                }
                break;
              default:
                utils.HierarchyRequestError();
            }
            break;
          case ELEMENT_NODE:
            if (child !== null) {
              if (isPreinsert && child.nodeType === DOCUMENT_TYPE_NODE)
                utils.HierarchyRequestError();
              for (kid = child.nextSibling;kid !== null; kid = kid.nextSibling) {
                if (kid.nodeType === DOCUMENT_TYPE_NODE)
                  utils.HierarchyRequestError();
              }
            }
            i = parent._countChildrenOfType(ELEMENT_NODE);
            if (isPreinsert) {
              if (i > 0)
                utils.HierarchyRequestError();
            } else {
              if (i > 1 || i === 1 && child.nodeType !== ELEMENT_NODE)
                utils.HierarchyRequestError();
            }
            break;
          case DOCUMENT_TYPE_NODE:
            if (child === null) {
              if (parent._countChildrenOfType(ELEMENT_NODE))
                utils.HierarchyRequestError();
            } else {
              for (kid = parent.firstChild;kid !== null; kid = kid.nextSibling) {
                if (kid === child)
                  break;
                if (kid.nodeType === ELEMENT_NODE)
                  utils.HierarchyRequestError();
              }
            }
            i = parent._countChildrenOfType(DOCUMENT_TYPE_NODE);
            if (isPreinsert) {
              if (i > 0)
                utils.HierarchyRequestError();
            } else {
              if (i > 1 || i === 1 && child.nodeType !== DOCUMENT_TYPE_NODE)
                utils.HierarchyRequestError();
            }
            break;
        }
      } else {
        if (node.nodeType === DOCUMENT_TYPE_NODE)
          utils.HierarchyRequestError();
      }
    } },
    insertBefore: { value: function insertBefore(node, child) {
      var parent = this;
      parent._ensureInsertValid(node, child, true);
      var refChild = child;
      if (refChild === node) {
        refChild = node.nextSibling;
      }
      parent.doc.adoptNode(node);
      node._insertOrReplace(parent, refChild, false);
      return node;
    } },
    appendChild: { value: function(child) {
      return this.insertBefore(child, null);
    } },
    _appendChild: { value: function(child) {
      child._insertOrReplace(this, null, false);
    } },
    removeChild: { value: function removeChild(child) {
      var parent = this;
      if (!child.nodeType)
        throw new TypeError("not a node");
      if (child.parentNode !== parent)
        utils.NotFoundError();
      child.remove();
      return child;
    } },
    replaceChild: { value: function replaceChild(node, child) {
      var parent = this;
      parent._ensureInsertValid(node, child, false);
      if (node.doc !== parent.doc) {
        parent.doc.adoptNode(node);
      }
      node._insertOrReplace(parent, child, true);
      return child;
    } },
    contains: { value: function contains(node) {
      if (node === null) {
        return false;
      }
      if (this === node) {
        return true;
      }
      return (this.compareDocumentPosition(node) & DOCUMENT_POSITION_CONTAINED_BY) !== 0;
    } },
    compareDocumentPosition: { value: function compareDocumentPosition(that) {
      if (this === that)
        return 0;
      if (this.doc !== that.doc || this.rooted !== that.rooted)
        return DOCUMENT_POSITION_DISCONNECTED + DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC;
      var these = [], those = [];
      for (var n = this;n !== null; n = n.parentNode)
        these.push(n);
      for (n = that;n !== null; n = n.parentNode)
        those.push(n);
      these.reverse();
      those.reverse();
      if (these[0] !== those[0])
        return DOCUMENT_POSITION_DISCONNECTED + DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC;
      n = Math.min(these.length, those.length);
      for (var i = 1;i < n; i++) {
        if (these[i] !== those[i]) {
          if (these[i].index < those[i].index)
            return DOCUMENT_POSITION_FOLLOWING;
          else
            return DOCUMENT_POSITION_PRECEDING;
        }
      }
      if (these.length < those.length)
        return DOCUMENT_POSITION_FOLLOWING + DOCUMENT_POSITION_CONTAINED_BY;
      else
        return DOCUMENT_POSITION_PRECEDING + DOCUMENT_POSITION_CONTAINS;
    } },
    isSameNode: { value: function isSameNode(node) {
      return this === node;
    } },
    isEqualNode: { value: function isEqualNode(node) {
      if (!node)
        return false;
      if (node.nodeType !== this.nodeType)
        return false;
      if (!this.isEqual(node))
        return false;
      for (var c1 = this.firstChild, c2 = node.firstChild;c1 && c2; c1 = c1.nextSibling, c2 = c2.nextSibling) {
        if (!c1.isEqualNode(c2))
          return false;
      }
      return c1 === null && c2 === null;
    } },
    cloneNode: { value: function(deep) {
      var clone = this.clone();
      if (deep) {
        for (var kid = this.firstChild;kid !== null; kid = kid.nextSibling) {
          clone._appendChild(kid.cloneNode(true));
        }
      }
      return clone;
    } },
    lookupPrefix: { value: function lookupPrefix(ns) {
      var e;
      if (ns === "" || ns === null || ns === undefined)
        return null;
      switch (this.nodeType) {
        case ELEMENT_NODE:
          return this._lookupNamespacePrefix(ns, this);
        case DOCUMENT_NODE:
          e = this.documentElement;
          return e ? e.lookupPrefix(ns) : null;
        case ENTITY_NODE:
        case NOTATION_NODE:
        case DOCUMENT_FRAGMENT_NODE:
        case DOCUMENT_TYPE_NODE:
          return null;
        case ATTRIBUTE_NODE:
          e = this.ownerElement;
          return e ? e.lookupPrefix(ns) : null;
        default:
          e = this.parentElement;
          return e ? e.lookupPrefix(ns) : null;
      }
    } },
    lookupNamespaceURI: { value: function lookupNamespaceURI(prefix) {
      if (prefix === "" || prefix === undefined) {
        prefix = null;
      }
      var e;
      switch (this.nodeType) {
        case ELEMENT_NODE:
          return utils.shouldOverride();
        case DOCUMENT_NODE:
          e = this.documentElement;
          return e ? e.lookupNamespaceURI(prefix) : null;
        case ENTITY_NODE:
        case NOTATION_NODE:
        case DOCUMENT_TYPE_NODE:
        case DOCUMENT_FRAGMENT_NODE:
          return null;
        case ATTRIBUTE_NODE:
          e = this.ownerElement;
          return e ? e.lookupNamespaceURI(prefix) : null;
        default:
          e = this.parentElement;
          return e ? e.lookupNamespaceURI(prefix) : null;
      }
    } },
    isDefaultNamespace: { value: function isDefaultNamespace(ns) {
      if (ns === "" || ns === undefined) {
        ns = null;
      }
      var defaultNamespace = this.lookupNamespaceURI(null);
      return defaultNamespace === ns;
    } },
    index: { get: function() {
      var parent = this.parentNode;
      if (this === parent.firstChild)
        return 0;
      var kids = parent.childNodes;
      if (this._index === undefined || kids[this._index] !== this) {
        for (var i = 0;i < kids.length; i++) {
          kids[i]._index = i;
        }
        utils.assert(kids[this._index] === this);
      }
      return this._index;
    } },
    isAncestor: { value: function(that) {
      if (this.doc !== that.doc)
        return false;
      if (this.rooted !== that.rooted)
        return false;
      for (var e = that;e; e = e.parentNode) {
        if (e === this)
          return true;
      }
      return false;
    } },
    ensureSameDoc: { value: function(that) {
      if (that.ownerDocument === null) {
        that.ownerDocument = this.doc;
      } else if (that.ownerDocument !== this.doc) {
        utils.WrongDocumentError();
      }
    } },
    removeChildren: { value: utils.shouldOverride },
    _insertOrReplace: { value: function _insertOrReplace(parent, before, isReplace) {
      var child = this, before_index, i;
      if (child.nodeType === DOCUMENT_FRAGMENT_NODE && child.rooted) {
        utils.HierarchyRequestError();
      }
      if (parent._childNodes) {
        before_index = before === null ? parent._childNodes.length : before.index;
        if (child.parentNode === parent) {
          var child_index = child.index;
          if (child_index < before_index) {
            before_index--;
          }
        }
      }
      if (isReplace) {
        if (before.rooted)
          before.doc.mutateRemove(before);
        before.parentNode = null;
      }
      var n = before;
      if (n === null) {
        n = parent.firstChild;
      }
      var bothRooted = child.rooted && parent.rooted;
      if (child.nodeType === DOCUMENT_FRAGMENT_NODE) {
        var spliceArgs = [0, isReplace ? 1 : 0], next;
        for (var kid = child.firstChild;kid !== null; kid = next) {
          next = kid.nextSibling;
          spliceArgs.push(kid);
          kid.parentNode = parent;
        }
        var len = spliceArgs.length;
        if (isReplace) {
          LinkedList.replace(n, len > 2 ? spliceArgs[2] : null);
        } else if (len > 2 && n !== null) {
          LinkedList.insertBefore(spliceArgs[2], n);
        }
        if (parent._childNodes) {
          spliceArgs[0] = before === null ? parent._childNodes.length : before._index;
          parent._childNodes.splice.apply(parent._childNodes, spliceArgs);
          for (i = 2;i < len; i++) {
            spliceArgs[i]._index = spliceArgs[0] + (i - 2);
          }
        } else if (parent._firstChild === before) {
          if (len > 2) {
            parent._firstChild = spliceArgs[2];
          } else if (isReplace) {
            parent._firstChild = null;
          }
        }
        if (child._childNodes) {
          child._childNodes.length = 0;
        } else {
          child._firstChild = null;
        }
        if (parent.rooted) {
          parent.modify();
          for (i = 2;i < len; i++) {
            parent.doc.mutateInsert(spliceArgs[i]);
          }
        }
      } else {
        if (before === child) {
          return;
        }
        if (bothRooted) {
          child._remove();
        } else if (child.parentNode) {
          child.remove();
        }
        child.parentNode = parent;
        if (isReplace) {
          LinkedList.replace(n, child);
          if (parent._childNodes) {
            child._index = before_index;
            parent._childNodes[before_index] = child;
          } else if (parent._firstChild === before) {
            parent._firstChild = child;
          }
        } else {
          if (n !== null) {
            LinkedList.insertBefore(child, n);
          }
          if (parent._childNodes) {
            child._index = before_index;
            parent._childNodes.splice(before_index, 0, child);
          } else if (parent._firstChild === before) {
            parent._firstChild = child;
          }
        }
        if (bothRooted) {
          parent.modify();
          parent.doc.mutateMove(child);
        } else if (parent.rooted) {
          parent.modify();
          parent.doc.mutateInsert(child);
        }
      }
    } },
    lastModTime: { get: function() {
      if (!this._lastModTime) {
        this._lastModTime = this.doc.modclock;
      }
      return this._lastModTime;
    } },
    modify: { value: function() {
      if (this.doc.modclock) {
        var time = ++this.doc.modclock;
        for (var n = this;n; n = n.parentElement) {
          if (n._lastModTime) {
            n._lastModTime = time;
          }
        }
      }
    } },
    doc: { get: function() {
      return this.ownerDocument || this;
    } },
    rooted: { get: function() {
      return !!this._nid;
    } },
    normalize: { value: function() {
      var next;
      for (var child = this.firstChild;child !== null; child = next) {
        next = child.nextSibling;
        if (child.normalize) {
          child.normalize();
        }
        if (child.nodeType !== Node.TEXT_NODE) {
          continue;
        }
        if (child.nodeValue === "") {
          this.removeChild(child);
          continue;
        }
        var prevChild = child.previousSibling;
        if (prevChild === null) {
          continue;
        } else if (prevChild.nodeType === Node.TEXT_NODE) {
          prevChild.appendData(child.nodeValue);
          this.removeChild(child);
        }
      }
    } },
    serialize: { value: function() {
      if (this._innerHTML) {
        return this._innerHTML;
      }
      var s = "";
      for (var kid = this.firstChild;kid !== null; kid = kid.nextSibling) {
        s += NodeUtils.serializeOne(kid, this);
      }
      return s;
    } },
    outerHTML: {
      get: function() {
        return NodeUtils.serializeOne(this, { nodeType: 0 });
      },
      set: utils.nyi
    },
    ELEMENT_NODE: { value: ELEMENT_NODE },
    ATTRIBUTE_NODE: { value: ATTRIBUTE_NODE },
    TEXT_NODE: { value: TEXT_NODE },
    CDATA_SECTION_NODE: { value: CDATA_SECTION_NODE },
    ENTITY_REFERENCE_NODE: { value: ENTITY_REFERENCE_NODE },
    ENTITY_NODE: { value: ENTITY_NODE },
    PROCESSING_INSTRUCTION_NODE: { value: PROCESSING_INSTRUCTION_NODE },
    COMMENT_NODE: { value: COMMENT_NODE },
    DOCUMENT_NODE: { value: DOCUMENT_NODE },
    DOCUMENT_TYPE_NODE: { value: DOCUMENT_TYPE_NODE },
    DOCUMENT_FRAGMENT_NODE: { value: DOCUMENT_FRAGMENT_NODE },
    NOTATION_NODE: { value: NOTATION_NODE },
    DOCUMENT_POSITION_DISCONNECTED: { value: DOCUMENT_POSITION_DISCONNECTED },
    DOCUMENT_POSITION_PRECEDING: { value: DOCUMENT_POSITION_PRECEDING },
    DOCUMENT_POSITION_FOLLOWING: { value: DOCUMENT_POSITION_FOLLOWING },
    DOCUMENT_POSITION_CONTAINS: { value: DOCUMENT_POSITION_CONTAINS },
    DOCUMENT_POSITION_CONTAINED_BY: { value: DOCUMENT_POSITION_CONTAINED_BY },
    DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: { value: DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC }
  });
});

// node_modules/@mixmark-io/domino/lib/NodeList.es6.js
var require_NodeList_es6 = __commonJS((exports, module) => {
  module.exports = class NodeList extends Array {
    constructor(a) {
      super(a && a.length || 0);
      if (a) {
        for (var idx in a) {
          this[idx] = a[idx];
        }
      }
    }
    item(i) {
      return this[i] || null;
    }
  };
});

// node_modules/@mixmark-io/domino/lib/NodeList.es5.js
var require_NodeList_es5 = __commonJS((exports, module) => {
  function item(i) {
    return this[i] || null;
  }
  function NodeList(a) {
    if (!a)
      a = [];
    a.item = item;
    return a;
  }
  module.exports = NodeList;
});

// node_modules/@mixmark-io/domino/lib/NodeList.js
var require_NodeList = __commonJS((exports, module) => {
  var NodeList;
  try {
    NodeList = require_NodeList_es6();
  } catch (e) {
    NodeList = require_NodeList_es5();
  }
  module.exports = NodeList;
});

// node_modules/@mixmark-io/domino/lib/ContainerNode.js
var require_ContainerNode = __commonJS((exports, module) => {
  module.exports = ContainerNode;
  var Node = require_Node2();
  var NodeList = require_NodeList();
  function ContainerNode() {
    Node.call(this);
    this._firstChild = this._childNodes = null;
  }
  ContainerNode.prototype = Object.create(Node.prototype, {
    hasChildNodes: { value: function() {
      if (this._childNodes) {
        return this._childNodes.length > 0;
      }
      return this._firstChild !== null;
    } },
    childNodes: { get: function() {
      this._ensureChildNodes();
      return this._childNodes;
    } },
    firstChild: { get: function() {
      if (this._childNodes) {
        return this._childNodes.length === 0 ? null : this._childNodes[0];
      }
      return this._firstChild;
    } },
    lastChild: { get: function() {
      var kids = this._childNodes, first;
      if (kids) {
        return kids.length === 0 ? null : kids[kids.length - 1];
      }
      first = this._firstChild;
      if (first === null) {
        return null;
      }
      return first._previousSibling;
    } },
    _ensureChildNodes: { value: function() {
      if (this._childNodes) {
        return;
      }
      var first = this._firstChild, kid = first, childNodes = this._childNodes = new NodeList;
      if (first)
        do {
          childNodes.push(kid);
          kid = kid._nextSibling;
        } while (kid !== first);
      this._firstChild = null;
    } },
    removeChildren: { value: function removeChildren() {
      var root = this.rooted ? this.ownerDocument : null, next = this.firstChild, kid;
      while (next !== null) {
        kid = next;
        next = kid.nextSibling;
        if (root)
          root.mutateRemove(kid);
        kid.parentNode = null;
      }
      if (this._childNodes) {
        this._childNodes.length = 0;
      } else {
        this._firstChild = null;
      }
      this.modify();
    } }
  });
});

// node_modules/@mixmark-io/domino/lib/xmlnames.js
var require_xmlnames = __commonJS((exports) => {
  exports.isValidName = isValidName;
  exports.isValidQName = isValidQName;
  var simplename = /^[_:A-Za-z][-.:\w]+$/;
  var simpleqname = /^([_A-Za-z][-.\w]+|[_A-Za-z][-.\w]+:[_A-Za-z][-.\w]+)$/;
  var ncnamestartchars = "_A-Za-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�";
  var ncnamechars = "-._A-Za-z0-9·À-ÖØ-öø-˿̀-ͽͿ-῿‌‍‿⁀⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�";
  var ncname = "[" + ncnamestartchars + "][" + ncnamechars + "]*";
  var namestartchars = ncnamestartchars + ":";
  var namechars = ncnamechars + ":";
  var name = new RegExp("^[" + namestartchars + "]" + "[" + namechars + "]*$");
  var qname = new RegExp("^(" + ncname + "|" + ncname + ":" + ncname + ")$");
  var hassurrogates = /[\uD800-\uDB7F\uDC00-\uDFFF]/;
  var surrogatechars = /[\uD800-\uDB7F\uDC00-\uDFFF]/g;
  var surrogatepairs = /[\uD800-\uDB7F][\uDC00-\uDFFF]/g;
  ncnamestartchars += "\uD800-\uDB7F\uDC00-\uDFFF";
  ncnamechars += "\uD800-\uDB7F\uDC00-\uDFFF";
  ncname = "[" + ncnamestartchars + "][" + ncnamechars + "]*";
  namestartchars = ncnamestartchars + ":";
  namechars = ncnamechars + ":";
  var surrogatename = new RegExp("^[" + namestartchars + "]" + "[" + namechars + "]*$");
  var surrogateqname = new RegExp("^(" + ncname + "|" + ncname + ":" + ncname + ")$");
  function isValidName(s) {
    if (simplename.test(s))
      return true;
    if (name.test(s))
      return true;
    if (!hassurrogates.test(s))
      return false;
    if (!surrogatename.test(s))
      return false;
    var chars = s.match(surrogatechars), pairs = s.match(surrogatepairs);
    return pairs !== null && 2 * pairs.length === chars.length;
  }
  function isValidQName(s) {
    if (simpleqname.test(s))
      return true;
    if (qname.test(s))
      return true;
    if (!hassurrogates.test(s))
      return false;
    if (!surrogateqname.test(s))
      return false;
    var chars = s.match(surrogatechars), pairs = s.match(surrogatepairs);
    return pairs !== null && 2 * pairs.length === chars.length;
  }
});

// node_modules/@mixmark-io/domino/lib/attributes.js
var require_attributes = __commonJS((exports) => {
  var utils = require_utils();
  exports.property = function(attr) {
    if (Array.isArray(attr.type)) {
      var valid = Object.create(null);
      attr.type.forEach(function(val) {
        valid[val.value || val] = val.alias || val;
      });
      var missingValueDefault = attr.missing;
      if (missingValueDefault === undefined) {
        missingValueDefault = null;
      }
      var invalidValueDefault = attr.invalid;
      if (invalidValueDefault === undefined) {
        invalidValueDefault = missingValueDefault;
      }
      return {
        get: function() {
          var v = this._getattr(attr.name);
          if (v === null)
            return missingValueDefault;
          v = valid[v.toLowerCase()];
          if (v !== undefined)
            return v;
          if (invalidValueDefault !== null)
            return invalidValueDefault;
          return v;
        },
        set: function(v) {
          this._setattr(attr.name, v);
        }
      };
    } else if (attr.type === Boolean) {
      return {
        get: function() {
          return this.hasAttribute(attr.name);
        },
        set: function(v) {
          if (v) {
            this._setattr(attr.name, "");
          } else {
            this.removeAttribute(attr.name);
          }
        }
      };
    } else if (attr.type === Number || attr.type === "long" || attr.type === "unsigned long" || attr.type === "limited unsigned long with fallback") {
      return numberPropDesc(attr);
    } else if (!attr.type || attr.type === String) {
      return {
        get: function() {
          return this._getattr(attr.name) || "";
        },
        set: function(v) {
          if (attr.treatNullAsEmptyString && v === null) {
            v = "";
          }
          this._setattr(attr.name, v);
        }
      };
    } else if (typeof attr.type === "function") {
      return attr.type(attr.name, attr);
    }
    throw new Error("Invalid attribute definition");
  };
  function numberPropDesc(a) {
    var def;
    if (typeof a.default === "function") {
      def = a.default;
    } else if (typeof a.default === "number") {
      def = function() {
        return a.default;
      };
    } else {
      def = function() {
        utils.assert(false, typeof a.default);
      };
    }
    var unsigned_long = a.type === "unsigned long";
    var signed_long = a.type === "long";
    var unsigned_fallback = a.type === "limited unsigned long with fallback";
    var { min, max, setmin } = a;
    if (min === undefined) {
      if (unsigned_long)
        min = 0;
      if (signed_long)
        min = -2147483648;
      if (unsigned_fallback)
        min = 1;
    }
    if (max === undefined) {
      if (unsigned_long || signed_long || unsigned_fallback)
        max = 2147483647;
    }
    return {
      get: function() {
        var v = this._getattr(a.name);
        var n = a.float ? parseFloat(v) : parseInt(v, 10);
        if (v === null || !isFinite(n) || min !== undefined && n < min || max !== undefined && n > max) {
          return def.call(this);
        }
        if (unsigned_long || signed_long || unsigned_fallback) {
          if (!/^[ \t\n\f\r]*[-+]?[0-9]/.test(v)) {
            return def.call(this);
          }
          n = n | 0;
        }
        return n;
      },
      set: function(v) {
        if (!a.float) {
          v = Math.floor(v);
        }
        if (setmin !== undefined && v < setmin) {
          utils.IndexSizeError(a.name + " set to " + v);
        }
        if (unsigned_long) {
          v = v < 0 || v > 2147483647 ? def.call(this) : v | 0;
        } else if (unsigned_fallback) {
          v = v < 1 || v > 2147483647 ? def.call(this) : v | 0;
        } else if (signed_long) {
          v = v < -2147483648 || v > 2147483647 ? def.call(this) : v | 0;
        }
        this._setattr(a.name, String(v));
      }
    };
  }
  exports.registerChangeHandler = function(c, name, handler3) {
    var p = c.prototype;
    if (!Object.prototype.hasOwnProperty.call(p, "_attributeChangeHandlers")) {
      p._attributeChangeHandlers = Object.create(p._attributeChangeHandlers || null);
    }
    p._attributeChangeHandlers[name] = handler3;
  };
});

// node_modules/@mixmark-io/domino/lib/FilteredElementList.js
var require_FilteredElementList = __commonJS((exports, module) => {
  module.exports = FilteredElementList;
  var Node = require_Node2();
  function FilteredElementList(root, filter) {
    this.root = root;
    this.filter = filter;
    this.lastModTime = root.lastModTime;
    this.done = false;
    this.cache = [];
    this.traverse();
  }
  FilteredElementList.prototype = Object.create(Object.prototype, {
    length: { get: function() {
      this.checkcache();
      if (!this.done)
        this.traverse();
      return this.cache.length;
    } },
    item: { value: function(n) {
      this.checkcache();
      if (!this.done && n >= this.cache.length) {
        this.traverse();
      }
      return this.cache[n];
    } },
    checkcache: { value: function() {
      if (this.lastModTime !== this.root.lastModTime) {
        for (var i = this.cache.length - 1;i >= 0; i--) {
          this[i] = undefined;
        }
        this.cache.length = 0;
        this.done = false;
        this.lastModTime = this.root.lastModTime;
      }
    } },
    traverse: { value: function(n) {
      if (n !== undefined)
        n++;
      var elt;
      while ((elt = this.next()) !== null) {
        this[this.cache.length] = elt;
        this.cache.push(elt);
        if (n && this.cache.length === n)
          return;
      }
      this.done = true;
    } },
    next: { value: function() {
      var start = this.cache.length === 0 ? this.root : this.cache[this.cache.length - 1];
      var elt;
      if (start.nodeType === Node.DOCUMENT_NODE)
        elt = start.documentElement;
      else
        elt = start.nextElement(this.root);
      while (elt) {
        if (this.filter(elt)) {
          return elt;
        }
        elt = elt.nextElement(this.root);
      }
      return null;
    } }
  });
});

// node_modules/@mixmark-io/domino/lib/DOMTokenList.js
var require_DOMTokenList = __commonJS((exports, module) => {
  var utils = require_utils();
  module.exports = DOMTokenList;
  function DOMTokenList(getter, setter) {
    this._getString = getter;
    this._setString = setter;
    this._length = 0;
    this._lastStringValue = "";
    this._update();
  }
  Object.defineProperties(DOMTokenList.prototype, {
    length: { get: function() {
      return this._length;
    } },
    item: { value: function(index) {
      var list = getList(this);
      if (index < 0 || index >= list.length) {
        return null;
      }
      return list[index];
    } },
    contains: { value: function(token) {
      token = String(token);
      var list = getList(this);
      return list.indexOf(token) > -1;
    } },
    add: { value: function() {
      var list = getList(this);
      for (var i = 0, len = arguments.length;i < len; i++) {
        var token = handleErrors(arguments[i]);
        if (list.indexOf(token) < 0) {
          list.push(token);
        }
      }
      this._update(list);
    } },
    remove: { value: function() {
      var list = getList(this);
      for (var i = 0, len = arguments.length;i < len; i++) {
        var token = handleErrors(arguments[i]);
        var index = list.indexOf(token);
        if (index > -1) {
          list.splice(index, 1);
        }
      }
      this._update(list);
    } },
    toggle: { value: function toggle(token, force) {
      token = handleErrors(token);
      if (this.contains(token)) {
        if (force === undefined || force === false) {
          this.remove(token);
          return false;
        }
        return true;
      } else {
        if (force === undefined || force === true) {
          this.add(token);
          return true;
        }
        return false;
      }
    } },
    replace: { value: function replace(token, newToken) {
      if (String(newToken) === "") {
        utils.SyntaxError();
      }
      token = handleErrors(token);
      newToken = handleErrors(newToken);
      var list = getList(this);
      var idx = list.indexOf(token);
      if (idx < 0) {
        return false;
      }
      var idx2 = list.indexOf(newToken);
      if (idx2 < 0) {
        list[idx] = newToken;
      } else {
        if (idx < idx2) {
          list[idx] = newToken;
          list.splice(idx2, 1);
        } else {
          list.splice(idx, 1);
        }
      }
      this._update(list);
      return true;
    } },
    toString: { value: function() {
      return this._getString();
    } },
    value: {
      get: function() {
        return this._getString();
      },
      set: function(v) {
        this._setString(v);
        this._update();
      }
    },
    _update: { value: function(list) {
      if (list) {
        fixIndex(this, list);
        this._setString(list.join(" ").trim());
      } else {
        fixIndex(this, getList(this));
      }
      this._lastStringValue = this._getString();
    } }
  });
  function fixIndex(clist, list) {
    var oldLength = clist._length;
    var i;
    clist._length = list.length;
    for (i = 0;i < list.length; i++) {
      clist[i] = list[i];
    }
    for (;i < oldLength; i++) {
      clist[i] = undefined;
    }
  }
  function handleErrors(token) {
    token = String(token);
    if (token === "") {
      utils.SyntaxError();
    }
    if (/[ \t\r\n\f]/.test(token)) {
      utils.InvalidCharacterError();
    }
    return token;
  }
  function toArray(clist) {
    var length = clist._length;
    var arr = Array(length);
    for (var i = 0;i < length; i++) {
      arr[i] = clist[i];
    }
    return arr;
  }
  function getList(clist) {
    var strProp = clist._getString();
    if (strProp === clist._lastStringValue) {
      return toArray(clist);
    }
    var str = strProp.replace(/(^[ \t\r\n\f]+)|([ \t\r\n\f]+$)/g, "");
    if (str === "") {
      return [];
    } else {
      var seen = Object.create(null);
      return str.split(/[ \t\r\n\f]+/g).filter(function(n) {
        var key = "$" + n;
        if (seen[key]) {
          return false;
        }
        seen[key] = true;
        return true;
      });
    }
  }
});

// node_modules/@mixmark-io/domino/lib/select.js
var require_select = __commonJS((exports, module) => {
  var window2 = Object.create(null, {
    location: { get: function() {
      throw new Error("window.location is not supported.");
    } }
  });
  var compareDocumentPosition = function(a, b) {
    return a.compareDocumentPosition(b);
  };
  var order = function(a, b) {
    return compareDocumentPosition(a, b) & 2 ? 1 : -1;
  };
  var next = function(el) {
    while ((el = el.nextSibling) && el.nodeType !== 1)
      ;
    return el;
  };
  var prev = function(el) {
    while ((el = el.previousSibling) && el.nodeType !== 1)
      ;
    return el;
  };
  var child = function(el) {
    if (el = el.firstChild) {
      while (el.nodeType !== 1 && (el = el.nextSibling))
        ;
    }
    return el;
  };
  var lastChild = function(el) {
    if (el = el.lastChild) {
      while (el.nodeType !== 1 && (el = el.previousSibling))
        ;
    }
    return el;
  };
  var parentIsElement = function(n) {
    if (!n.parentNode) {
      return false;
    }
    var nodeType = n.parentNode.nodeType;
    return nodeType === 1 || nodeType === 9;
  };
  var unquote = function(str) {
    if (!str)
      return str;
    var ch = str[0];
    if (ch === '"' || ch === "'") {
      if (str[str.length - 1] === ch) {
        str = str.slice(1, -1);
      } else {
        str = str.slice(1);
      }
      return str.replace(rules.str_escape, function(s) {
        var m = /^\\(?:([0-9A-Fa-f]+)|([\r\n\f]+))/.exec(s);
        if (!m) {
          return s.slice(1);
        }
        if (m[2]) {
          return "";
        }
        var cp = parseInt(m[1], 16);
        return String.fromCodePoint ? String.fromCodePoint(cp) : String.fromCharCode(cp);
      });
    } else if (rules.ident.test(str)) {
      return decodeid(str);
    } else {
      return str;
    }
  };
  var decodeid = function(str) {
    return str.replace(rules.escape, function(s) {
      var m = /^\\([0-9A-Fa-f]+)/.exec(s);
      if (!m) {
        return s[1];
      }
      var cp = parseInt(m[1], 16);
      return String.fromCodePoint ? String.fromCodePoint(cp) : String.fromCharCode(cp);
    });
  };
  var indexOf = function() {
    if (Array.prototype.indexOf) {
      return Array.prototype.indexOf;
    }
    return function(obj, item) {
      var i = this.length;
      while (i--) {
        if (this[i] === item)
          return i;
      }
      return -1;
    };
  }();
  var makeInside = function(start, end) {
    var regex = rules.inside.source.replace(/</g, start).replace(/>/g, end);
    return new RegExp(regex);
  };
  var replace = function(regex, name, val) {
    regex = regex.source;
    regex = regex.replace(name, val.source || val);
    return new RegExp(regex);
  };
  var truncateUrl = function(url, num2) {
    return url.replace(/^(?:\w+:\/\/|\/+)/, "").replace(/(?:\/+|\/*#.*?)$/, "").split("/", num2).join("/");
  };
  var parseNth = function(param_, test) {
    var param = param_.replace(/\s+/g, ""), cap;
    if (param === "even") {
      param = "2n+0";
    } else if (param === "odd") {
      param = "2n+1";
    } else if (param.indexOf("n") === -1) {
      param = "0n" + param;
    }
    cap = /^([+-])?(\d+)?n([+-])?(\d+)?$/.exec(param);
    return {
      group: cap[1] === "-" ? -(cap[2] || 1) : +(cap[2] || 1),
      offset: cap[4] ? cap[3] === "-" ? -cap[4] : +cap[4] : 0
    };
  };
  var nth = function(param_, test, last) {
    var param = parseNth(param_), group = param.group, offset = param.offset, find2 = !last ? child : lastChild, advance = !last ? next : prev;
    return function(el) {
      if (!parentIsElement(el))
        return;
      var rel = find2(el.parentNode), pos = 0;
      while (rel) {
        if (test(rel, el))
          pos++;
        if (rel === el) {
          pos -= offset;
          return group && pos ? pos % group === 0 && pos < 0 === group < 0 : !pos;
        }
        rel = advance(rel);
      }
    };
  };
  var selectors = {
    "*": function() {
      if (false) {}
      return function() {
        return true;
      };
    }(),
    type: function(type) {
      type = type.toLowerCase();
      return function(el) {
        return el.nodeName.toLowerCase() === type;
      };
    },
    attr: function(key, op, val, i) {
      op = operators[op];
      return function(el) {
        var attr;
        switch (key) {
          case "for":
            attr = el.htmlFor;
            break;
          case "class":
            attr = el.className;
            if (attr === "" && el.getAttribute("class") == null) {
              attr = null;
            }
            break;
          case "href":
          case "src":
            attr = el.getAttribute(key, 2);
            break;
          case "title":
            attr = el.getAttribute("title") || null;
            break;
          case "id":
          case "lang":
          case "dir":
          case "accessKey":
          case "hidden":
          case "tabIndex":
          case "style":
            if (el.getAttribute) {
              attr = el.getAttribute(key);
              break;
            }
          default:
            if (el.hasAttribute && !el.hasAttribute(key)) {
              break;
            }
            attr = el[key] != null ? el[key] : el.getAttribute && el.getAttribute(key);
            break;
        }
        if (attr == null)
          return;
        attr = attr + "";
        if (i) {
          attr = attr.toLowerCase();
          val = val.toLowerCase();
        }
        return op(attr, val);
      };
    },
    ":first-child": function(el) {
      return !prev(el) && parentIsElement(el);
    },
    ":last-child": function(el) {
      return !next(el) && parentIsElement(el);
    },
    ":only-child": function(el) {
      return !prev(el) && !next(el) && parentIsElement(el);
    },
    ":nth-child": function(param, last) {
      return nth(param, function() {
        return true;
      }, last);
    },
    ":nth-last-child": function(param) {
      return selectors[":nth-child"](param, true);
    },
    ":root": function(el) {
      return el.ownerDocument.documentElement === el;
    },
    ":empty": function(el) {
      return !el.firstChild;
    },
    ":not": function(sel) {
      var test = compileGroup(sel);
      return function(el) {
        return !test(el);
      };
    },
    ":first-of-type": function(el) {
      if (!parentIsElement(el))
        return;
      var type = el.nodeName;
      while (el = prev(el)) {
        if (el.nodeName === type)
          return;
      }
      return true;
    },
    ":last-of-type": function(el) {
      if (!parentIsElement(el))
        return;
      var type = el.nodeName;
      while (el = next(el)) {
        if (el.nodeName === type)
          return;
      }
      return true;
    },
    ":only-of-type": function(el) {
      return selectors[":first-of-type"](el) && selectors[":last-of-type"](el);
    },
    ":nth-of-type": function(param, last) {
      return nth(param, function(rel, el) {
        return rel.nodeName === el.nodeName;
      }, last);
    },
    ":nth-last-of-type": function(param) {
      return selectors[":nth-of-type"](param, true);
    },
    ":checked": function(el) {
      return !!(el.checked || el.selected);
    },
    ":indeterminate": function(el) {
      return !selectors[":checked"](el);
    },
    ":enabled": function(el) {
      return !el.disabled && el.type !== "hidden";
    },
    ":disabled": function(el) {
      return !!el.disabled;
    },
    ":target": function(el) {
      return el.id === window2.location.hash.substring(1);
    },
    ":focus": function(el) {
      return el === el.ownerDocument.activeElement;
    },
    ":is": function(sel) {
      return compileGroup(sel);
    },
    ":matches": function(sel) {
      return selectors[":is"](sel);
    },
    ":nth-match": function(param, last) {
      var args = param.split(/\s*,\s*/), arg = args.shift(), test = compileGroup(args.join(","));
      return nth(arg, test, last);
    },
    ":nth-last-match": function(param) {
      return selectors[":nth-match"](param, true);
    },
    ":links-here": function(el) {
      return el + "" === window2.location + "";
    },
    ":lang": function(param) {
      return function(el) {
        while (el) {
          if (el.lang)
            return el.lang.indexOf(param) === 0;
          el = el.parentNode;
        }
      };
    },
    ":dir": function(param) {
      return function(el) {
        while (el) {
          if (el.dir)
            return el.dir === param;
          el = el.parentNode;
        }
      };
    },
    ":scope": function(el, con) {
      var context = con || el.ownerDocument;
      if (context.nodeType === 9) {
        return el === context.documentElement;
      }
      return el === context;
    },
    ":any-link": function(el) {
      return typeof el.href === "string";
    },
    ":local-link": function(el) {
      if (el.nodeName) {
        return el.href && el.host === window2.location.host;
      }
      var param = +el + 1;
      return function(el2) {
        if (!el2.href)
          return;
        var url = window2.location + "", href = el2 + "";
        return truncateUrl(url, param) === truncateUrl(href, param);
      };
    },
    ":default": function(el) {
      return !!el.defaultSelected;
    },
    ":valid": function(el) {
      return el.willValidate || el.validity && el.validity.valid;
    },
    ":invalid": function(el) {
      return !selectors[":valid"](el);
    },
    ":in-range": function(el) {
      return el.value > el.min && el.value <= el.max;
    },
    ":out-of-range": function(el) {
      return !selectors[":in-range"](el);
    },
    ":required": function(el) {
      return !!el.required;
    },
    ":optional": function(el) {
      return !el.required;
    },
    ":read-only": function(el) {
      if (el.readOnly)
        return true;
      var attr = el.getAttribute("contenteditable"), prop = el.contentEditable, name = el.nodeName.toLowerCase();
      name = name !== "input" && name !== "textarea";
      return (name || el.disabled) && attr == null && prop !== "true";
    },
    ":read-write": function(el) {
      return !selectors[":read-only"](el);
    },
    ":hover": function() {
      throw new Error(":hover is not supported.");
    },
    ":active": function() {
      throw new Error(":active is not supported.");
    },
    ":link": function() {
      throw new Error(":link is not supported.");
    },
    ":visited": function() {
      throw new Error(":visited is not supported.");
    },
    ":column": function() {
      throw new Error(":column is not supported.");
    },
    ":nth-column": function() {
      throw new Error(":nth-column is not supported.");
    },
    ":nth-last-column": function() {
      throw new Error(":nth-last-column is not supported.");
    },
    ":current": function() {
      throw new Error(":current is not supported.");
    },
    ":past": function() {
      throw new Error(":past is not supported.");
    },
    ":future": function() {
      throw new Error(":future is not supported.");
    },
    ":contains": function(param) {
      return function(el) {
        var text = el.innerText || el.textContent || el.value || "";
        return text.indexOf(param) !== -1;
      };
    },
    ":has": function(param) {
      return function(el) {
        return find(param, el).length > 0;
      };
    }
  };
  var operators = {
    "-": function() {
      return true;
    },
    "=": function(attr, val) {
      return attr === val;
    },
    "*=": function(attr, val) {
      return attr.indexOf(val) !== -1;
    },
    "~=": function(attr, val) {
      var i, s, f, l;
      for (s = 0;; s = i + 1) {
        i = attr.indexOf(val, s);
        if (i === -1)
          return false;
        f = attr[i - 1];
        l = attr[i + val.length];
        if ((!f || f === " ") && (!l || l === " "))
          return true;
      }
    },
    "|=": function(attr, val) {
      var i = attr.indexOf(val), l;
      if (i !== 0)
        return;
      l = attr[i + val.length];
      return l === "-" || !l;
    },
    "^=": function(attr, val) {
      return attr.indexOf(val) === 0;
    },
    "$=": function(attr, val) {
      var i = attr.lastIndexOf(val);
      return i !== -1 && i + val.length === attr.length;
    },
    "!=": function(attr, val) {
      return attr !== val;
    }
  };
  var combinators = {
    " ": function(test) {
      return function(el) {
        while (el = el.parentNode) {
          if (test(el))
            return el;
        }
      };
    },
    ">": function(test) {
      return function(el) {
        if (el = el.parentNode) {
          return test(el) && el;
        }
      };
    },
    "+": function(test) {
      return function(el) {
        if (el = prev(el)) {
          return test(el) && el;
        }
      };
    },
    "~": function(test) {
      return function(el) {
        while (el = prev(el)) {
          if (test(el))
            return el;
        }
      };
    },
    noop: function(test) {
      return function(el) {
        return test(el) && el;
      };
    },
    ref: function(test, name) {
      var node;
      function ref(el) {
        var doc = el.ownerDocument, nodes = doc.getElementsByTagName("*"), i = nodes.length;
        while (i--) {
          node = nodes[i];
          if (ref.test(el)) {
            node = null;
            return true;
          }
        }
        node = null;
      }
      ref.combinator = function(el) {
        if (!node || !node.getAttribute)
          return;
        var attr = node.getAttribute(name) || "";
        if (attr[0] === "#")
          attr = attr.substring(1);
        if (attr === el.id && test(node)) {
          return node;
        }
      };
      return ref;
    }
  };
  var rules = {
    escape: /\\(?:[^0-9A-Fa-f\r\n]|[0-9A-Fa-f]{1,6}[\r\n\t ]?)/g,
    str_escape: /(escape)|\\(\n|\r\n?|\f)/g,
    nonascii: /[\u00A0-\uFFFF]/,
    cssid: /(?:(?!-?[0-9])(?:escape|nonascii|[-_a-zA-Z0-9])+)/,
    qname: /^ *(cssid|\*)/,
    simple: /^(?:([.#]cssid)|pseudo|attr)/,
    ref: /^ *\/(cssid)\/ */,
    combinator: /^(?: +([^ \w*.#\\]) +|( )+|([^ \w*.#\\]))(?! *$)/,
    attr: /^\[(cssid)(?:([^\w]?=)(inside))?\]/,
    pseudo: /^(:cssid)(?:\((inside)\))?/,
    inside: /(?:"(?:\\"|[^"])*"|'(?:\\'|[^'])*'|<[^"'>]*>|\\["'>]|[^"'>])*/,
    ident: /^(cssid)$/
  };
  rules.cssid = replace(rules.cssid, "nonascii", rules.nonascii);
  rules.cssid = replace(rules.cssid, "escape", rules.escape);
  rules.qname = replace(rules.qname, "cssid", rules.cssid);
  rules.simple = replace(rules.simple, "cssid", rules.cssid);
  rules.ref = replace(rules.ref, "cssid", rules.cssid);
  rules.attr = replace(rules.attr, "cssid", rules.cssid);
  rules.pseudo = replace(rules.pseudo, "cssid", rules.cssid);
  rules.inside = replace(rules.inside, `[^"'>]*`, rules.inside);
  rules.attr = replace(rules.attr, "inside", makeInside("\\[", "\\]"));
  rules.pseudo = replace(rules.pseudo, "inside", makeInside("\\(", "\\)"));
  rules.simple = replace(rules.simple, "pseudo", rules.pseudo);
  rules.simple = replace(rules.simple, "attr", rules.attr);
  rules.ident = replace(rules.ident, "cssid", rules.cssid);
  rules.str_escape = replace(rules.str_escape, "escape", rules.escape);
  var compile = function(sel_) {
    var sel = sel_.replace(/^\s+|\s+$/g, ""), test, filter = [], buff = [], subject, qname, cap, op, ref;
    while (sel) {
      if (cap = rules.qname.exec(sel)) {
        sel = sel.substring(cap[0].length);
        qname = decodeid(cap[1]);
        buff.push(tok(qname, true));
      } else if (cap = rules.simple.exec(sel)) {
        sel = sel.substring(cap[0].length);
        qname = "*";
        buff.push(tok(qname, true));
        buff.push(tok(cap));
      } else {
        throw new SyntaxError("Invalid selector.");
      }
      while (cap = rules.simple.exec(sel)) {
        sel = sel.substring(cap[0].length);
        buff.push(tok(cap));
      }
      if (sel[0] === "!") {
        sel = sel.substring(1);
        subject = makeSubject();
        subject.qname = qname;
        buff.push(subject.simple);
      }
      if (cap = rules.ref.exec(sel)) {
        sel = sel.substring(cap[0].length);
        ref = combinators.ref(makeSimple(buff), decodeid(cap[1]));
        filter.push(ref.combinator);
        buff = [];
        continue;
      }
      if (cap = rules.combinator.exec(sel)) {
        sel = sel.substring(cap[0].length);
        op = cap[1] || cap[2] || cap[3];
        if (op === ",") {
          filter.push(combinators.noop(makeSimple(buff)));
          break;
        }
      } else {
        op = "noop";
      }
      if (!combinators[op]) {
        throw new SyntaxError("Bad combinator.");
      }
      filter.push(combinators[op](makeSimple(buff)));
      buff = [];
    }
    test = makeTest(filter);
    test.qname = qname;
    test.sel = sel;
    if (subject) {
      subject.lname = test.qname;
      subject.test = test;
      subject.qname = subject.qname;
      subject.sel = test.sel;
      test = subject;
    }
    if (ref) {
      ref.test = test;
      ref.qname = test.qname;
      ref.sel = test.sel;
      test = ref;
    }
    return test;
  };
  var tok = function(cap, qname) {
    if (qname) {
      return cap === "*" ? selectors["*"] : selectors.type(cap);
    }
    if (cap[1]) {
      return cap[1][0] === "." ? selectors.attr("class", "~=", decodeid(cap[1].substring(1)), false) : selectors.attr("id", "=", decodeid(cap[1].substring(1)), false);
    }
    if (cap[2]) {
      return cap[3] ? selectors[decodeid(cap[2])](unquote(cap[3])) : selectors[decodeid(cap[2])];
    }
    if (cap[4]) {
      var value = cap[6];
      var i = /["'\s]\s*I$/i.test(value);
      if (i) {
        value = value.replace(/\s*I$/i, "");
      }
      return selectors.attr(decodeid(cap[4]), cap[5] || "-", unquote(value), i);
    }
    throw new SyntaxError("Unknown Selector.");
  };
  var makeSimple = function(func) {
    var l = func.length, i;
    if (l < 2)
      return func[0];
    return function(el) {
      if (!el)
        return;
      for (i = 0;i < l; i++) {
        if (!func[i](el))
          return;
      }
      return true;
    };
  };
  var makeTest = function(func) {
    if (func.length < 2) {
      return function(el) {
        return !!func[0](el);
      };
    }
    return function(el) {
      var i = func.length;
      while (i--) {
        if (!(el = func[i](el)))
          return;
      }
      return true;
    };
  };
  var makeSubject = function() {
    var target;
    function subject(el) {
      var node = el.ownerDocument, scope = node.getElementsByTagName(subject.lname), i = scope.length;
      while (i--) {
        if (subject.test(scope[i]) && target === el) {
          target = null;
          return true;
        }
      }
      target = null;
    }
    subject.simple = function(el) {
      target = el;
      return true;
    };
    return subject;
  };
  var compileGroup = function(sel) {
    var test = compile(sel), tests = [test];
    while (test.sel) {
      test = compile(test.sel);
      tests.push(test);
    }
    if (tests.length < 2)
      return test;
    return function(el) {
      var l = tests.length, i = 0;
      for (;i < l; i++) {
        if (tests[i](el))
          return true;
      }
    };
  };
  var find = function(sel, node) {
    var results = [], test = compile(sel), scope = node.getElementsByTagName(test.qname), i = 0, el;
    while (el = scope[i++]) {
      if (test(el))
        results.push(el);
    }
    if (test.sel) {
      while (test.sel) {
        test = compile(test.sel);
        scope = node.getElementsByTagName(test.qname);
        i = 0;
        while (el = scope[i++]) {
          if (test(el) && indexOf.call(results, el) === -1) {
            results.push(el);
          }
        }
      }
      results.sort(order);
    }
    return results;
  };
  module.exports = exports = function(sel, context) {
    var id, r;
    if (context.nodeType !== 11 && sel.indexOf(" ") === -1) {
      if (sel[0] === "#" && context.rooted && /^#[A-Z_][-A-Z0-9_]*$/i.test(sel)) {
        if (context.doc._hasMultipleElementsWithId) {
          id = sel.substring(1);
          if (!context.doc._hasMultipleElementsWithId(id)) {
            r = context.doc.getElementById(id);
            return r ? [r] : [];
          }
        }
      }
      if (sel[0] === "." && /^\.\w+$/.test(sel)) {
        return context.getElementsByClassName(sel.substring(1));
      }
      if (/^\w+$/.test(sel)) {
        return context.getElementsByTagName(sel);
      }
    }
    return find(sel, context);
  };
  exports.selectors = selectors;
  exports.operators = operators;
  exports.combinators = combinators;
  exports.matches = function(el, sel) {
    var test = { sel };
    do {
      test = compile(test.sel);
      if (test(el)) {
        return true;
      }
    } while (test.sel);
    return false;
  };
});

// node_modules/@mixmark-io/domino/lib/ChildNode.js
var require_ChildNode = __commonJS((exports, module) => {
  var Node = require_Node2();
  var LinkedList = require_LinkedList();
  var createDocumentFragmentFromArguments = function(document, args) {
    var docFrag = document.createDocumentFragment();
    for (var i = 0;i < args.length; i++) {
      var argItem = args[i];
      var isNode = argItem instanceof Node;
      docFrag.appendChild(isNode ? argItem : document.createTextNode(String(argItem)));
    }
    return docFrag;
  };
  var ChildNode = {
    after: { value: function after() {
      var argArr = Array.prototype.slice.call(arguments);
      var parentNode = this.parentNode, nextSibling = this.nextSibling;
      if (parentNode === null) {
        return;
      }
      while (nextSibling && argArr.some(function(v) {
        return v === nextSibling;
      }))
        nextSibling = nextSibling.nextSibling;
      var docFrag = createDocumentFragmentFromArguments(this.doc, argArr);
      parentNode.insertBefore(docFrag, nextSibling);
    } },
    before: { value: function before() {
      var argArr = Array.prototype.slice.call(arguments);
      var parentNode = this.parentNode, prevSibling = this.previousSibling;
      if (parentNode === null) {
        return;
      }
      while (prevSibling && argArr.some(function(v) {
        return v === prevSibling;
      }))
        prevSibling = prevSibling.previousSibling;
      var docFrag = createDocumentFragmentFromArguments(this.doc, argArr);
      var nextSibling = prevSibling ? prevSibling.nextSibling : parentNode.firstChild;
      parentNode.insertBefore(docFrag, nextSibling);
    } },
    remove: { value: function remove() {
      if (this.parentNode === null)
        return;
      if (this.doc) {
        this.doc._preremoveNodeIterators(this);
        if (this.rooted) {
          this.doc.mutateRemove(this);
        }
      }
      this._remove();
      this.parentNode = null;
    } },
    _remove: { value: function _remove() {
      var parent = this.parentNode;
      if (parent === null)
        return;
      if (parent._childNodes) {
        parent._childNodes.splice(this.index, 1);
      } else if (parent._firstChild === this) {
        if (this._nextSibling === this) {
          parent._firstChild = null;
        } else {
          parent._firstChild = this._nextSibling;
        }
      }
      LinkedList.remove(this);
      parent.modify();
    } },
    replaceWith: { value: function replaceWith() {
      var argArr = Array.prototype.slice.call(arguments);
      var parentNode = this.parentNode, nextSibling = this.nextSibling;
      if (parentNode === null) {
        return;
      }
      while (nextSibling && argArr.some(function(v) {
        return v === nextSibling;
      }))
        nextSibling = nextSibling.nextSibling;
      var docFrag = createDocumentFragmentFromArguments(this.doc, argArr);
      if (this.parentNode === parentNode) {
        parentNode.replaceChild(docFrag, this);
      } else {
        parentNode.insertBefore(docFrag, nextSibling);
      }
    } }
  };
  module.exports = ChildNode;
});

// node_modules/@mixmark-io/domino/lib/NonDocumentTypeChildNode.js
var require_NonDocumentTypeChildNode = __commonJS((exports, module) => {
  var Node = require_Node2();
  var NonDocumentTypeChildNode = {
    nextElementSibling: { get: function() {
      if (this.parentNode) {
        for (var kid = this.nextSibling;kid !== null; kid = kid.nextSibling) {
          if (kid.nodeType === Node.ELEMENT_NODE)
            return kid;
        }
      }
      return null;
    } },
    previousElementSibling: { get: function() {
      if (this.parentNode) {
        for (var kid = this.previousSibling;kid !== null; kid = kid.previousSibling) {
          if (kid.nodeType === Node.ELEMENT_NODE)
            return kid;
        }
      }
      return null;
    } }
  };
  module.exports = NonDocumentTypeChildNode;
});

// node_modules/@mixmark-io/domino/lib/NamedNodeMap.js
var require_NamedNodeMap = __commonJS((exports, module) => {
  module.exports = NamedNodeMap;
  var utils = require_utils();
  function NamedNodeMap(element) {
    this.element = element;
  }
  Object.defineProperties(NamedNodeMap.prototype, {
    length: { get: utils.shouldOverride },
    item: { value: utils.shouldOverride },
    getNamedItem: { value: function getNamedItem(qualifiedName) {
      return this.element.getAttributeNode(qualifiedName);
    } },
    getNamedItemNS: { value: function getNamedItemNS(namespace, localName) {
      return this.element.getAttributeNodeNS(namespace, localName);
    } },
    setNamedItem: { value: utils.nyi },
    setNamedItemNS: { value: utils.nyi },
    removeNamedItem: { value: function removeNamedItem(qualifiedName) {
      var attr = this.element.getAttributeNode(qualifiedName);
      if (attr) {
        this.element.removeAttribute(qualifiedName);
        return attr;
      }
      utils.NotFoundError();
    } },
    removeNamedItemNS: { value: function removeNamedItemNS(ns, lname) {
      var attr = this.element.getAttributeNodeNS(ns, lname);
      if (attr) {
        this.element.removeAttributeNS(ns, lname);
        return attr;
      }
      utils.NotFoundError();
    } }
  });
});

// node_modules/@mixmark-io/domino/lib/Element.js
var require_Element = __commonJS((exports, module) => {
  module.exports = Element;
  var xml = require_xmlnames();
  var utils = require_utils();
  var NAMESPACE = utils.NAMESPACE;
  var attributes = require_attributes();
  var Node = require_Node2();
  var NodeList = require_NodeList();
  var NodeUtils = require_NodeUtils();
  var FilteredElementList = require_FilteredElementList();
  var DOMException2 = require_DOMException();
  var DOMTokenList = require_DOMTokenList();
  var select = require_select();
  var ContainerNode = require_ContainerNode();
  var ChildNode = require_ChildNode();
  var NonDocumentTypeChildNode = require_NonDocumentTypeChildNode();
  var NamedNodeMap = require_NamedNodeMap();
  var uppercaseCache = Object.create(null);
  function Element(doc, localName, namespaceURI, prefix) {
    ContainerNode.call(this);
    this.nodeType = Node.ELEMENT_NODE;
    this.ownerDocument = doc;
    this.localName = localName;
    this.namespaceURI = namespaceURI;
    this.prefix = prefix;
    this._tagName = undefined;
    this._attrsByQName = Object.create(null);
    this._attrsByLName = Object.create(null);
    this._attrKeys = [];
  }
  function recursiveGetText(node, a) {
    if (node.nodeType === Node.TEXT_NODE) {
      a.push(node._data);
    } else {
      for (var i = 0, n = node.childNodes.length;i < n; i++)
        recursiveGetText(node.childNodes[i], a);
    }
  }
  Element.prototype = Object.create(ContainerNode.prototype, {
    isHTML: { get: function isHTML() {
      return this.namespaceURI === NAMESPACE.HTML && this.ownerDocument.isHTML;
    } },
    tagName: { get: function tagName() {
      if (this._tagName === undefined) {
        var tn;
        if (this.prefix === null) {
          tn = this.localName;
        } else {
          tn = this.prefix + ":" + this.localName;
        }
        if (this.isHTML) {
          var up = uppercaseCache[tn];
          if (!up) {
            uppercaseCache[tn] = up = utils.toASCIIUpperCase(tn);
          }
          tn = up;
        }
        this._tagName = tn;
      }
      return this._tagName;
    } },
    nodeName: { get: function() {
      return this.tagName;
    } },
    nodeValue: {
      get: function() {
        return null;
      },
      set: function() {}
    },
    textContent: {
      get: function() {
        var strings = [];
        recursiveGetText(this, strings);
        return strings.join("");
      },
      set: function(newtext) {
        this.removeChildren();
        if (newtext !== null && newtext !== undefined && newtext !== "") {
          this._appendChild(this.ownerDocument.createTextNode(newtext));
        }
      }
    },
    innerText: {
      get: function() {
        var strings = [];
        recursiveGetText(this, strings);
        return strings.join("").replace(/[ \t\n\f\r]+/g, " ").trim();
      },
      set: function(newtext) {
        this.removeChildren();
        if (newtext !== null && newtext !== undefined && newtext !== "") {
          this._appendChild(this.ownerDocument.createTextNode(newtext));
        }
      }
    },
    innerHTML: {
      get: function() {
        return this.serialize();
      },
      set: utils.nyi
    },
    outerHTML: {
      get: function() {
        return NodeUtils.serializeOne(this, { nodeType: 0 });
      },
      set: function(v) {
        var document = this.ownerDocument;
        var parent = this.parentNode;
        if (parent === null) {
          return;
        }
        if (parent.nodeType === Node.DOCUMENT_NODE) {
          utils.NoModificationAllowedError();
        }
        if (parent.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
          parent = parent.ownerDocument.createElement("body");
        }
        var parser2 = document.implementation.mozHTMLParser(document._address, parent);
        parser2.parse(v === null ? "" : String(v), true);
        this.replaceWith(parser2._asDocumentFragment());
      }
    },
    _insertAdjacent: { value: function _insertAdjacent(position, node) {
      var first = false;
      switch (position) {
        case "beforebegin":
          first = true;
        case "afterend":
          var parent = this.parentNode;
          if (parent === null) {
            return null;
          }
          return parent.insertBefore(node, first ? this : this.nextSibling);
        case "afterbegin":
          first = true;
        case "beforeend":
          return this.insertBefore(node, first ? this.firstChild : null);
        default:
          return utils.SyntaxError();
      }
    } },
    insertAdjacentElement: { value: function insertAdjacentElement(position, element) {
      if (element.nodeType !== Node.ELEMENT_NODE) {
        throw new TypeError("not an element");
      }
      position = utils.toASCIILowerCase(String(position));
      return this._insertAdjacent(position, element);
    } },
    insertAdjacentText: { value: function insertAdjacentText(position, data) {
      var textNode = this.ownerDocument.createTextNode(data);
      position = utils.toASCIILowerCase(String(position));
      this._insertAdjacent(position, textNode);
    } },
    insertAdjacentHTML: { value: function insertAdjacentHTML(position, text) {
      position = utils.toASCIILowerCase(String(position));
      text = String(text);
      var context;
      switch (position) {
        case "beforebegin":
        case "afterend":
          context = this.parentNode;
          if (context === null || context.nodeType === Node.DOCUMENT_NODE) {
            utils.NoModificationAllowedError();
          }
          break;
        case "afterbegin":
        case "beforeend":
          context = this;
          break;
        default:
          utils.SyntaxError();
      }
      if (!(context instanceof Element) || context.ownerDocument.isHTML && context.localName === "html" && context.namespaceURI === NAMESPACE.HTML) {
        context = context.ownerDocument.createElementNS(NAMESPACE.HTML, "body");
      }
      var parser2 = this.ownerDocument.implementation.mozHTMLParser(this.ownerDocument._address, context);
      parser2.parse(text, true);
      this._insertAdjacent(position, parser2._asDocumentFragment());
    } },
    children: { get: function() {
      if (!this._children) {
        this._children = new ChildrenCollection(this);
      }
      return this._children;
    } },
    attributes: { get: function() {
      if (!this._attributes) {
        this._attributes = new AttributesArray(this);
      }
      return this._attributes;
    } },
    firstElementChild: { get: function() {
      for (var kid = this.firstChild;kid !== null; kid = kid.nextSibling) {
        if (kid.nodeType === Node.ELEMENT_NODE)
          return kid;
      }
      return null;
    } },
    lastElementChild: { get: function() {
      for (var kid = this.lastChild;kid !== null; kid = kid.previousSibling) {
        if (kid.nodeType === Node.ELEMENT_NODE)
          return kid;
      }
      return null;
    } },
    childElementCount: { get: function() {
      return this.children.length;
    } },
    nextElement: { value: function(root) {
      if (!root)
        root = this.ownerDocument.documentElement;
      var next = this.firstElementChild;
      if (!next) {
        if (this === root)
          return null;
        next = this.nextElementSibling;
      }
      if (next)
        return next;
      for (var parent = this.parentElement;parent && parent !== root; parent = parent.parentElement) {
        next = parent.nextElementSibling;
        if (next)
          return next;
      }
      return null;
    } },
    getElementsByTagName: { value: function getElementsByTagName(lname) {
      var filter;
      if (!lname)
        return new NodeList;
      if (lname === "*")
        filter = function() {
          return true;
        };
      else if (this.isHTML)
        filter = htmlLocalNameElementFilter(lname);
      else
        filter = localNameElementFilter(lname);
      return new FilteredElementList(this, filter);
    } },
    getElementsByTagNameNS: { value: function getElementsByTagNameNS(ns, lname) {
      var filter;
      if (ns === "*" && lname === "*")
        filter = function() {
          return true;
        };
      else if (ns === "*")
        filter = localNameElementFilter(lname);
      else if (lname === "*")
        filter = namespaceElementFilter(ns);
      else
        filter = namespaceLocalNameElementFilter(ns, lname);
      return new FilteredElementList(this, filter);
    } },
    getElementsByClassName: { value: function getElementsByClassName(names) {
      names = String(names).trim();
      if (names === "") {
        var result = new NodeList;
        return result;
      }
      names = names.split(/[ \t\r\n\f]+/);
      return new FilteredElementList(this, classNamesElementFilter(names));
    } },
    getElementsByName: { value: function getElementsByName(name) {
      return new FilteredElementList(this, elementNameFilter(String(name)));
    } },
    clone: { value: function clone() {
      var e;
      if (this.namespaceURI !== NAMESPACE.HTML || this.prefix || !this.ownerDocument.isHTML) {
        e = this.ownerDocument.createElementNS(this.namespaceURI, this.prefix !== null ? this.prefix + ":" + this.localName : this.localName);
      } else {
        e = this.ownerDocument.createElement(this.localName);
      }
      for (var i = 0, n = this._attrKeys.length;i < n; i++) {
        var lname = this._attrKeys[i];
        var a = this._attrsByLName[lname];
        var b = a.cloneNode();
        b._setOwnerElement(e);
        e._attrsByLName[lname] = b;
        e._addQName(b);
      }
      e._attrKeys = this._attrKeys.concat();
      return e;
    } },
    isEqual: { value: function isEqual(that) {
      if (this.localName !== that.localName || this.namespaceURI !== that.namespaceURI || this.prefix !== that.prefix || this._numattrs !== that._numattrs)
        return false;
      for (var i = 0, n = this._numattrs;i < n; i++) {
        var a = this._attr(i);
        if (!that.hasAttributeNS(a.namespaceURI, a.localName))
          return false;
        if (that.getAttributeNS(a.namespaceURI, a.localName) !== a.value)
          return false;
      }
      return true;
    } },
    _lookupNamespacePrefix: { value: function _lookupNamespacePrefix(ns, originalElement) {
      if (this.namespaceURI && this.namespaceURI === ns && this.prefix !== null && originalElement.lookupNamespaceURI(this.prefix) === ns) {
        return this.prefix;
      }
      for (var i = 0, n = this._numattrs;i < n; i++) {
        var a = this._attr(i);
        if (a.prefix === "xmlns" && a.value === ns && originalElement.lookupNamespaceURI(a.localName) === ns) {
          return a.localName;
        }
      }
      var parent = this.parentElement;
      return parent ? parent._lookupNamespacePrefix(ns, originalElement) : null;
    } },
    lookupNamespaceURI: { value: function lookupNamespaceURI(prefix) {
      if (prefix === "" || prefix === undefined) {
        prefix = null;
      }
      if (this.namespaceURI !== null && this.prefix === prefix)
        return this.namespaceURI;
      for (var i = 0, n = this._numattrs;i < n; i++) {
        var a = this._attr(i);
        if (a.namespaceURI === NAMESPACE.XMLNS) {
          if (a.prefix === "xmlns" && a.localName === prefix || prefix === null && a.prefix === null && a.localName === "xmlns") {
            return a.value || null;
          }
        }
      }
      var parent = this.parentElement;
      return parent ? parent.lookupNamespaceURI(prefix) : null;
    } },
    getAttribute: { value: function getAttribute(qname) {
      var attr = this.getAttributeNode(qname);
      return attr ? attr.value : null;
    } },
    getAttributeNS: { value: function getAttributeNS(ns, lname) {
      var attr = this.getAttributeNodeNS(ns, lname);
      return attr ? attr.value : null;
    } },
    getAttributeNode: { value: function getAttributeNode(qname) {
      qname = String(qname);
      if (/[A-Z]/.test(qname) && this.isHTML)
        qname = utils.toASCIILowerCase(qname);
      var attr = this._attrsByQName[qname];
      if (!attr)
        return null;
      if (Array.isArray(attr))
        attr = attr[0];
      return attr;
    } },
    getAttributeNodeNS: { value: function getAttributeNodeNS(ns, lname) {
      ns = ns === undefined || ns === null ? "" : String(ns);
      lname = String(lname);
      var attr = this._attrsByLName[ns + "|" + lname];
      return attr ? attr : null;
    } },
    hasAttribute: { value: function hasAttribute(qname) {
      qname = String(qname);
      if (/[A-Z]/.test(qname) && this.isHTML)
        qname = utils.toASCIILowerCase(qname);
      return this._attrsByQName[qname] !== undefined;
    } },
    hasAttributeNS: { value: function hasAttributeNS(ns, lname) {
      ns = ns === undefined || ns === null ? "" : String(ns);
      lname = String(lname);
      var key = ns + "|" + lname;
      return this._attrsByLName[key] !== undefined;
    } },
    hasAttributes: { value: function hasAttributes() {
      return this._numattrs > 0;
    } },
    toggleAttribute: { value: function toggleAttribute(qname, force) {
      qname = String(qname);
      if (!xml.isValidName(qname))
        utils.InvalidCharacterError();
      if (/[A-Z]/.test(qname) && this.isHTML)
        qname = utils.toASCIILowerCase(qname);
      var a = this._attrsByQName[qname];
      if (a === undefined) {
        if (force === undefined || force === true) {
          this._setAttribute(qname, "");
          return true;
        }
        return false;
      } else {
        if (force === undefined || force === false) {
          this.removeAttribute(qname);
          return false;
        }
        return true;
      }
    } },
    _setAttribute: { value: function _setAttribute(qname, value) {
      var attr = this._attrsByQName[qname];
      var isnew;
      if (!attr) {
        attr = this._newattr(qname);
        isnew = true;
      } else {
        if (Array.isArray(attr))
          attr = attr[0];
      }
      attr.value = value;
      if (this._attributes)
        this._attributes[qname] = attr;
      if (isnew && this._newattrhook)
        this._newattrhook(qname, value);
    } },
    setAttribute: { value: function setAttribute(qname, value) {
      qname = String(qname);
      if (!xml.isValidName(qname))
        utils.InvalidCharacterError();
      if (/[A-Z]/.test(qname) && this.isHTML)
        qname = utils.toASCIILowerCase(qname);
      this._setAttribute(qname, String(value));
    } },
    _setAttributeNS: { value: function _setAttributeNS(ns, qname, value) {
      var pos = qname.indexOf(":"), prefix, lname;
      if (pos < 0) {
        prefix = null;
        lname = qname;
      } else {
        prefix = qname.substring(0, pos);
        lname = qname.substring(pos + 1);
      }
      if (ns === "" || ns === undefined)
        ns = null;
      var key = (ns === null ? "" : ns) + "|" + lname;
      var attr = this._attrsByLName[key];
      var isnew;
      if (!attr) {
        attr = new Attr(this, lname, prefix, ns);
        isnew = true;
        this._attrsByLName[key] = attr;
        if (this._attributes) {
          this._attributes[this._attrKeys.length] = attr;
        }
        this._attrKeys.push(key);
        this._addQName(attr);
      } else if (false) {}
      attr.value = value;
      if (isnew && this._newattrhook)
        this._newattrhook(qname, value);
    } },
    setAttributeNS: { value: function setAttributeNS(ns, qname, value) {
      ns = ns === null || ns === undefined || ns === "" ? null : String(ns);
      qname = String(qname);
      if (!xml.isValidQName(qname))
        utils.InvalidCharacterError();
      var pos = qname.indexOf(":");
      var prefix = pos < 0 ? null : qname.substring(0, pos);
      if (prefix !== null && ns === null || prefix === "xml" && ns !== NAMESPACE.XML || (qname === "xmlns" || prefix === "xmlns") && ns !== NAMESPACE.XMLNS || ns === NAMESPACE.XMLNS && !(qname === "xmlns" || prefix === "xmlns"))
        utils.NamespaceError();
      this._setAttributeNS(ns, qname, String(value));
    } },
    setAttributeNode: { value: function setAttributeNode(attr) {
      if (attr.ownerElement !== null && attr.ownerElement !== this) {
        throw new DOMException2(DOMException2.INUSE_ATTRIBUTE_ERR);
      }
      var result = null;
      var oldAttrs = this._attrsByQName[attr.name];
      if (oldAttrs) {
        if (!Array.isArray(oldAttrs)) {
          oldAttrs = [oldAttrs];
        }
        if (oldAttrs.some(function(a) {
          return a === attr;
        })) {
          return attr;
        } else if (attr.ownerElement !== null) {
          throw new DOMException2(DOMException2.INUSE_ATTRIBUTE_ERR);
        }
        oldAttrs.forEach(function(a) {
          this.removeAttributeNode(a);
        }, this);
        result = oldAttrs[0];
      }
      this.setAttributeNodeNS(attr);
      return result;
    } },
    setAttributeNodeNS: { value: function setAttributeNodeNS(attr) {
      if (attr.ownerElement !== null) {
        throw new DOMException2(DOMException2.INUSE_ATTRIBUTE_ERR);
      }
      var ns = attr.namespaceURI;
      var key = (ns === null ? "" : ns) + "|" + attr.localName;
      var oldAttr = this._attrsByLName[key];
      if (oldAttr) {
        this.removeAttributeNode(oldAttr);
      }
      attr._setOwnerElement(this);
      this._attrsByLName[key] = attr;
      if (this._attributes) {
        this._attributes[this._attrKeys.length] = attr;
      }
      this._attrKeys.push(key);
      this._addQName(attr);
      if (this._newattrhook)
        this._newattrhook(attr.name, attr.value);
      return oldAttr || null;
    } },
    removeAttribute: { value: function removeAttribute(qname) {
      qname = String(qname);
      if (/[A-Z]/.test(qname) && this.isHTML)
        qname = utils.toASCIILowerCase(qname);
      var attr = this._attrsByQName[qname];
      if (!attr)
        return;
      if (Array.isArray(attr)) {
        if (attr.length > 2) {
          attr = attr.shift();
        } else {
          this._attrsByQName[qname] = attr[1];
          attr = attr[0];
        }
      } else {
        this._attrsByQName[qname] = undefined;
      }
      var ns = attr.namespaceURI;
      var key = (ns === null ? "" : ns) + "|" + attr.localName;
      this._attrsByLName[key] = undefined;
      var i = this._attrKeys.indexOf(key);
      if (this._attributes) {
        Array.prototype.splice.call(this._attributes, i, 1);
        this._attributes[qname] = undefined;
      }
      this._attrKeys.splice(i, 1);
      var onchange = attr.onchange;
      attr._setOwnerElement(null);
      if (onchange) {
        onchange.call(attr, this, attr.localName, attr.value, null);
      }
      if (this.rooted)
        this.ownerDocument.mutateRemoveAttr(attr);
    } },
    removeAttributeNS: { value: function removeAttributeNS(ns, lname) {
      ns = ns === undefined || ns === null ? "" : String(ns);
      lname = String(lname);
      var key = ns + "|" + lname;
      var attr = this._attrsByLName[key];
      if (!attr)
        return;
      this._attrsByLName[key] = undefined;
      var i = this._attrKeys.indexOf(key);
      if (this._attributes) {
        Array.prototype.splice.call(this._attributes, i, 1);
      }
      this._attrKeys.splice(i, 1);
      this._removeQName(attr);
      var onchange = attr.onchange;
      attr._setOwnerElement(null);
      if (onchange) {
        onchange.call(attr, this, attr.localName, attr.value, null);
      }
      if (this.rooted)
        this.ownerDocument.mutateRemoveAttr(attr);
    } },
    removeAttributeNode: { value: function removeAttributeNode(attr) {
      var ns = attr.namespaceURI;
      var key = (ns === null ? "" : ns) + "|" + attr.localName;
      if (this._attrsByLName[key] !== attr) {
        utils.NotFoundError();
      }
      this.removeAttributeNS(ns, attr.localName);
      return attr;
    } },
    getAttributeNames: { value: function getAttributeNames() {
      var elt = this;
      return this._attrKeys.map(function(key) {
        return elt._attrsByLName[key].name;
      });
    } },
    _getattr: { value: function _getattr(qname) {
      var attr = this._attrsByQName[qname];
      return attr ? attr.value : null;
    } },
    _setattr: { value: function _setattr(qname, value) {
      var attr = this._attrsByQName[qname];
      var isnew;
      if (!attr) {
        attr = this._newattr(qname);
        isnew = true;
      }
      attr.value = String(value);
      if (this._attributes)
        this._attributes[qname] = attr;
      if (isnew && this._newattrhook)
        this._newattrhook(qname, value);
    } },
    _newattr: { value: function _newattr(qname) {
      var attr = new Attr(this, qname, null, null);
      var key = "|" + qname;
      this._attrsByQName[qname] = attr;
      this._attrsByLName[key] = attr;
      if (this._attributes) {
        this._attributes[this._attrKeys.length] = attr;
      }
      this._attrKeys.push(key);
      return attr;
    } },
    _addQName: { value: function(attr) {
      var qname = attr.name;
      var existing = this._attrsByQName[qname];
      if (!existing) {
        this._attrsByQName[qname] = attr;
      } else if (Array.isArray(existing)) {
        existing.push(attr);
      } else {
        this._attrsByQName[qname] = [existing, attr];
      }
      if (this._attributes)
        this._attributes[qname] = attr;
    } },
    _removeQName: { value: function(attr) {
      var qname = attr.name;
      var target = this._attrsByQName[qname];
      if (Array.isArray(target)) {
        var idx = target.indexOf(attr);
        utils.assert(idx !== -1);
        if (target.length === 2) {
          this._attrsByQName[qname] = target[1 - idx];
          if (this._attributes) {
            this._attributes[qname] = this._attrsByQName[qname];
          }
        } else {
          target.splice(idx, 1);
          if (this._attributes && this._attributes[qname] === attr) {
            this._attributes[qname] = target[0];
          }
        }
      } else {
        utils.assert(target === attr);
        this._attrsByQName[qname] = undefined;
        if (this._attributes) {
          this._attributes[qname] = undefined;
        }
      }
    } },
    _numattrs: { get: function() {
      return this._attrKeys.length;
    } },
    _attr: { value: function(n) {
      return this._attrsByLName[this._attrKeys[n]];
    } },
    id: attributes.property({ name: "id" }),
    className: attributes.property({ name: "class" }),
    classList: { get: function() {
      var self = this;
      if (this._classList) {
        return this._classList;
      }
      var dtlist = new DOMTokenList(function() {
        return self.className || "";
      }, function(v) {
        self.className = v;
      });
      this._classList = dtlist;
      return dtlist;
    }, set: function(v) {
      this.className = v;
    } },
    matches: { value: function(selector) {
      return select.matches(this, selector);
    } },
    closest: { value: function(selector) {
      var el = this;
      do {
        if (el.matches && el.matches(selector)) {
          return el;
        }
        el = el.parentElement || el.parentNode;
      } while (el !== null && el.nodeType === Node.ELEMENT_NODE);
      return null;
    } },
    querySelector: { value: function(selector) {
      return select(selector, this)[0];
    } },
    querySelectorAll: { value: function(selector) {
      var nodes = select(selector, this);
      return nodes.item ? nodes : new NodeList(nodes);
    } }
  });
  Object.defineProperties(Element.prototype, ChildNode);
  Object.defineProperties(Element.prototype, NonDocumentTypeChildNode);
  attributes.registerChangeHandler(Element, "id", function(element, lname, oldval, newval) {
    if (element.rooted) {
      if (oldval) {
        element.ownerDocument.delId(oldval, element);
      }
      if (newval) {
        element.ownerDocument.addId(newval, element);
      }
    }
  });
  attributes.registerChangeHandler(Element, "class", function(element, lname, oldval, newval) {
    if (element._classList) {
      element._classList._update();
    }
  });
  function Attr(elt, lname, prefix, namespace, value) {
    this.localName = lname;
    this.prefix = prefix === null || prefix === "" ? null : "" + prefix;
    this.namespaceURI = namespace === null || namespace === "" ? null : "" + namespace;
    this.data = value;
    this._setOwnerElement(elt);
  }
  Attr.prototype = Object.create(Object.prototype, {
    ownerElement: {
      get: function() {
        return this._ownerElement;
      }
    },
    _setOwnerElement: { value: function _setOwnerElement(elt) {
      this._ownerElement = elt;
      if (this.prefix === null && this.namespaceURI === null && elt) {
        this.onchange = elt._attributeChangeHandlers[this.localName];
      } else {
        this.onchange = null;
      }
    } },
    name: { get: function() {
      return this.prefix ? this.prefix + ":" + this.localName : this.localName;
    } },
    specified: { get: function() {
      return true;
    } },
    value: {
      get: function() {
        return this.data;
      },
      set: function(value) {
        var oldval = this.data;
        value = value === undefined ? "" : value + "";
        if (value === oldval)
          return;
        this.data = value;
        if (this.ownerElement) {
          if (this.onchange)
            this.onchange(this.ownerElement, this.localName, oldval, value);
          if (this.ownerElement.rooted)
            this.ownerElement.ownerDocument.mutateAttr(this, oldval);
        }
      }
    },
    cloneNode: { value: function cloneNode(deep) {
      return new Attr(null, this.localName, this.prefix, this.namespaceURI, this.data);
    } },
    nodeType: { get: function() {
      return Node.ATTRIBUTE_NODE;
    } },
    nodeName: { get: function() {
      return this.name;
    } },
    nodeValue: {
      get: function() {
        return this.value;
      },
      set: function(v) {
        this.value = v;
      }
    },
    textContent: {
      get: function() {
        return this.value;
      },
      set: function(v) {
        if (v === null || v === undefined) {
          v = "";
        }
        this.value = v;
      }
    },
    innerText: {
      get: function() {
        return this.value;
      },
      set: function(v) {
        if (v === null || v === undefined) {
          v = "";
        }
        this.value = v;
      }
    }
  });
  Element._Attr = Attr;
  function AttributesArray(elt) {
    NamedNodeMap.call(this, elt);
    for (var name in elt._attrsByQName) {
      this[name] = elt._attrsByQName[name];
    }
    for (var i = 0;i < elt._attrKeys.length; i++) {
      this[i] = elt._attrsByLName[elt._attrKeys[i]];
    }
  }
  AttributesArray.prototype = Object.create(NamedNodeMap.prototype, {
    length: { get: function() {
      return this.element._attrKeys.length;
    }, set: function() {} },
    item: { value: function(n) {
      n = n >>> 0;
      if (n >= this.length) {
        return null;
      }
      return this.element._attrsByLName[this.element._attrKeys[n]];
    } }
  });
  if (globalThis.Symbol?.iterator) {
    AttributesArray.prototype[globalThis.Symbol.iterator] = function() {
      var i = 0, n = this.length, self = this;
      return {
        next: function() {
          if (i < n)
            return { value: self.item(i++) };
          return { done: true };
        }
      };
    };
  }
  function ChildrenCollection(e) {
    this.element = e;
    this.updateCache();
  }
  ChildrenCollection.prototype = Object.create(Object.prototype, {
    length: { get: function() {
      this.updateCache();
      return this.childrenByNumber.length;
    } },
    item: { value: function item(n) {
      this.updateCache();
      return this.childrenByNumber[n] || null;
    } },
    namedItem: { value: function namedItem(name) {
      this.updateCache();
      return this.childrenByName[name] || null;
    } },
    namedItems: { get: function() {
      this.updateCache();
      return this.childrenByName;
    } },
    updateCache: { value: function updateCache() {
      var namedElts = /^(a|applet|area|embed|form|frame|frameset|iframe|img|object)$/;
      if (this.lastModTime !== this.element.lastModTime) {
        this.lastModTime = this.element.lastModTime;
        var n = this.childrenByNumber && this.childrenByNumber.length || 0;
        for (var i = 0;i < n; i++) {
          this[i] = undefined;
        }
        this.childrenByNumber = [];
        this.childrenByName = Object.create(null);
        for (var c = this.element.firstChild;c !== null; c = c.nextSibling) {
          if (c.nodeType === Node.ELEMENT_NODE) {
            this[this.childrenByNumber.length] = c;
            this.childrenByNumber.push(c);
            var id = c.getAttribute("id");
            if (id && !this.childrenByName[id])
              this.childrenByName[id] = c;
            var name = c.getAttribute("name");
            if (name && this.element.namespaceURI === NAMESPACE.HTML && namedElts.test(this.element.localName) && !this.childrenByName[name])
              this.childrenByName[id] = c;
          }
        }
      }
    } }
  });
  function localNameElementFilter(lname) {
    return function(e) {
      return e.localName === lname;
    };
  }
  function htmlLocalNameElementFilter(lname) {
    var lclname = utils.toASCIILowerCase(lname);
    if (lclname === lname)
      return localNameElementFilter(lname);
    return function(e) {
      return e.isHTML ? e.localName === lclname : e.localName === lname;
    };
  }
  function namespaceElementFilter(ns) {
    return function(e) {
      return e.namespaceURI === ns;
    };
  }
  function namespaceLocalNameElementFilter(ns, lname) {
    return function(e) {
      return e.namespaceURI === ns && e.localName === lname;
    };
  }
  function classNamesElementFilter(names) {
    return function(e) {
      return names.every(function(n) {
        return e.classList.contains(n);
      });
    };
  }
  function elementNameFilter(name) {
    return function(e) {
      if (e.namespaceURI !== NAMESPACE.HTML) {
        return false;
      }
      return e.getAttribute("name") === name;
    };
  }
});

// node_modules/@mixmark-io/domino/lib/Leaf.js
var require_Leaf = __commonJS((exports, module) => {
  module.exports = Leaf;
  var Node = require_Node2();
  var NodeList = require_NodeList();
  var utils = require_utils();
  var HierarchyRequestError = utils.HierarchyRequestError;
  var NotFoundError2 = utils.NotFoundError;
  function Leaf() {
    Node.call(this);
  }
  Leaf.prototype = Object.create(Node.prototype, {
    hasChildNodes: { value: function() {
      return false;
    } },
    firstChild: { value: null },
    lastChild: { value: null },
    insertBefore: { value: function(node, child) {
      if (!node.nodeType)
        throw new TypeError("not a node");
      HierarchyRequestError();
    } },
    replaceChild: { value: function(node, child) {
      if (!node.nodeType)
        throw new TypeError("not a node");
      HierarchyRequestError();
    } },
    removeChild: { value: function(node) {
      if (!node.nodeType)
        throw new TypeError("not a node");
      NotFoundError2();
    } },
    removeChildren: { value: function() {} },
    childNodes: { get: function() {
      if (!this._childNodes)
        this._childNodes = new NodeList;
      return this._childNodes;
    } }
  });
});

// node_modules/@mixmark-io/domino/lib/CharacterData.js
var require_CharacterData = __commonJS((exports, module) => {
  module.exports = CharacterData;
  var Leaf = require_Leaf();
  var utils = require_utils();
  var ChildNode = require_ChildNode();
  var NonDocumentTypeChildNode = require_NonDocumentTypeChildNode();
  function CharacterData() {
    Leaf.call(this);
  }
  CharacterData.prototype = Object.create(Leaf.prototype, {
    substringData: { value: function substringData(offset, count) {
      if (arguments.length < 2) {
        throw new TypeError("Not enough arguments");
      }
      offset = offset >>> 0;
      count = count >>> 0;
      if (offset > this.data.length || offset < 0 || count < 0) {
        utils.IndexSizeError();
      }
      return this.data.substring(offset, offset + count);
    } },
    appendData: { value: function appendData(data) {
      if (arguments.length < 1) {
        throw new TypeError("Not enough arguments");
      }
      this.data += String(data);
    } },
    insertData: { value: function insertData(offset, data) {
      return this.replaceData(offset, 0, data);
    } },
    deleteData: { value: function deleteData(offset, count) {
      return this.replaceData(offset, count, "");
    } },
    replaceData: { value: function replaceData(offset, count, data) {
      var curtext = this.data, len = curtext.length;
      offset = offset >>> 0;
      count = count >>> 0;
      data = String(data);
      if (offset > len || offset < 0)
        utils.IndexSizeError();
      if (offset + count > len)
        count = len - offset;
      var prefix = curtext.substring(0, offset), suffix = curtext.substring(offset + count);
      this.data = prefix + data + suffix;
    } },
    isEqual: { value: function isEqual(n) {
      return this._data === n._data;
    } },
    length: { get: function() {
      return this.data.length;
    } }
  });
  Object.defineProperties(CharacterData.prototype, ChildNode);
  Object.defineProperties(CharacterData.prototype, NonDocumentTypeChildNode);
});

// node_modules/@mixmark-io/domino/lib/Text.js
var require_Text = __commonJS((exports, module) => {
  module.exports = Text;
  var utils = require_utils();
  var Node = require_Node2();
  var CharacterData = require_CharacterData();
  function Text(doc, data) {
    CharacterData.call(this);
    this.nodeType = Node.TEXT_NODE;
    this.ownerDocument = doc;
    this._data = data;
    this._index = undefined;
  }
  var nodeValue = {
    get: function() {
      return this._data;
    },
    set: function(v) {
      if (v === null || v === undefined) {
        v = "";
      } else {
        v = String(v);
      }
      if (v === this._data)
        return;
      this._data = v;
      if (this.rooted)
        this.ownerDocument.mutateValue(this);
      if (this.parentNode && this.parentNode._textchangehook)
        this.parentNode._textchangehook(this);
    }
  };
  Text.prototype = Object.create(CharacterData.prototype, {
    nodeName: { value: "#text" },
    nodeValue,
    textContent: nodeValue,
    innerText: nodeValue,
    data: {
      get: nodeValue.get,
      set: function(v) {
        nodeValue.set.call(this, v === null ? "" : String(v));
      }
    },
    splitText: { value: function splitText(offset) {
      if (offset > this._data.length || offset < 0)
        utils.IndexSizeError();
      var newdata = this._data.substring(offset), newnode = this.ownerDocument.createTextNode(newdata);
      this.data = this.data.substring(0, offset);
      var parent = this.parentNode;
      if (parent !== null)
        parent.insertBefore(newnode, this.nextSibling);
      return newnode;
    } },
    wholeText: { get: function wholeText() {
      var result = this.textContent;
      for (var next = this.nextSibling;next; next = next.nextSibling) {
        if (next.nodeType !== Node.TEXT_NODE) {
          break;
        }
        result += next.textContent;
      }
      return result;
    } },
    replaceWholeText: { value: utils.nyi },
    clone: { value: function clone() {
      return new Text(this.ownerDocument, this._data);
    } }
  });
});

// node_modules/@mixmark-io/domino/lib/Comment.js
var require_Comment = __commonJS((exports, module) => {
  module.exports = Comment;
  var Node = require_Node2();
  var CharacterData = require_CharacterData();
  function Comment(doc, data) {
    CharacterData.call(this);
    this.nodeType = Node.COMMENT_NODE;
    this.ownerDocument = doc;
    this._data = data;
  }
  var nodeValue = {
    get: function() {
      return this._data;
    },
    set: function(v) {
      if (v === null || v === undefined) {
        v = "";
      } else {
        v = String(v);
      }
      this._data = v;
      if (this.rooted)
        this.ownerDocument.mutateValue(this);
    }
  };
  Comment.prototype = Object.create(CharacterData.prototype, {
    nodeName: { value: "#comment" },
    nodeValue,
    textContent: nodeValue,
    innerText: nodeValue,
    data: {
      get: nodeValue.get,
      set: function(v) {
        nodeValue.set.call(this, v === null ? "" : String(v));
      }
    },
    clone: { value: function clone() {
      return new Comment(this.ownerDocument, this._data);
    } }
  });
});

// node_modules/@mixmark-io/domino/lib/DocumentFragment.js
var require_DocumentFragment = __commonJS((exports, module) => {
  module.exports = DocumentFragment;
  var Node = require_Node2();
  var NodeList = require_NodeList();
  var ContainerNode = require_ContainerNode();
  var Element = require_Element();
  var select = require_select();
  var utils = require_utils();
  function DocumentFragment(doc) {
    ContainerNode.call(this);
    this.nodeType = Node.DOCUMENT_FRAGMENT_NODE;
    this.ownerDocument = doc;
  }
  DocumentFragment.prototype = Object.create(ContainerNode.prototype, {
    nodeName: { value: "#document-fragment" },
    nodeValue: {
      get: function() {
        return null;
      },
      set: function() {}
    },
    textContent: Object.getOwnPropertyDescriptor(Element.prototype, "textContent"),
    innerText: Object.getOwnPropertyDescriptor(Element.prototype, "innerText"),
    querySelector: { value: function(selector) {
      var nodes = this.querySelectorAll(selector);
      return nodes.length ? nodes[0] : null;
    } },
    querySelectorAll: { value: function(selector) {
      var context = Object.create(this);
      context.isHTML = true;
      context.getElementsByTagName = Element.prototype.getElementsByTagName;
      context.nextElement = Object.getOwnPropertyDescriptor(Element.prototype, "firstElementChild").get;
      var nodes = select(selector, context);
      return nodes.item ? nodes : new NodeList(nodes);
    } },
    clone: { value: function clone() {
      return new DocumentFragment(this.ownerDocument);
    } },
    isEqual: { value: function isEqual(n) {
      return true;
    } },
    innerHTML: {
      get: function() {
        return this.serialize();
      },
      set: utils.nyi
    },
    outerHTML: {
      get: function() {
        return this.serialize();
      },
      set: utils.nyi
    }
  });
});

// node_modules/@mixmark-io/domino/lib/ProcessingInstruction.js
var require_ProcessingInstruction = __commonJS((exports, module) => {
  module.exports = ProcessingInstruction;
  var Node = require_Node2();
  var CharacterData = require_CharacterData();
  function ProcessingInstruction(doc, target, data) {
    CharacterData.call(this);
    this.nodeType = Node.PROCESSING_INSTRUCTION_NODE;
    this.ownerDocument = doc;
    this.target = target;
    this._data = data;
  }
  var nodeValue = {
    get: function() {
      return this._data;
    },
    set: function(v) {
      if (v === null || v === undefined) {
        v = "";
      } else {
        v = String(v);
      }
      this._data = v;
      if (this.rooted)
        this.ownerDocument.mutateValue(this);
    }
  };
  ProcessingInstruction.prototype = Object.create(CharacterData.prototype, {
    nodeName: { get: function() {
      return this.target;
    } },
    nodeValue,
    textContent: nodeValue,
    innerText: nodeValue,
    data: {
      get: nodeValue.get,
      set: function(v) {
        nodeValue.set.call(this, v === null ? "" : String(v));
      }
    },
    clone: { value: function clone() {
      return new ProcessingInstruction(this.ownerDocument, this.target, this._data);
    } },
    isEqual: { value: function isEqual(n) {
      return this.target === n.target && this._data === n._data;
    } }
  });
});

// node_modules/@mixmark-io/domino/lib/NodeFilter.js
var require_NodeFilter = __commonJS((exports, module) => {
  var NodeFilter = {
    FILTER_ACCEPT: 1,
    FILTER_REJECT: 2,
    FILTER_SKIP: 3,
    SHOW_ALL: 4294967295,
    SHOW_ELEMENT: 1,
    SHOW_ATTRIBUTE: 2,
    SHOW_TEXT: 4,
    SHOW_CDATA_SECTION: 8,
    SHOW_ENTITY_REFERENCE: 16,
    SHOW_ENTITY: 32,
    SHOW_PROCESSING_INSTRUCTION: 64,
    SHOW_COMMENT: 128,
    SHOW_DOCUMENT: 256,
    SHOW_DOCUMENT_TYPE: 512,
    SHOW_DOCUMENT_FRAGMENT: 1024,
    SHOW_NOTATION: 2048
  };
  module.exports = NodeFilter.constructor = NodeFilter.prototype = NodeFilter;
});

// node_modules/@mixmark-io/domino/lib/NodeTraversal.js
var require_NodeTraversal = __commonJS((exports, module) => {
  var NodeTraversal = module.exports = {
    nextSkippingChildren,
    nextAncestorSibling,
    next,
    previous,
    deepLastChild
  };
  function nextSkippingChildren(node, stayWithin) {
    if (node === stayWithin) {
      return null;
    }
    if (node.nextSibling !== null) {
      return node.nextSibling;
    }
    return nextAncestorSibling(node, stayWithin);
  }
  function nextAncestorSibling(node, stayWithin) {
    for (node = node.parentNode;node !== null; node = node.parentNode) {
      if (node === stayWithin) {
        return null;
      }
      if (node.nextSibling !== null) {
        return node.nextSibling;
      }
    }
    return null;
  }
  function next(node, stayWithin) {
    var n;
    n = node.firstChild;
    if (n !== null) {
      return n;
    }
    if (node === stayWithin) {
      return null;
    }
    n = node.nextSibling;
    if (n !== null) {
      return n;
    }
    return nextAncestorSibling(node, stayWithin);
  }
  function deepLastChild(node) {
    while (node.lastChild) {
      node = node.lastChild;
    }
    return node;
  }
  function previous(node, stayWithin) {
    var p;
    p = node.previousSibling;
    if (p !== null) {
      return deepLastChild(p);
    }
    p = node.parentNode;
    if (p === stayWithin) {
      return null;
    }
    return p;
  }
});

// node_modules/@mixmark-io/domino/lib/TreeWalker.js
var require_TreeWalker = __commonJS((exports, module) => {
  module.exports = TreeWalker;
  var Node = require_Node2();
  var NodeFilter = require_NodeFilter();
  var NodeTraversal = require_NodeTraversal();
  var utils = require_utils();
  var mapChild = {
    first: "firstChild",
    last: "lastChild",
    next: "firstChild",
    previous: "lastChild"
  };
  var mapSibling = {
    first: "nextSibling",
    last: "previousSibling",
    next: "nextSibling",
    previous: "previousSibling"
  };
  function traverseChildren(tw, type) {
    var child, node, parent, result, sibling;
    node = tw._currentNode[mapChild[type]];
    while (node !== null) {
      result = tw._internalFilter(node);
      if (result === NodeFilter.FILTER_ACCEPT) {
        tw._currentNode = node;
        return node;
      }
      if (result === NodeFilter.FILTER_SKIP) {
        child = node[mapChild[type]];
        if (child !== null) {
          node = child;
          continue;
        }
      }
      while (node !== null) {
        sibling = node[mapSibling[type]];
        if (sibling !== null) {
          node = sibling;
          break;
        }
        parent = node.parentNode;
        if (parent === null || parent === tw.root || parent === tw._currentNode) {
          return null;
        } else {
          node = parent;
        }
      }
    }
    return null;
  }
  function traverseSiblings(tw, type) {
    var node, result, sibling;
    node = tw._currentNode;
    if (node === tw.root) {
      return null;
    }
    while (true) {
      sibling = node[mapSibling[type]];
      while (sibling !== null) {
        node = sibling;
        result = tw._internalFilter(node);
        if (result === NodeFilter.FILTER_ACCEPT) {
          tw._currentNode = node;
          return node;
        }
        sibling = node[mapChild[type]];
        if (result === NodeFilter.FILTER_REJECT || sibling === null) {
          sibling = node[mapSibling[type]];
        }
      }
      node = node.parentNode;
      if (node === null || node === tw.root) {
        return null;
      }
      if (tw._internalFilter(node) === NodeFilter.FILTER_ACCEPT) {
        return null;
      }
    }
  }
  function TreeWalker(root, whatToShow, filter) {
    if (!root || !root.nodeType) {
      utils.NotSupportedError();
    }
    this._root = root;
    this._whatToShow = Number(whatToShow) || 0;
    this._filter = filter || null;
    this._active = false;
    this._currentNode = root;
  }
  Object.defineProperties(TreeWalker.prototype, {
    root: { get: function() {
      return this._root;
    } },
    whatToShow: { get: function() {
      return this._whatToShow;
    } },
    filter: { get: function() {
      return this._filter;
    } },
    currentNode: {
      get: function currentNode() {
        return this._currentNode;
      },
      set: function setCurrentNode(v) {
        if (!(v instanceof Node)) {
          throw new TypeError("Not a Node");
        }
        this._currentNode = v;
      }
    },
    _internalFilter: { value: function _internalFilter(node) {
      var result, filter;
      if (this._active) {
        utils.InvalidStateError();
      }
      if (!(1 << node.nodeType - 1 & this._whatToShow)) {
        return NodeFilter.FILTER_SKIP;
      }
      filter = this._filter;
      if (filter === null) {
        result = NodeFilter.FILTER_ACCEPT;
      } else {
        this._active = true;
        try {
          if (typeof filter === "function") {
            result = filter(node);
          } else {
            result = filter.acceptNode(node);
          }
        } finally {
          this._active = false;
        }
      }
      return +result;
    } },
    parentNode: { value: function parentNode() {
      var node = this._currentNode;
      while (node !== this.root) {
        node = node.parentNode;
        if (node === null) {
          return null;
        }
        if (this._internalFilter(node) === NodeFilter.FILTER_ACCEPT) {
          this._currentNode = node;
          return node;
        }
      }
      return null;
    } },
    firstChild: { value: function firstChild() {
      return traverseChildren(this, "first");
    } },
    lastChild: { value: function lastChild() {
      return traverseChildren(this, "last");
    } },
    previousSibling: { value: function previousSibling() {
      return traverseSiblings(this, "previous");
    } },
    nextSibling: { value: function nextSibling() {
      return traverseSiblings(this, "next");
    } },
    previousNode: { value: function previousNode() {
      var node, result, previousSibling, lastChild;
      node = this._currentNode;
      while (node !== this._root) {
        for (previousSibling = node.previousSibling;previousSibling; previousSibling = node.previousSibling) {
          node = previousSibling;
          result = this._internalFilter(node);
          if (result === NodeFilter.FILTER_REJECT) {
            continue;
          }
          for (lastChild = node.lastChild;lastChild; lastChild = node.lastChild) {
            node = lastChild;
            result = this._internalFilter(node);
            if (result === NodeFilter.FILTER_REJECT) {
              break;
            }
          }
          if (result === NodeFilter.FILTER_ACCEPT) {
            this._currentNode = node;
            return node;
          }
        }
        if (node === this.root || node.parentNode === null) {
          return null;
        }
        node = node.parentNode;
        if (this._internalFilter(node) === NodeFilter.FILTER_ACCEPT) {
          this._currentNode = node;
          return node;
        }
      }
      return null;
    } },
    nextNode: { value: function nextNode() {
      var node, result, firstChild, nextSibling;
      node = this._currentNode;
      result = NodeFilter.FILTER_ACCEPT;
      CHILDREN:
        while (true) {
          for (firstChild = node.firstChild;firstChild; firstChild = node.firstChild) {
            node = firstChild;
            result = this._internalFilter(node);
            if (result === NodeFilter.FILTER_ACCEPT) {
              this._currentNode = node;
              return node;
            } else if (result === NodeFilter.FILTER_REJECT) {
              break;
            }
          }
          for (nextSibling = NodeTraversal.nextSkippingChildren(node, this.root);nextSibling; nextSibling = NodeTraversal.nextSkippingChildren(node, this.root)) {
            node = nextSibling;
            result = this._internalFilter(node);
            if (result === NodeFilter.FILTER_ACCEPT) {
              this._currentNode = node;
              return node;
            } else if (result === NodeFilter.FILTER_SKIP) {
              continue CHILDREN;
            }
          }
          return null;
        }
    } },
    toString: { value: function toString() {
      return "[object TreeWalker]";
    } }
  });
});

// node_modules/@mixmark-io/domino/lib/NodeIterator.js
var require_NodeIterator = __commonJS((exports, module) => {
  module.exports = NodeIterator;
  var NodeFilter = require_NodeFilter();
  var NodeTraversal = require_NodeTraversal();
  var utils = require_utils();
  function move(node, stayWithin, directionIsNext) {
    if (directionIsNext) {
      return NodeTraversal.next(node, stayWithin);
    } else {
      if (node === stayWithin) {
        return null;
      }
      return NodeTraversal.previous(node, null);
    }
  }
  function isInclusiveAncestor(node, possibleChild) {
    for (;possibleChild; possibleChild = possibleChild.parentNode) {
      if (node === possibleChild) {
        return true;
      }
    }
    return false;
  }
  function traverse(ni, directionIsNext) {
    var node, beforeNode;
    node = ni._referenceNode;
    beforeNode = ni._pointerBeforeReferenceNode;
    while (true) {
      if (beforeNode === directionIsNext) {
        beforeNode = !beforeNode;
      } else {
        node = move(node, ni._root, directionIsNext);
        if (node === null) {
          return null;
        }
      }
      var result = ni._internalFilter(node);
      if (result === NodeFilter.FILTER_ACCEPT) {
        break;
      }
    }
    ni._referenceNode = node;
    ni._pointerBeforeReferenceNode = beforeNode;
    return node;
  }
  function NodeIterator(root, whatToShow, filter) {
    if (!root || !root.nodeType) {
      utils.NotSupportedError();
    }
    this._root = root;
    this._referenceNode = root;
    this._pointerBeforeReferenceNode = true;
    this._whatToShow = Number(whatToShow) || 0;
    this._filter = filter || null;
    this._active = false;
    root.doc._attachNodeIterator(this);
  }
  Object.defineProperties(NodeIterator.prototype, {
    root: { get: function root() {
      return this._root;
    } },
    referenceNode: { get: function referenceNode() {
      return this._referenceNode;
    } },
    pointerBeforeReferenceNode: { get: function pointerBeforeReferenceNode() {
      return this._pointerBeforeReferenceNode;
    } },
    whatToShow: { get: function whatToShow() {
      return this._whatToShow;
    } },
    filter: { get: function filter() {
      return this._filter;
    } },
    _internalFilter: { value: function _internalFilter(node) {
      var result, filter;
      if (this._active) {
        utils.InvalidStateError();
      }
      if (!(1 << node.nodeType - 1 & this._whatToShow)) {
        return NodeFilter.FILTER_SKIP;
      }
      filter = this._filter;
      if (filter === null) {
        result = NodeFilter.FILTER_ACCEPT;
      } else {
        this._active = true;
        try {
          if (typeof filter === "function") {
            result = filter(node);
          } else {
            result = filter.acceptNode(node);
          }
        } finally {
          this._active = false;
        }
      }
      return +result;
    } },
    _preremove: { value: function _preremove(toBeRemovedNode) {
      if (isInclusiveAncestor(toBeRemovedNode, this._root)) {
        return;
      }
      if (!isInclusiveAncestor(toBeRemovedNode, this._referenceNode)) {
        return;
      }
      if (this._pointerBeforeReferenceNode) {
        var next = toBeRemovedNode;
        while (next.lastChild) {
          next = next.lastChild;
        }
        next = NodeTraversal.next(next, this.root);
        if (next) {
          this._referenceNode = next;
          return;
        }
        this._pointerBeforeReferenceNode = false;
      }
      if (toBeRemovedNode.previousSibling === null) {
        this._referenceNode = toBeRemovedNode.parentNode;
      } else {
        this._referenceNode = toBeRemovedNode.previousSibling;
        var lastChild;
        for (lastChild = this._referenceNode.lastChild;lastChild; lastChild = this._referenceNode.lastChild) {
          this._referenceNode = lastChild;
        }
      }
    } },
    nextNode: { value: function nextNode() {
      return traverse(this, true);
    } },
    previousNode: { value: function previousNode() {
      return traverse(this, false);
    } },
    detach: { value: function detach() {} },
    toString: { value: function toString() {
      return "[object NodeIterator]";
    } }
  });
});

// node_modules/@mixmark-io/domino/lib/URL.js
var require_URL = __commonJS((exports, module) => {
  module.exports = URL2;
  function URL2(url) {
    if (!url)
      return Object.create(URL2.prototype);
    this.url = url.replace(/^[ \t\n\r\f]+|[ \t\n\r\f]+$/g, "");
    var match = URL2.pattern.exec(this.url);
    if (match) {
      if (match[2])
        this.scheme = match[2];
      if (match[4]) {
        var userinfo = match[4].match(URL2.userinfoPattern);
        if (userinfo) {
          this.username = userinfo[1];
          this.password = userinfo[3];
          match[4] = match[4].substring(userinfo[0].length);
        }
        if (match[4].match(URL2.portPattern)) {
          var pos = match[4].lastIndexOf(":");
          this.host = match[4].substring(0, pos);
          this.port = match[4].substring(pos + 1);
        } else {
          this.host = match[4];
        }
      }
      if (match[5])
        this.path = match[5];
      if (match[6])
        this.query = match[7];
      if (match[8])
        this.fragment = match[9];
    }
  }
  URL2.pattern = /^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/;
  URL2.userinfoPattern = /^([^@:]*)(:([^@]*))?@/;
  URL2.portPattern = /:\d+$/;
  URL2.authorityPattern = /^[^:\/?#]+:\/\//;
  URL2.hierarchyPattern = /^[^:\/?#]+:\//;
  URL2.percentEncode = function percentEncode(s) {
    var c = s.charCodeAt(0);
    if (c < 256)
      return "%" + c.toString(16);
    else
      throw Error("can't percent-encode codepoints > 255 yet");
  };
  URL2.prototype = {
    constructor: URL2,
    isAbsolute: function() {
      return !!this.scheme;
    },
    isAuthorityBased: function() {
      return URL2.authorityPattern.test(this.url);
    },
    isHierarchical: function() {
      return URL2.hierarchyPattern.test(this.url);
    },
    toString: function() {
      var s = "";
      if (this.scheme !== undefined)
        s += this.scheme + ":";
      if (this.isAbsolute()) {
        s += "//";
        if (this.username || this.password) {
          s += this.username || "";
          if (this.password) {
            s += ":" + this.password;
          }
          s += "@";
        }
        if (this.host) {
          s += this.host;
        }
      }
      if (this.port !== undefined)
        s += ":" + this.port;
      if (this.path !== undefined)
        s += this.path;
      if (this.query !== undefined)
        s += "?" + this.query;
      if (this.fragment !== undefined)
        s += "#" + this.fragment;
      return s;
    },
    resolve: function(relative) {
      var base = this;
      var r = new URL2(relative);
      var t = new URL2;
      if (r.scheme !== undefined) {
        t.scheme = r.scheme;
        t.username = r.username;
        t.password = r.password;
        t.host = r.host;
        t.port = r.port;
        t.path = remove_dot_segments(r.path);
        t.query = r.query;
      } else {
        t.scheme = base.scheme;
        if (r.host !== undefined) {
          t.username = r.username;
          t.password = r.password;
          t.host = r.host;
          t.port = r.port;
          t.path = remove_dot_segments(r.path);
          t.query = r.query;
        } else {
          t.username = base.username;
          t.password = base.password;
          t.host = base.host;
          t.port = base.port;
          if (!r.path) {
            t.path = base.path;
            if (r.query !== undefined)
              t.query = r.query;
            else
              t.query = base.query;
          } else {
            if (r.path.charAt(0) === "/") {
              t.path = remove_dot_segments(r.path);
            } else {
              t.path = merge(base.path, r.path);
              t.path = remove_dot_segments(t.path);
            }
            t.query = r.query;
          }
        }
      }
      t.fragment = r.fragment;
      return t.toString();
      function merge(basepath, refpath) {
        if (base.host !== undefined && !base.path)
          return "/" + refpath;
        var lastslash = basepath.lastIndexOf("/");
        if (lastslash === -1)
          return refpath;
        else
          return basepath.substring(0, lastslash + 1) + refpath;
      }
      function remove_dot_segments(path40) {
        if (!path40)
          return path40;
        var output = "";
        while (path40.length > 0) {
          if (path40 === "." || path40 === "..") {
            path40 = "";
            break;
          }
          var twochars = path40.substring(0, 2);
          var threechars = path40.substring(0, 3);
          var fourchars = path40.substring(0, 4);
          if (threechars === "../") {
            path40 = path40.substring(3);
          } else if (twochars === "./") {
            path40 = path40.substring(2);
          } else if (threechars === "/./") {
            path40 = "/" + path40.substring(3);
          } else if (twochars === "/." && path40.length === 2) {
            path40 = "/";
          } else if (fourchars === "/../" || threechars === "/.." && path40.length === 3) {
            path40 = "/" + path40.substring(4);
            output = output.replace(/\/?[^\/]*$/, "");
          } else {
            var segment = path40.match(/(\/?([^\/]*))/)[0];
            output += segment;
            path40 = path40.substring(segment.length);
          }
        }
        return output;
      }
    }
  };
});

// node_modules/@mixmark-io/domino/lib/CustomEvent.js
var require_CustomEvent = __commonJS((exports, module) => {
  module.exports = CustomEvent;
  var Event = require_Event();
  function CustomEvent(type, dictionary) {
    Event.call(this, type, dictionary);
  }
  CustomEvent.prototype = Object.create(Event.prototype, {
    constructor: { value: CustomEvent }
  });
});

// node_modules/@mixmark-io/domino/lib/events.js
var require_events = __commonJS((exports, module) => {
  module.exports = {
    Event: require_Event(),
    UIEvent: require_UIEvent(),
    MouseEvent: require_MouseEvent(),
    CustomEvent: require_CustomEvent()
  };
});

// node_modules/@mixmark-io/domino/lib/style_parser.js
var require_style_parser = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.hyphenate = exports.parse = undefined;
  function parse(value) {
    const styles = [];
    let i = 0;
    let parenDepth = 0;
    let quote = 0;
    let valueStart = 0;
    let propStart = 0;
    let currentProp = null;
    while (i < value.length) {
      const token = value.charCodeAt(i++);
      switch (token) {
        case 40:
          parenDepth++;
          break;
        case 41:
          parenDepth--;
          break;
        case 39:
          if (quote === 0) {
            quote = 39;
          } else if (quote === 39 && value.charCodeAt(i - 1) !== 92) {
            quote = 0;
          }
          break;
        case 34:
          if (quote === 0) {
            quote = 34;
          } else if (quote === 34 && value.charCodeAt(i - 1) !== 92) {
            quote = 0;
          }
          break;
        case 58:
          if (!currentProp && parenDepth === 0 && quote === 0) {
            currentProp = hyphenate(value.substring(propStart, i - 1).trim());
            valueStart = i;
          }
          break;
        case 59:
          if (currentProp && valueStart > 0 && parenDepth === 0 && quote === 0) {
            const styleVal = value.substring(valueStart, i - 1).trim();
            styles.push(currentProp, styleVal);
            propStart = i;
            valueStart = 0;
            currentProp = null;
          }
          break;
      }
    }
    if (currentProp && valueStart) {
      const styleVal = value.slice(valueStart).trim();
      styles.push(currentProp, styleVal);
    }
    return styles;
  }
  exports.parse = parse;
  function hyphenate(value) {
    return value.replace(/[a-z][A-Z]/g, (v) => {
      return v.charAt(0) + "-" + v.charAt(1);
    }).toLowerCase();
  }
  exports.hyphenate = hyphenate;
});

// node_modules/@mixmark-io/domino/lib/CSSStyleDeclaration.js
var require_CSSStyleDeclaration = __commonJS((exports, module) => {
  var { parse } = require_style_parser();
  module.exports = function(elt) {
    const style = new CSSStyleDeclaration(elt);
    const handler3 = {
      get: function(target, property) {
        return property in target ? target[property] : target.getPropertyValue(dasherizeProperty(property));
      },
      has: function(target, key) {
        return true;
      },
      set: function(target, property, value) {
        if (property in target) {
          target[property] = value;
        } else {
          target.setProperty(dasherizeProperty(property), value ?? undefined);
        }
        return true;
      }
    };
    return new Proxy(style, handler3);
  };
  function dasherizeProperty(property) {
    return property.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
  }
  function CSSStyleDeclaration(elt) {
    this._element = elt;
  }
  var IMPORTANT_BANG = "!important";
  function parseStyles(value) {
    const result = {
      property: {},
      priority: {}
    };
    if (!value) {
      return result;
    }
    const styleValues = parse(value);
    if (styleValues.length < 2) {
      return result;
    }
    for (let i = 0;i < styleValues.length; i += 2) {
      const name = styleValues[i];
      let value2 = styleValues[i + 1];
      if (value2.endsWith(IMPORTANT_BANG)) {
        result.priority[name] = "important";
        value2 = value2.slice(0, -IMPORTANT_BANG.length).trim();
      }
      result.property[name] = value2;
    }
    return result;
  }
  var NO_CHANGE = {};
  CSSStyleDeclaration.prototype = Object.create(Object.prototype, {
    _parsed: { get: function() {
      if (!this._parsedStyles || this.cssText !== this._lastParsedText) {
        var text = this.cssText;
        this._parsedStyles = parseStyles(text);
        this._lastParsedText = text;
        delete this._names;
      }
      return this._parsedStyles;
    } },
    _serialize: { value: function() {
      var styles = this._parsed;
      var s = "";
      for (var name in styles.property) {
        if (s)
          s += " ";
        s += name + ": " + styles.property[name];
        if (styles.priority[name]) {
          s += " !" + styles.priority[name];
        }
        s += ";";
      }
      this.cssText = s;
      this._lastParsedText = s;
      delete this._names;
    } },
    cssText: {
      get: function() {
        return this._element.getAttribute("style");
      },
      set: function(value) {
        this._element.setAttribute("style", value);
      }
    },
    length: { get: function() {
      if (!this._names)
        this._names = Object.getOwnPropertyNames(this._parsed.property);
      return this._names.length;
    } },
    item: { value: function(n) {
      if (!this._names)
        this._names = Object.getOwnPropertyNames(this._parsed.property);
      return this._names[n];
    } },
    getPropertyValue: { value: function(property) {
      property = property.toLowerCase();
      return this._parsed.property[property] || "";
    } },
    getPropertyPriority: { value: function(property) {
      property = property.toLowerCase();
      return this._parsed.priority[property] || "";
    } },
    setProperty: { value: function(property, value, priority) {
      property = property.toLowerCase();
      if (value === null || value === undefined) {
        value = "";
      }
      if (priority === null || priority === undefined) {
        priority = "";
      }
      if (value !== NO_CHANGE) {
        value = "" + value;
      }
      value = value.trim();
      if (value === "") {
        this.removeProperty(property);
        return;
      }
      if (priority !== "" && priority !== NO_CHANGE && !/^important$/i.test(priority)) {
        return;
      }
      var styles = this._parsed;
      if (value === NO_CHANGE) {
        if (!styles.property[property]) {
          return;
        }
        if (priority !== "") {
          styles.priority[property] = "important";
        } else {
          delete styles.priority[property];
        }
      } else {
        if (value.indexOf(";") !== -1)
          return;
        var newprops = parseStyles(property + ":" + value);
        if (Object.getOwnPropertyNames(newprops.property).length === 0) {
          return;
        }
        if (Object.getOwnPropertyNames(newprops.priority).length !== 0) {
          return;
        }
        for (var p in newprops.property) {
          styles.property[p] = newprops.property[p];
          if (priority === NO_CHANGE) {
            continue;
          } else if (priority !== "") {
            styles.priority[p] = "important";
          } else if (styles.priority[p]) {
            delete styles.priority[p];
          }
        }
      }
      this._serialize();
    } },
    setPropertyValue: { value: function(property, value) {
      return this.setProperty(property, value, NO_CHANGE);
    } },
    setPropertyPriority: { value: function(property, priority) {
      return this.setProperty(property, NO_CHANGE, priority);
    } },
    removeProperty: { value: function(property) {
      property = property.toLowerCase();
      var styles = this._parsed;
      if (property in styles.property) {
        delete styles.property[property];
        delete styles.priority[property];
        this._serialize();
      }
    } }
  });
});

// node_modules/@mixmark-io/domino/lib/URLUtils.js
var require_URLUtils = __commonJS((exports, module) => {
  var URL2 = require_URL();
  module.exports = URLUtils;
  function URLUtils() {}
  URLUtils.prototype = Object.create(Object.prototype, {
    _url: { get: function() {
      return new URL2(this.href);
    } },
    protocol: {
      get: function() {
        var url = this._url;
        if (url && url.scheme)
          return url.scheme + ":";
        else
          return ":";
      },
      set: function(v) {
        var output = this.href;
        var url = new URL2(output);
        if (url.isAbsolute()) {
          v = v.replace(/:+$/, "");
          v = v.replace(/[^-+\.a-zA-Z0-9]/g, URL2.percentEncode);
          if (v.length > 0) {
            url.scheme = v;
            output = url.toString();
          }
        }
        this.href = output;
      }
    },
    host: {
      get: function() {
        var url = this._url;
        if (url.isAbsolute() && url.isAuthorityBased())
          return url.host + (url.port ? ":" + url.port : "");
        else
          return "";
      },
      set: function(v) {
        var output = this.href;
        var url = new URL2(output);
        if (url.isAbsolute() && url.isAuthorityBased()) {
          v = v.replace(/[^-+\._~!$&'()*,;:=a-zA-Z0-9]/g, URL2.percentEncode);
          if (v.length > 0) {
            url.host = v;
            delete url.port;
            output = url.toString();
          }
        }
        this.href = output;
      }
    },
    hostname: {
      get: function() {
        var url = this._url;
        if (url.isAbsolute() && url.isAuthorityBased())
          return url.host;
        else
          return "";
      },
      set: function(v) {
        var output = this.href;
        var url = new URL2(output);
        if (url.isAbsolute() && url.isAuthorityBased()) {
          v = v.replace(/^\/+/, "");
          v = v.replace(/[^-+\._~!$&'()*,;:=a-zA-Z0-9]/g, URL2.percentEncode);
          if (v.length > 0) {
            url.host = v;
            output = url.toString();
          }
        }
        this.href = output;
      }
    },
    port: {
      get: function() {
        var url = this._url;
        if (url.isAbsolute() && url.isAuthorityBased() && url.port !== undefined)
          return url.port;
        else
          return "";
      },
      set: function(v) {
        var output = this.href;
        var url = new URL2(output);
        if (url.isAbsolute() && url.isAuthorityBased()) {
          v = "" + v;
          v = v.replace(/[^0-9].*$/, "");
          v = v.replace(/^0+/, "");
          if (v.length === 0)
            v = "0";
          if (parseInt(v, 10) <= 65535) {
            url.port = v;
            output = url.toString();
          }
        }
        this.href = output;
      }
    },
    pathname: {
      get: function() {
        var url = this._url;
        if (url.isAbsolute() && url.isHierarchical())
          return url.path;
        else
          return "";
      },
      set: function(v) {
        var output = this.href;
        var url = new URL2(output);
        if (url.isAbsolute() && url.isHierarchical()) {
          if (v.charAt(0) !== "/")
            v = "/" + v;
          v = v.replace(/[^-+\._~!$&'()*,;:=@\/a-zA-Z0-9]/g, URL2.percentEncode);
          url.path = v;
          output = url.toString();
        }
        this.href = output;
      }
    },
    search: {
      get: function() {
        var url = this._url;
        if (url.isAbsolute() && url.isHierarchical() && url.query !== undefined)
          return "?" + url.query;
        else
          return "";
      },
      set: function(v) {
        var output = this.href;
        var url = new URL2(output);
        if (url.isAbsolute() && url.isHierarchical()) {
          if (v.charAt(0) === "?")
            v = v.substring(1);
          v = v.replace(/[^-+\._~!$&'()*,;:=@\/?a-zA-Z0-9]/g, URL2.percentEncode);
          url.query = v;
          output = url.toString();
        }
        this.href = output;
      }
    },
    hash: {
      get: function() {
        var url = this._url;
        if (url == null || url.fragment == null || url.fragment === "") {
          return "";
        } else {
          return "#" + url.fragment;
        }
      },
      set: function(v) {
        var output = this.href;
        var url = new URL2(output);
        if (v.charAt(0) === "#")
          v = v.substring(1);
        v = v.replace(/[^-+\._~!$&'()*,;:=@\/?a-zA-Z0-9]/g, URL2.percentEncode);
        url.fragment = v;
        output = url.toString();
        this.href = output;
      }
    },
    username: {
      get: function() {
        var url = this._url;
        return url.username || "";
      },
      set: function(v) {
        var output = this.href;
        var url = new URL2(output);
        if (url.isAbsolute()) {
          v = v.replace(/[\x00-\x1F\x7F-\uFFFF "#<>?`\/@\\:]/g, URL2.percentEncode);
          url.username = v;
          output = url.toString();
        }
        this.href = output;
      }
    },
    password: {
      get: function() {
        var url = this._url;
        return url.password || "";
      },
      set: function(v) {
        var output = this.href;
        var url = new URL2(output);
        if (url.isAbsolute()) {
          if (v === "") {
            url.password = null;
          } else {
            v = v.replace(/[\x00-\x1F\x7F-\uFFFF "#<>?`\/@\\]/g, URL2.percentEncode);
            url.password = v;
          }
          output = url.toString();
        }
        this.href = output;
      }
    },
    origin: { get: function() {
      var url = this._url;
      if (url == null) {
        return "";
      }
      var originForPort = function(defaultPort) {
        var origin = [url.scheme, url.host, +url.port || defaultPort];
        return origin[0] + "://" + origin[1] + (origin[2] === defaultPort ? "" : ":" + origin[2]);
      };
      switch (url.scheme) {
        case "ftp":
          return originForPort(21);
        case "gopher":
          return originForPort(70);
        case "http":
        case "ws":
          return originForPort(80);
        case "https":
        case "wss":
          return originForPort(443);
        default:
          return url.scheme + "://";
      }
    } }
  });
  URLUtils._inherit = function(proto) {
    Object.getOwnPropertyNames(URLUtils.prototype).forEach(function(p) {
      if (p === "constructor" || p === "href") {
        return;
      }
      var desc = Object.getOwnPropertyDescriptor(URLUtils.prototype, p);
      Object.defineProperty(proto, p, desc);
    });
  };
});

// node_modules/@mixmark-io/domino/lib/defineElement.js
var require_defineElement = __commonJS((exports, module) => {
  var attributes = require_attributes();
  var isApiWritable = require_config().isApiWritable;
  module.exports = function(spec, defaultConstructor, tagList, tagNameToImpl) {
    var c = spec.ctor;
    if (c) {
      var props = spec.props || {};
      if (spec.attributes) {
        for (var n in spec.attributes) {
          var attr = spec.attributes[n];
          if (typeof attr !== "object" || Array.isArray(attr))
            attr = { type: attr };
          if (!attr.name)
            attr.name = n.toLowerCase();
          props[n] = attributes.property(attr);
        }
      }
      props.constructor = { value: c, writable: isApiWritable };
      c.prototype = Object.create((spec.superclass || defaultConstructor).prototype, props);
      if (spec.events) {
        addEventHandlers(c, spec.events);
      }
      tagList[spec.name] = c;
    } else {
      c = defaultConstructor;
    }
    (spec.tags || spec.tag && [spec.tag] || []).forEach(function(tag) {
      tagNameToImpl[tag] = c;
    });
    return c;
  };
  function EventHandlerBuilder(body, document, form, element) {
    this.body = body;
    this.document = document;
    this.form = form;
    this.element = element;
  }
  EventHandlerBuilder.prototype.build = function() {
    return () => {};
  };
  function EventHandlerChangeHandler(elt, name, oldval, newval) {
    var doc = elt.ownerDocument || Object.create(null);
    var form = elt.form || Object.create(null);
    elt[name] = new EventHandlerBuilder(newval, doc, form, elt).build();
  }
  function addEventHandlers(c, eventHandlerTypes) {
    var p = c.prototype;
    eventHandlerTypes.forEach(function(type) {
      Object.defineProperty(p, "on" + type, {
        get: function() {
          return this._getEventHandler(type);
        },
        set: function(v) {
          this._setEventHandler(type, v);
        }
      });
      attributes.registerChangeHandler(c, "on" + type, EventHandlerChangeHandler);
    });
  }
});

// node_modules/@mixmark-io/domino/lib/htmlelts.js
var require_htmlelts = __commonJS((exports) => {
  var Node = require_Node2();
  var Element = require_Element();
  var CSSStyleDeclaration = require_CSSStyleDeclaration();
  var utils = require_utils();
  var URLUtils = require_URLUtils();
  var defineElement = require_defineElement();
  var htmlElements = exports.elements = {};
  var htmlNameToImpl = Object.create(null);
  exports.createElement = function(doc, localName, prefix) {
    var impl = htmlNameToImpl[localName] || HTMLUnknownElement;
    return new impl(doc, localName, prefix);
  };
  function define(spec) {
    return defineElement(spec, HTMLElement, htmlElements, htmlNameToImpl);
  }
  function URL2(attr) {
    return {
      get: function() {
        var v = this._getattr(attr);
        if (v === null) {
          return "";
        }
        var url = this.doc._resolve(v);
        return url === null ? v : url;
      },
      set: function(value) {
        this._setattr(attr, value);
      }
    };
  }
  function CORS(attr) {
    return {
      get: function() {
        var v = this._getattr(attr);
        if (v === null) {
          return null;
        }
        if (v.toLowerCase() === "use-credentials") {
          return "use-credentials";
        }
        return "anonymous";
      },
      set: function(value) {
        if (value === null || value === undefined) {
          this.removeAttribute(attr);
        } else {
          this._setattr(attr, value);
        }
      }
    };
  }
  var REFERRER = {
    type: ["", "no-referrer", "no-referrer-when-downgrade", "same-origin", "origin", "strict-origin", "origin-when-cross-origin", "strict-origin-when-cross-origin", "unsafe-url"],
    missing: ""
  };
  var focusableElements = {
    A: true,
    LINK: true,
    BUTTON: true,
    INPUT: true,
    SELECT: true,
    TEXTAREA: true,
    COMMAND: true
  };
  var HTMLFormElement = function(doc, localName, prefix) {
    HTMLElement.call(this, doc, localName, prefix);
    this._form = null;
  };
  var HTMLElement = exports.HTMLElement = define({
    superclass: Element,
    name: "HTMLElement",
    ctor: function HTMLElement2(doc, localName, prefix) {
      Element.call(this, doc, localName, utils.NAMESPACE.HTML, prefix);
    },
    props: {
      dangerouslySetInnerHTML: {
        set: function(v) {
          this._innerHTML = v;
        }
      },
      innerHTML: {
        get: function() {
          return this.serialize();
        },
        set: function(v) {
          var parser2 = this.ownerDocument.implementation.mozHTMLParser(this.ownerDocument._address, this);
          parser2.parse(v === null ? "" : String(v), true);
          var target = this instanceof htmlNameToImpl.template ? this.content : this;
          while (target.hasChildNodes())
            target.removeChild(target.firstChild);
          target.appendChild(parser2._asDocumentFragment());
        }
      },
      style: { get: function() {
        if (!this._style)
          this._style = new CSSStyleDeclaration(this);
        return this._style;
      }, set: function(v) {
        if (v === null || v === undefined) {
          v = "";
        }
        this._setattr("style", String(v));
      } },
      blur: { value: function() {} },
      focus: { value: function() {} },
      forceSpellCheck: { value: function() {} },
      click: { value: function() {
        if (this._click_in_progress)
          return;
        this._click_in_progress = true;
        try {
          if (this._pre_click_activation_steps)
            this._pre_click_activation_steps();
          var event = this.ownerDocument.createEvent("MouseEvent");
          event.initMouseEvent("click", true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
          var success = this.dispatchEvent(event);
          if (success) {
            if (this._post_click_activation_steps)
              this._post_click_activation_steps(event);
          } else {
            if (this._cancelled_activation_steps)
              this._cancelled_activation_steps();
          }
        } finally {
          this._click_in_progress = false;
        }
      } },
      submit: { value: utils.nyi }
    },
    attributes: {
      title: String,
      lang: String,
      dir: { type: ["ltr", "rtl", "auto"], missing: "" },
      draggable: { type: ["true", "false"], treatNullAsEmptyString: true },
      spellcheck: { type: ["true", "false"], missing: "" },
      enterKeyHint: { type: ["enter", "done", "go", "next", "previous", "search", "send"], missing: "" },
      autoCapitalize: { type: ["off", "on", "none", "sentences", "words", "characters"], missing: "" },
      autoFocus: Boolean,
      accessKey: String,
      nonce: String,
      hidden: Boolean,
      translate: { type: ["no", "yes"], missing: "" },
      tabIndex: { type: "long", default: function() {
        if (this.tagName in focusableElements || this.contentEditable)
          return 0;
        else
          return -1;
      } }
    },
    events: [
      "abort",
      "canplay",
      "canplaythrough",
      "change",
      "click",
      "contextmenu",
      "cuechange",
      "dblclick",
      "drag",
      "dragend",
      "dragenter",
      "dragleave",
      "dragover",
      "dragstart",
      "drop",
      "durationchange",
      "emptied",
      "ended",
      "input",
      "invalid",
      "keydown",
      "keypress",
      "keyup",
      "loadeddata",
      "loadedmetadata",
      "loadstart",
      "mousedown",
      "mousemove",
      "mouseout",
      "mouseover",
      "mouseup",
      "mousewheel",
      "pause",
      "play",
      "playing",
      "progress",
      "ratechange",
      "readystatechange",
      "reset",
      "seeked",
      "seeking",
      "select",
      "show",
      "stalled",
      "submit",
      "suspend",
      "timeupdate",
      "volumechange",
      "waiting",
      "blur",
      "error",
      "focus",
      "load",
      "scroll"
    ]
  });
  var HTMLUnknownElement = define({
    name: "HTMLUnknownElement",
    ctor: function HTMLUnknownElement2(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    }
  });
  var formAssociatedProps = {
    form: { get: function() {
      return this._form;
    } }
  };
  define({
    tag: "a",
    name: "HTMLAnchorElement",
    ctor: function HTMLAnchorElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    props: {
      _post_click_activation_steps: { value: function(e) {
        if (this.href) {
          this.ownerDocument.defaultView.location = this.href;
        }
      } }
    },
    attributes: {
      href: URL2,
      ping: String,
      download: String,
      target: String,
      rel: String,
      media: String,
      hreflang: String,
      type: String,
      referrerPolicy: REFERRER,
      coords: String,
      charset: String,
      name: String,
      rev: String,
      shape: String
    }
  });
  URLUtils._inherit(htmlNameToImpl.a.prototype);
  define({
    tag: "area",
    name: "HTMLAreaElement",
    ctor: function HTMLAreaElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    attributes: {
      alt: String,
      target: String,
      download: String,
      rel: String,
      media: String,
      href: URL2,
      hreflang: String,
      type: String,
      shape: String,
      coords: String,
      ping: String,
      referrerPolicy: REFERRER,
      noHref: Boolean
    }
  });
  URLUtils._inherit(htmlNameToImpl.area.prototype);
  define({
    tag: "br",
    name: "HTMLBRElement",
    ctor: function HTMLBRElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    attributes: {
      clear: String
    }
  });
  define({
    tag: "base",
    name: "HTMLBaseElement",
    ctor: function HTMLBaseElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    attributes: {
      target: String
    }
  });
  define({
    tag: "body",
    name: "HTMLBodyElement",
    ctor: function HTMLBodyElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    events: [
      "afterprint",
      "beforeprint",
      "beforeunload",
      "blur",
      "error",
      "focus",
      "hashchange",
      "load",
      "message",
      "offline",
      "online",
      "pagehide",
      "pageshow",
      "popstate",
      "resize",
      "scroll",
      "storage",
      "unload"
    ],
    attributes: {
      text: { type: String, treatNullAsEmptyString: true },
      link: { type: String, treatNullAsEmptyString: true },
      vLink: { type: String, treatNullAsEmptyString: true },
      aLink: { type: String, treatNullAsEmptyString: true },
      bgColor: { type: String, treatNullAsEmptyString: true },
      background: String
    }
  });
  define({
    tag: "button",
    name: "HTMLButtonElement",
    ctor: function HTMLButtonElement(doc, localName, prefix) {
      HTMLFormElement.call(this, doc, localName, prefix);
    },
    props: formAssociatedProps,
    attributes: {
      name: String,
      value: String,
      disabled: Boolean,
      autofocus: Boolean,
      type: { type: ["submit", "reset", "button", "menu"], missing: "submit" },
      formTarget: String,
      formAction: URL2,
      formNoValidate: Boolean,
      formMethod: { type: ["get", "post", "dialog"], invalid: "get", missing: "" },
      formEnctype: { type: ["application/x-www-form-urlencoded", "multipart/form-data", "text/plain"], invalid: "application/x-www-form-urlencoded", missing: "" }
    }
  });
  define({
    tag: "dl",
    name: "HTMLDListElement",
    ctor: function HTMLDListElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    attributes: {
      compact: Boolean
    }
  });
  define({
    tag: "data",
    name: "HTMLDataElement",
    ctor: function HTMLDataElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    attributes: {
      value: String
    }
  });
  define({
    tag: "datalist",
    name: "HTMLDataListElement",
    ctor: function HTMLDataListElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    }
  });
  define({
    tag: "details",
    name: "HTMLDetailsElement",
    ctor: function HTMLDetailsElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    attributes: {
      open: Boolean
    }
  });
  define({
    tag: "div",
    name: "HTMLDivElement",
    ctor: function HTMLDivElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    attributes: {
      align: String
    }
  });
  define({
    tag: "embed",
    name: "HTMLEmbedElement",
    ctor: function HTMLEmbedElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    attributes: {
      src: URL2,
      type: String,
      width: String,
      height: String,
      align: String,
      name: String
    }
  });
  define({
    tag: "fieldset",
    name: "HTMLFieldSetElement",
    ctor: function HTMLFieldSetElement(doc, localName, prefix) {
      HTMLFormElement.call(this, doc, localName, prefix);
    },
    props: formAssociatedProps,
    attributes: {
      disabled: Boolean,
      name: String
    }
  });
  define({
    tag: "form",
    name: "HTMLFormElement",
    ctor: function HTMLFormElement2(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    attributes: {
      action: String,
      autocomplete: { type: ["on", "off"], missing: "on" },
      name: String,
      acceptCharset: { name: "accept-charset" },
      target: String,
      noValidate: Boolean,
      method: { type: ["get", "post", "dialog"], invalid: "get", missing: "get" },
      enctype: { type: ["application/x-www-form-urlencoded", "multipart/form-data", "text/plain"], invalid: "application/x-www-form-urlencoded", missing: "application/x-www-form-urlencoded" },
      encoding: { name: "enctype", type: ["application/x-www-form-urlencoded", "multipart/form-data", "text/plain"], invalid: "application/x-www-form-urlencoded", missing: "application/x-www-form-urlencoded" }
    }
  });
  define({
    tag: "hr",
    name: "HTMLHRElement",
    ctor: function HTMLHRElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    attributes: {
      align: String,
      color: String,
      noShade: Boolean,
      size: String,
      width: String
    }
  });
  define({
    tag: "head",
    name: "HTMLHeadElement",
    ctor: function HTMLHeadElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    }
  });
  define({
    tags: ["h1", "h2", "h3", "h4", "h5", "h6"],
    name: "HTMLHeadingElement",
    ctor: function HTMLHeadingElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    attributes: {
      align: String
    }
  });
  define({
    tag: "html",
    name: "HTMLHtmlElement",
    ctor: function HTMLHtmlElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    attributes: {
      xmlns: URL2,
      version: String
    }
  });
  define({
    tag: "iframe",
    name: "HTMLIFrameElement",
    ctor: function HTMLIFrameElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    attributes: {
      src: URL2,
      srcdoc: String,
      name: String,
      width: String,
      height: String,
      seamless: Boolean,
      allow: Boolean,
      allowFullscreen: Boolean,
      allowUserMedia: Boolean,
      allowPaymentRequest: Boolean,
      referrerPolicy: REFERRER,
      loading: { type: ["eager", "lazy"], treatNullAsEmptyString: true },
      align: String,
      scrolling: String,
      frameBorder: String,
      longDesc: URL2,
      marginHeight: { type: String, treatNullAsEmptyString: true },
      marginWidth: { type: String, treatNullAsEmptyString: true }
    }
  });
  define({
    tag: "img",
    name: "HTMLImageElement",
    ctor: function HTMLImageElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    attributes: {
      alt: String,
      src: URL2,
      srcset: String,
      crossOrigin: CORS,
      useMap: String,
      isMap: Boolean,
      sizes: String,
      height: { type: "unsigned long", default: 0 },
      width: { type: "unsigned long", default: 0 },
      referrerPolicy: REFERRER,
      loading: { type: ["eager", "lazy"], missing: "" },
      name: String,
      lowsrc: URL2,
      align: String,
      hspace: { type: "unsigned long", default: 0 },
      vspace: { type: "unsigned long", default: 0 },
      longDesc: URL2,
      border: { type: String, treatNullAsEmptyString: true }
    }
  });
  define({
    tag: "input",
    name: "HTMLInputElement",
    ctor: function HTMLInputElement(doc, localName, prefix) {
      HTMLFormElement.call(this, doc, localName, prefix);
    },
    props: {
      form: formAssociatedProps.form,
      _post_click_activation_steps: { value: function(e) {
        if (this.type === "checkbox") {
          this.checked = !this.checked;
        } else if (this.type === "radio") {
          var group = this.form.getElementsByName(this.name);
          for (var i = group.length - 1;i >= 0; i--) {
            var el = group[i];
            el.checked = el === this;
          }
        }
      } }
    },
    attributes: {
      name: String,
      disabled: Boolean,
      autofocus: Boolean,
      accept: String,
      alt: String,
      max: String,
      min: String,
      pattern: String,
      placeholder: String,
      step: String,
      dirName: String,
      defaultValue: { name: "value" },
      multiple: Boolean,
      required: Boolean,
      readOnly: Boolean,
      checked: Boolean,
      value: String,
      src: URL2,
      defaultChecked: { name: "checked", type: Boolean },
      size: { type: "unsigned long", default: 20, min: 1, setmin: 1 },
      width: { type: "unsigned long", min: 0, setmin: 0, default: 0 },
      height: { type: "unsigned long", min: 0, setmin: 0, default: 0 },
      minLength: { type: "unsigned long", min: 0, setmin: 0, default: -1 },
      maxLength: { type: "unsigned long", min: 0, setmin: 0, default: -1 },
      autocomplete: String,
      type: {
        type: [
          "text",
          "hidden",
          "search",
          "tel",
          "url",
          "email",
          "password",
          "datetime",
          "date",
          "month",
          "week",
          "time",
          "datetime-local",
          "number",
          "range",
          "color",
          "checkbox",
          "radio",
          "file",
          "submit",
          "image",
          "reset",
          "button"
        ],
        missing: "text"
      },
      formTarget: String,
      formNoValidate: Boolean,
      formMethod: { type: ["get", "post"], invalid: "get", missing: "" },
      formEnctype: { type: ["application/x-www-form-urlencoded", "multipart/form-data", "text/plain"], invalid: "application/x-www-form-urlencoded", missing: "" },
      inputMode: { type: ["verbatim", "latin", "latin-name", "latin-prose", "full-width-latin", "kana", "kana-name", "katakana", "numeric", "tel", "email", "url"], missing: "" },
      align: String,
      useMap: String
    }
  });
  define({
    tag: "keygen",
    name: "HTMLKeygenElement",
    ctor: function HTMLKeygenElement(doc, localName, prefix) {
      HTMLFormElement.call(this, doc, localName, prefix);
    },
    props: formAssociatedProps,
    attributes: {
      name: String,
      disabled: Boolean,
      autofocus: Boolean,
      challenge: String,
      keytype: { type: ["rsa"], missing: "" }
    }
  });
  define({
    tag: "li",
    name: "HTMLLIElement",
    ctor: function HTMLLIElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    attributes: {
      value: { type: "long", default: 0 },
      type: String
    }
  });
  define({
    tag: "label",
    name: "HTMLLabelElement",
    ctor: function HTMLLabelElement(doc, localName, prefix) {
      HTMLFormElement.call(this, doc, localName, prefix);
    },
    props: formAssociatedProps,
    attributes: {
      htmlFor: { name: "for", type: String }
    }
  });
  define({
    tag: "legend",
    name: "HTMLLegendElement",
    ctor: function HTMLLegendElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    attributes: {
      align: String
    }
  });
  define({
    tag: "link",
    name: "HTMLLinkElement",
    ctor: function HTMLLinkElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    attributes: {
      href: URL2,
      rel: String,
      media: String,
      hreflang: String,
      type: String,
      crossOrigin: CORS,
      nonce: String,
      integrity: String,
      referrerPolicy: REFERRER,
      imageSizes: String,
      imageSrcset: String,
      charset: String,
      rev: String,
      target: String
    }
  });
  define({
    tag: "map",
    name: "HTMLMapElement",
    ctor: function HTMLMapElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    attributes: {
      name: String
    }
  });
  define({
    tag: "menu",
    name: "HTMLMenuElement",
    ctor: function HTMLMenuElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    attributes: {
      type: { type: ["context", "popup", "toolbar"], missing: "toolbar" },
      label: String,
      compact: Boolean
    }
  });
  define({
    tag: "meta",
    name: "HTMLMetaElement",
    ctor: function HTMLMetaElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    attributes: {
      name: String,
      content: String,
      httpEquiv: { name: "http-equiv", type: String },
      scheme: String
    }
  });
  define({
    tag: "meter",
    name: "HTMLMeterElement",
    ctor: function HTMLMeterElement(doc, localName, prefix) {
      HTMLFormElement.call(this, doc, localName, prefix);
    },
    props: formAssociatedProps
  });
  define({
    tags: ["ins", "del"],
    name: "HTMLModElement",
    ctor: function HTMLModElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    attributes: {
      cite: URL2,
      dateTime: String
    }
  });
  define({
    tag: "ol",
    name: "HTMLOListElement",
    ctor: function HTMLOListElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    props: {
      _numitems: { get: function() {
        var items = 0;
        this.childNodes.forEach(function(n) {
          if (n.nodeType === Node.ELEMENT_NODE && n.tagName === "LI")
            items++;
        });
        return items;
      } }
    },
    attributes: {
      type: String,
      reversed: Boolean,
      start: {
        type: "long",
        default: function() {
          if (this.reversed)
            return this._numitems;
          else
            return 1;
        }
      },
      compact: Boolean
    }
  });
  define({
    tag: "object",
    name: "HTMLObjectElement",
    ctor: function HTMLObjectElement(doc, localName, prefix) {
      HTMLFormElement.call(this, doc, localName, prefix);
    },
    props: formAssociatedProps,
    attributes: {
      data: URL2,
      type: String,
      name: String,
      useMap: String,
      typeMustMatch: Boolean,
      width: String,
      height: String,
      align: String,
      archive: String,
      code: String,
      declare: Boolean,
      hspace: { type: "unsigned long", default: 0 },
      standby: String,
      vspace: { type: "unsigned long", default: 0 },
      codeBase: URL2,
      codeType: String,
      border: { type: String, treatNullAsEmptyString: true }
    }
  });
  define({
    tag: "optgroup",
    name: "HTMLOptGroupElement",
    ctor: function HTMLOptGroupElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    attributes: {
      disabled: Boolean,
      label: String
    }
  });
  define({
    tag: "option",
    name: "HTMLOptionElement",
    ctor: function HTMLOptionElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    props: {
      form: { get: function() {
        var p = this.parentNode;
        while (p && p.nodeType === Node.ELEMENT_NODE) {
          if (p.localName === "select")
            return p.form;
          p = p.parentNode;
        }
      } },
      value: {
        get: function() {
          return this._getattr("value") || this.text;
        },
        set: function(v) {
          this._setattr("value", v);
        }
      },
      text: {
        get: function() {
          return this.textContent.replace(/[ \t\n\f\r]+/g, " ").trim();
        },
        set: function(v) {
          this.textContent = v;
        }
      }
    },
    attributes: {
      disabled: Boolean,
      defaultSelected: { name: "selected", type: Boolean },
      label: String
    }
  });
  define({
    tag: "output",
    name: "HTMLOutputElement",
    ctor: function HTMLOutputElement(doc, localName, prefix) {
      HTMLFormElement.call(this, doc, localName, prefix);
    },
    props: formAssociatedProps,
    attributes: {
      name: String
    }
  });
  define({
    tag: "p",
    name: "HTMLParagraphElement",
    ctor: function HTMLParagraphElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    attributes: {
      align: String
    }
  });
  define({
    tag: "param",
    name: "HTMLParamElement",
    ctor: function HTMLParamElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    attributes: {
      name: String,
      value: String,
      type: String,
      valueType: String
    }
  });
  define({
    tags: ["pre", "listing", "xmp"],
    name: "HTMLPreElement",
    ctor: function HTMLPreElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    attributes: {
      width: { type: "long", default: 0 }
    }
  });
  define({
    tag: "progress",
    name: "HTMLProgressElement",
    ctor: function HTMLProgressElement(doc, localName, prefix) {
      HTMLFormElement.call(this, doc, localName, prefix);
    },
    props: formAssociatedProps,
    attributes: {
      max: { type: Number, float: true, default: 1, min: 0 }
    }
  });
  define({
    tags: ["q", "blockquote"],
    name: "HTMLQuoteElement",
    ctor: function HTMLQuoteElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    attributes: {
      cite: URL2
    }
  });
  define({
    tag: "script",
    name: "HTMLScriptElement",
    ctor: function HTMLScriptElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    props: {
      text: {
        get: function() {
          var s = "";
          for (var i = 0, n = this.childNodes.length;i < n; i++) {
            var child = this.childNodes[i];
            if (child.nodeType === Node.TEXT_NODE)
              s += child._data;
          }
          return s;
        },
        set: function(value) {
          this.removeChildren();
          if (value !== null && value !== "") {
            this.appendChild(this.ownerDocument.createTextNode(value));
          }
        }
      }
    },
    attributes: {
      src: URL2,
      type: String,
      charset: String,
      referrerPolicy: REFERRER,
      defer: Boolean,
      async: Boolean,
      nomodule: Boolean,
      crossOrigin: CORS,
      nonce: String,
      integrity: String
    }
  });
  define({
    tag: "select",
    name: "HTMLSelectElement",
    ctor: function HTMLSelectElement(doc, localName, prefix) {
      HTMLFormElement.call(this, doc, localName, prefix);
    },
    props: {
      form: formAssociatedProps.form,
      options: { get: function() {
        return this.getElementsByTagName("option");
      } }
    },
    attributes: {
      autocomplete: String,
      name: String,
      disabled: Boolean,
      autofocus: Boolean,
      multiple: Boolean,
      required: Boolean,
      size: { type: "unsigned long", default: 0 }
    }
  });
  define({
    tag: "span",
    name: "HTMLSpanElement",
    ctor: function HTMLSpanElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    }
  });
  define({
    tag: "style",
    name: "HTMLStyleElement",
    ctor: function HTMLStyleElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    attributes: {
      media: String,
      type: String,
      scoped: Boolean
    }
  });
  define({
    tag: "caption",
    name: "HTMLTableCaptionElement",
    ctor: function HTMLTableCaptionElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    attributes: {
      align: String
    }
  });
  define({
    name: "HTMLTableCellElement",
    ctor: function HTMLTableCellElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    attributes: {
      colSpan: { type: "unsigned long", default: 1 },
      rowSpan: { type: "unsigned long", default: 1 },
      scope: { type: ["row", "col", "rowgroup", "colgroup"], missing: "" },
      abbr: String,
      align: String,
      axis: String,
      height: String,
      width: String,
      ch: { name: "char", type: String },
      chOff: { name: "charoff", type: String },
      noWrap: Boolean,
      vAlign: String,
      bgColor: { type: String, treatNullAsEmptyString: true }
    }
  });
  define({
    tags: ["col", "colgroup"],
    name: "HTMLTableColElement",
    ctor: function HTMLTableColElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    attributes: {
      span: { type: "limited unsigned long with fallback", default: 1, min: 1 },
      align: String,
      ch: { name: "char", type: String },
      chOff: { name: "charoff", type: String },
      vAlign: String,
      width: String
    }
  });
  define({
    tag: "table",
    name: "HTMLTableElement",
    ctor: function HTMLTableElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    props: {
      rows: { get: function() {
        return this.getElementsByTagName("tr");
      } }
    },
    attributes: {
      align: String,
      border: String,
      frame: String,
      rules: String,
      summary: String,
      width: String,
      bgColor: { type: String, treatNullAsEmptyString: true },
      cellPadding: { type: String, treatNullAsEmptyString: true },
      cellSpacing: { type: String, treatNullAsEmptyString: true }
    }
  });
  define({
    tag: "template",
    name: "HTMLTemplateElement",
    ctor: function HTMLTemplateElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
      this._contentFragment = doc._templateDoc.createDocumentFragment();
    },
    props: {
      content: { get: function() {
        return this._contentFragment;
      } },
      serialize: { value: function() {
        return this.content.serialize();
      } }
    }
  });
  define({
    tag: "tr",
    name: "HTMLTableRowElement",
    ctor: function HTMLTableRowElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    props: {
      cells: { get: function() {
        return this.querySelectorAll("td,th");
      } }
    },
    attributes: {
      align: String,
      ch: { name: "char", type: String },
      chOff: { name: "charoff", type: String },
      vAlign: String,
      bgColor: { type: String, treatNullAsEmptyString: true }
    }
  });
  define({
    tags: ["thead", "tfoot", "tbody"],
    name: "HTMLTableSectionElement",
    ctor: function HTMLTableSectionElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    props: {
      rows: { get: function() {
        return this.getElementsByTagName("tr");
      } }
    },
    attributes: {
      align: String,
      ch: { name: "char", type: String },
      chOff: { name: "charoff", type: String },
      vAlign: String
    }
  });
  define({
    tag: "textarea",
    name: "HTMLTextAreaElement",
    ctor: function HTMLTextAreaElement(doc, localName, prefix) {
      HTMLFormElement.call(this, doc, localName, prefix);
    },
    props: {
      form: formAssociatedProps.form,
      type: { get: function() {
        return "textarea";
      } },
      defaultValue: {
        get: function() {
          return this.textContent;
        },
        set: function(v) {
          this.textContent = v;
        }
      },
      value: {
        get: function() {
          return this.defaultValue;
        },
        set: function(v) {
          this.defaultValue = v;
        }
      },
      textLength: { get: function() {
        return this.value.length;
      } }
    },
    attributes: {
      autocomplete: String,
      name: String,
      disabled: Boolean,
      autofocus: Boolean,
      placeholder: String,
      wrap: String,
      dirName: String,
      required: Boolean,
      readOnly: Boolean,
      rows: { type: "limited unsigned long with fallback", default: 2 },
      cols: { type: "limited unsigned long with fallback", default: 20 },
      maxLength: { type: "unsigned long", min: 0, setmin: 0, default: -1 },
      minLength: { type: "unsigned long", min: 0, setmin: 0, default: -1 },
      inputMode: { type: ["verbatim", "latin", "latin-name", "latin-prose", "full-width-latin", "kana", "kana-name", "katakana", "numeric", "tel", "email", "url"], missing: "" }
    }
  });
  define({
    tag: "time",
    name: "HTMLTimeElement",
    ctor: function HTMLTimeElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    attributes: {
      dateTime: String,
      pubDate: Boolean
    }
  });
  define({
    tag: "title",
    name: "HTMLTitleElement",
    ctor: function HTMLTitleElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    props: {
      text: { get: function() {
        return this.textContent;
      } }
    }
  });
  define({
    tag: "ul",
    name: "HTMLUListElement",
    ctor: function HTMLUListElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    attributes: {
      type: String,
      compact: Boolean
    }
  });
  define({
    name: "HTMLMediaElement",
    ctor: function HTMLMediaElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    attributes: {
      src: URL2,
      crossOrigin: CORS,
      preload: { type: ["metadata", "none", "auto", { value: "", alias: "auto" }], missing: "auto" },
      loop: Boolean,
      autoplay: Boolean,
      mediaGroup: String,
      controls: Boolean,
      defaultMuted: { name: "muted", type: Boolean }
    }
  });
  define({
    name: "HTMLAudioElement",
    tag: "audio",
    superclass: htmlElements.HTMLMediaElement,
    ctor: function HTMLAudioElement(doc, localName, prefix) {
      htmlElements.HTMLMediaElement.call(this, doc, localName, prefix);
    }
  });
  define({
    name: "HTMLVideoElement",
    tag: "video",
    superclass: htmlElements.HTMLMediaElement,
    ctor: function HTMLVideoElement(doc, localName, prefix) {
      htmlElements.HTMLMediaElement.call(this, doc, localName, prefix);
    },
    attributes: {
      poster: URL2,
      width: { type: "unsigned long", min: 0, default: 0 },
      height: { type: "unsigned long", min: 0, default: 0 }
    }
  });
  define({
    tag: "td",
    name: "HTMLTableDataCellElement",
    superclass: htmlElements.HTMLTableCellElement,
    ctor: function HTMLTableDataCellElement(doc, localName, prefix) {
      htmlElements.HTMLTableCellElement.call(this, doc, localName, prefix);
    }
  });
  define({
    tag: "th",
    name: "HTMLTableHeaderCellElement",
    superclass: htmlElements.HTMLTableCellElement,
    ctor: function HTMLTableHeaderCellElement(doc, localName, prefix) {
      htmlElements.HTMLTableCellElement.call(this, doc, localName, prefix);
    }
  });
  define({
    tag: "frameset",
    name: "HTMLFrameSetElement",
    ctor: function HTMLFrameSetElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    }
  });
  define({
    tag: "frame",
    name: "HTMLFrameElement",
    ctor: function HTMLFrameElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    }
  });
  define({
    tag: "canvas",
    name: "HTMLCanvasElement",
    ctor: function HTMLCanvasElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    props: {
      getContext: { value: utils.nyi },
      probablySupportsContext: { value: utils.nyi },
      setContext: { value: utils.nyi },
      transferControlToProxy: { value: utils.nyi },
      toDataURL: { value: utils.nyi },
      toBlob: { value: utils.nyi }
    },
    attributes: {
      width: { type: "unsigned long", default: 300 },
      height: { type: "unsigned long", default: 150 }
    }
  });
  define({
    tag: "dialog",
    name: "HTMLDialogElement",
    ctor: function HTMLDialogElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    props: {
      show: { value: utils.nyi },
      showModal: { value: utils.nyi },
      close: { value: utils.nyi }
    },
    attributes: {
      open: Boolean,
      returnValue: String
    }
  });
  define({
    tag: "menuitem",
    name: "HTMLMenuItemElement",
    ctor: function HTMLMenuItemElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    props: {
      _label: {
        get: function() {
          var val = this._getattr("label");
          if (val !== null && val !== "") {
            return val;
          }
          val = this.textContent;
          return val.replace(/[ \t\n\f\r]+/g, " ").trim();
        }
      },
      label: {
        get: function() {
          var val = this._getattr("label");
          if (val !== null) {
            return val;
          }
          return this._label;
        },
        set: function(v) {
          this._setattr("label", v);
        }
      }
    },
    attributes: {
      type: { type: ["command", "checkbox", "radio"], missing: "command" },
      icon: URL2,
      disabled: Boolean,
      checked: Boolean,
      radiogroup: String,
      default: Boolean
    }
  });
  define({
    tag: "source",
    name: "HTMLSourceElement",
    ctor: function HTMLSourceElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    attributes: {
      srcset: String,
      sizes: String,
      media: String,
      src: URL2,
      type: String,
      width: String,
      height: String
    }
  });
  define({
    tag: "track",
    name: "HTMLTrackElement",
    ctor: function HTMLTrackElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    attributes: {
      src: URL2,
      srclang: String,
      label: String,
      default: Boolean,
      kind: { type: ["subtitles", "captions", "descriptions", "chapters", "metadata"], missing: "subtitles", invalid: "metadata" }
    },
    props: {
      NONE: { get: function() {
        return 0;
      } },
      LOADING: { get: function() {
        return 1;
      } },
      LOADED: { get: function() {
        return 2;
      } },
      ERROR: { get: function() {
        return 3;
      } },
      readyState: { get: utils.nyi },
      track: { get: utils.nyi }
    }
  });
  define({
    tag: "font",
    name: "HTMLFontElement",
    ctor: function HTMLFontElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    attributes: {
      color: { type: String, treatNullAsEmptyString: true },
      face: { type: String },
      size: { type: String }
    }
  });
  define({
    tag: "dir",
    name: "HTMLDirectoryElement",
    ctor: function HTMLDirectoryElement(doc, localName, prefix) {
      HTMLElement.call(this, doc, localName, prefix);
    },
    attributes: {
      compact: Boolean
    }
  });
  define({
    tags: [
      "abbr",
      "address",
      "article",
      "aside",
      "b",
      "bdi",
      "bdo",
      "cite",
      "content",
      "code",
      "dd",
      "dfn",
      "dt",
      "em",
      "figcaption",
      "figure",
      "footer",
      "header",
      "hgroup",
      "i",
      "kbd",
      "main",
      "mark",
      "nav",
      "noscript",
      "rb",
      "rp",
      "rt",
      "rtc",
      "ruby",
      "s",
      "samp",
      "section",
      "small",
      "strong",
      "sub",
      "summary",
      "sup",
      "u",
      "var",
      "wbr",
      "acronym",
      "basefont",
      "big",
      "center",
      "nobr",
      "noembed",
      "noframes",
      "plaintext",
      "strike",
      "tt"
    ]
  });
});

// node_modules/@mixmark-io/domino/lib/svg.js
var require_svg = __commonJS((exports) => {
  var Element = require_Element();
  var defineElement = require_defineElement();
  var utils = require_utils();
  var CSSStyleDeclaration = require_CSSStyleDeclaration();
  var svgElements = exports.elements = {};
  var svgNameToImpl = Object.create(null);
  exports.createElement = function(doc, localName, prefix) {
    var impl = svgNameToImpl[localName] || SVGElement;
    return new impl(doc, localName, prefix);
  };
  function define(spec) {
    return defineElement(spec, SVGElement, svgElements, svgNameToImpl);
  }
  var SVGElement = define({
    superclass: Element,
    name: "SVGElement",
    ctor: function SVGElement2(doc, localName, prefix) {
      Element.call(this, doc, localName, utils.NAMESPACE.SVG, prefix);
    },
    props: {
      style: { get: function() {
        if (!this._style)
          this._style = new CSSStyleDeclaration(this);
        return this._style;
      } }
    }
  });
  define({
    name: "SVGSVGElement",
    ctor: function SVGSVGElement(doc, localName, prefix) {
      SVGElement.call(this, doc, localName, prefix);
    },
    tag: "svg",
    props: {
      createSVGRect: { value: function() {
        return exports.createElement(this.ownerDocument, "rect", null);
      } }
    }
  });
  define({
    tags: [
      "a",
      "altGlyph",
      "altGlyphDef",
      "altGlyphItem",
      "animate",
      "animateColor",
      "animateMotion",
      "animateTransform",
      "circle",
      "clipPath",
      "color-profile",
      "cursor",
      "defs",
      "desc",
      "ellipse",
      "feBlend",
      "feColorMatrix",
      "feComponentTransfer",
      "feComposite",
      "feConvolveMatrix",
      "feDiffuseLighting",
      "feDisplacementMap",
      "feDistantLight",
      "feFlood",
      "feFuncA",
      "feFuncB",
      "feFuncG",
      "feFuncR",
      "feGaussianBlur",
      "feImage",
      "feMerge",
      "feMergeNode",
      "feMorphology",
      "feOffset",
      "fePointLight",
      "feSpecularLighting",
      "feSpotLight",
      "feTile",
      "feTurbulence",
      "filter",
      "font",
      "font-face",
      "font-face-format",
      "font-face-name",
      "font-face-src",
      "font-face-uri",
      "foreignObject",
      "g",
      "glyph",
      "glyphRef",
      "hkern",
      "image",
      "line",
      "linearGradient",
      "marker",
      "mask",
      "metadata",
      "missing-glyph",
      "mpath",
      "path",
      "pattern",
      "polygon",
      "polyline",
      "radialGradient",
      "rect",
      "script",
      "set",
      "stop",
      "style",
      "switch",
      "symbol",
      "text",
      "textPath",
      "title",
      "tref",
      "tspan",
      "use",
      "view",
      "vkern"
    ]
  });
});

// node_modules/@mixmark-io/domino/lib/MutationConstants.js
var require_MutationConstants = __commonJS((exports, module) => {
  module.exports = {
    VALUE: 1,
    ATTR: 2,
    REMOVE_ATTR: 3,
    REMOVE: 4,
    MOVE: 5,
    INSERT: 6
  };
});

// node_modules/@mixmark-io/domino/lib/Document.js
var require_Document2 = __commonJS((exports, module) => {
  module.exports = Document2;
  var Node = require_Node2();
  var NodeList = require_NodeList();
  var ContainerNode = require_ContainerNode();
  var Element = require_Element();
  var Text = require_Text();
  var Comment = require_Comment();
  var Event = require_Event();
  var DocumentFragment = require_DocumentFragment();
  var ProcessingInstruction = require_ProcessingInstruction();
  var DOMImplementation = require_DOMImplementation();
  var TreeWalker = require_TreeWalker();
  var NodeIterator = require_NodeIterator();
  var NodeFilter = require_NodeFilter();
  var URL2 = require_URL();
  var select = require_select();
  var events = require_events();
  var xml = require_xmlnames();
  var html = require_htmlelts();
  var svg = require_svg();
  var utils = require_utils();
  var MUTATE = require_MutationConstants();
  var NAMESPACE = utils.NAMESPACE;
  var isApiWritable = require_config().isApiWritable;
  function Document2(isHTML, address) {
    ContainerNode.call(this);
    this.nodeType = Node.DOCUMENT_NODE;
    this.isHTML = isHTML;
    this._address = address || "about:blank";
    this.readyState = "loading";
    this.implementation = new DOMImplementation(this);
    this.ownerDocument = null;
    this._contentType = isHTML ? "text/html" : "application/xml";
    this.doctype = null;
    this.documentElement = null;
    this._templateDocCache = null;
    this._nodeIterators = null;
    this._nid = 1;
    this._nextnid = 2;
    this._nodes = [null, this];
    this.byId = Object.create(null);
    this.modclock = 0;
  }
  var supportedEvents = {
    event: "Event",
    customevent: "CustomEvent",
    uievent: "UIEvent",
    mouseevent: "MouseEvent"
  };
  var replacementEvent = {
    events: "event",
    htmlevents: "event",
    mouseevents: "mouseevent",
    mutationevents: "mutationevent",
    uievents: "uievent"
  };
  var mirrorAttr = function(f, name, defaultValue) {
    return {
      get: function() {
        var o = f.call(this);
        if (o) {
          return o[name];
        }
        return defaultValue;
      },
      set: function(value) {
        var o = f.call(this);
        if (o) {
          o[name] = value;
        }
      }
    };
  };
  function validateAndExtract(namespace, qualifiedName) {
    var prefix, localName, pos;
    if (namespace === "") {
      namespace = null;
    }
    if (!xml.isValidQName(qualifiedName)) {
      utils.InvalidCharacterError();
    }
    prefix = null;
    localName = qualifiedName;
    pos = qualifiedName.indexOf(":");
    if (pos >= 0) {
      prefix = qualifiedName.substring(0, pos);
      localName = qualifiedName.substring(pos + 1);
    }
    if (prefix !== null && namespace === null) {
      utils.NamespaceError();
    }
    if (prefix === "xml" && namespace !== NAMESPACE.XML) {
      utils.NamespaceError();
    }
    if ((prefix === "xmlns" || qualifiedName === "xmlns") && namespace !== NAMESPACE.XMLNS) {
      utils.NamespaceError();
    }
    if (namespace === NAMESPACE.XMLNS && !(prefix === "xmlns" || qualifiedName === "xmlns")) {
      utils.NamespaceError();
    }
    return { namespace, prefix, localName };
  }
  Document2.prototype = Object.create(ContainerNode.prototype, {
    _setMutationHandler: { value: function(handler3) {
      this.mutationHandler = handler3;
    } },
    _dispatchRendererEvent: { value: function(targetNid, type, details) {
      var target = this._nodes[targetNid];
      if (!target)
        return;
      target._dispatchEvent(new Event(type, details), true);
    } },
    nodeName: { value: "#document" },
    nodeValue: {
      get: function() {
        return null;
      },
      set: function() {}
    },
    documentURI: { get: function() {
      return this._address;
    }, set: utils.nyi },
    compatMode: { get: function() {
      return this._quirks ? "BackCompat" : "CSS1Compat";
    } },
    createTextNode: { value: function(data) {
      return new Text(this, String(data));
    } },
    createComment: { value: function(data) {
      return new Comment(this, data);
    } },
    createDocumentFragment: { value: function() {
      return new DocumentFragment(this);
    } },
    createProcessingInstruction: { value: function(target, data) {
      if (!xml.isValidName(target) || data.indexOf("?>") !== -1)
        utils.InvalidCharacterError();
      return new ProcessingInstruction(this, target, data);
    } },
    createAttribute: { value: function(localName) {
      localName = String(localName);
      if (!xml.isValidName(localName))
        utils.InvalidCharacterError();
      if (this.isHTML) {
        localName = utils.toASCIILowerCase(localName);
      }
      return new Element._Attr(null, localName, null, null, "");
    } },
    createAttributeNS: { value: function(namespace, qualifiedName) {
      namespace = namespace === null || namespace === undefined || namespace === "" ? null : String(namespace);
      qualifiedName = String(qualifiedName);
      var ve = validateAndExtract(namespace, qualifiedName);
      return new Element._Attr(null, ve.localName, ve.prefix, ve.namespace, "");
    } },
    createElement: { value: function(localName) {
      localName = String(localName);
      if (!xml.isValidName(localName))
        utils.InvalidCharacterError();
      if (this.isHTML) {
        if (/[A-Z]/.test(localName))
          localName = utils.toASCIILowerCase(localName);
        return html.createElement(this, localName, null);
      } else if (this.contentType === "application/xhtml+xml") {
        return html.createElement(this, localName, null);
      } else {
        return new Element(this, localName, null, null);
      }
    }, writable: isApiWritable },
    createElementNS: { value: function(namespace, qualifiedName) {
      namespace = namespace === null || namespace === undefined || namespace === "" ? null : String(namespace);
      qualifiedName = String(qualifiedName);
      var ve = validateAndExtract(namespace, qualifiedName);
      return this._createElementNS(ve.localName, ve.namespace, ve.prefix);
    }, writable: isApiWritable },
    _createElementNS: { value: function(localName, namespace, prefix) {
      if (namespace === NAMESPACE.HTML) {
        return html.createElement(this, localName, prefix);
      } else if (namespace === NAMESPACE.SVG) {
        return svg.createElement(this, localName, prefix);
      }
      return new Element(this, localName, namespace, prefix);
    } },
    createEvent: { value: function createEvent(interfaceName) {
      interfaceName = interfaceName.toLowerCase();
      var name = replacementEvent[interfaceName] || interfaceName;
      var constructor = events[supportedEvents[name]];
      if (constructor) {
        var e = new constructor;
        e._initialized = false;
        return e;
      } else {
        utils.NotSupportedError();
      }
    } },
    createTreeWalker: { value: function(root2, whatToShow, filter) {
      if (!root2) {
        throw new TypeError("root argument is required");
      }
      if (!(root2 instanceof Node)) {
        throw new TypeError("root not a node");
      }
      whatToShow = whatToShow === undefined ? NodeFilter.SHOW_ALL : +whatToShow;
      filter = filter === undefined ? null : filter;
      return new TreeWalker(root2, whatToShow, filter);
    } },
    createNodeIterator: { value: function(root2, whatToShow, filter) {
      if (!root2) {
        throw new TypeError("root argument is required");
      }
      if (!(root2 instanceof Node)) {
        throw new TypeError("root not a node");
      }
      whatToShow = whatToShow === undefined ? NodeFilter.SHOW_ALL : +whatToShow;
      filter = filter === undefined ? null : filter;
      return new NodeIterator(root2, whatToShow, filter);
    } },
    _attachNodeIterator: { value: function(ni) {
      if (!this._nodeIterators) {
        this._nodeIterators = [];
      }
      this._nodeIterators.push(ni);
    } },
    _detachNodeIterator: { value: function(ni) {
      var idx = this._nodeIterators.indexOf(ni);
      this._nodeIterators.splice(idx, 1);
    } },
    _preremoveNodeIterators: { value: function(toBeRemoved) {
      if (this._nodeIterators) {
        this._nodeIterators.forEach(function(ni) {
          ni._preremove(toBeRemoved);
        });
      }
    } },
    _updateDocTypeElement: { value: function _updateDocTypeElement() {
      this.doctype = this.documentElement = null;
      for (var kid = this.firstChild;kid !== null; kid = kid.nextSibling) {
        if (kid.nodeType === Node.DOCUMENT_TYPE_NODE)
          this.doctype = kid;
        else if (kid.nodeType === Node.ELEMENT_NODE)
          this.documentElement = kid;
      }
    } },
    insertBefore: { value: function insertBefore(child, refChild) {
      Node.prototype.insertBefore.call(this, child, refChild);
      this._updateDocTypeElement();
      return child;
    } },
    replaceChild: { value: function replaceChild(node, child) {
      Node.prototype.replaceChild.call(this, node, child);
      this._updateDocTypeElement();
      return child;
    } },
    removeChild: { value: function removeChild(child) {
      Node.prototype.removeChild.call(this, child);
      this._updateDocTypeElement();
      return child;
    } },
    getElementById: { value: function(id) {
      var n = this.byId[id];
      if (!n)
        return null;
      if (n instanceof MultiId) {
        return n.getFirst();
      }
      return n;
    } },
    _hasMultipleElementsWithId: { value: function(id) {
      return this.byId[id] instanceof MultiId;
    } },
    getElementsByName: { value: Element.prototype.getElementsByName },
    getElementsByTagName: { value: Element.prototype.getElementsByTagName },
    getElementsByTagNameNS: { value: Element.prototype.getElementsByTagNameNS },
    getElementsByClassName: { value: Element.prototype.getElementsByClassName },
    adoptNode: { value: function adoptNode(node) {
      if (node.nodeType === Node.DOCUMENT_NODE)
        utils.NotSupportedError();
      if (node.nodeType === Node.ATTRIBUTE_NODE) {
        return node;
      }
      if (node.parentNode)
        node.parentNode.removeChild(node);
      if (node.ownerDocument !== this)
        recursivelySetOwner(node, this);
      return node;
    } },
    importNode: { value: function importNode(node, deep) {
      return this.adoptNode(node.cloneNode(deep));
    }, writable: isApiWritable },
    origin: { get: function origin() {
      return null;
    } },
    characterSet: { get: function characterSet() {
      return "UTF-8";
    } },
    contentType: { get: function contentType() {
      return this._contentType;
    } },
    URL: { get: function URL3() {
      return this._address;
    } },
    domain: { get: utils.nyi, set: utils.nyi },
    referrer: { get: utils.nyi },
    cookie: { get: utils.nyi, set: utils.nyi },
    lastModified: { get: utils.nyi },
    location: {
      get: function() {
        return this.defaultView ? this.defaultView.location : null;
      },
      set: utils.nyi
    },
    _titleElement: {
      get: function() {
        return this.getElementsByTagName("title").item(0) || null;
      }
    },
    title: {
      get: function() {
        var elt = this._titleElement;
        var value = elt ? elt.textContent : "";
        return value.replace(/[ \t\n\r\f]+/g, " ").replace(/(^ )|( $)/g, "");
      },
      set: function(value) {
        var elt = this._titleElement;
        var head = this.head;
        if (!elt && !head) {
          return;
        }
        if (!elt) {
          elt = this.createElement("title");
          head.appendChild(elt);
        }
        elt.textContent = value;
      }
    },
    dir: mirrorAttr(function() {
      var htmlElement = this.documentElement;
      if (htmlElement && htmlElement.tagName === "HTML") {
        return htmlElement;
      }
    }, "dir", ""),
    fgColor: mirrorAttr(function() {
      return this.body;
    }, "text", ""),
    linkColor: mirrorAttr(function() {
      return this.body;
    }, "link", ""),
    vlinkColor: mirrorAttr(function() {
      return this.body;
    }, "vLink", ""),
    alinkColor: mirrorAttr(function() {
      return this.body;
    }, "aLink", ""),
    bgColor: mirrorAttr(function() {
      return this.body;
    }, "bgColor", ""),
    charset: { get: function() {
      return this.characterSet;
    } },
    inputEncoding: { get: function() {
      return this.characterSet;
    } },
    scrollingElement: {
      get: function() {
        return this._quirks ? this.body : this.documentElement;
      }
    },
    body: {
      get: function() {
        return namedHTMLChild(this.documentElement, "body");
      },
      set: utils.nyi
    },
    head: { get: function() {
      return namedHTMLChild(this.documentElement, "head");
    } },
    images: { get: utils.nyi },
    embeds: { get: utils.nyi },
    plugins: { get: utils.nyi },
    links: { get: utils.nyi },
    forms: { get: utils.nyi },
    scripts: { get: utils.nyi },
    applets: { get: function() {
      return [];
    } },
    activeElement: { get: function() {
      return null;
    } },
    innerHTML: {
      get: function() {
        return this.serialize();
      },
      set: utils.nyi
    },
    outerHTML: {
      get: function() {
        return this.serialize();
      },
      set: utils.nyi
    },
    write: { value: function(args) {
      if (!this.isHTML)
        utils.InvalidStateError();
      if (!this._parser)
        return;
      if (!this._parser) {}
      var s = arguments.join("");
      this._parser.parse(s);
    } },
    writeln: { value: function writeln(args) {
      this.write(Array.prototype.join.call(arguments, "") + `
`);
    } },
    open: { value: function() {
      this.documentElement = null;
    } },
    close: { value: function() {
      this.readyState = "interactive";
      this._dispatchEvent(new Event("readystatechange"), true);
      this._dispatchEvent(new Event("DOMContentLoaded"), true);
      this.readyState = "complete";
      this._dispatchEvent(new Event("readystatechange"), true);
      if (this.defaultView) {
        this.defaultView._dispatchEvent(new Event("load"), true);
      }
    } },
    clone: { value: function clone() {
      var d = new Document2(this.isHTML, this._address);
      d._quirks = this._quirks;
      d._contentType = this._contentType;
      return d;
    } },
    cloneNode: { value: function cloneNode(deep) {
      var clone = Node.prototype.cloneNode.call(this, false);
      if (deep) {
        for (var kid = this.firstChild;kid !== null; kid = kid.nextSibling) {
          clone._appendChild(clone.importNode(kid, true));
        }
      }
      clone._updateDocTypeElement();
      return clone;
    } },
    isEqual: { value: function isEqual(n) {
      return true;
    } },
    mutateValue: { value: function(node) {
      if (this.mutationHandler) {
        this.mutationHandler({
          type: MUTATE.VALUE,
          target: node,
          data: node.data
        });
      }
    } },
    mutateAttr: { value: function(attr, oldval) {
      if (this.mutationHandler) {
        this.mutationHandler({
          type: MUTATE.ATTR,
          target: attr.ownerElement,
          attr
        });
      }
    } },
    mutateRemoveAttr: { value: function(attr) {
      if (this.mutationHandler) {
        this.mutationHandler({
          type: MUTATE.REMOVE_ATTR,
          target: attr.ownerElement,
          attr
        });
      }
    } },
    mutateRemove: { value: function(node) {
      if (this.mutationHandler) {
        this.mutationHandler({
          type: MUTATE.REMOVE,
          target: node.parentNode,
          node
        });
      }
      recursivelyUproot(node);
    } },
    mutateInsert: { value: function(node) {
      recursivelyRoot(node);
      if (this.mutationHandler) {
        this.mutationHandler({
          type: MUTATE.INSERT,
          target: node.parentNode,
          node
        });
      }
    } },
    mutateMove: { value: function(node) {
      if (this.mutationHandler) {
        this.mutationHandler({
          type: MUTATE.MOVE,
          target: node
        });
      }
    } },
    addId: { value: function addId(id, n) {
      var val = this.byId[id];
      if (!val) {
        this.byId[id] = n;
      } else {
        if (!(val instanceof MultiId)) {
          val = new MultiId(val);
          this.byId[id] = val;
        }
        val.add(n);
      }
    } },
    delId: { value: function delId(id, n) {
      var val = this.byId[id];
      utils.assert(val);
      if (val instanceof MultiId) {
        val.del(n);
        if (val.length === 1) {
          this.byId[id] = val.downgrade();
        }
      } else {
        this.byId[id] = undefined;
      }
    } },
    _resolve: { value: function(href) {
      return new URL2(this._documentBaseURL).resolve(href);
    } },
    _documentBaseURL: { get: function() {
      var url = this._address;
      if (url === "about:blank")
        url = "/";
      var base = this.querySelector("base[href]");
      if (base) {
        return new URL2(url).resolve(base.getAttribute("href"));
      }
      return url;
    } },
    _templateDoc: { get: function() {
      if (!this._templateDocCache) {
        var newDoc = new Document2(this.isHTML, this._address);
        this._templateDocCache = newDoc._templateDocCache = newDoc;
      }
      return this._templateDocCache;
    } },
    querySelector: { value: function(selector) {
      return select(selector, this)[0];
    } },
    querySelectorAll: { value: function(selector) {
      var nodes = select(selector, this);
      return nodes.item ? nodes : new NodeList(nodes);
    } }
  });
  var eventHandlerTypes = [
    "abort",
    "canplay",
    "canplaythrough",
    "change",
    "click",
    "contextmenu",
    "cuechange",
    "dblclick",
    "drag",
    "dragend",
    "dragenter",
    "dragleave",
    "dragover",
    "dragstart",
    "drop",
    "durationchange",
    "emptied",
    "ended",
    "input",
    "invalid",
    "keydown",
    "keypress",
    "keyup",
    "loadeddata",
    "loadedmetadata",
    "loadstart",
    "mousedown",
    "mousemove",
    "mouseout",
    "mouseover",
    "mouseup",
    "mousewheel",
    "pause",
    "play",
    "playing",
    "progress",
    "ratechange",
    "readystatechange",
    "reset",
    "seeked",
    "seeking",
    "select",
    "show",
    "stalled",
    "submit",
    "suspend",
    "timeupdate",
    "volumechange",
    "waiting",
    "blur",
    "error",
    "focus",
    "load",
    "scroll"
  ];
  eventHandlerTypes.forEach(function(type) {
    Object.defineProperty(Document2.prototype, "on" + type, {
      get: function() {
        return this._getEventHandler(type);
      },
      set: function(v) {
        this._setEventHandler(type, v);
      }
    });
  });
  function namedHTMLChild(parent, name) {
    if (parent && parent.isHTML) {
      for (var kid = parent.firstChild;kid !== null; kid = kid.nextSibling) {
        if (kid.nodeType === Node.ELEMENT_NODE && kid.localName === name && kid.namespaceURI === NAMESPACE.HTML) {
          return kid;
        }
      }
    }
    return null;
  }
  function root(n) {
    n._nid = n.ownerDocument._nextnid++;
    n.ownerDocument._nodes[n._nid] = n;
    if (n.nodeType === Node.ELEMENT_NODE) {
      var id = n.getAttribute("id");
      if (id)
        n.ownerDocument.addId(id, n);
      if (n._roothook)
        n._roothook();
    }
  }
  function uproot(n) {
    if (n.nodeType === Node.ELEMENT_NODE) {
      var id = n.getAttribute("id");
      if (id)
        n.ownerDocument.delId(id, n);
    }
    n.ownerDocument._nodes[n._nid] = undefined;
    n._nid = undefined;
  }
  function recursivelyRoot(node) {
    root(node);
    if (node.nodeType === Node.ELEMENT_NODE) {
      for (var kid = node.firstChild;kid !== null; kid = kid.nextSibling)
        recursivelyRoot(kid);
    }
  }
  function recursivelyUproot(node) {
    uproot(node);
    for (var kid = node.firstChild;kid !== null; kid = kid.nextSibling)
      recursivelyUproot(kid);
  }
  function recursivelySetOwner(node, owner) {
    node.ownerDocument = owner;
    node._lastModTime = undefined;
    if (Object.prototype.hasOwnProperty.call(node, "_tagName")) {
      node._tagName = undefined;
    }
    for (var kid = node.firstChild;kid !== null; kid = kid.nextSibling)
      recursivelySetOwner(kid, owner);
  }
  function MultiId(node) {
    this.nodes = Object.create(null);
    this.nodes[node._nid] = node;
    this.length = 1;
    this.firstNode = undefined;
  }
  MultiId.prototype.add = function(node) {
    if (!this.nodes[node._nid]) {
      this.nodes[node._nid] = node;
      this.length++;
      this.firstNode = undefined;
    }
  };
  MultiId.prototype.del = function(node) {
    if (this.nodes[node._nid]) {
      delete this.nodes[node._nid];
      this.length--;
      this.firstNode = undefined;
    }
  };
  MultiId.prototype.getFirst = function() {
    if (!this.firstNode) {
      var nid;
      for (nid in this.nodes) {
        if (this.firstNode === undefined || this.firstNode.compareDocumentPosition(this.nodes[nid]) & Node.DOCUMENT_POSITION_PRECEDING) {
          this.firstNode = this.nodes[nid];
        }
      }
    }
    return this.firstNode;
  };
  MultiId.prototype.downgrade = function() {
    if (this.length === 1) {
      var nid;
      for (nid in this.nodes) {
        return this.nodes[nid];
      }
    }
    return this;
  };
});

// node_modules/@mixmark-io/domino/lib/DocumentType.js
var require_DocumentType = __commonJS((exports, module) => {
  module.exports = DocumentType;
  var Node = require_Node2();
  var Leaf = require_Leaf();
  var ChildNode = require_ChildNode();
  function DocumentType(ownerDocument, name, publicId, systemId) {
    Leaf.call(this);
    this.nodeType = Node.DOCUMENT_TYPE_NODE;
    this.ownerDocument = ownerDocument || null;
    this.name = name;
    this.publicId = publicId || "";
    this.systemId = systemId || "";
  }
  DocumentType.prototype = Object.create(Leaf.prototype, {
    nodeName: { get: function() {
      return this.name;
    } },
    nodeValue: {
      get: function() {
        return null;
      },
      set: function() {}
    },
    clone: { value: function clone() {
      return new DocumentType(this.ownerDocument, this.name, this.publicId, this.systemId);
    } },
    isEqual: { value: function isEqual(n) {
      return this.name === n.name && this.publicId === n.publicId && this.systemId === n.systemId;
    } }
  });
  Object.defineProperties(DocumentType.prototype, ChildNode);
});

// node_modules/@mixmark-io/domino/lib/HTMLParser.js
var require_HTMLParser = __commonJS((exports, module) => {
  module.exports = HTMLParser;
  var Document2 = require_Document2();
  var DocumentType = require_DocumentType();
  var Node = require_Node2();
  var NAMESPACE = require_utils().NAMESPACE;
  var html = require_htmlelts();
  var impl = html.elements;
  var pushAll = Function.prototype.apply.bind(Array.prototype.push);
  var EOF = -1;
  var TEXT = 1;
  var TAG = 2;
  var ENDTAG = 3;
  var COMMENT = 4;
  var DOCTYPE = 5;
  var NOATTRS = [];
  var quirkyPublicIds = /^HTML$|^-\/\/W3O\/\/DTD W3 HTML Strict 3\.0\/\/EN\/\/$|^-\/W3C\/DTD HTML 4\.0 Transitional\/EN$|^\+\/\/Silmaril\/\/dtd html Pro v0r11 19970101\/\/|^-\/\/AdvaSoft Ltd\/\/DTD HTML 3\.0 asWedit \+ extensions\/\/|^-\/\/AS\/\/DTD HTML 3\.0 asWedit \+ extensions\/\/|^-\/\/IETF\/\/DTD HTML 2\.0 Level 1\/\/|^-\/\/IETF\/\/DTD HTML 2\.0 Level 2\/\/|^-\/\/IETF\/\/DTD HTML 2\.0 Strict Level 1\/\/|^-\/\/IETF\/\/DTD HTML 2\.0 Strict Level 2\/\/|^-\/\/IETF\/\/DTD HTML 2\.0 Strict\/\/|^-\/\/IETF\/\/DTD HTML 2\.0\/\/|^-\/\/IETF\/\/DTD HTML 2\.1E\/\/|^-\/\/IETF\/\/DTD HTML 3\.0\/\/|^-\/\/IETF\/\/DTD HTML 3\.2 Final\/\/|^-\/\/IETF\/\/DTD HTML 3\.2\/\/|^-\/\/IETF\/\/DTD HTML 3\/\/|^-\/\/IETF\/\/DTD HTML Level 0\/\/|^-\/\/IETF\/\/DTD HTML Level 1\/\/|^-\/\/IETF\/\/DTD HTML Level 2\/\/|^-\/\/IETF\/\/DTD HTML Level 3\/\/|^-\/\/IETF\/\/DTD HTML Strict Level 0\/\/|^-\/\/IETF\/\/DTD HTML Strict Level 1\/\/|^-\/\/IETF\/\/DTD HTML Strict Level 2\/\/|^-\/\/IETF\/\/DTD HTML Strict Level 3\/\/|^-\/\/IETF\/\/DTD HTML Strict\/\/|^-\/\/IETF\/\/DTD HTML\/\/|^-\/\/Metrius\/\/DTD Metrius Presentational\/\/|^-\/\/Microsoft\/\/DTD Internet Explorer 2\.0 HTML Strict\/\/|^-\/\/Microsoft\/\/DTD Internet Explorer 2\.0 HTML\/\/|^-\/\/Microsoft\/\/DTD Internet Explorer 2\.0 Tables\/\/|^-\/\/Microsoft\/\/DTD Internet Explorer 3\.0 HTML Strict\/\/|^-\/\/Microsoft\/\/DTD Internet Explorer 3\.0 HTML\/\/|^-\/\/Microsoft\/\/DTD Internet Explorer 3\.0 Tables\/\/|^-\/\/Netscape Comm\. Corp\.\/\/DTD HTML\/\/|^-\/\/Netscape Comm\. Corp\.\/\/DTD Strict HTML\/\/|^-\/\/O'Reilly and Associates\/\/DTD HTML 2\.0\/\/|^-\/\/O'Reilly and Associates\/\/DTD HTML Extended 1\.0\/\/|^-\/\/O'Reilly and Associates\/\/DTD HTML Extended Relaxed 1\.0\/\/|^-\/\/SoftQuad Software\/\/DTD HoTMetaL PRO 6\.0::19990601::extensions to HTML 4\.0\/\/|^-\/\/SoftQuad\/\/DTD HoTMetaL PRO 4\.0::19971010::extensions to HTML 4\.0\/\/|^-\/\/Spyglass\/\/DTD HTML 2\.0 Extended\/\/|^-\/\/SQ\/\/DTD HTML 2\.0 HoTMetaL \+ extensions\/\/|^-\/\/Sun Microsystems Corp\.\/\/DTD HotJava HTML\/\/|^-\/\/Sun Microsystems Corp\.\/\/DTD HotJava Strict HTML\/\/|^-\/\/W3C\/\/DTD HTML 3 1995-03-24\/\/|^-\/\/W3C\/\/DTD HTML 3\.2 Draft\/\/|^-\/\/W3C\/\/DTD HTML 3\.2 Final\/\/|^-\/\/W3C\/\/DTD HTML 3\.2\/\/|^-\/\/W3C\/\/DTD HTML 3\.2S Draft\/\/|^-\/\/W3C\/\/DTD HTML 4\.0 Frameset\/\/|^-\/\/W3C\/\/DTD HTML 4\.0 Transitional\/\/|^-\/\/W3C\/\/DTD HTML Experimental 19960712\/\/|^-\/\/W3C\/\/DTD HTML Experimental 970421\/\/|^-\/\/W3C\/\/DTD W3 HTML\/\/|^-\/\/W3O\/\/DTD W3 HTML 3\.0\/\/|^-\/\/WebTechs\/\/DTD Mozilla HTML 2\.0\/\/|^-\/\/WebTechs\/\/DTD Mozilla HTML\/\//i;
  var quirkySystemId = "http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd";
  var conditionallyQuirkyPublicIds = /^-\/\/W3C\/\/DTD HTML 4\.01 Frameset\/\/|^-\/\/W3C\/\/DTD HTML 4\.01 Transitional\/\//i;
  var limitedQuirkyPublicIds = /^-\/\/W3C\/\/DTD XHTML 1\.0 Frameset\/\/|^-\/\/W3C\/\/DTD XHTML 1\.0 Transitional\/\//i;
  var specialSet = Object.create(null);
  specialSet[NAMESPACE.HTML] = {
    __proto__: null,
    address: true,
    applet: true,
    area: true,
    article: true,
    aside: true,
    base: true,
    basefont: true,
    bgsound: true,
    blockquote: true,
    body: true,
    br: true,
    button: true,
    caption: true,
    center: true,
    col: true,
    colgroup: true,
    dd: true,
    details: true,
    dir: true,
    div: true,
    dl: true,
    dt: true,
    embed: true,
    fieldset: true,
    figcaption: true,
    figure: true,
    footer: true,
    form: true,
    frame: true,
    frameset: true,
    h1: true,
    h2: true,
    h3: true,
    h4: true,
    h5: true,
    h6: true,
    head: true,
    header: true,
    hgroup: true,
    hr: true,
    html: true,
    iframe: true,
    img: true,
    input: true,
    li: true,
    link: true,
    listing: true,
    main: true,
    marquee: true,
    menu: true,
    meta: true,
    nav: true,
    noembed: true,
    noframes: true,
    noscript: true,
    object: true,
    ol: true,
    p: true,
    param: true,
    plaintext: true,
    pre: true,
    script: true,
    section: true,
    select: true,
    source: true,
    style: true,
    summary: true,
    table: true,
    tbody: true,
    td: true,
    template: true,
    textarea: true,
    tfoot: true,
    th: true,
    thead: true,
    title: true,
    tr: true,
    track: true,
    ul: true,
    wbr: true,
    xmp: true
  };
  specialSet[NAMESPACE.SVG] = {
    __proto__: null,
    foreignObject: true,
    desc: true,
    title: true
  };
  specialSet[NAMESPACE.MATHML] = {
    __proto__: null,
    mi: true,
    mo: true,
    mn: true,
    ms: true,
    mtext: true,
    "annotation-xml": true
  };
  var addressdivpSet = Object.create(null);
  addressdivpSet[NAMESPACE.HTML] = {
    __proto__: null,
    address: true,
    div: true,
    p: true
  };
  var dddtSet = Object.create(null);
  dddtSet[NAMESPACE.HTML] = {
    __proto__: null,
    dd: true,
    dt: true
  };
  var tablesectionrowSet = Object.create(null);
  tablesectionrowSet[NAMESPACE.HTML] = {
    __proto__: null,
    table: true,
    thead: true,
    tbody: true,
    tfoot: true,
    tr: true
  };
  var impliedEndTagsSet = Object.create(null);
  impliedEndTagsSet[NAMESPACE.HTML] = {
    __proto__: null,
    dd: true,
    dt: true,
    li: true,
    menuitem: true,
    optgroup: true,
    option: true,
    p: true,
    rb: true,
    rp: true,
    rt: true,
    rtc: true
  };
  var thoroughImpliedEndTagsSet = Object.create(null);
  thoroughImpliedEndTagsSet[NAMESPACE.HTML] = {
    __proto__: null,
    caption: true,
    colgroup: true,
    dd: true,
    dt: true,
    li: true,
    optgroup: true,
    option: true,
    p: true,
    rb: true,
    rp: true,
    rt: true,
    rtc: true,
    tbody: true,
    td: true,
    tfoot: true,
    th: true,
    thead: true,
    tr: true
  };
  var tableContextSet = Object.create(null);
  tableContextSet[NAMESPACE.HTML] = {
    __proto__: null,
    table: true,
    template: true,
    html: true
  };
  var tableBodyContextSet = Object.create(null);
  tableBodyContextSet[NAMESPACE.HTML] = {
    __proto__: null,
    tbody: true,
    tfoot: true,
    thead: true,
    template: true,
    html: true
  };
  var tableRowContextSet = Object.create(null);
  tableRowContextSet[NAMESPACE.HTML] = {
    __proto__: null,
    tr: true,
    template: true,
    html: true
  };
  var formassociatedSet = Object.create(null);
  formassociatedSet[NAMESPACE.HTML] = {
    __proto__: null,
    button: true,
    fieldset: true,
    input: true,
    keygen: true,
    object: true,
    output: true,
    select: true,
    textarea: true,
    img: true
  };
  var inScopeSet = Object.create(null);
  inScopeSet[NAMESPACE.HTML] = {
    __proto__: null,
    applet: true,
    caption: true,
    html: true,
    table: true,
    td: true,
    th: true,
    marquee: true,
    object: true,
    template: true
  };
  inScopeSet[NAMESPACE.MATHML] = {
    __proto__: null,
    mi: true,
    mo: true,
    mn: true,
    ms: true,
    mtext: true,
    "annotation-xml": true
  };
  inScopeSet[NAMESPACE.SVG] = {
    __proto__: null,
    foreignObject: true,
    desc: true,
    title: true
  };
  var inListItemScopeSet = Object.create(inScopeSet);
  inListItemScopeSet[NAMESPACE.HTML] = Object.create(inScopeSet[NAMESPACE.HTML]);
  inListItemScopeSet[NAMESPACE.HTML].ol = true;
  inListItemScopeSet[NAMESPACE.HTML].ul = true;
  var inButtonScopeSet = Object.create(inScopeSet);
  inButtonScopeSet[NAMESPACE.HTML] = Object.create(inScopeSet[NAMESPACE.HTML]);
  inButtonScopeSet[NAMESPACE.HTML].button = true;
  var inTableScopeSet = Object.create(null);
  inTableScopeSet[NAMESPACE.HTML] = {
    __proto__: null,
    html: true,
    table: true,
    template: true
  };
  var invertedSelectScopeSet = Object.create(null);
  invertedSelectScopeSet[NAMESPACE.HTML] = {
    __proto__: null,
    optgroup: true,
    option: true
  };
  var mathmlTextIntegrationPointSet = Object.create(null);
  mathmlTextIntegrationPointSet[NAMESPACE.MATHML] = {
    __proto__: null,
    mi: true,
    mo: true,
    mn: true,
    ms: true,
    mtext: true
  };
  var htmlIntegrationPointSet = Object.create(null);
  htmlIntegrationPointSet[NAMESPACE.SVG] = {
    __proto__: null,
    foreignObject: true,
    desc: true,
    title: true
  };
  var foreignAttributes = {
    __proto__: null,
    "xlink:actuate": NAMESPACE.XLINK,
    "xlink:arcrole": NAMESPACE.XLINK,
    "xlink:href": NAMESPACE.XLINK,
    "xlink:role": NAMESPACE.XLINK,
    "xlink:show": NAMESPACE.XLINK,
    "xlink:title": NAMESPACE.XLINK,
    "xlink:type": NAMESPACE.XLINK,
    "xml:base": NAMESPACE.XML,
    "xml:lang": NAMESPACE.XML,
    "xml:space": NAMESPACE.XML,
    xmlns: NAMESPACE.XMLNS,
    "xmlns:xlink": NAMESPACE.XMLNS
  };
  var svgAttrAdjustments = {
    __proto__: null,
    attributename: "attributeName",
    attributetype: "attributeType",
    basefrequency: "baseFrequency",
    baseprofile: "baseProfile",
    calcmode: "calcMode",
    clippathunits: "clipPathUnits",
    diffuseconstant: "diffuseConstant",
    edgemode: "edgeMode",
    filterunits: "filterUnits",
    glyphref: "glyphRef",
    gradienttransform: "gradientTransform",
    gradientunits: "gradientUnits",
    kernelmatrix: "kernelMatrix",
    kernelunitlength: "kernelUnitLength",
    keypoints: "keyPoints",
    keysplines: "keySplines",
    keytimes: "keyTimes",
    lengthadjust: "lengthAdjust",
    limitingconeangle: "limitingConeAngle",
    markerheight: "markerHeight",
    markerunits: "markerUnits",
    markerwidth: "markerWidth",
    maskcontentunits: "maskContentUnits",
    maskunits: "maskUnits",
    numoctaves: "numOctaves",
    pathlength: "pathLength",
    patterncontentunits: "patternContentUnits",
    patterntransform: "patternTransform",
    patternunits: "patternUnits",
    pointsatx: "pointsAtX",
    pointsaty: "pointsAtY",
    pointsatz: "pointsAtZ",
    preservealpha: "preserveAlpha",
    preserveaspectratio: "preserveAspectRatio",
    primitiveunits: "primitiveUnits",
    refx: "refX",
    refy: "refY",
    repeatcount: "repeatCount",
    repeatdur: "repeatDur",
    requiredextensions: "requiredExtensions",
    requiredfeatures: "requiredFeatures",
    specularconstant: "specularConstant",
    specularexponent: "specularExponent",
    spreadmethod: "spreadMethod",
    startoffset: "startOffset",
    stddeviation: "stdDeviation",
    stitchtiles: "stitchTiles",
    surfacescale: "surfaceScale",
    systemlanguage: "systemLanguage",
    tablevalues: "tableValues",
    targetx: "targetX",
    targety: "targetY",
    textlength: "textLength",
    viewbox: "viewBox",
    viewtarget: "viewTarget",
    xchannelselector: "xChannelSelector",
    ychannelselector: "yChannelSelector",
    zoomandpan: "zoomAndPan"
  };
  var svgTagNameAdjustments = {
    __proto__: null,
    altglyph: "altGlyph",
    altglyphdef: "altGlyphDef",
    altglyphitem: "altGlyphItem",
    animatecolor: "animateColor",
    animatemotion: "animateMotion",
    animatetransform: "animateTransform",
    clippath: "clipPath",
    feblend: "feBlend",
    fecolormatrix: "feColorMatrix",
    fecomponenttransfer: "feComponentTransfer",
    fecomposite: "feComposite",
    feconvolvematrix: "feConvolveMatrix",
    fediffuselighting: "feDiffuseLighting",
    fedisplacementmap: "feDisplacementMap",
    fedistantlight: "feDistantLight",
    feflood: "feFlood",
    fefunca: "feFuncA",
    fefuncb: "feFuncB",
    fefuncg: "feFuncG",
    fefuncr: "feFuncR",
    fegaussianblur: "feGaussianBlur",
    feimage: "feImage",
    femerge: "feMerge",
    femergenode: "feMergeNode",
    femorphology: "feMorphology",
    feoffset: "feOffset",
    fepointlight: "fePointLight",
    fespecularlighting: "feSpecularLighting",
    fespotlight: "feSpotLight",
    fetile: "feTile",
    feturbulence: "feTurbulence",
    foreignobject: "foreignObject",
    glyphref: "glyphRef",
    lineargradient: "linearGradient",
    radialgradient: "radialGradient",
    textpath: "textPath"
  };
  var numericCharRefReplacements = {
    __proto__: null,
    0: 65533,
    128: 8364,
    130: 8218,
    131: 402,
    132: 8222,
    133: 8230,
    134: 8224,
    135: 8225,
    136: 710,
    137: 8240,
    138: 352,
    139: 8249,
    140: 338,
    142: 381,
    145: 8216,
    146: 8217,
    147: 8220,
    148: 8221,
    149: 8226,
    150: 8211,
    151: 8212,
    152: 732,
    153: 8482,
    154: 353,
    155: 8250,
    156: 339,
    158: 382,
    159: 376
  };
  var namedCharRefs = {
    __proto__: null,
    AElig: 198,
    "AElig;": 198,
    AMP: 38,
    "AMP;": 38,
    Aacute: 193,
    "Aacute;": 193,
    "Abreve;": 258,
    Acirc: 194,
    "Acirc;": 194,
    "Acy;": 1040,
    "Afr;": [55349, 56580],
    Agrave: 192,
    "Agrave;": 192,
    "Alpha;": 913,
    "Amacr;": 256,
    "And;": 10835,
    "Aogon;": 260,
    "Aopf;": [55349, 56632],
    "ApplyFunction;": 8289,
    Aring: 197,
    "Aring;": 197,
    "Ascr;": [55349, 56476],
    "Assign;": 8788,
    Atilde: 195,
    "Atilde;": 195,
    Auml: 196,
    "Auml;": 196,
    "Backslash;": 8726,
    "Barv;": 10983,
    "Barwed;": 8966,
    "Bcy;": 1041,
    "Because;": 8757,
    "Bernoullis;": 8492,
    "Beta;": 914,
    "Bfr;": [55349, 56581],
    "Bopf;": [55349, 56633],
    "Breve;": 728,
    "Bscr;": 8492,
    "Bumpeq;": 8782,
    "CHcy;": 1063,
    COPY: 169,
    "COPY;": 169,
    "Cacute;": 262,
    "Cap;": 8914,
    "CapitalDifferentialD;": 8517,
    "Cayleys;": 8493,
    "Ccaron;": 268,
    Ccedil: 199,
    "Ccedil;": 199,
    "Ccirc;": 264,
    "Cconint;": 8752,
    "Cdot;": 266,
    "Cedilla;": 184,
    "CenterDot;": 183,
    "Cfr;": 8493,
    "Chi;": 935,
    "CircleDot;": 8857,
    "CircleMinus;": 8854,
    "CirclePlus;": 8853,
    "CircleTimes;": 8855,
    "ClockwiseContourIntegral;": 8754,
    "CloseCurlyDoubleQuote;": 8221,
    "CloseCurlyQuote;": 8217,
    "Colon;": 8759,
    "Colone;": 10868,
    "Congruent;": 8801,
    "Conint;": 8751,
    "ContourIntegral;": 8750,
    "Copf;": 8450,
    "Coproduct;": 8720,
    "CounterClockwiseContourIntegral;": 8755,
    "Cross;": 10799,
    "Cscr;": [55349, 56478],
    "Cup;": 8915,
    "CupCap;": 8781,
    "DD;": 8517,
    "DDotrahd;": 10513,
    "DJcy;": 1026,
    "DScy;": 1029,
    "DZcy;": 1039,
    "Dagger;": 8225,
    "Darr;": 8609,
    "Dashv;": 10980,
    "Dcaron;": 270,
    "Dcy;": 1044,
    "Del;": 8711,
    "Delta;": 916,
    "Dfr;": [55349, 56583],
    "DiacriticalAcute;": 180,
    "DiacriticalDot;": 729,
    "DiacriticalDoubleAcute;": 733,
    "DiacriticalGrave;": 96,
    "DiacriticalTilde;": 732,
    "Diamond;": 8900,
    "DifferentialD;": 8518,
    "Dopf;": [55349, 56635],
    "Dot;": 168,
    "DotDot;": 8412,
    "DotEqual;": 8784,
    "DoubleContourIntegral;": 8751,
    "DoubleDot;": 168,
    "DoubleDownArrow;": 8659,
    "DoubleLeftArrow;": 8656,
    "DoubleLeftRightArrow;": 8660,
    "DoubleLeftTee;": 10980,
    "DoubleLongLeftArrow;": 10232,
    "DoubleLongLeftRightArrow;": 10234,
    "DoubleLongRightArrow;": 10233,
    "DoubleRightArrow;": 8658,
    "DoubleRightTee;": 8872,
    "DoubleUpArrow;": 8657,
    "DoubleUpDownArrow;": 8661,
    "DoubleVerticalBar;": 8741,
    "DownArrow;": 8595,
    "DownArrowBar;": 10515,
    "DownArrowUpArrow;": 8693,
    "DownBreve;": 785,
    "DownLeftRightVector;": 10576,
    "DownLeftTeeVector;": 10590,
    "DownLeftVector;": 8637,
    "DownLeftVectorBar;": 10582,
    "DownRightTeeVector;": 10591,
    "DownRightVector;": 8641,
    "DownRightVectorBar;": 10583,
    "DownTee;": 8868,
    "DownTeeArrow;": 8615,
    "Downarrow;": 8659,
    "Dscr;": [55349, 56479],
    "Dstrok;": 272,
    "ENG;": 330,
    ETH: 208,
    "ETH;": 208,
    Eacute: 201,
    "Eacute;": 201,
    "Ecaron;": 282,
    Ecirc: 202,
    "Ecirc;": 202,
    "Ecy;": 1069,
    "Edot;": 278,
    "Efr;": [55349, 56584],
    Egrave: 200,
    "Egrave;": 200,
    "Element;": 8712,
    "Emacr;": 274,
    "EmptySmallSquare;": 9723,
    "EmptyVerySmallSquare;": 9643,
    "Eogon;": 280,
    "Eopf;": [55349, 56636],
    "Epsilon;": 917,
    "Equal;": 10869,
    "EqualTilde;": 8770,
    "Equilibrium;": 8652,
    "Escr;": 8496,
    "Esim;": 10867,
    "Eta;": 919,
    Euml: 203,
    "Euml;": 203,
    "Exists;": 8707,
    "ExponentialE;": 8519,
    "Fcy;": 1060,
    "Ffr;": [55349, 56585],
    "FilledSmallSquare;": 9724,
    "FilledVerySmallSquare;": 9642,
    "Fopf;": [55349, 56637],
    "ForAll;": 8704,
    "Fouriertrf;": 8497,
    "Fscr;": 8497,
    "GJcy;": 1027,
    GT: 62,
    "GT;": 62,
    "Gamma;": 915,
    "Gammad;": 988,
    "Gbreve;": 286,
    "Gcedil;": 290,
    "Gcirc;": 284,
    "Gcy;": 1043,
    "Gdot;": 288,
    "Gfr;": [55349, 56586],
    "Gg;": 8921,
    "Gopf;": [55349, 56638],
    "GreaterEqual;": 8805,
    "GreaterEqualLess;": 8923,
    "GreaterFullEqual;": 8807,
    "GreaterGreater;": 10914,
    "GreaterLess;": 8823,
    "GreaterSlantEqual;": 10878,
    "GreaterTilde;": 8819,
    "Gscr;": [55349, 56482],
    "Gt;": 8811,
    "HARDcy;": 1066,
    "Hacek;": 711,
    "Hat;": 94,
    "Hcirc;": 292,
    "Hfr;": 8460,
    "HilbertSpace;": 8459,
    "Hopf;": 8461,
    "HorizontalLine;": 9472,
    "Hscr;": 8459,
    "Hstrok;": 294,
    "HumpDownHump;": 8782,
    "HumpEqual;": 8783,
    "IEcy;": 1045,
    "IJlig;": 306,
    "IOcy;": 1025,
    Iacute: 205,
    "Iacute;": 205,
    Icirc: 206,
    "Icirc;": 206,
    "Icy;": 1048,
    "Idot;": 304,
    "Ifr;": 8465,
    Igrave: 204,
    "Igrave;": 204,
    "Im;": 8465,
    "Imacr;": 298,
    "ImaginaryI;": 8520,
    "Implies;": 8658,
    "Int;": 8748,
    "Integral;": 8747,
    "Intersection;": 8898,
    "InvisibleComma;": 8291,
    "InvisibleTimes;": 8290,
    "Iogon;": 302,
    "Iopf;": [55349, 56640],
    "Iota;": 921,
    "Iscr;": 8464,
    "Itilde;": 296,
    "Iukcy;": 1030,
    Iuml: 207,
    "Iuml;": 207,
    "Jcirc;": 308,
    "Jcy;": 1049,
    "Jfr;": [55349, 56589],
    "Jopf;": [55349, 56641],
    "Jscr;": [55349, 56485],
    "Jsercy;": 1032,
    "Jukcy;": 1028,
    "KHcy;": 1061,
    "KJcy;": 1036,
    "Kappa;": 922,
    "Kcedil;": 310,
    "Kcy;": 1050,
    "Kfr;": [55349, 56590],
    "Kopf;": [55349, 56642],
    "Kscr;": [55349, 56486],
    "LJcy;": 1033,
    LT: 60,
    "LT;": 60,
    "Lacute;": 313,
    "Lambda;": 923,
    "Lang;": 10218,
    "Laplacetrf;": 8466,
    "Larr;": 8606,
    "Lcaron;": 317,
    "Lcedil;": 315,
    "Lcy;": 1051,
    "LeftAngleBracket;": 10216,
    "LeftArrow;": 8592,
    "LeftArrowBar;": 8676,
    "LeftArrowRightArrow;": 8646,
    "LeftCeiling;": 8968,
    "LeftDoubleBracket;": 10214,
    "LeftDownTeeVector;": 10593,
    "LeftDownVector;": 8643,
    "LeftDownVectorBar;": 10585,
    "LeftFloor;": 8970,
    "LeftRightArrow;": 8596,
    "LeftRightVector;": 10574,
    "LeftTee;": 8867,
    "LeftTeeArrow;": 8612,
    "LeftTeeVector;": 10586,
    "LeftTriangle;": 8882,
    "LeftTriangleBar;": 10703,
    "LeftTriangleEqual;": 8884,
    "LeftUpDownVector;": 10577,
    "LeftUpTeeVector;": 10592,
    "LeftUpVector;": 8639,
    "LeftUpVectorBar;": 10584,
    "LeftVector;": 8636,
    "LeftVectorBar;": 10578,
    "Leftarrow;": 8656,
    "Leftrightarrow;": 8660,
    "LessEqualGreater;": 8922,
    "LessFullEqual;": 8806,
    "LessGreater;": 8822,
    "LessLess;": 10913,
    "LessSlantEqual;": 10877,
    "LessTilde;": 8818,
    "Lfr;": [55349, 56591],
    "Ll;": 8920,
    "Lleftarrow;": 8666,
    "Lmidot;": 319,
    "LongLeftArrow;": 10229,
    "LongLeftRightArrow;": 10231,
    "LongRightArrow;": 10230,
    "Longleftarrow;": 10232,
    "Longleftrightarrow;": 10234,
    "Longrightarrow;": 10233,
    "Lopf;": [55349, 56643],
    "LowerLeftArrow;": 8601,
    "LowerRightArrow;": 8600,
    "Lscr;": 8466,
    "Lsh;": 8624,
    "Lstrok;": 321,
    "Lt;": 8810,
    "Map;": 10501,
    "Mcy;": 1052,
    "MediumSpace;": 8287,
    "Mellintrf;": 8499,
    "Mfr;": [55349, 56592],
    "MinusPlus;": 8723,
    "Mopf;": [55349, 56644],
    "Mscr;": 8499,
    "Mu;": 924,
    "NJcy;": 1034,
    "Nacute;": 323,
    "Ncaron;": 327,
    "Ncedil;": 325,
    "Ncy;": 1053,
    "NegativeMediumSpace;": 8203,
    "NegativeThickSpace;": 8203,
    "NegativeThinSpace;": 8203,
    "NegativeVeryThinSpace;": 8203,
    "NestedGreaterGreater;": 8811,
    "NestedLessLess;": 8810,
    "NewLine;": 10,
    "Nfr;": [55349, 56593],
    "NoBreak;": 8288,
    "NonBreakingSpace;": 160,
    "Nopf;": 8469,
    "Not;": 10988,
    "NotCongruent;": 8802,
    "NotCupCap;": 8813,
    "NotDoubleVerticalBar;": 8742,
    "NotElement;": 8713,
    "NotEqual;": 8800,
    "NotEqualTilde;": [8770, 824],
    "NotExists;": 8708,
    "NotGreater;": 8815,
    "NotGreaterEqual;": 8817,
    "NotGreaterFullEqual;": [8807, 824],
    "NotGreaterGreater;": [8811, 824],
    "NotGreaterLess;": 8825,
    "NotGreaterSlantEqual;": [10878, 824],
    "NotGreaterTilde;": 8821,
    "NotHumpDownHump;": [8782, 824],
    "NotHumpEqual;": [8783, 824],
    "NotLeftTriangle;": 8938,
    "NotLeftTriangleBar;": [10703, 824],
    "NotLeftTriangleEqual;": 8940,
    "NotLess;": 8814,
    "NotLessEqual;": 8816,
    "NotLessGreater;": 8824,
    "NotLessLess;": [8810, 824],
    "NotLessSlantEqual;": [10877, 824],
    "NotLessTilde;": 8820,
    "NotNestedGreaterGreater;": [10914, 824],
    "NotNestedLessLess;": [10913, 824],
    "NotPrecedes;": 8832,
    "NotPrecedesEqual;": [10927, 824],
    "NotPrecedesSlantEqual;": 8928,
    "NotReverseElement;": 8716,
    "NotRightTriangle;": 8939,
    "NotRightTriangleBar;": [10704, 824],
    "NotRightTriangleEqual;": 8941,
    "NotSquareSubset;": [8847, 824],
    "NotSquareSubsetEqual;": 8930,
    "NotSquareSuperset;": [8848, 824],
    "NotSquareSupersetEqual;": 8931,
    "NotSubset;": [8834, 8402],
    "NotSubsetEqual;": 8840,
    "NotSucceeds;": 8833,
    "NotSucceedsEqual;": [10928, 824],
    "NotSucceedsSlantEqual;": 8929,
    "NotSucceedsTilde;": [8831, 824],
    "NotSuperset;": [8835, 8402],
    "NotSupersetEqual;": 8841,
    "NotTilde;": 8769,
    "NotTildeEqual;": 8772,
    "NotTildeFullEqual;": 8775,
    "NotTildeTilde;": 8777,
    "NotVerticalBar;": 8740,
    "Nscr;": [55349, 56489],
    Ntilde: 209,
    "Ntilde;": 209,
    "Nu;": 925,
    "OElig;": 338,
    Oacute: 211,
    "Oacute;": 211,
    Ocirc: 212,
    "Ocirc;": 212,
    "Ocy;": 1054,
    "Odblac;": 336,
    "Ofr;": [55349, 56594],
    Ograve: 210,
    "Ograve;": 210,
    "Omacr;": 332,
    "Omega;": 937,
    "Omicron;": 927,
    "Oopf;": [55349, 56646],
    "OpenCurlyDoubleQuote;": 8220,
    "OpenCurlyQuote;": 8216,
    "Or;": 10836,
    "Oscr;": [55349, 56490],
    Oslash: 216,
    "Oslash;": 216,
    Otilde: 213,
    "Otilde;": 213,
    "Otimes;": 10807,
    Ouml: 214,
    "Ouml;": 214,
    "OverBar;": 8254,
    "OverBrace;": 9182,
    "OverBracket;": 9140,
    "OverParenthesis;": 9180,
    "PartialD;": 8706,
    "Pcy;": 1055,
    "Pfr;": [55349, 56595],
    "Phi;": 934,
    "Pi;": 928,
    "PlusMinus;": 177,
    "Poincareplane;": 8460,
    "Popf;": 8473,
    "Pr;": 10939,
    "Precedes;": 8826,
    "PrecedesEqual;": 10927,
    "PrecedesSlantEqual;": 8828,
    "PrecedesTilde;": 8830,
    "Prime;": 8243,
    "Product;": 8719,
    "Proportion;": 8759,
    "Proportional;": 8733,
    "Pscr;": [55349, 56491],
    "Psi;": 936,
    QUOT: 34,
    "QUOT;": 34,
    "Qfr;": [55349, 56596],
    "Qopf;": 8474,
    "Qscr;": [55349, 56492],
    "RBarr;": 10512,
    REG: 174,
    "REG;": 174,
    "Racute;": 340,
    "Rang;": 10219,
    "Rarr;": 8608,
    "Rarrtl;": 10518,
    "Rcaron;": 344,
    "Rcedil;": 342,
    "Rcy;": 1056,
    "Re;": 8476,
    "ReverseElement;": 8715,
    "ReverseEquilibrium;": 8651,
    "ReverseUpEquilibrium;": 10607,
    "Rfr;": 8476,
    "Rho;": 929,
    "RightAngleBracket;": 10217,
    "RightArrow;": 8594,
    "RightArrowBar;": 8677,
    "RightArrowLeftArrow;": 8644,
    "RightCeiling;": 8969,
    "RightDoubleBracket;": 10215,
    "RightDownTeeVector;": 10589,
    "RightDownVector;": 8642,
    "RightDownVectorBar;": 10581,
    "RightFloor;": 8971,
    "RightTee;": 8866,
    "RightTeeArrow;": 8614,
    "RightTeeVector;": 10587,
    "RightTriangle;": 8883,
    "RightTriangleBar;": 10704,
    "RightTriangleEqual;": 8885,
    "RightUpDownVector;": 10575,
    "RightUpTeeVector;": 10588,
    "RightUpVector;": 8638,
    "RightUpVectorBar;": 10580,
    "RightVector;": 8640,
    "RightVectorBar;": 10579,
    "Rightarrow;": 8658,
    "Ropf;": 8477,
    "RoundImplies;": 10608,
    "Rrightarrow;": 8667,
    "Rscr;": 8475,
    "Rsh;": 8625,
    "RuleDelayed;": 10740,
    "SHCHcy;": 1065,
    "SHcy;": 1064,
    "SOFTcy;": 1068,
    "Sacute;": 346,
    "Sc;": 10940,
    "Scaron;": 352,
    "Scedil;": 350,
    "Scirc;": 348,
    "Scy;": 1057,
    "Sfr;": [55349, 56598],
    "ShortDownArrow;": 8595,
    "ShortLeftArrow;": 8592,
    "ShortRightArrow;": 8594,
    "ShortUpArrow;": 8593,
    "Sigma;": 931,
    "SmallCircle;": 8728,
    "Sopf;": [55349, 56650],
    "Sqrt;": 8730,
    "Square;": 9633,
    "SquareIntersection;": 8851,
    "SquareSubset;": 8847,
    "SquareSubsetEqual;": 8849,
    "SquareSuperset;": 8848,
    "SquareSupersetEqual;": 8850,
    "SquareUnion;": 8852,
    "Sscr;": [55349, 56494],
    "Star;": 8902,
    "Sub;": 8912,
    "Subset;": 8912,
    "SubsetEqual;": 8838,
    "Succeeds;": 8827,
    "SucceedsEqual;": 10928,
    "SucceedsSlantEqual;": 8829,
    "SucceedsTilde;": 8831,
    "SuchThat;": 8715,
    "Sum;": 8721,
    "Sup;": 8913,
    "Superset;": 8835,
    "SupersetEqual;": 8839,
    "Supset;": 8913,
    THORN: 222,
    "THORN;": 222,
    "TRADE;": 8482,
    "TSHcy;": 1035,
    "TScy;": 1062,
    "Tab;": 9,
    "Tau;": 932,
    "Tcaron;": 356,
    "Tcedil;": 354,
    "Tcy;": 1058,
    "Tfr;": [55349, 56599],
    "Therefore;": 8756,
    "Theta;": 920,
    "ThickSpace;": [8287, 8202],
    "ThinSpace;": 8201,
    "Tilde;": 8764,
    "TildeEqual;": 8771,
    "TildeFullEqual;": 8773,
    "TildeTilde;": 8776,
    "Topf;": [55349, 56651],
    "TripleDot;": 8411,
    "Tscr;": [55349, 56495],
    "Tstrok;": 358,
    Uacute: 218,
    "Uacute;": 218,
    "Uarr;": 8607,
    "Uarrocir;": 10569,
    "Ubrcy;": 1038,
    "Ubreve;": 364,
    Ucirc: 219,
    "Ucirc;": 219,
    "Ucy;": 1059,
    "Udblac;": 368,
    "Ufr;": [55349, 56600],
    Ugrave: 217,
    "Ugrave;": 217,
    "Umacr;": 362,
    "UnderBar;": 95,
    "UnderBrace;": 9183,
    "UnderBracket;": 9141,
    "UnderParenthesis;": 9181,
    "Union;": 8899,
    "UnionPlus;": 8846,
    "Uogon;": 370,
    "Uopf;": [55349, 56652],
    "UpArrow;": 8593,
    "UpArrowBar;": 10514,
    "UpArrowDownArrow;": 8645,
    "UpDownArrow;": 8597,
    "UpEquilibrium;": 10606,
    "UpTee;": 8869,
    "UpTeeArrow;": 8613,
    "Uparrow;": 8657,
    "Updownarrow;": 8661,
    "UpperLeftArrow;": 8598,
    "UpperRightArrow;": 8599,
    "Upsi;": 978,
    "Upsilon;": 933,
    "Uring;": 366,
    "Uscr;": [55349, 56496],
    "Utilde;": 360,
    Uuml: 220,
    "Uuml;": 220,
    "VDash;": 8875,
    "Vbar;": 10987,
    "Vcy;": 1042,
    "Vdash;": 8873,
    "Vdashl;": 10982,
    "Vee;": 8897,
    "Verbar;": 8214,
    "Vert;": 8214,
    "VerticalBar;": 8739,
    "VerticalLine;": 124,
    "VerticalSeparator;": 10072,
    "VerticalTilde;": 8768,
    "VeryThinSpace;": 8202,
    "Vfr;": [55349, 56601],
    "Vopf;": [55349, 56653],
    "Vscr;": [55349, 56497],
    "Vvdash;": 8874,
    "Wcirc;": 372,
    "Wedge;": 8896,
    "Wfr;": [55349, 56602],
    "Wopf;": [55349, 56654],
    "Wscr;": [55349, 56498],
    "Xfr;": [55349, 56603],
    "Xi;": 926,
    "Xopf;": [55349, 56655],
    "Xscr;": [55349, 56499],
    "YAcy;": 1071,
    "YIcy;": 1031,
    "YUcy;": 1070,
    Yacute: 221,
    "Yacute;": 221,
    "Ycirc;": 374,
    "Ycy;": 1067,
    "Yfr;": [55349, 56604],
    "Yopf;": [55349, 56656],
    "Yscr;": [55349, 56500],
    "Yuml;": 376,
    "ZHcy;": 1046,
    "Zacute;": 377,
    "Zcaron;": 381,
    "Zcy;": 1047,
    "Zdot;": 379,
    "ZeroWidthSpace;": 8203,
    "Zeta;": 918,
    "Zfr;": 8488,
    "Zopf;": 8484,
    "Zscr;": [55349, 56501],
    aacute: 225,
    "aacute;": 225,
    "abreve;": 259,
    "ac;": 8766,
    "acE;": [8766, 819],
    "acd;": 8767,
    acirc: 226,
    "acirc;": 226,
    acute: 180,
    "acute;": 180,
    "acy;": 1072,
    aelig: 230,
    "aelig;": 230,
    "af;": 8289,
    "afr;": [55349, 56606],
    agrave: 224,
    "agrave;": 224,
    "alefsym;": 8501,
    "aleph;": 8501,
    "alpha;": 945,
    "amacr;": 257,
    "amalg;": 10815,
    amp: 38,
    "amp;": 38,
    "and;": 8743,
    "andand;": 10837,
    "andd;": 10844,
    "andslope;": 10840,
    "andv;": 10842,
    "ang;": 8736,
    "ange;": 10660,
    "angle;": 8736,
    "angmsd;": 8737,
    "angmsdaa;": 10664,
    "angmsdab;": 10665,
    "angmsdac;": 10666,
    "angmsdad;": 10667,
    "angmsdae;": 10668,
    "angmsdaf;": 10669,
    "angmsdag;": 10670,
    "angmsdah;": 10671,
    "angrt;": 8735,
    "angrtvb;": 8894,
    "angrtvbd;": 10653,
    "angsph;": 8738,
    "angst;": 197,
    "angzarr;": 9084,
    "aogon;": 261,
    "aopf;": [55349, 56658],
    "ap;": 8776,
    "apE;": 10864,
    "apacir;": 10863,
    "ape;": 8778,
    "apid;": 8779,
    "apos;": 39,
    "approx;": 8776,
    "approxeq;": 8778,
    aring: 229,
    "aring;": 229,
    "ascr;": [55349, 56502],
    "ast;": 42,
    "asymp;": 8776,
    "asympeq;": 8781,
    atilde: 227,
    "atilde;": 227,
    auml: 228,
    "auml;": 228,
    "awconint;": 8755,
    "awint;": 10769,
    "bNot;": 10989,
    "backcong;": 8780,
    "backepsilon;": 1014,
    "backprime;": 8245,
    "backsim;": 8765,
    "backsimeq;": 8909,
    "barvee;": 8893,
    "barwed;": 8965,
    "barwedge;": 8965,
    "bbrk;": 9141,
    "bbrktbrk;": 9142,
    "bcong;": 8780,
    "bcy;": 1073,
    "bdquo;": 8222,
    "becaus;": 8757,
    "because;": 8757,
    "bemptyv;": 10672,
    "bepsi;": 1014,
    "bernou;": 8492,
    "beta;": 946,
    "beth;": 8502,
    "between;": 8812,
    "bfr;": [55349, 56607],
    "bigcap;": 8898,
    "bigcirc;": 9711,
    "bigcup;": 8899,
    "bigodot;": 10752,
    "bigoplus;": 10753,
    "bigotimes;": 10754,
    "bigsqcup;": 10758,
    "bigstar;": 9733,
    "bigtriangledown;": 9661,
    "bigtriangleup;": 9651,
    "biguplus;": 10756,
    "bigvee;": 8897,
    "bigwedge;": 8896,
    "bkarow;": 10509,
    "blacklozenge;": 10731,
    "blacksquare;": 9642,
    "blacktriangle;": 9652,
    "blacktriangledown;": 9662,
    "blacktriangleleft;": 9666,
    "blacktriangleright;": 9656,
    "blank;": 9251,
    "blk12;": 9618,
    "blk14;": 9617,
    "blk34;": 9619,
    "block;": 9608,
    "bne;": [61, 8421],
    "bnequiv;": [8801, 8421],
    "bnot;": 8976,
    "bopf;": [55349, 56659],
    "bot;": 8869,
    "bottom;": 8869,
    "bowtie;": 8904,
    "boxDL;": 9559,
    "boxDR;": 9556,
    "boxDl;": 9558,
    "boxDr;": 9555,
    "boxH;": 9552,
    "boxHD;": 9574,
    "boxHU;": 9577,
    "boxHd;": 9572,
    "boxHu;": 9575,
    "boxUL;": 9565,
    "boxUR;": 9562,
    "boxUl;": 9564,
    "boxUr;": 9561,
    "boxV;": 9553,
    "boxVH;": 9580,
    "boxVL;": 9571,
    "boxVR;": 9568,
    "boxVh;": 9579,
    "boxVl;": 9570,
    "boxVr;": 9567,
    "boxbox;": 10697,
    "boxdL;": 9557,
    "boxdR;": 9554,
    "boxdl;": 9488,
    "boxdr;": 9484,
    "boxh;": 9472,
    "boxhD;": 9573,
    "boxhU;": 9576,
    "boxhd;": 9516,
    "boxhu;": 9524,
    "boxminus;": 8863,
    "boxplus;": 8862,
    "boxtimes;": 8864,
    "boxuL;": 9563,
    "boxuR;": 9560,
    "boxul;": 9496,
    "boxur;": 9492,
    "boxv;": 9474,
    "boxvH;": 9578,
    "boxvL;": 9569,
    "boxvR;": 9566,
    "boxvh;": 9532,
    "boxvl;": 9508,
    "boxvr;": 9500,
    "bprime;": 8245,
    "breve;": 728,
    brvbar: 166,
    "brvbar;": 166,
    "bscr;": [55349, 56503],
    "bsemi;": 8271,
    "bsim;": 8765,
    "bsime;": 8909,
    "bsol;": 92,
    "bsolb;": 10693,
    "bsolhsub;": 10184,
    "bull;": 8226,
    "bullet;": 8226,
    "bump;": 8782,
    "bumpE;": 10926,
    "bumpe;": 8783,
    "bumpeq;": 8783,
    "cacute;": 263,
    "cap;": 8745,
    "capand;": 10820,
    "capbrcup;": 10825,
    "capcap;": 10827,
    "capcup;": 10823,
    "capdot;": 10816,
    "caps;": [8745, 65024],
    "caret;": 8257,
    "caron;": 711,
    "ccaps;": 10829,
    "ccaron;": 269,
    ccedil: 231,
    "ccedil;": 231,
    "ccirc;": 265,
    "ccups;": 10828,
    "ccupssm;": 10832,
    "cdot;": 267,
    cedil: 184,
    "cedil;": 184,
    "cemptyv;": 10674,
    cent: 162,
    "cent;": 162,
    "centerdot;": 183,
    "cfr;": [55349, 56608],
    "chcy;": 1095,
    "check;": 10003,
    "checkmark;": 10003,
    "chi;": 967,
    "cir;": 9675,
    "cirE;": 10691,
    "circ;": 710,
    "circeq;": 8791,
    "circlearrowleft;": 8634,
    "circlearrowright;": 8635,
    "circledR;": 174,
    "circledS;": 9416,
    "circledast;": 8859,
    "circledcirc;": 8858,
    "circleddash;": 8861,
    "cire;": 8791,
    "cirfnint;": 10768,
    "cirmid;": 10991,
    "cirscir;": 10690,
    "clubs;": 9827,
    "clubsuit;": 9827,
    "colon;": 58,
    "colone;": 8788,
    "coloneq;": 8788,
    "comma;": 44,
    "commat;": 64,
    "comp;": 8705,
    "compfn;": 8728,
    "complement;": 8705,
    "complexes;": 8450,
    "cong;": 8773,
    "congdot;": 10861,
    "conint;": 8750,
    "copf;": [55349, 56660],
    "coprod;": 8720,
    copy: 169,
    "copy;": 169,
    "copysr;": 8471,
    "crarr;": 8629,
    "cross;": 10007,
    "cscr;": [55349, 56504],
    "csub;": 10959,
    "csube;": 10961,
    "csup;": 10960,
    "csupe;": 10962,
    "ctdot;": 8943,
    "cudarrl;": 10552,
    "cudarrr;": 10549,
    "cuepr;": 8926,
    "cuesc;": 8927,
    "cularr;": 8630,
    "cularrp;": 10557,
    "cup;": 8746,
    "cupbrcap;": 10824,
    "cupcap;": 10822,
    "cupcup;": 10826,
    "cupdot;": 8845,
    "cupor;": 10821,
    "cups;": [8746, 65024],
    "curarr;": 8631,
    "curarrm;": 10556,
    "curlyeqprec;": 8926,
    "curlyeqsucc;": 8927,
    "curlyvee;": 8910,
    "curlywedge;": 8911,
    curren: 164,
    "curren;": 164,
    "curvearrowleft;": 8630,
    "curvearrowright;": 8631,
    "cuvee;": 8910,
    "cuwed;": 8911,
    "cwconint;": 8754,
    "cwint;": 8753,
    "cylcty;": 9005,
    "dArr;": 8659,
    "dHar;": 10597,
    "dagger;": 8224,
    "daleth;": 8504,
    "darr;": 8595,
    "dash;": 8208,
    "dashv;": 8867,
    "dbkarow;": 10511,
    "dblac;": 733,
    "dcaron;": 271,
    "dcy;": 1076,
    "dd;": 8518,
    "ddagger;": 8225,
    "ddarr;": 8650,
    "ddotseq;": 10871,
    deg: 176,
    "deg;": 176,
    "delta;": 948,
    "demptyv;": 10673,
    "dfisht;": 10623,
    "dfr;": [55349, 56609],
    "dharl;": 8643,
    "dharr;": 8642,
    "diam;": 8900,
    "diamond;": 8900,
    "diamondsuit;": 9830,
    "diams;": 9830,
    "die;": 168,
    "digamma;": 989,
    "disin;": 8946,
    "div;": 247,
    divide: 247,
    "divide;": 247,
    "divideontimes;": 8903,
    "divonx;": 8903,
    "djcy;": 1106,
    "dlcorn;": 8990,
    "dlcrop;": 8973,
    "dollar;": 36,
    "dopf;": [55349, 56661],
    "dot;": 729,
    "doteq;": 8784,
    "doteqdot;": 8785,
    "dotminus;": 8760,
    "dotplus;": 8724,
    "dotsquare;": 8865,
    "doublebarwedge;": 8966,
    "downarrow;": 8595,
    "downdownarrows;": 8650,
    "downharpoonleft;": 8643,
    "downharpoonright;": 8642,
    "drbkarow;": 10512,
    "drcorn;": 8991,
    "drcrop;": 8972,
    "dscr;": [55349, 56505],
    "dscy;": 1109,
    "dsol;": 10742,
    "dstrok;": 273,
    "dtdot;": 8945,
    "dtri;": 9663,
    "dtrif;": 9662,
    "duarr;": 8693,
    "duhar;": 10607,
    "dwangle;": 10662,
    "dzcy;": 1119,
    "dzigrarr;": 10239,
    "eDDot;": 10871,
    "eDot;": 8785,
    eacute: 233,
    "eacute;": 233,
    "easter;": 10862,
    "ecaron;": 283,
    "ecir;": 8790,
    ecirc: 234,
    "ecirc;": 234,
    "ecolon;": 8789,
    "ecy;": 1101,
    "edot;": 279,
    "ee;": 8519,
    "efDot;": 8786,
    "efr;": [55349, 56610],
    "eg;": 10906,
    egrave: 232,
    "egrave;": 232,
    "egs;": 10902,
    "egsdot;": 10904,
    "el;": 10905,
    "elinters;": 9191,
    "ell;": 8467,
    "els;": 10901,
    "elsdot;": 10903,
    "emacr;": 275,
    "empty;": 8709,
    "emptyset;": 8709,
    "emptyv;": 8709,
    "emsp13;": 8196,
    "emsp14;": 8197,
    "emsp;": 8195,
    "eng;": 331,
    "ensp;": 8194,
    "eogon;": 281,
    "eopf;": [55349, 56662],
    "epar;": 8917,
    "eparsl;": 10723,
    "eplus;": 10865,
    "epsi;": 949,
    "epsilon;": 949,
    "epsiv;": 1013,
    "eqcirc;": 8790,
    "eqcolon;": 8789,
    "eqsim;": 8770,
    "eqslantgtr;": 10902,
    "eqslantless;": 10901,
    "equals;": 61,
    "equest;": 8799,
    "equiv;": 8801,
    "equivDD;": 10872,
    "eqvparsl;": 10725,
    "erDot;": 8787,
    "erarr;": 10609,
    "escr;": 8495,
    "esdot;": 8784,
    "esim;": 8770,
    "eta;": 951,
    eth: 240,
    "eth;": 240,
    euml: 235,
    "euml;": 235,
    "euro;": 8364,
    "excl;": 33,
    "exist;": 8707,
    "expectation;": 8496,
    "exponentiale;": 8519,
    "fallingdotseq;": 8786,
    "fcy;": 1092,
    "female;": 9792,
    "ffilig;": 64259,
    "fflig;": 64256,
    "ffllig;": 64260,
    "ffr;": [55349, 56611],
    "filig;": 64257,
    "fjlig;": [102, 106],
    "flat;": 9837,
    "fllig;": 64258,
    "fltns;": 9649,
    "fnof;": 402,
    "fopf;": [55349, 56663],
    "forall;": 8704,
    "fork;": 8916,
    "forkv;": 10969,
    "fpartint;": 10765,
    frac12: 189,
    "frac12;": 189,
    "frac13;": 8531,
    frac14: 188,
    "frac14;": 188,
    "frac15;": 8533,
    "frac16;": 8537,
    "frac18;": 8539,
    "frac23;": 8532,
    "frac25;": 8534,
    frac34: 190,
    "frac34;": 190,
    "frac35;": 8535,
    "frac38;": 8540,
    "frac45;": 8536,
    "frac56;": 8538,
    "frac58;": 8541,
    "frac78;": 8542,
    "frasl;": 8260,
    "frown;": 8994,
    "fscr;": [55349, 56507],
    "gE;": 8807,
    "gEl;": 10892,
    "gacute;": 501,
    "gamma;": 947,
    "gammad;": 989,
    "gap;": 10886,
    "gbreve;": 287,
    "gcirc;": 285,
    "gcy;": 1075,
    "gdot;": 289,
    "ge;": 8805,
    "gel;": 8923,
    "geq;": 8805,
    "geqq;": 8807,
    "geqslant;": 10878,
    "ges;": 10878,
    "gescc;": 10921,
    "gesdot;": 10880,
    "gesdoto;": 10882,
    "gesdotol;": 10884,
    "gesl;": [8923, 65024],
    "gesles;": 10900,
    "gfr;": [55349, 56612],
    "gg;": 8811,
    "ggg;": 8921,
    "gimel;": 8503,
    "gjcy;": 1107,
    "gl;": 8823,
    "glE;": 10898,
    "gla;": 10917,
    "glj;": 10916,
    "gnE;": 8809,
    "gnap;": 10890,
    "gnapprox;": 10890,
    "gne;": 10888,
    "gneq;": 10888,
    "gneqq;": 8809,
    "gnsim;": 8935,
    "gopf;": [55349, 56664],
    "grave;": 96,
    "gscr;": 8458,
    "gsim;": 8819,
    "gsime;": 10894,
    "gsiml;": 10896,
    gt: 62,
    "gt;": 62,
    "gtcc;": 10919,
    "gtcir;": 10874,
    "gtdot;": 8919,
    "gtlPar;": 10645,
    "gtquest;": 10876,
    "gtrapprox;": 10886,
    "gtrarr;": 10616,
    "gtrdot;": 8919,
    "gtreqless;": 8923,
    "gtreqqless;": 10892,
    "gtrless;": 8823,
    "gtrsim;": 8819,
    "gvertneqq;": [8809, 65024],
    "gvnE;": [8809, 65024],
    "hArr;": 8660,
    "hairsp;": 8202,
    "half;": 189,
    "hamilt;": 8459,
    "hardcy;": 1098,
    "harr;": 8596,
    "harrcir;": 10568,
    "harrw;": 8621,
    "hbar;": 8463,
    "hcirc;": 293,
    "hearts;": 9829,
    "heartsuit;": 9829,
    "hellip;": 8230,
    "hercon;": 8889,
    "hfr;": [55349, 56613],
    "hksearow;": 10533,
    "hkswarow;": 10534,
    "hoarr;": 8703,
    "homtht;": 8763,
    "hookleftarrow;": 8617,
    "hookrightarrow;": 8618,
    "hopf;": [55349, 56665],
    "horbar;": 8213,
    "hscr;": [55349, 56509],
    "hslash;": 8463,
    "hstrok;": 295,
    "hybull;": 8259,
    "hyphen;": 8208,
    iacute: 237,
    "iacute;": 237,
    "ic;": 8291,
    icirc: 238,
    "icirc;": 238,
    "icy;": 1080,
    "iecy;": 1077,
    iexcl: 161,
    "iexcl;": 161,
    "iff;": 8660,
    "ifr;": [55349, 56614],
    igrave: 236,
    "igrave;": 236,
    "ii;": 8520,
    "iiiint;": 10764,
    "iiint;": 8749,
    "iinfin;": 10716,
    "iiota;": 8489,
    "ijlig;": 307,
    "imacr;": 299,
    "image;": 8465,
    "imagline;": 8464,
    "imagpart;": 8465,
    "imath;": 305,
    "imof;": 8887,
    "imped;": 437,
    "in;": 8712,
    "incare;": 8453,
    "infin;": 8734,
    "infintie;": 10717,
    "inodot;": 305,
    "int;": 8747,
    "intcal;": 8890,
    "integers;": 8484,
    "intercal;": 8890,
    "intlarhk;": 10775,
    "intprod;": 10812,
    "iocy;": 1105,
    "iogon;": 303,
    "iopf;": [55349, 56666],
    "iota;": 953,
    "iprod;": 10812,
    iquest: 191,
    "iquest;": 191,
    "iscr;": [55349, 56510],
    "isin;": 8712,
    "isinE;": 8953,
    "isindot;": 8949,
    "isins;": 8948,
    "isinsv;": 8947,
    "isinv;": 8712,
    "it;": 8290,
    "itilde;": 297,
    "iukcy;": 1110,
    iuml: 239,
    "iuml;": 239,
    "jcirc;": 309,
    "jcy;": 1081,
    "jfr;": [55349, 56615],
    "jmath;": 567,
    "jopf;": [55349, 56667],
    "jscr;": [55349, 56511],
    "jsercy;": 1112,
    "jukcy;": 1108,
    "kappa;": 954,
    "kappav;": 1008,
    "kcedil;": 311,
    "kcy;": 1082,
    "kfr;": [55349, 56616],
    "kgreen;": 312,
    "khcy;": 1093,
    "kjcy;": 1116,
    "kopf;": [55349, 56668],
    "kscr;": [55349, 56512],
    "lAarr;": 8666,
    "lArr;": 8656,
    "lAtail;": 10523,
    "lBarr;": 10510,
    "lE;": 8806,
    "lEg;": 10891,
    "lHar;": 10594,
    "lacute;": 314,
    "laemptyv;": 10676,
    "lagran;": 8466,
    "lambda;": 955,
    "lang;": 10216,
    "langd;": 10641,
    "langle;": 10216,
    "lap;": 10885,
    laquo: 171,
    "laquo;": 171,
    "larr;": 8592,
    "larrb;": 8676,
    "larrbfs;": 10527,
    "larrfs;": 10525,
    "larrhk;": 8617,
    "larrlp;": 8619,
    "larrpl;": 10553,
    "larrsim;": 10611,
    "larrtl;": 8610,
    "lat;": 10923,
    "latail;": 10521,
    "late;": 10925,
    "lates;": [10925, 65024],
    "lbarr;": 10508,
    "lbbrk;": 10098,
    "lbrace;": 123,
    "lbrack;": 91,
    "lbrke;": 10635,
    "lbrksld;": 10639,
    "lbrkslu;": 10637,
    "lcaron;": 318,
    "lcedil;": 316,
    "lceil;": 8968,
    "lcub;": 123,
    "lcy;": 1083,
    "ldca;": 10550,
    "ldquo;": 8220,
    "ldquor;": 8222,
    "ldrdhar;": 10599,
    "ldrushar;": 10571,
    "ldsh;": 8626,
    "le;": 8804,
    "leftarrow;": 8592,
    "leftarrowtail;": 8610,
    "leftharpoondown;": 8637,
    "leftharpoonup;": 8636,
    "leftleftarrows;": 8647,
    "leftrightarrow;": 8596,
    "leftrightarrows;": 8646,
    "leftrightharpoons;": 8651,
    "leftrightsquigarrow;": 8621,
    "leftthreetimes;": 8907,
    "leg;": 8922,
    "leq;": 8804,
    "leqq;": 8806,
    "leqslant;": 10877,
    "les;": 10877,
    "lescc;": 10920,
    "lesdot;": 10879,
    "lesdoto;": 10881,
    "lesdotor;": 10883,
    "lesg;": [8922, 65024],
    "lesges;": 10899,
    "lessapprox;": 10885,
    "lessdot;": 8918,
    "lesseqgtr;": 8922,
    "lesseqqgtr;": 10891,
    "lessgtr;": 8822,
    "lesssim;": 8818,
    "lfisht;": 10620,
    "lfloor;": 8970,
    "lfr;": [55349, 56617],
    "lg;": 8822,
    "lgE;": 10897,
    "lhard;": 8637,
    "lharu;": 8636,
    "lharul;": 10602,
    "lhblk;": 9604,
    "ljcy;": 1113,
    "ll;": 8810,
    "llarr;": 8647,
    "llcorner;": 8990,
    "llhard;": 10603,
    "lltri;": 9722,
    "lmidot;": 320,
    "lmoust;": 9136,
    "lmoustache;": 9136,
    "lnE;": 8808,
    "lnap;": 10889,
    "lnapprox;": 10889,
    "lne;": 10887,
    "lneq;": 10887,
    "lneqq;": 8808,
    "lnsim;": 8934,
    "loang;": 10220,
    "loarr;": 8701,
    "lobrk;": 10214,
    "longleftarrow;": 10229,
    "longleftrightarrow;": 10231,
    "longmapsto;": 10236,
    "longrightarrow;": 10230,
    "looparrowleft;": 8619,
    "looparrowright;": 8620,
    "lopar;": 10629,
    "lopf;": [55349, 56669],
    "loplus;": 10797,
    "lotimes;": 10804,
    "lowast;": 8727,
    "lowbar;": 95,
    "loz;": 9674,
    "lozenge;": 9674,
    "lozf;": 10731,
    "lpar;": 40,
    "lparlt;": 10643,
    "lrarr;": 8646,
    "lrcorner;": 8991,
    "lrhar;": 8651,
    "lrhard;": 10605,
    "lrm;": 8206,
    "lrtri;": 8895,
    "lsaquo;": 8249,
    "lscr;": [55349, 56513],
    "lsh;": 8624,
    "lsim;": 8818,
    "lsime;": 10893,
    "lsimg;": 10895,
    "lsqb;": 91,
    "lsquo;": 8216,
    "lsquor;": 8218,
    "lstrok;": 322,
    lt: 60,
    "lt;": 60,
    "ltcc;": 10918,
    "ltcir;": 10873,
    "ltdot;": 8918,
    "lthree;": 8907,
    "ltimes;": 8905,
    "ltlarr;": 10614,
    "ltquest;": 10875,
    "ltrPar;": 10646,
    "ltri;": 9667,
    "ltrie;": 8884,
    "ltrif;": 9666,
    "lurdshar;": 10570,
    "luruhar;": 10598,
    "lvertneqq;": [8808, 65024],
    "lvnE;": [8808, 65024],
    "mDDot;": 8762,
    macr: 175,
    "macr;": 175,
    "male;": 9794,
    "malt;": 10016,
    "maltese;": 10016,
    "map;": 8614,
    "mapsto;": 8614,
    "mapstodown;": 8615,
    "mapstoleft;": 8612,
    "mapstoup;": 8613,
    "marker;": 9646,
    "mcomma;": 10793,
    "mcy;": 1084,
    "mdash;": 8212,
    "measuredangle;": 8737,
    "mfr;": [55349, 56618],
    "mho;": 8487,
    micro: 181,
    "micro;": 181,
    "mid;": 8739,
    "midast;": 42,
    "midcir;": 10992,
    middot: 183,
    "middot;": 183,
    "minus;": 8722,
    "minusb;": 8863,
    "minusd;": 8760,
    "minusdu;": 10794,
    "mlcp;": 10971,
    "mldr;": 8230,
    "mnplus;": 8723,
    "models;": 8871,
    "mopf;": [55349, 56670],
    "mp;": 8723,
    "mscr;": [55349, 56514],
    "mstpos;": 8766,
    "mu;": 956,
    "multimap;": 8888,
    "mumap;": 8888,
    "nGg;": [8921, 824],
    "nGt;": [8811, 8402],
    "nGtv;": [8811, 824],
    "nLeftarrow;": 8653,
    "nLeftrightarrow;": 8654,
    "nLl;": [8920, 824],
    "nLt;": [8810, 8402],
    "nLtv;": [8810, 824],
    "nRightarrow;": 8655,
    "nVDash;": 8879,
    "nVdash;": 8878,
    "nabla;": 8711,
    "nacute;": 324,
    "nang;": [8736, 8402],
    "nap;": 8777,
    "napE;": [10864, 824],
    "napid;": [8779, 824],
    "napos;": 329,
    "napprox;": 8777,
    "natur;": 9838,
    "natural;": 9838,
    "naturals;": 8469,
    nbsp: 160,
    "nbsp;": 160,
    "nbump;": [8782, 824],
    "nbumpe;": [8783, 824],
    "ncap;": 10819,
    "ncaron;": 328,
    "ncedil;": 326,
    "ncong;": 8775,
    "ncongdot;": [10861, 824],
    "ncup;": 10818,
    "ncy;": 1085,
    "ndash;": 8211,
    "ne;": 8800,
    "neArr;": 8663,
    "nearhk;": 10532,
    "nearr;": 8599,
    "nearrow;": 8599,
    "nedot;": [8784, 824],
    "nequiv;": 8802,
    "nesear;": 10536,
    "nesim;": [8770, 824],
    "nexist;": 8708,
    "nexists;": 8708,
    "nfr;": [55349, 56619],
    "ngE;": [8807, 824],
    "nge;": 8817,
    "ngeq;": 8817,
    "ngeqq;": [8807, 824],
    "ngeqslant;": [10878, 824],
    "nges;": [10878, 824],
    "ngsim;": 8821,
    "ngt;": 8815,
    "ngtr;": 8815,
    "nhArr;": 8654,
    "nharr;": 8622,
    "nhpar;": 10994,
    "ni;": 8715,
    "nis;": 8956,
    "nisd;": 8954,
    "niv;": 8715,
    "njcy;": 1114,
    "nlArr;": 8653,
    "nlE;": [8806, 824],
    "nlarr;": 8602,
    "nldr;": 8229,
    "nle;": 8816,
    "nleftarrow;": 8602,
    "nleftrightarrow;": 8622,
    "nleq;": 8816,
    "nleqq;": [8806, 824],
    "nleqslant;": [10877, 824],
    "nles;": [10877, 824],
    "nless;": 8814,
    "nlsim;": 8820,
    "nlt;": 8814,
    "nltri;": 8938,
    "nltrie;": 8940,
    "nmid;": 8740,
    "nopf;": [55349, 56671],
    not: 172,
    "not;": 172,
    "notin;": 8713,
    "notinE;": [8953, 824],
    "notindot;": [8949, 824],
    "notinva;": 8713,
    "notinvb;": 8951,
    "notinvc;": 8950,
    "notni;": 8716,
    "notniva;": 8716,
    "notnivb;": 8958,
    "notnivc;": 8957,
    "npar;": 8742,
    "nparallel;": 8742,
    "nparsl;": [11005, 8421],
    "npart;": [8706, 824],
    "npolint;": 10772,
    "npr;": 8832,
    "nprcue;": 8928,
    "npre;": [10927, 824],
    "nprec;": 8832,
    "npreceq;": [10927, 824],
    "nrArr;": 8655,
    "nrarr;": 8603,
    "nrarrc;": [10547, 824],
    "nrarrw;": [8605, 824],
    "nrightarrow;": 8603,
    "nrtri;": 8939,
    "nrtrie;": 8941,
    "nsc;": 8833,
    "nsccue;": 8929,
    "nsce;": [10928, 824],
    "nscr;": [55349, 56515],
    "nshortmid;": 8740,
    "nshortparallel;": 8742,
    "nsim;": 8769,
    "nsime;": 8772,
    "nsimeq;": 8772,
    "nsmid;": 8740,
    "nspar;": 8742,
    "nsqsube;": 8930,
    "nsqsupe;": 8931,
    "nsub;": 8836,
    "nsubE;": [10949, 824],
    "nsube;": 8840,
    "nsubset;": [8834, 8402],
    "nsubseteq;": 8840,
    "nsubseteqq;": [10949, 824],
    "nsucc;": 8833,
    "nsucceq;": [10928, 824],
    "nsup;": 8837,
    "nsupE;": [10950, 824],
    "nsupe;": 8841,
    "nsupset;": [8835, 8402],
    "nsupseteq;": 8841,
    "nsupseteqq;": [10950, 824],
    "ntgl;": 8825,
    ntilde: 241,
    "ntilde;": 241,
    "ntlg;": 8824,
    "ntriangleleft;": 8938,
    "ntrianglelefteq;": 8940,
    "ntriangleright;": 8939,
    "ntrianglerighteq;": 8941,
    "nu;": 957,
    "num;": 35,
    "numero;": 8470,
    "numsp;": 8199,
    "nvDash;": 8877,
    "nvHarr;": 10500,
    "nvap;": [8781, 8402],
    "nvdash;": 8876,
    "nvge;": [8805, 8402],
    "nvgt;": [62, 8402],
    "nvinfin;": 10718,
    "nvlArr;": 10498,
    "nvle;": [8804, 8402],
    "nvlt;": [60, 8402],
    "nvltrie;": [8884, 8402],
    "nvrArr;": 10499,
    "nvrtrie;": [8885, 8402],
    "nvsim;": [8764, 8402],
    "nwArr;": 8662,
    "nwarhk;": 10531,
    "nwarr;": 8598,
    "nwarrow;": 8598,
    "nwnear;": 10535,
    "oS;": 9416,
    oacute: 243,
    "oacute;": 243,
    "oast;": 8859,
    "ocir;": 8858,
    ocirc: 244,
    "ocirc;": 244,
    "ocy;": 1086,
    "odash;": 8861,
    "odblac;": 337,
    "odiv;": 10808,
    "odot;": 8857,
    "odsold;": 10684,
    "oelig;": 339,
    "ofcir;": 10687,
    "ofr;": [55349, 56620],
    "ogon;": 731,
    ograve: 242,
    "ograve;": 242,
    "ogt;": 10689,
    "ohbar;": 10677,
    "ohm;": 937,
    "oint;": 8750,
    "olarr;": 8634,
    "olcir;": 10686,
    "olcross;": 10683,
    "oline;": 8254,
    "olt;": 10688,
    "omacr;": 333,
    "omega;": 969,
    "omicron;": 959,
    "omid;": 10678,
    "ominus;": 8854,
    "oopf;": [55349, 56672],
    "opar;": 10679,
    "operp;": 10681,
    "oplus;": 8853,
    "or;": 8744,
    "orarr;": 8635,
    "ord;": 10845,
    "order;": 8500,
    "orderof;": 8500,
    ordf: 170,
    "ordf;": 170,
    ordm: 186,
    "ordm;": 186,
    "origof;": 8886,
    "oror;": 10838,
    "orslope;": 10839,
    "orv;": 10843,
    "oscr;": 8500,
    oslash: 248,
    "oslash;": 248,
    "osol;": 8856,
    otilde: 245,
    "otilde;": 245,
    "otimes;": 8855,
    "otimesas;": 10806,
    ouml: 246,
    "ouml;": 246,
    "ovbar;": 9021,
    "par;": 8741,
    para: 182,
    "para;": 182,
    "parallel;": 8741,
    "parsim;": 10995,
    "parsl;": 11005,
    "part;": 8706,
    "pcy;": 1087,
    "percnt;": 37,
    "period;": 46,
    "permil;": 8240,
    "perp;": 8869,
    "pertenk;": 8241,
    "pfr;": [55349, 56621],
    "phi;": 966,
    "phiv;": 981,
    "phmmat;": 8499,
    "phone;": 9742,
    "pi;": 960,
    "pitchfork;": 8916,
    "piv;": 982,
    "planck;": 8463,
    "planckh;": 8462,
    "plankv;": 8463,
    "plus;": 43,
    "plusacir;": 10787,
    "plusb;": 8862,
    "pluscir;": 10786,
    "plusdo;": 8724,
    "plusdu;": 10789,
    "pluse;": 10866,
    plusmn: 177,
    "plusmn;": 177,
    "plussim;": 10790,
    "plustwo;": 10791,
    "pm;": 177,
    "pointint;": 10773,
    "popf;": [55349, 56673],
    pound: 163,
    "pound;": 163,
    "pr;": 8826,
    "prE;": 10931,
    "prap;": 10935,
    "prcue;": 8828,
    "pre;": 10927,
    "prec;": 8826,
    "precapprox;": 10935,
    "preccurlyeq;": 8828,
    "preceq;": 10927,
    "precnapprox;": 10937,
    "precneqq;": 10933,
    "precnsim;": 8936,
    "precsim;": 8830,
    "prime;": 8242,
    "primes;": 8473,
    "prnE;": 10933,
    "prnap;": 10937,
    "prnsim;": 8936,
    "prod;": 8719,
    "profalar;": 9006,
    "profline;": 8978,
    "profsurf;": 8979,
    "prop;": 8733,
    "propto;": 8733,
    "prsim;": 8830,
    "prurel;": 8880,
    "pscr;": [55349, 56517],
    "psi;": 968,
    "puncsp;": 8200,
    "qfr;": [55349, 56622],
    "qint;": 10764,
    "qopf;": [55349, 56674],
    "qprime;": 8279,
    "qscr;": [55349, 56518],
    "quaternions;": 8461,
    "quatint;": 10774,
    "quest;": 63,
    "questeq;": 8799,
    quot: 34,
    "quot;": 34,
    "rAarr;": 8667,
    "rArr;": 8658,
    "rAtail;": 10524,
    "rBarr;": 10511,
    "rHar;": 10596,
    "race;": [8765, 817],
    "racute;": 341,
    "radic;": 8730,
    "raemptyv;": 10675,
    "rang;": 10217,
    "rangd;": 10642,
    "range;": 10661,
    "rangle;": 10217,
    raquo: 187,
    "raquo;": 187,
    "rarr;": 8594,
    "rarrap;": 10613,
    "rarrb;": 8677,
    "rarrbfs;": 10528,
    "rarrc;": 10547,
    "rarrfs;": 10526,
    "rarrhk;": 8618,
    "rarrlp;": 8620,
    "rarrpl;": 10565,
    "rarrsim;": 10612,
    "rarrtl;": 8611,
    "rarrw;": 8605,
    "ratail;": 10522,
    "ratio;": 8758,
    "rationals;": 8474,
    "rbarr;": 10509,
    "rbbrk;": 10099,
    "rbrace;": 125,
    "rbrack;": 93,
    "rbrke;": 10636,
    "rbrksld;": 10638,
    "rbrkslu;": 10640,
    "rcaron;": 345,
    "rcedil;": 343,
    "rceil;": 8969,
    "rcub;": 125,
    "rcy;": 1088,
    "rdca;": 10551,
    "rdldhar;": 10601,
    "rdquo;": 8221,
    "rdquor;": 8221,
    "rdsh;": 8627,
    "real;": 8476,
    "realine;": 8475,
    "realpart;": 8476,
    "reals;": 8477,
    "rect;": 9645,
    reg: 174,
    "reg;": 174,
    "rfisht;": 10621,
    "rfloor;": 8971,
    "rfr;": [55349, 56623],
    "rhard;": 8641,
    "rharu;": 8640,
    "rharul;": 10604,
    "rho;": 961,
    "rhov;": 1009,
    "rightarrow;": 8594,
    "rightarrowtail;": 8611,
    "rightharpoondown;": 8641,
    "rightharpoonup;": 8640,
    "rightleftarrows;": 8644,
    "rightleftharpoons;": 8652,
    "rightrightarrows;": 8649,
    "rightsquigarrow;": 8605,
    "rightthreetimes;": 8908,
    "ring;": 730,
    "risingdotseq;": 8787,
    "rlarr;": 8644,
    "rlhar;": 8652,
    "rlm;": 8207,
    "rmoust;": 9137,
    "rmoustache;": 9137,
    "rnmid;": 10990,
    "roang;": 10221,
    "roarr;": 8702,
    "robrk;": 10215,
    "ropar;": 10630,
    "ropf;": [55349, 56675],
    "roplus;": 10798,
    "rotimes;": 10805,
    "rpar;": 41,
    "rpargt;": 10644,
    "rppolint;": 10770,
    "rrarr;": 8649,
    "rsaquo;": 8250,
    "rscr;": [55349, 56519],
    "rsh;": 8625,
    "rsqb;": 93,
    "rsquo;": 8217,
    "rsquor;": 8217,
    "rthree;": 8908,
    "rtimes;": 8906,
    "rtri;": 9657,
    "rtrie;": 8885,
    "rtrif;": 9656,
    "rtriltri;": 10702,
    "ruluhar;": 10600,
    "rx;": 8478,
    "sacute;": 347,
    "sbquo;": 8218,
    "sc;": 8827,
    "scE;": 10932,
    "scap;": 10936,
    "scaron;": 353,
    "sccue;": 8829,
    "sce;": 10928,
    "scedil;": 351,
    "scirc;": 349,
    "scnE;": 10934,
    "scnap;": 10938,
    "scnsim;": 8937,
    "scpolint;": 10771,
    "scsim;": 8831,
    "scy;": 1089,
    "sdot;": 8901,
    "sdotb;": 8865,
    "sdote;": 10854,
    "seArr;": 8664,
    "searhk;": 10533,
    "searr;": 8600,
    "searrow;": 8600,
    sect: 167,
    "sect;": 167,
    "semi;": 59,
    "seswar;": 10537,
    "setminus;": 8726,
    "setmn;": 8726,
    "sext;": 10038,
    "sfr;": [55349, 56624],
    "sfrown;": 8994,
    "sharp;": 9839,
    "shchcy;": 1097,
    "shcy;": 1096,
    "shortmid;": 8739,
    "shortparallel;": 8741,
    shy: 173,
    "shy;": 173,
    "sigma;": 963,
    "sigmaf;": 962,
    "sigmav;": 962,
    "sim;": 8764,
    "simdot;": 10858,
    "sime;": 8771,
    "simeq;": 8771,
    "simg;": 10910,
    "simgE;": 10912,
    "siml;": 10909,
    "simlE;": 10911,
    "simne;": 8774,
    "simplus;": 10788,
    "simrarr;": 10610,
    "slarr;": 8592,
    "smallsetminus;": 8726,
    "smashp;": 10803,
    "smeparsl;": 10724,
    "smid;": 8739,
    "smile;": 8995,
    "smt;": 10922,
    "smte;": 10924,
    "smtes;": [10924, 65024],
    "softcy;": 1100,
    "sol;": 47,
    "solb;": 10692,
    "solbar;": 9023,
    "sopf;": [55349, 56676],
    "spades;": 9824,
    "spadesuit;": 9824,
    "spar;": 8741,
    "sqcap;": 8851,
    "sqcaps;": [8851, 65024],
    "sqcup;": 8852,
    "sqcups;": [8852, 65024],
    "sqsub;": 8847,
    "sqsube;": 8849,
    "sqsubset;": 8847,
    "sqsubseteq;": 8849,
    "sqsup;": 8848,
    "sqsupe;": 8850,
    "sqsupset;": 8848,
    "sqsupseteq;": 8850,
    "squ;": 9633,
    "square;": 9633,
    "squarf;": 9642,
    "squf;": 9642,
    "srarr;": 8594,
    "sscr;": [55349, 56520],
    "ssetmn;": 8726,
    "ssmile;": 8995,
    "sstarf;": 8902,
    "star;": 9734,
    "starf;": 9733,
    "straightepsilon;": 1013,
    "straightphi;": 981,
    "strns;": 175,
    "sub;": 8834,
    "subE;": 10949,
    "subdot;": 10941,
    "sube;": 8838,
    "subedot;": 10947,
    "submult;": 10945,
    "subnE;": 10955,
    "subne;": 8842,
    "subplus;": 10943,
    "subrarr;": 10617,
    "subset;": 8834,
    "subseteq;": 8838,
    "subseteqq;": 10949,
    "subsetneq;": 8842,
    "subsetneqq;": 10955,
    "subsim;": 10951,
    "subsub;": 10965,
    "subsup;": 10963,
    "succ;": 8827,
    "succapprox;": 10936,
    "succcurlyeq;": 8829,
    "succeq;": 10928,
    "succnapprox;": 10938,
    "succneqq;": 10934,
    "succnsim;": 8937,
    "succsim;": 8831,
    "sum;": 8721,
    "sung;": 9834,
    sup1: 185,
    "sup1;": 185,
    sup2: 178,
    "sup2;": 178,
    sup3: 179,
    "sup3;": 179,
    "sup;": 8835,
    "supE;": 10950,
    "supdot;": 10942,
    "supdsub;": 10968,
    "supe;": 8839,
    "supedot;": 10948,
    "suphsol;": 10185,
    "suphsub;": 10967,
    "suplarr;": 10619,
    "supmult;": 10946,
    "supnE;": 10956,
    "supne;": 8843,
    "supplus;": 10944,
    "supset;": 8835,
    "supseteq;": 8839,
    "supseteqq;": 10950,
    "supsetneq;": 8843,
    "supsetneqq;": 10956,
    "supsim;": 10952,
    "supsub;": 10964,
    "supsup;": 10966,
    "swArr;": 8665,
    "swarhk;": 10534,
    "swarr;": 8601,
    "swarrow;": 8601,
    "swnwar;": 10538,
    szlig: 223,
    "szlig;": 223,
    "target;": 8982,
    "tau;": 964,
    "tbrk;": 9140,
    "tcaron;": 357,
    "tcedil;": 355,
    "tcy;": 1090,
    "tdot;": 8411,
    "telrec;": 8981,
    "tfr;": [55349, 56625],
    "there4;": 8756,
    "therefore;": 8756,
    "theta;": 952,
    "thetasym;": 977,
    "thetav;": 977,
    "thickapprox;": 8776,
    "thicksim;": 8764,
    "thinsp;": 8201,
    "thkap;": 8776,
    "thksim;": 8764,
    thorn: 254,
    "thorn;": 254,
    "tilde;": 732,
    times: 215,
    "times;": 215,
    "timesb;": 8864,
    "timesbar;": 10801,
    "timesd;": 10800,
    "tint;": 8749,
    "toea;": 10536,
    "top;": 8868,
    "topbot;": 9014,
    "topcir;": 10993,
    "topf;": [55349, 56677],
    "topfork;": 10970,
    "tosa;": 10537,
    "tprime;": 8244,
    "trade;": 8482,
    "triangle;": 9653,
    "triangledown;": 9663,
    "triangleleft;": 9667,
    "trianglelefteq;": 8884,
    "triangleq;": 8796,
    "triangleright;": 9657,
    "trianglerighteq;": 8885,
    "tridot;": 9708,
    "trie;": 8796,
    "triminus;": 10810,
    "triplus;": 10809,
    "trisb;": 10701,
    "tritime;": 10811,
    "trpezium;": 9186,
    "tscr;": [55349, 56521],
    "tscy;": 1094,
    "tshcy;": 1115,
    "tstrok;": 359,
    "twixt;": 8812,
    "twoheadleftarrow;": 8606,
    "twoheadrightarrow;": 8608,
    "uArr;": 8657,
    "uHar;": 10595,
    uacute: 250,
    "uacute;": 250,
    "uarr;": 8593,
    "ubrcy;": 1118,
    "ubreve;": 365,
    ucirc: 251,
    "ucirc;": 251,
    "ucy;": 1091,
    "udarr;": 8645,
    "udblac;": 369,
    "udhar;": 10606,
    "ufisht;": 10622,
    "ufr;": [55349, 56626],
    ugrave: 249,
    "ugrave;": 249,
    "uharl;": 8639,
    "uharr;": 8638,
    "uhblk;": 9600,
    "ulcorn;": 8988,
    "ulcorner;": 8988,
    "ulcrop;": 8975,
    "ultri;": 9720,
    "umacr;": 363,
    uml: 168,
    "uml;": 168,
    "uogon;": 371,
    "uopf;": [55349, 56678],
    "uparrow;": 8593,
    "updownarrow;": 8597,
    "upharpoonleft;": 8639,
    "upharpoonright;": 8638,
    "uplus;": 8846,
    "upsi;": 965,
    "upsih;": 978,
    "upsilon;": 965,
    "upuparrows;": 8648,
    "urcorn;": 8989,
    "urcorner;": 8989,
    "urcrop;": 8974,
    "uring;": 367,
    "urtri;": 9721,
    "uscr;": [55349, 56522],
    "utdot;": 8944,
    "utilde;": 361,
    "utri;": 9653,
    "utrif;": 9652,
    "uuarr;": 8648,
    uuml: 252,
    "uuml;": 252,
    "uwangle;": 10663,
    "vArr;": 8661,
    "vBar;": 10984,
    "vBarv;": 10985,
    "vDash;": 8872,
    "vangrt;": 10652,
    "varepsilon;": 1013,
    "varkappa;": 1008,
    "varnothing;": 8709,
    "varphi;": 981,
    "varpi;": 982,
    "varpropto;": 8733,
    "varr;": 8597,
    "varrho;": 1009,
    "varsigma;": 962,
    "varsubsetneq;": [8842, 65024],
    "varsubsetneqq;": [10955, 65024],
    "varsupsetneq;": [8843, 65024],
    "varsupsetneqq;": [10956, 65024],
    "vartheta;": 977,
    "vartriangleleft;": 8882,
    "vartriangleright;": 8883,
    "vcy;": 1074,
    "vdash;": 8866,
    "vee;": 8744,
    "veebar;": 8891,
    "veeeq;": 8794,
    "vellip;": 8942,
    "verbar;": 124,
    "vert;": 124,
    "vfr;": [55349, 56627],
    "vltri;": 8882,
    "vnsub;": [8834, 8402],
    "vnsup;": [8835, 8402],
    "vopf;": [55349, 56679],
    "vprop;": 8733,
    "vrtri;": 8883,
    "vscr;": [55349, 56523],
    "vsubnE;": [10955, 65024],
    "vsubne;": [8842, 65024],
    "vsupnE;": [10956, 65024],
    "vsupne;": [8843, 65024],
    "vzigzag;": 10650,
    "wcirc;": 373,
    "wedbar;": 10847,
    "wedge;": 8743,
    "wedgeq;": 8793,
    "weierp;": 8472,
    "wfr;": [55349, 56628],
    "wopf;": [55349, 56680],
    "wp;": 8472,
    "wr;": 8768,
    "wreath;": 8768,
    "wscr;": [55349, 56524],
    "xcap;": 8898,
    "xcirc;": 9711,
    "xcup;": 8899,
    "xdtri;": 9661,
    "xfr;": [55349, 56629],
    "xhArr;": 10234,
    "xharr;": 10231,
    "xi;": 958,
    "xlArr;": 10232,
    "xlarr;": 10229,
    "xmap;": 10236,
    "xnis;": 8955,
    "xodot;": 10752,
    "xopf;": [55349, 56681],
    "xoplus;": 10753,
    "xotime;": 10754,
    "xrArr;": 10233,
    "xrarr;": 10230,
    "xscr;": [55349, 56525],
    "xsqcup;": 10758,
    "xuplus;": 10756,
    "xutri;": 9651,
    "xvee;": 8897,
    "xwedge;": 8896,
    yacute: 253,
    "yacute;": 253,
    "yacy;": 1103,
    "ycirc;": 375,
    "ycy;": 1099,
    yen: 165,
    "yen;": 165,
    "yfr;": [55349, 56630],
    "yicy;": 1111,
    "yopf;": [55349, 56682],
    "yscr;": [55349, 56526],
    "yucy;": 1102,
    yuml: 255,
    "yuml;": 255,
    "zacute;": 378,
    "zcaron;": 382,
    "zcy;": 1079,
    "zdot;": 380,
    "zeetrf;": 8488,
    "zeta;": 950,
    "zfr;": [55349, 56631],
    "zhcy;": 1078,
    "zigrarr;": 8669,
    "zopf;": [55349, 56683],
    "zscr;": [55349, 56527],
    "zwj;": 8205,
    "zwnj;": 8204
  };
  var NAMEDCHARREF = /(A(?:Elig;?|MP;?|acute;?|breve;|c(?:irc;?|y;)|fr;|grave;?|lpha;|macr;|nd;|o(?:gon;|pf;)|pplyFunction;|ring;?|s(?:cr;|sign;)|tilde;?|uml;?)|B(?:a(?:ckslash;|r(?:v;|wed;))|cy;|e(?:cause;|rnoullis;|ta;)|fr;|opf;|reve;|scr;|umpeq;)|C(?:Hcy;|OPY;?|a(?:cute;|p(?:;|italDifferentialD;)|yleys;)|c(?:aron;|edil;?|irc;|onint;)|dot;|e(?:dilla;|nterDot;)|fr;|hi;|ircle(?:Dot;|Minus;|Plus;|Times;)|lo(?:ckwiseContourIntegral;|seCurly(?:DoubleQuote;|Quote;))|o(?:lon(?:;|e;)|n(?:gruent;|int;|tourIntegral;)|p(?:f;|roduct;)|unterClockwiseContourIntegral;)|ross;|scr;|up(?:;|Cap;))|D(?:D(?:;|otrahd;)|Jcy;|Scy;|Zcy;|a(?:gger;|rr;|shv;)|c(?:aron;|y;)|el(?:;|ta;)|fr;|i(?:a(?:critical(?:Acute;|Do(?:t;|ubleAcute;)|Grave;|Tilde;)|mond;)|fferentialD;)|o(?:pf;|t(?:;|Dot;|Equal;)|uble(?:ContourIntegral;|Do(?:t;|wnArrow;)|L(?:eft(?:Arrow;|RightArrow;|Tee;)|ong(?:Left(?:Arrow;|RightArrow;)|RightArrow;))|Right(?:Arrow;|Tee;)|Up(?:Arrow;|DownArrow;)|VerticalBar;)|wn(?:Arrow(?:;|Bar;|UpArrow;)|Breve;|Left(?:RightVector;|TeeVector;|Vector(?:;|Bar;))|Right(?:TeeVector;|Vector(?:;|Bar;))|Tee(?:;|Arrow;)|arrow;))|s(?:cr;|trok;))|E(?:NG;|TH;?|acute;?|c(?:aron;|irc;?|y;)|dot;|fr;|grave;?|lement;|m(?:acr;|pty(?:SmallSquare;|VerySmallSquare;))|o(?:gon;|pf;)|psilon;|qu(?:al(?:;|Tilde;)|ilibrium;)|s(?:cr;|im;)|ta;|uml;?|x(?:ists;|ponentialE;))|F(?:cy;|fr;|illed(?:SmallSquare;|VerySmallSquare;)|o(?:pf;|rAll;|uriertrf;)|scr;)|G(?:Jcy;|T;?|amma(?:;|d;)|breve;|c(?:edil;|irc;|y;)|dot;|fr;|g;|opf;|reater(?:Equal(?:;|Less;)|FullEqual;|Greater;|Less;|SlantEqual;|Tilde;)|scr;|t;)|H(?:ARDcy;|a(?:cek;|t;)|circ;|fr;|ilbertSpace;|o(?:pf;|rizontalLine;)|s(?:cr;|trok;)|ump(?:DownHump;|Equal;))|I(?:Ecy;|Jlig;|Ocy;|acute;?|c(?:irc;?|y;)|dot;|fr;|grave;?|m(?:;|a(?:cr;|ginaryI;)|plies;)|n(?:t(?:;|e(?:gral;|rsection;))|visible(?:Comma;|Times;))|o(?:gon;|pf;|ta;)|scr;|tilde;|u(?:kcy;|ml;?))|J(?:c(?:irc;|y;)|fr;|opf;|s(?:cr;|ercy;)|ukcy;)|K(?:Hcy;|Jcy;|appa;|c(?:edil;|y;)|fr;|opf;|scr;)|L(?:Jcy;|T;?|a(?:cute;|mbda;|ng;|placetrf;|rr;)|c(?:aron;|edil;|y;)|e(?:ft(?:A(?:ngleBracket;|rrow(?:;|Bar;|RightArrow;))|Ceiling;|Do(?:ubleBracket;|wn(?:TeeVector;|Vector(?:;|Bar;)))|Floor;|Right(?:Arrow;|Vector;)|T(?:ee(?:;|Arrow;|Vector;)|riangle(?:;|Bar;|Equal;))|Up(?:DownVector;|TeeVector;|Vector(?:;|Bar;))|Vector(?:;|Bar;)|arrow;|rightarrow;)|ss(?:EqualGreater;|FullEqual;|Greater;|Less;|SlantEqual;|Tilde;))|fr;|l(?:;|eftarrow;)|midot;|o(?:ng(?:Left(?:Arrow;|RightArrow;)|RightArrow;|left(?:arrow;|rightarrow;)|rightarrow;)|pf;|wer(?:LeftArrow;|RightArrow;))|s(?:cr;|h;|trok;)|t;)|M(?:ap;|cy;|e(?:diumSpace;|llintrf;)|fr;|inusPlus;|opf;|scr;|u;)|N(?:Jcy;|acute;|c(?:aron;|edil;|y;)|e(?:gative(?:MediumSpace;|Thi(?:ckSpace;|nSpace;)|VeryThinSpace;)|sted(?:GreaterGreater;|LessLess;)|wLine;)|fr;|o(?:Break;|nBreakingSpace;|pf;|t(?:;|C(?:ongruent;|upCap;)|DoubleVerticalBar;|E(?:lement;|qual(?:;|Tilde;)|xists;)|Greater(?:;|Equal;|FullEqual;|Greater;|Less;|SlantEqual;|Tilde;)|Hump(?:DownHump;|Equal;)|Le(?:ftTriangle(?:;|Bar;|Equal;)|ss(?:;|Equal;|Greater;|Less;|SlantEqual;|Tilde;))|Nested(?:GreaterGreater;|LessLess;)|Precedes(?:;|Equal;|SlantEqual;)|R(?:everseElement;|ightTriangle(?:;|Bar;|Equal;))|S(?:quareSu(?:bset(?:;|Equal;)|perset(?:;|Equal;))|u(?:bset(?:;|Equal;)|cceeds(?:;|Equal;|SlantEqual;|Tilde;)|perset(?:;|Equal;)))|Tilde(?:;|Equal;|FullEqual;|Tilde;)|VerticalBar;))|scr;|tilde;?|u;)|O(?:Elig;|acute;?|c(?:irc;?|y;)|dblac;|fr;|grave;?|m(?:acr;|ega;|icron;)|opf;|penCurly(?:DoubleQuote;|Quote;)|r;|s(?:cr;|lash;?)|ti(?:lde;?|mes;)|uml;?|ver(?:B(?:ar;|rac(?:e;|ket;))|Parenthesis;))|P(?:artialD;|cy;|fr;|hi;|i;|lusMinus;|o(?:incareplane;|pf;)|r(?:;|ecedes(?:;|Equal;|SlantEqual;|Tilde;)|ime;|o(?:duct;|portion(?:;|al;)))|s(?:cr;|i;))|Q(?:UOT;?|fr;|opf;|scr;)|R(?:Barr;|EG;?|a(?:cute;|ng;|rr(?:;|tl;))|c(?:aron;|edil;|y;)|e(?:;|verse(?:E(?:lement;|quilibrium;)|UpEquilibrium;))|fr;|ho;|ight(?:A(?:ngleBracket;|rrow(?:;|Bar;|LeftArrow;))|Ceiling;|Do(?:ubleBracket;|wn(?:TeeVector;|Vector(?:;|Bar;)))|Floor;|T(?:ee(?:;|Arrow;|Vector;)|riangle(?:;|Bar;|Equal;))|Up(?:DownVector;|TeeVector;|Vector(?:;|Bar;))|Vector(?:;|Bar;)|arrow;)|o(?:pf;|undImplies;)|rightarrow;|s(?:cr;|h;)|uleDelayed;)|S(?:H(?:CHcy;|cy;)|OFTcy;|acute;|c(?:;|aron;|edil;|irc;|y;)|fr;|hort(?:DownArrow;|LeftArrow;|RightArrow;|UpArrow;)|igma;|mallCircle;|opf;|q(?:rt;|uare(?:;|Intersection;|Su(?:bset(?:;|Equal;)|perset(?:;|Equal;))|Union;))|scr;|tar;|u(?:b(?:;|set(?:;|Equal;))|c(?:ceeds(?:;|Equal;|SlantEqual;|Tilde;)|hThat;)|m;|p(?:;|erset(?:;|Equal;)|set;)))|T(?:HORN;?|RADE;|S(?:Hcy;|cy;)|a(?:b;|u;)|c(?:aron;|edil;|y;)|fr;|h(?:e(?:refore;|ta;)|i(?:ckSpace;|nSpace;))|ilde(?:;|Equal;|FullEqual;|Tilde;)|opf;|ripleDot;|s(?:cr;|trok;))|U(?:a(?:cute;?|rr(?:;|ocir;))|br(?:cy;|eve;)|c(?:irc;?|y;)|dblac;|fr;|grave;?|macr;|n(?:der(?:B(?:ar;|rac(?:e;|ket;))|Parenthesis;)|ion(?:;|Plus;))|o(?:gon;|pf;)|p(?:Arrow(?:;|Bar;|DownArrow;)|DownArrow;|Equilibrium;|Tee(?:;|Arrow;)|arrow;|downarrow;|per(?:LeftArrow;|RightArrow;)|si(?:;|lon;))|ring;|scr;|tilde;|uml;?)|V(?:Dash;|bar;|cy;|dash(?:;|l;)|e(?:e;|r(?:bar;|t(?:;|ical(?:Bar;|Line;|Separator;|Tilde;))|yThinSpace;))|fr;|opf;|scr;|vdash;)|W(?:circ;|edge;|fr;|opf;|scr;)|X(?:fr;|i;|opf;|scr;)|Y(?:Acy;|Icy;|Ucy;|acute;?|c(?:irc;|y;)|fr;|opf;|scr;|uml;)|Z(?:Hcy;|acute;|c(?:aron;|y;)|dot;|e(?:roWidthSpace;|ta;)|fr;|opf;|scr;)|a(?:acute;?|breve;|c(?:;|E;|d;|irc;?|ute;?|y;)|elig;?|f(?:;|r;)|grave;?|l(?:e(?:fsym;|ph;)|pha;)|m(?:a(?:cr;|lg;)|p;?)|n(?:d(?:;|and;|d;|slope;|v;)|g(?:;|e;|le;|msd(?:;|a(?:a;|b;|c;|d;|e;|f;|g;|h;))|rt(?:;|vb(?:;|d;))|s(?:ph;|t;)|zarr;))|o(?:gon;|pf;)|p(?:;|E;|acir;|e;|id;|os;|prox(?:;|eq;))|ring;?|s(?:cr;|t;|ymp(?:;|eq;))|tilde;?|uml;?|w(?:conint;|int;))|b(?:Not;|a(?:ck(?:cong;|epsilon;|prime;|sim(?:;|eq;))|r(?:vee;|wed(?:;|ge;)))|brk(?:;|tbrk;)|c(?:ong;|y;)|dquo;|e(?:caus(?:;|e;)|mptyv;|psi;|rnou;|t(?:a;|h;|ween;))|fr;|ig(?:c(?:ap;|irc;|up;)|o(?:dot;|plus;|times;)|s(?:qcup;|tar;)|triangle(?:down;|up;)|uplus;|vee;|wedge;)|karow;|l(?:a(?:ck(?:lozenge;|square;|triangle(?:;|down;|left;|right;))|nk;)|k(?:1(?:2;|4;)|34;)|ock;)|n(?:e(?:;|quiv;)|ot;)|o(?:pf;|t(?:;|tom;)|wtie;|x(?:D(?:L;|R;|l;|r;)|H(?:;|D;|U;|d;|u;)|U(?:L;|R;|l;|r;)|V(?:;|H;|L;|R;|h;|l;|r;)|box;|d(?:L;|R;|l;|r;)|h(?:;|D;|U;|d;|u;)|minus;|plus;|times;|u(?:L;|R;|l;|r;)|v(?:;|H;|L;|R;|h;|l;|r;)))|prime;|r(?:eve;|vbar;?)|s(?:cr;|emi;|im(?:;|e;)|ol(?:;|b;|hsub;))|u(?:ll(?:;|et;)|mp(?:;|E;|e(?:;|q;))))|c(?:a(?:cute;|p(?:;|and;|brcup;|c(?:ap;|up;)|dot;|s;)|r(?:et;|on;))|c(?:a(?:ps;|ron;)|edil;?|irc;|ups(?:;|sm;))|dot;|e(?:dil;?|mptyv;|nt(?:;|erdot;|))|fr;|h(?:cy;|eck(?:;|mark;)|i;)|ir(?:;|E;|c(?:;|eq;|le(?:arrow(?:left;|right;)|d(?:R;|S;|ast;|circ;|dash;)))|e;|fnint;|mid;|scir;)|lubs(?:;|uit;)|o(?:lon(?:;|e(?:;|q;))|m(?:ma(?:;|t;)|p(?:;|fn;|le(?:ment;|xes;)))|n(?:g(?:;|dot;)|int;)|p(?:f;|rod;|y(?:;|sr;|)))|r(?:arr;|oss;)|s(?:cr;|u(?:b(?:;|e;)|p(?:;|e;)))|tdot;|u(?:darr(?:l;|r;)|e(?:pr;|sc;)|larr(?:;|p;)|p(?:;|brcap;|c(?:ap;|up;)|dot;|or;|s;)|r(?:arr(?:;|m;)|ly(?:eq(?:prec;|succ;)|vee;|wedge;)|ren;?|vearrow(?:left;|right;))|vee;|wed;)|w(?:conint;|int;)|ylcty;)|d(?:Arr;|Har;|a(?:gger;|leth;|rr;|sh(?:;|v;))|b(?:karow;|lac;)|c(?:aron;|y;)|d(?:;|a(?:gger;|rr;)|otseq;)|e(?:g;?|lta;|mptyv;)|f(?:isht;|r;)|har(?:l;|r;)|i(?:am(?:;|ond(?:;|suit;)|s;)|e;|gamma;|sin;|v(?:;|ide(?:;|ontimes;|)|onx;))|jcy;|lc(?:orn;|rop;)|o(?:llar;|pf;|t(?:;|eq(?:;|dot;)|minus;|plus;|square;)|ublebarwedge;|wn(?:arrow;|downarrows;|harpoon(?:left;|right;)))|r(?:bkarow;|c(?:orn;|rop;))|s(?:c(?:r;|y;)|ol;|trok;)|t(?:dot;|ri(?:;|f;))|u(?:arr;|har;)|wangle;|z(?:cy;|igrarr;))|e(?:D(?:Dot;|ot;)|a(?:cute;?|ster;)|c(?:aron;|ir(?:;|c;?)|olon;|y;)|dot;|e;|f(?:Dot;|r;)|g(?:;|rave;?|s(?:;|dot;))|l(?:;|inters;|l;|s(?:;|dot;))|m(?:acr;|pty(?:;|set;|v;)|sp(?:1(?:3;|4;)|;))|n(?:g;|sp;)|o(?:gon;|pf;)|p(?:ar(?:;|sl;)|lus;|si(?:;|lon;|v;))|q(?:c(?:irc;|olon;)|s(?:im;|lant(?:gtr;|less;))|u(?:als;|est;|iv(?:;|DD;))|vparsl;)|r(?:Dot;|arr;)|s(?:cr;|dot;|im;)|t(?:a;|h;?)|u(?:ml;?|ro;)|x(?:cl;|ist;|p(?:ectation;|onentiale;)))|f(?:allingdotseq;|cy;|emale;|f(?:ilig;|l(?:ig;|lig;)|r;)|ilig;|jlig;|l(?:at;|lig;|tns;)|nof;|o(?:pf;|r(?:all;|k(?:;|v;)))|partint;|r(?:a(?:c(?:1(?:2;?|3;|4;?|5;|6;|8;)|2(?:3;|5;)|3(?:4;?|5;|8;)|45;|5(?:6;|8;)|78;)|sl;)|own;)|scr;)|g(?:E(?:;|l;)|a(?:cute;|mma(?:;|d;)|p;)|breve;|c(?:irc;|y;)|dot;|e(?:;|l;|q(?:;|q;|slant;)|s(?:;|cc;|dot(?:;|o(?:;|l;))|l(?:;|es;)))|fr;|g(?:;|g;)|imel;|jcy;|l(?:;|E;|a;|j;)|n(?:E;|ap(?:;|prox;)|e(?:;|q(?:;|q;))|sim;)|opf;|rave;|s(?:cr;|im(?:;|e;|l;))|t(?:;|c(?:c;|ir;)|dot;|lPar;|quest;|r(?:a(?:pprox;|rr;)|dot;|eq(?:less;|qless;)|less;|sim;)|)|v(?:ertneqq;|nE;))|h(?:Arr;|a(?:irsp;|lf;|milt;|r(?:dcy;|r(?:;|cir;|w;)))|bar;|circ;|e(?:arts(?:;|uit;)|llip;|rcon;)|fr;|ks(?:earow;|warow;)|o(?:arr;|mtht;|ok(?:leftarrow;|rightarrow;)|pf;|rbar;)|s(?:cr;|lash;|trok;)|y(?:bull;|phen;))|i(?:acute;?|c(?:;|irc;?|y;)|e(?:cy;|xcl;?)|f(?:f;|r;)|grave;?|i(?:;|i(?:int;|nt;)|nfin;|ota;)|jlig;|m(?:a(?:cr;|g(?:e;|line;|part;)|th;)|of;|ped;)|n(?:;|care;|fin(?:;|tie;)|odot;|t(?:;|cal;|e(?:gers;|rcal;)|larhk;|prod;))|o(?:cy;|gon;|pf;|ta;)|prod;|quest;?|s(?:cr;|in(?:;|E;|dot;|s(?:;|v;)|v;))|t(?:;|ilde;)|u(?:kcy;|ml;?))|j(?:c(?:irc;|y;)|fr;|math;|opf;|s(?:cr;|ercy;)|ukcy;)|k(?:appa(?:;|v;)|c(?:edil;|y;)|fr;|green;|hcy;|jcy;|opf;|scr;)|l(?:A(?:arr;|rr;|tail;)|Barr;|E(?:;|g;)|Har;|a(?:cute;|emptyv;|gran;|mbda;|ng(?:;|d;|le;)|p;|quo;?|rr(?:;|b(?:;|fs;)|fs;|hk;|lp;|pl;|sim;|tl;)|t(?:;|ail;|e(?:;|s;)))|b(?:arr;|brk;|r(?:ac(?:e;|k;)|k(?:e;|sl(?:d;|u;))))|c(?:aron;|e(?:dil;|il;)|ub;|y;)|d(?:ca;|quo(?:;|r;)|r(?:dhar;|ushar;)|sh;)|e(?:;|ft(?:arrow(?:;|tail;)|harpoon(?:down;|up;)|leftarrows;|right(?:arrow(?:;|s;)|harpoons;|squigarrow;)|threetimes;)|g;|q(?:;|q;|slant;)|s(?:;|cc;|dot(?:;|o(?:;|r;))|g(?:;|es;)|s(?:approx;|dot;|eq(?:gtr;|qgtr;)|gtr;|sim;)))|f(?:isht;|loor;|r;)|g(?:;|E;)|h(?:ar(?:d;|u(?:;|l;))|blk;)|jcy;|l(?:;|arr;|corner;|hard;|tri;)|m(?:idot;|oust(?:;|ache;))|n(?:E;|ap(?:;|prox;)|e(?:;|q(?:;|q;))|sim;)|o(?:a(?:ng;|rr;)|brk;|ng(?:left(?:arrow;|rightarrow;)|mapsto;|rightarrow;)|oparrow(?:left;|right;)|p(?:ar;|f;|lus;)|times;|w(?:ast;|bar;)|z(?:;|enge;|f;))|par(?:;|lt;)|r(?:arr;|corner;|har(?:;|d;)|m;|tri;)|s(?:aquo;|cr;|h;|im(?:;|e;|g;)|q(?:b;|uo(?:;|r;))|trok;)|t(?:;|c(?:c;|ir;)|dot;|hree;|imes;|larr;|quest;|r(?:Par;|i(?:;|e;|f;))|)|ur(?:dshar;|uhar;)|v(?:ertneqq;|nE;))|m(?:DDot;|a(?:cr;?|l(?:e;|t(?:;|ese;))|p(?:;|sto(?:;|down;|left;|up;))|rker;)|c(?:omma;|y;)|dash;|easuredangle;|fr;|ho;|i(?:cro;?|d(?:;|ast;|cir;|dot;?)|nus(?:;|b;|d(?:;|u;)))|l(?:cp;|dr;)|nplus;|o(?:dels;|pf;)|p;|s(?:cr;|tpos;)|u(?:;|ltimap;|map;))|n(?:G(?:g;|t(?:;|v;))|L(?:eft(?:arrow;|rightarrow;)|l;|t(?:;|v;))|Rightarrow;|V(?:Dash;|dash;)|a(?:bla;|cute;|ng;|p(?:;|E;|id;|os;|prox;)|tur(?:;|al(?:;|s;)))|b(?:sp;?|ump(?:;|e;))|c(?:a(?:p;|ron;)|edil;|ong(?:;|dot;)|up;|y;)|dash;|e(?:;|Arr;|ar(?:hk;|r(?:;|ow;))|dot;|quiv;|s(?:ear;|im;)|xist(?:;|s;))|fr;|g(?:E;|e(?:;|q(?:;|q;|slant;)|s;)|sim;|t(?:;|r;))|h(?:Arr;|arr;|par;)|i(?:;|s(?:;|d;)|v;)|jcy;|l(?:Arr;|E;|arr;|dr;|e(?:;|ft(?:arrow;|rightarrow;)|q(?:;|q;|slant;)|s(?:;|s;))|sim;|t(?:;|ri(?:;|e;)))|mid;|o(?:pf;|t(?:;|in(?:;|E;|dot;|v(?:a;|b;|c;))|ni(?:;|v(?:a;|b;|c;))|))|p(?:ar(?:;|allel;|sl;|t;)|olint;|r(?:;|cue;|e(?:;|c(?:;|eq;))))|r(?:Arr;|arr(?:;|c;|w;)|ightarrow;|tri(?:;|e;))|s(?:c(?:;|cue;|e;|r;)|hort(?:mid;|parallel;)|im(?:;|e(?:;|q;))|mid;|par;|qsu(?:be;|pe;)|u(?:b(?:;|E;|e;|set(?:;|eq(?:;|q;)))|cc(?:;|eq;)|p(?:;|E;|e;|set(?:;|eq(?:;|q;)))))|t(?:gl;|ilde;?|lg;|riangle(?:left(?:;|eq;)|right(?:;|eq;)))|u(?:;|m(?:;|ero;|sp;))|v(?:Dash;|Harr;|ap;|dash;|g(?:e;|t;)|infin;|l(?:Arr;|e;|t(?:;|rie;))|r(?:Arr;|trie;)|sim;)|w(?:Arr;|ar(?:hk;|r(?:;|ow;))|near;))|o(?:S;|a(?:cute;?|st;)|c(?:ir(?:;|c;?)|y;)|d(?:ash;|blac;|iv;|ot;|sold;)|elig;|f(?:cir;|r;)|g(?:on;|rave;?|t;)|h(?:bar;|m;)|int;|l(?:arr;|c(?:ir;|ross;)|ine;|t;)|m(?:acr;|ega;|i(?:cron;|d;|nus;))|opf;|p(?:ar;|erp;|lus;)|r(?:;|arr;|d(?:;|er(?:;|of;)|f;?|m;?)|igof;|or;|slope;|v;)|s(?:cr;|lash;?|ol;)|ti(?:lde;?|mes(?:;|as;))|uml;?|vbar;)|p(?:ar(?:;|a(?:;|llel;|)|s(?:im;|l;)|t;)|cy;|er(?:cnt;|iod;|mil;|p;|tenk;)|fr;|h(?:i(?:;|v;)|mmat;|one;)|i(?:;|tchfork;|v;)|l(?:an(?:ck(?:;|h;)|kv;)|us(?:;|acir;|b;|cir;|d(?:o;|u;)|e;|mn;?|sim;|two;))|m;|o(?:intint;|pf;|und;?)|r(?:;|E;|ap;|cue;|e(?:;|c(?:;|approx;|curlyeq;|eq;|n(?:approx;|eqq;|sim;)|sim;))|ime(?:;|s;)|n(?:E;|ap;|sim;)|o(?:d;|f(?:alar;|line;|surf;)|p(?:;|to;))|sim;|urel;)|s(?:cr;|i;)|uncsp;)|q(?:fr;|int;|opf;|prime;|scr;|u(?:at(?:ernions;|int;)|est(?:;|eq;)|ot;?))|r(?:A(?:arr;|rr;|tail;)|Barr;|Har;|a(?:c(?:e;|ute;)|dic;|emptyv;|ng(?:;|d;|e;|le;)|quo;?|rr(?:;|ap;|b(?:;|fs;)|c;|fs;|hk;|lp;|pl;|sim;|tl;|w;)|t(?:ail;|io(?:;|nals;)))|b(?:arr;|brk;|r(?:ac(?:e;|k;)|k(?:e;|sl(?:d;|u;))))|c(?:aron;|e(?:dil;|il;)|ub;|y;)|d(?:ca;|ldhar;|quo(?:;|r;)|sh;)|e(?:al(?:;|ine;|part;|s;)|ct;|g;?)|f(?:isht;|loor;|r;)|h(?:ar(?:d;|u(?:;|l;))|o(?:;|v;))|i(?:ght(?:arrow(?:;|tail;)|harpoon(?:down;|up;)|left(?:arrows;|harpoons;)|rightarrows;|squigarrow;|threetimes;)|ng;|singdotseq;)|l(?:arr;|har;|m;)|moust(?:;|ache;)|nmid;|o(?:a(?:ng;|rr;)|brk;|p(?:ar;|f;|lus;)|times;)|p(?:ar(?:;|gt;)|polint;)|rarr;|s(?:aquo;|cr;|h;|q(?:b;|uo(?:;|r;)))|t(?:hree;|imes;|ri(?:;|e;|f;|ltri;))|uluhar;|x;)|s(?:acute;|bquo;|c(?:;|E;|a(?:p;|ron;)|cue;|e(?:;|dil;)|irc;|n(?:E;|ap;|sim;)|polint;|sim;|y;)|dot(?:;|b;|e;)|e(?:Arr;|ar(?:hk;|r(?:;|ow;))|ct;?|mi;|swar;|tm(?:inus;|n;)|xt;)|fr(?:;|own;)|h(?:arp;|c(?:hcy;|y;)|ort(?:mid;|parallel;)|y;?)|i(?:gma(?:;|f;|v;)|m(?:;|dot;|e(?:;|q;)|g(?:;|E;)|l(?:;|E;)|ne;|plus;|rarr;))|larr;|m(?:a(?:llsetminus;|shp;)|eparsl;|i(?:d;|le;)|t(?:;|e(?:;|s;)))|o(?:ftcy;|l(?:;|b(?:;|ar;))|pf;)|pa(?:des(?:;|uit;)|r;)|q(?:c(?:ap(?:;|s;)|up(?:;|s;))|su(?:b(?:;|e;|set(?:;|eq;))|p(?:;|e;|set(?:;|eq;)))|u(?:;|ar(?:e;|f;)|f;))|rarr;|s(?:cr;|etmn;|mile;|tarf;)|t(?:ar(?:;|f;)|r(?:aight(?:epsilon;|phi;)|ns;))|u(?:b(?:;|E;|dot;|e(?:;|dot;)|mult;|n(?:E;|e;)|plus;|rarr;|s(?:et(?:;|eq(?:;|q;)|neq(?:;|q;))|im;|u(?:b;|p;)))|cc(?:;|approx;|curlyeq;|eq;|n(?:approx;|eqq;|sim;)|sim;)|m;|ng;|p(?:1;?|2;?|3;?|;|E;|d(?:ot;|sub;)|e(?:;|dot;)|hs(?:ol;|ub;)|larr;|mult;|n(?:E;|e;)|plus;|s(?:et(?:;|eq(?:;|q;)|neq(?:;|q;))|im;|u(?:b;|p;))))|w(?:Arr;|ar(?:hk;|r(?:;|ow;))|nwar;)|zlig;?)|t(?:a(?:rget;|u;)|brk;|c(?:aron;|edil;|y;)|dot;|elrec;|fr;|h(?:e(?:re(?:4;|fore;)|ta(?:;|sym;|v;))|i(?:ck(?:approx;|sim;)|nsp;)|k(?:ap;|sim;)|orn;?)|i(?:lde;|mes(?:;|b(?:;|ar;)|d;|)|nt;)|o(?:ea;|p(?:;|bot;|cir;|f(?:;|ork;))|sa;)|prime;|r(?:ade;|i(?:angle(?:;|down;|left(?:;|eq;)|q;|right(?:;|eq;))|dot;|e;|minus;|plus;|sb;|time;)|pezium;)|s(?:c(?:r;|y;)|hcy;|trok;)|w(?:ixt;|ohead(?:leftarrow;|rightarrow;)))|u(?:Arr;|Har;|a(?:cute;?|rr;)|br(?:cy;|eve;)|c(?:irc;?|y;)|d(?:arr;|blac;|har;)|f(?:isht;|r;)|grave;?|h(?:ar(?:l;|r;)|blk;)|l(?:c(?:orn(?:;|er;)|rop;)|tri;)|m(?:acr;|l;?)|o(?:gon;|pf;)|p(?:arrow;|downarrow;|harpoon(?:left;|right;)|lus;|si(?:;|h;|lon;)|uparrows;)|r(?:c(?:orn(?:;|er;)|rop;)|ing;|tri;)|scr;|t(?:dot;|ilde;|ri(?:;|f;))|u(?:arr;|ml;?)|wangle;)|v(?:Arr;|Bar(?:;|v;)|Dash;|a(?:ngrt;|r(?:epsilon;|kappa;|nothing;|p(?:hi;|i;|ropto;)|r(?:;|ho;)|s(?:igma;|u(?:bsetneq(?:;|q;)|psetneq(?:;|q;)))|t(?:heta;|riangle(?:left;|right;))))|cy;|dash;|e(?:e(?:;|bar;|eq;)|llip;|r(?:bar;|t;))|fr;|ltri;|nsu(?:b;|p;)|opf;|prop;|rtri;|s(?:cr;|u(?:bn(?:E;|e;)|pn(?:E;|e;)))|zigzag;)|w(?:circ;|e(?:d(?:bar;|ge(?:;|q;))|ierp;)|fr;|opf;|p;|r(?:;|eath;)|scr;)|x(?:c(?:ap;|irc;|up;)|dtri;|fr;|h(?:Arr;|arr;)|i;|l(?:Arr;|arr;)|map;|nis;|o(?:dot;|p(?:f;|lus;)|time;)|r(?:Arr;|arr;)|s(?:cr;|qcup;)|u(?:plus;|tri;)|vee;|wedge;)|y(?:ac(?:ute;?|y;)|c(?:irc;|y;)|en;?|fr;|icy;|opf;|scr;|u(?:cy;|ml;?))|z(?:acute;|c(?:aron;|y;)|dot;|e(?:etrf;|ta;)|fr;|hcy;|igrarr;|opf;|scr;|w(?:j;|nj;)))|[\s\S]/g;
  var NAMEDCHARREF_MAXLEN = 32;
  var DBLQUOTEATTRVAL = /[^\r"&\u0000]+/g;
  var SINGLEQUOTEATTRVAL = /[^\r'&\u0000]+/g;
  var UNQUOTEDATTRVAL = /[^\r\t\n\f &>\u0000]+/g;
  var TAGNAME = /[^\r\t\n\f \/>A-Z\u0000]+/g;
  var ATTRNAME = /[^\r\t\n\f \/=>A-Z\u0000]+/g;
  var CDATATEXT = /[^\]\r\u0000\uffff]*/g;
  var DATATEXT = /[^&<\r\u0000\uffff]*/g;
  var RAWTEXT = /[^<\r\u0000\uffff]*/g;
  var PLAINTEXT = /[^\r\u0000\uffff]*/g;
  var SIMPLETAG = /(?:(\/)?([a-z]+)>)|[\s\S]/g;
  var SIMPLEATTR = /(?:([-a-z]+)[ \t\n\f]*=[ \t\n\f]*('[^'&\r\u0000]*'|"[^"&\r\u0000]*"|[^\t\n\r\f "&'\u0000>][^&> \t\n\r\f\u0000]*[ \t\n\f]))|[\s\S]/g;
  var NONWS = /[^\x09\x0A\x0C\x0D\x20]/;
  var ALLNONWS = /[^\x09\x0A\x0C\x0D\x20]/g;
  var NONWSNONNUL = /[^\x00\x09\x0A\x0C\x0D\x20]/;
  var LEADINGWS = /^[\x09\x0A\x0C\x0D\x20]+/;
  var NULCHARS = /\x00/g;
  function buf2str(buf) {
    var CHUNKSIZE = 16384;
    if (buf.length < CHUNKSIZE) {
      return String.fromCharCode.apply(String, buf);
    }
    var result = "";
    for (var i = 0;i < buf.length; i += CHUNKSIZE) {
      result += String.fromCharCode.apply(String, buf.slice(i, i + CHUNKSIZE));
    }
    return result;
  }
  function str2buf(s) {
    var result = [];
    for (var i = 0;i < s.length; i++) {
      result[i] = s.charCodeAt(i);
    }
    return result;
  }
  function isA(elt, set) {
    if (typeof set === "string") {
      return elt.namespaceURI === NAMESPACE.HTML && elt.localName === set;
    }
    var tagnames = set[elt.namespaceURI];
    return tagnames && tagnames[elt.localName];
  }
  function isMathmlTextIntegrationPoint(n) {
    return isA(n, mathmlTextIntegrationPointSet);
  }
  function isHTMLIntegrationPoint(n) {
    if (isA(n, htmlIntegrationPointSet))
      return true;
    if (n.namespaceURI === NAMESPACE.MATHML && n.localName === "annotation-xml") {
      var encoding = n.getAttribute("encoding");
      if (encoding)
        encoding = encoding.toLowerCase();
      if (encoding === "text/html" || encoding === "application/xhtml+xml")
        return true;
    }
    return false;
  }
  function adjustSVGTagName(name) {
    if (name in svgTagNameAdjustments)
      return svgTagNameAdjustments[name];
    else
      return name;
  }
  function adjustSVGAttributes(attrs) {
    for (var i = 0, n = attrs.length;i < n; i++) {
      if (attrs[i][0] in svgAttrAdjustments) {
        attrs[i][0] = svgAttrAdjustments[attrs[i][0]];
      }
    }
  }
  function adjustMathMLAttributes(attrs) {
    for (var i = 0, n = attrs.length;i < n; i++) {
      if (attrs[i][0] === "definitionurl") {
        attrs[i][0] = "definitionURL";
        break;
      }
    }
  }
  function adjustForeignAttributes(attrs) {
    for (var i = 0, n = attrs.length;i < n; i++) {
      if (attrs[i][0] in foreignAttributes) {
        attrs[i].push(foreignAttributes[attrs[i][0]]);
      }
    }
  }
  function transferAttributes(attrs, elt) {
    for (var i = 0, n = attrs.length;i < n; i++) {
      var name = attrs[i][0], value = attrs[i][1];
      if (elt.hasAttribute(name))
        continue;
      elt._setAttribute(name, value);
    }
  }
  HTMLParser.ElementStack = function ElementStack() {
    this.elements = [];
    this.top = null;
  };
  HTMLParser.ElementStack.prototype.push = function(e) {
    this.elements.push(e);
    this.top = e;
  };
  HTMLParser.ElementStack.prototype.pop = function(e) {
    this.elements.pop();
    this.top = this.elements[this.elements.length - 1];
  };
  HTMLParser.ElementStack.prototype.popTag = function(tag) {
    for (var i = this.elements.length - 1;i > 0; i--) {
      var e = this.elements[i];
      if (isA(e, tag))
        break;
    }
    this.elements.length = i;
    this.top = this.elements[i - 1];
  };
  HTMLParser.ElementStack.prototype.popElementType = function(type) {
    for (var i = this.elements.length - 1;i > 0; i--) {
      if (this.elements[i] instanceof type)
        break;
    }
    this.elements.length = i;
    this.top = this.elements[i - 1];
  };
  HTMLParser.ElementStack.prototype.popElement = function(e) {
    for (var i = this.elements.length - 1;i > 0; i--) {
      if (this.elements[i] === e)
        break;
    }
    this.elements.length = i;
    this.top = this.elements[i - 1];
  };
  HTMLParser.ElementStack.prototype.removeElement = function(e) {
    if (this.top === e)
      this.pop();
    else {
      var idx = this.elements.lastIndexOf(e);
      if (idx !== -1)
        this.elements.splice(idx, 1);
    }
  };
  HTMLParser.ElementStack.prototype.clearToContext = function(set) {
    for (var i = this.elements.length - 1;i > 0; i--) {
      if (isA(this.elements[i], set))
        break;
    }
    this.elements.length = i + 1;
    this.top = this.elements[i];
  };
  HTMLParser.ElementStack.prototype.contains = function(tag) {
    return this.inSpecificScope(tag, Object.create(null));
  };
  HTMLParser.ElementStack.prototype.inSpecificScope = function(tag, set) {
    for (var i = this.elements.length - 1;i >= 0; i--) {
      var elt = this.elements[i];
      if (isA(elt, tag))
        return true;
      if (isA(elt, set))
        return false;
    }
    return false;
  };
  HTMLParser.ElementStack.prototype.elementInSpecificScope = function(target, set) {
    for (var i = this.elements.length - 1;i >= 0; i--) {
      var elt = this.elements[i];
      if (elt === target)
        return true;
      if (isA(elt, set))
        return false;
    }
    return false;
  };
  HTMLParser.ElementStack.prototype.elementTypeInSpecificScope = function(target, set) {
    for (var i = this.elements.length - 1;i >= 0; i--) {
      var elt = this.elements[i];
      if (elt instanceof target)
        return true;
      if (isA(elt, set))
        return false;
    }
    return false;
  };
  HTMLParser.ElementStack.prototype.inScope = function(tag) {
    return this.inSpecificScope(tag, inScopeSet);
  };
  HTMLParser.ElementStack.prototype.elementInScope = function(e) {
    return this.elementInSpecificScope(e, inScopeSet);
  };
  HTMLParser.ElementStack.prototype.elementTypeInScope = function(type) {
    return this.elementTypeInSpecificScope(type, inScopeSet);
  };
  HTMLParser.ElementStack.prototype.inButtonScope = function(tag) {
    return this.inSpecificScope(tag, inButtonScopeSet);
  };
  HTMLParser.ElementStack.prototype.inListItemScope = function(tag) {
    return this.inSpecificScope(tag, inListItemScopeSet);
  };
  HTMLParser.ElementStack.prototype.inTableScope = function(tag) {
    return this.inSpecificScope(tag, inTableScopeSet);
  };
  HTMLParser.ElementStack.prototype.inSelectScope = function(tag) {
    for (var i = this.elements.length - 1;i >= 0; i--) {
      var elt = this.elements[i];
      if (elt.namespaceURI !== NAMESPACE.HTML)
        return false;
      var localname = elt.localName;
      if (localname === tag)
        return true;
      if (localname !== "optgroup" && localname !== "option")
        return false;
    }
    return false;
  };
  HTMLParser.ElementStack.prototype.generateImpliedEndTags = function(butnot, thorough) {
    var endTagSet = thorough ? thoroughImpliedEndTagsSet : impliedEndTagsSet;
    for (var i = this.elements.length - 1;i >= 0; i--) {
      var e = this.elements[i];
      if (butnot && isA(e, butnot))
        break;
      if (!isA(this.elements[i], endTagSet))
        break;
    }
    this.elements.length = i + 1;
    this.top = this.elements[i];
  };
  HTMLParser.ActiveFormattingElements = function AFE() {
    this.list = [];
    this.attrs = [];
  };
  HTMLParser.ActiveFormattingElements.prototype.MARKER = { localName: "|" };
  HTMLParser.ActiveFormattingElements.prototype.insertMarker = function() {
    this.list.push(this.MARKER);
    this.attrs.push(this.MARKER);
  };
  HTMLParser.ActiveFormattingElements.prototype.push = function(elt, attrs) {
    var count = 0;
    for (var i = this.list.length - 1;i >= 0; i--) {
      if (this.list[i] === this.MARKER)
        break;
      if (equal(elt, this.list[i], this.attrs[i])) {
        count++;
        if (count === 3) {
          this.list.splice(i, 1);
          this.attrs.splice(i, 1);
          break;
        }
      }
    }
    this.list.push(elt);
    var attrcopy = [];
    for (var ii = 0;ii < attrs.length; ii++) {
      attrcopy[ii] = attrs[ii];
    }
    this.attrs.push(attrcopy);
    function equal(newelt, oldelt, oldattrs) {
      if (newelt.localName !== oldelt.localName)
        return false;
      if (newelt._numattrs !== oldattrs.length)
        return false;
      for (var i2 = 0, n = oldattrs.length;i2 < n; i2++) {
        var oldname = oldattrs[i2][0];
        var oldval = oldattrs[i2][1];
        if (!newelt.hasAttribute(oldname))
          return false;
        if (newelt.getAttribute(oldname) !== oldval)
          return false;
      }
      return true;
    }
  };
  HTMLParser.ActiveFormattingElements.prototype.clearToMarker = function() {
    for (var i = this.list.length - 1;i >= 0; i--) {
      if (this.list[i] === this.MARKER)
        break;
    }
    if (i < 0)
      i = 0;
    this.list.length = i;
    this.attrs.length = i;
  };
  HTMLParser.ActiveFormattingElements.prototype.findElementByTag = function(tag) {
    for (var i = this.list.length - 1;i >= 0; i--) {
      var elt = this.list[i];
      if (elt === this.MARKER)
        break;
      if (elt.localName === tag)
        return elt;
    }
    return null;
  };
  HTMLParser.ActiveFormattingElements.prototype.indexOf = function(e) {
    return this.list.lastIndexOf(e);
  };
  HTMLParser.ActiveFormattingElements.prototype.remove = function(e) {
    var idx = this.list.lastIndexOf(e);
    if (idx !== -1) {
      this.list.splice(idx, 1);
      this.attrs.splice(idx, 1);
    }
  };
  HTMLParser.ActiveFormattingElements.prototype.replace = function(a, b, attrs) {
    var idx = this.list.lastIndexOf(a);
    if (idx !== -1) {
      this.list[idx] = b;
      this.attrs[idx] = attrs;
    }
  };
  HTMLParser.ActiveFormattingElements.prototype.insertAfter = function(a, b) {
    var idx = this.list.lastIndexOf(a);
    if (idx !== -1) {
      this.list.splice(idx, 0, b);
      this.attrs.splice(idx, 0, b);
    }
  };
  function HTMLParser(address, fragmentContext, options) {
    var chars = null;
    var numchars = 0;
    var nextchar = 0;
    var input_complete = false;
    var scanner_skip_newline = false;
    var reentrant_invocations = 0;
    var saved_scanner_state = [];
    var leftovers = "";
    var first_batch = true;
    var paused = 0;
    var tokenizer = data_state;
    var return_state;
    var character_reference_code;
    var tagnamebuf = "";
    var lasttagname = "";
    var tempbuf = [];
    var attrnamebuf = "";
    var attrvaluebuf = "";
    var commentbuf = [];
    var doctypenamebuf = [];
    var doctypepublicbuf = [];
    var doctypesystembuf = [];
    var attributes = [];
    var is_end_tag = false;
    var parser2 = initial_mode;
    var originalInsertionMode = null;
    var templateInsertionModes = [];
    var stack = new HTMLParser.ElementStack;
    var afe = new HTMLParser.ActiveFormattingElements;
    var fragment = fragmentContext !== undefined;
    var head_element_pointer = null;
    var form_element_pointer = null;
    var scripting_enabled = true;
    if (fragmentContext) {
      scripting_enabled = fragmentContext.ownerDocument._scripting_enabled;
    }
    if (options && options.scripting_enabled === false)
      scripting_enabled = false;
    var frameset_ok = true;
    var force_quirks = false;
    var pending_table_text;
    var text_integration_mode;
    var textrun = [];
    var textIncludesNUL = false;
    var ignore_linefeed = false;
    var htmlparser = {
      document: function() {
        return doc;
      },
      _asDocumentFragment: function() {
        var frag = doc.createDocumentFragment();
        var root2 = doc.firstChild;
        while (root2.hasChildNodes()) {
          frag.appendChild(root2.firstChild);
        }
        return frag;
      },
      pause: function() {
        paused++;
      },
      resume: function() {
        paused--;
        this.parse("");
      },
      parse: function(s, end, shouldPauseFunc) {
        var moreToDo;
        if (paused > 0) {
          leftovers += s;
          return true;
        }
        if (reentrant_invocations === 0) {
          if (leftovers) {
            s = leftovers + s;
            leftovers = "";
          }
          if (end) {
            s += "￿";
            input_complete = true;
          }
          chars = s;
          numchars = s.length;
          nextchar = 0;
          if (first_batch) {
            first_batch = false;
            if (chars.charCodeAt(0) === 65279)
              nextchar = 1;
          }
          reentrant_invocations++;
          moreToDo = scanChars(shouldPauseFunc);
          leftovers = chars.substring(nextchar, numchars);
          reentrant_invocations--;
        } else {
          reentrant_invocations++;
          saved_scanner_state.push(chars, numchars, nextchar);
          chars = s;
          numchars = s.length;
          nextchar = 0;
          scanChars();
          moreToDo = false;
          leftovers = chars.substring(nextchar, numchars);
          nextchar = saved_scanner_state.pop();
          numchars = saved_scanner_state.pop();
          chars = saved_scanner_state.pop();
          if (leftovers) {
            chars = leftovers + chars.substring(nextchar);
            numchars = chars.length;
            nextchar = 0;
            leftovers = "";
          }
          reentrant_invocations--;
        }
        return moreToDo;
      }
    };
    var doc = new Document2(true, address);
    doc._parser = htmlparser;
    doc._scripting_enabled = scripting_enabled;
    if (fragmentContext) {
      if (fragmentContext.ownerDocument._quirks)
        doc._quirks = true;
      if (fragmentContext.ownerDocument._limitedQuirks)
        doc._limitedQuirks = true;
      if (fragmentContext.namespaceURI === NAMESPACE.HTML) {
        switch (fragmentContext.localName) {
          case "title":
          case "textarea":
            tokenizer = rcdata_state;
            break;
          case "style":
          case "xmp":
          case "iframe":
          case "noembed":
          case "noframes":
          case "script":
          case "plaintext":
            tokenizer = plaintext_state;
            break;
        }
      }
      var root = doc.createElement("html");
      doc._appendChild(root);
      stack.push(root);
      if (fragmentContext instanceof impl.HTMLTemplateElement) {
        templateInsertionModes.push(in_template_mode);
      }
      resetInsertionMode();
      for (var e = fragmentContext;e !== null; e = e.parentElement) {
        if (e instanceof impl.HTMLFormElement) {
          form_element_pointer = e;
          break;
        }
      }
    }
    function scanChars(shouldPauseFunc) {
      var codepoint, s, pattern, eof;
      while (nextchar < numchars) {
        if (paused > 0 || shouldPauseFunc && shouldPauseFunc()) {
          return true;
        }
        switch (typeof tokenizer.lookahead) {
          case "undefined":
            codepoint = chars.charCodeAt(nextchar++);
            if (scanner_skip_newline) {
              scanner_skip_newline = false;
              if (codepoint === 10) {
                nextchar++;
                continue;
              }
            }
            switch (codepoint) {
              case 13:
                if (nextchar < numchars) {
                  if (chars.charCodeAt(nextchar) === 10)
                    nextchar++;
                } else {
                  scanner_skip_newline = true;
                }
                tokenizer(10);
                break;
              case 65535:
                if (input_complete && nextchar === numchars) {
                  tokenizer(EOF);
                  break;
                }
              default:
                tokenizer(codepoint);
                break;
            }
            break;
          case "number":
            codepoint = chars.charCodeAt(nextchar);
            var n = tokenizer.lookahead;
            var needsString = true;
            if (n < 0) {
              needsString = false;
              n = -n;
            }
            if (n < numchars - nextchar) {
              s = needsString ? chars.substring(nextchar, nextchar + n) : null;
              eof = false;
            } else {
              if (input_complete) {
                s = needsString ? chars.substring(nextchar, numchars) : null;
                eof = true;
                if (codepoint === 65535 && nextchar === numchars - 1)
                  codepoint = EOF;
              } else {
                return true;
              }
            }
            tokenizer(codepoint, s, eof);
            break;
          case "string":
            codepoint = chars.charCodeAt(nextchar);
            pattern = tokenizer.lookahead;
            var pos = chars.indexOf(pattern, nextchar);
            if (pos !== -1) {
              s = chars.substring(nextchar, pos + pattern.length);
              eof = false;
            } else {
              if (!input_complete)
                return true;
              s = chars.substring(nextchar, numchars);
              if (codepoint === 65535 && nextchar === numchars - 1)
                codepoint = EOF;
              eof = true;
            }
            tokenizer(codepoint, s, eof);
            break;
        }
      }
      return false;
    }
    function addAttribute(name, value) {
      for (var i = 0;i < attributes.length; i++) {
        if (attributes[i][0] === name)
          return;
      }
      if (value !== undefined) {
        attributes.push([name, value]);
      } else {
        attributes.push([name]);
      }
    }
    function handleSimpleAttribute() {
      SIMPLEATTR.lastIndex = nextchar - 1;
      var matched = SIMPLEATTR.exec(chars);
      if (!matched)
        throw new Error("should never happen");
      var name = matched[1];
      if (!name)
        return false;
      var value = matched[2];
      var len = value.length;
      switch (value[0]) {
        case '"':
        case "'":
          value = value.substring(1, len - 1);
          nextchar += matched[0].length - 1;
          tokenizer = after_attribute_value_quoted_state;
          break;
        default:
          tokenizer = before_attribute_name_state;
          nextchar += matched[0].length - 1;
          value = value.substring(0, len - 1);
          break;
      }
      for (var i = 0;i < attributes.length; i++) {
        if (attributes[i][0] === name)
          return true;
      }
      attributes.push([name, value]);
      return true;
    }
    function beginTagName() {
      is_end_tag = false;
      tagnamebuf = "";
      attributes.length = 0;
    }
    function beginEndTagName() {
      is_end_tag = true;
      tagnamebuf = "";
      attributes.length = 0;
    }
    function beginTempBuf() {
      tempbuf.length = 0;
    }
    function beginAttrName() {
      attrnamebuf = "";
    }
    function beginAttrValue() {
      attrvaluebuf = "";
    }
    function beginComment() {
      commentbuf.length = 0;
    }
    function beginDoctype() {
      doctypenamebuf.length = 0;
      doctypepublicbuf = null;
      doctypesystembuf = null;
    }
    function beginDoctypePublicId() {
      doctypepublicbuf = [];
    }
    function beginDoctypeSystemId() {
      doctypesystembuf = [];
    }
    function forcequirks() {
      force_quirks = true;
    }
    function cdataAllowed() {
      return stack.top && stack.top.namespaceURI !== "http://www.w3.org/1999/xhtml";
    }
    function appropriateEndTag(buf) {
      return lasttagname === buf;
    }
    function flushText() {
      if (textrun.length > 0) {
        var s = buf2str(textrun);
        textrun.length = 0;
        if (ignore_linefeed) {
          ignore_linefeed = false;
          if (s[0] === `
`)
            s = s.substring(1);
          if (s.length === 0)
            return;
        }
        insertToken(TEXT, s);
        textIncludesNUL = false;
      }
      ignore_linefeed = false;
    }
    function getMatchingChars(pattern) {
      pattern.lastIndex = nextchar - 1;
      var match = pattern.exec(chars);
      if (match && match.index === nextchar - 1) {
        match = match[0];
        nextchar += match.length - 1;
        if (input_complete && nextchar === numchars) {
          match = match.slice(0, -1);
          nextchar--;
        }
        return match;
      } else {
        throw new Error("should never happen");
      }
    }
    function emitCharsWhile(pattern) {
      pattern.lastIndex = nextchar - 1;
      var match = pattern.exec(chars)[0];
      if (!match)
        return false;
      emitCharString(match);
      nextchar += match.length - 1;
      return true;
    }
    function emitCharString(s) {
      if (textrun.length > 0)
        flushText();
      if (ignore_linefeed) {
        ignore_linefeed = false;
        if (s[0] === `
`)
          s = s.substring(1);
        if (s.length === 0)
          return;
      }
      insertToken(TEXT, s);
    }
    function emitTag() {
      if (is_end_tag)
        insertToken(ENDTAG, tagnamebuf);
      else {
        var tagname = tagnamebuf;
        tagnamebuf = "";
        lasttagname = tagname;
        insertToken(TAG, tagname, attributes);
      }
    }
    function emitSimpleTag() {
      if (nextchar === numchars) {
        return false;
      }
      SIMPLETAG.lastIndex = nextchar;
      var matched = SIMPLETAG.exec(chars);
      if (!matched)
        throw new Error("should never happen");
      var tagname = matched[2];
      if (!tagname)
        return false;
      var endtag = matched[1];
      if (endtag) {
        nextchar += tagname.length + 2;
        insertToken(ENDTAG, tagname);
      } else {
        nextchar += tagname.length + 1;
        lasttagname = tagname;
        insertToken(TAG, tagname, NOATTRS);
      }
      return true;
    }
    function emitSelfClosingTag() {
      if (is_end_tag)
        insertToken(ENDTAG, tagnamebuf, null, true);
      else {
        insertToken(TAG, tagnamebuf, attributes, true);
      }
    }
    function emitDoctype() {
      insertToken(DOCTYPE, buf2str(doctypenamebuf), doctypepublicbuf ? buf2str(doctypepublicbuf) : undefined, doctypesystembuf ? buf2str(doctypesystembuf) : undefined);
    }
    function emitEOF() {
      flushText();
      parser2(EOF);
      doc.modclock = 1;
    }
    var insertToken = htmlparser.insertToken = function insertToken2(t, value, arg3, arg4) {
      flushText();
      var current = stack.top;
      if (!current || current.namespaceURI === NAMESPACE.HTML) {
        parser2(t, value, arg3, arg4);
      } else {
        if (t !== TAG && t !== TEXT) {
          insertForeignToken(t, value, arg3, arg4);
        } else {
          if (isMathmlTextIntegrationPoint(current) && (t === TEXT || t === TAG && value !== "mglyph" && value !== "malignmark") || t === TAG && value === "svg" && current.namespaceURI === NAMESPACE.MATHML && current.localName === "annotation-xml" || isHTMLIntegrationPoint(current)) {
            text_integration_mode = true;
            parser2(t, value, arg3, arg4);
            text_integration_mode = false;
          } else {
            insertForeignToken(t, value, arg3, arg4);
          }
        }
      }
    };
    function insertComment(data) {
      var parent = stack.top;
      if (foster_parent_mode && isA(parent, tablesectionrowSet)) {
        fosterParent(function(doc2) {
          return doc2.createComment(data);
        });
      } else {
        if (parent instanceof impl.HTMLTemplateElement) {
          parent = parent.content;
        }
        parent._appendChild(parent.ownerDocument.createComment(data));
      }
    }
    function insertText(s) {
      var parent = stack.top;
      if (foster_parent_mode && isA(parent, tablesectionrowSet)) {
        fosterParent(function(doc2) {
          return doc2.createTextNode(s);
        });
      } else {
        if (parent instanceof impl.HTMLTemplateElement) {
          parent = parent.content;
        }
        var lastChild = parent.lastChild;
        if (lastChild && lastChild.nodeType === Node.TEXT_NODE) {
          lastChild.appendData(s);
        } else {
          parent._appendChild(parent.ownerDocument.createTextNode(s));
        }
      }
    }
    function createHTMLElt(doc2, name, attrs) {
      var elt = html.createElement(doc2, name, null);
      if (attrs) {
        for (var i = 0, n = attrs.length;i < n; i++) {
          elt._setAttribute(attrs[i][0], attrs[i][1]);
        }
      }
      return elt;
    }
    var foster_parent_mode = false;
    function insertHTMLElement(name, attrs) {
      var elt = insertElement(function(doc2) {
        return createHTMLElt(doc2, name, attrs);
      });
      if (isA(elt, formassociatedSet)) {
        elt._form = form_element_pointer;
      }
      return elt;
    }
    function insertElement(eltFunc) {
      var elt;
      if (foster_parent_mode && isA(stack.top, tablesectionrowSet)) {
        elt = fosterParent(eltFunc);
      } else if (stack.top instanceof impl.HTMLTemplateElement) {
        elt = eltFunc(stack.top.content.ownerDocument);
        stack.top.content._appendChild(elt);
      } else {
        elt = eltFunc(stack.top.ownerDocument);
        stack.top._appendChild(elt);
      }
      stack.push(elt);
      return elt;
    }
    function insertForeignElement(name, attrs, ns) {
      return insertElement(function(doc2) {
        var elt = doc2._createElementNS(name, ns, null);
        if (attrs) {
          for (var i = 0, n = attrs.length;i < n; i++) {
            var attr = attrs[i];
            if (attr.length === 2)
              elt._setAttribute(attr[0], attr[1]);
            else {
              elt._setAttributeNS(attr[2], attr[0], attr[1]);
            }
          }
        }
        return elt;
      });
    }
    function lastElementOfType(type) {
      for (var i = stack.elements.length - 1;i >= 0; i--) {
        if (stack.elements[i] instanceof type) {
          return i;
        }
      }
      return -1;
    }
    function fosterParent(eltFunc) {
      var parent, before, lastTable = -1, lastTemplate = -1, elt;
      lastTable = lastElementOfType(impl.HTMLTableElement);
      lastTemplate = lastElementOfType(impl.HTMLTemplateElement);
      if (lastTemplate >= 0 && (lastTable < 0 || lastTemplate > lastTable)) {
        parent = stack.elements[lastTemplate];
      } else if (lastTable >= 0) {
        parent = stack.elements[lastTable].parentNode;
        if (parent) {
          before = stack.elements[lastTable];
        } else {
          parent = stack.elements[lastTable - 1];
        }
      }
      if (!parent)
        parent = stack.elements[0];
      if (parent instanceof impl.HTMLTemplateElement) {
        parent = parent.content;
      }
      elt = eltFunc(parent.ownerDocument);
      if (elt.nodeType === Node.TEXT_NODE) {
        var prev;
        if (before)
          prev = before.previousSibling;
        else
          prev = parent.lastChild;
        if (prev && prev.nodeType === Node.TEXT_NODE) {
          prev.appendData(elt.data);
          return elt;
        }
      }
      if (before)
        parent.insertBefore(elt, before);
      else
        parent._appendChild(elt);
      return elt;
    }
    function resetInsertionMode() {
      var last = false;
      for (var i = stack.elements.length - 1;i >= 0; i--) {
        var node = stack.elements[i];
        if (i === 0) {
          last = true;
          if (fragment) {
            node = fragmentContext;
          }
        }
        if (node.namespaceURI === NAMESPACE.HTML) {
          var tag = node.localName;
          switch (tag) {
            case "select":
              for (var j = i;j > 0; ) {
                var ancestor = stack.elements[--j];
                if (ancestor instanceof impl.HTMLTemplateElement) {
                  break;
                } else if (ancestor instanceof impl.HTMLTableElement) {
                  parser2 = in_select_in_table_mode;
                  return;
                }
              }
              parser2 = in_select_mode;
              return;
            case "tr":
              parser2 = in_row_mode;
              return;
            case "tbody":
            case "tfoot":
            case "thead":
              parser2 = in_table_body_mode;
              return;
            case "caption":
              parser2 = in_caption_mode;
              return;
            case "colgroup":
              parser2 = in_column_group_mode;
              return;
            case "table":
              parser2 = in_table_mode;
              return;
            case "template":
              parser2 = templateInsertionModes[templateInsertionModes.length - 1];
              return;
            case "body":
              parser2 = in_body_mode;
              return;
            case "frameset":
              parser2 = in_frameset_mode;
              return;
            case "html":
              if (head_element_pointer === null) {
                parser2 = before_head_mode;
              } else {
                parser2 = after_head_mode;
              }
              return;
            default:
              if (!last) {
                if (tag === "head") {
                  parser2 = in_head_mode;
                  return;
                }
                if (tag === "td" || tag === "th") {
                  parser2 = in_cell_mode;
                  return;
                }
              }
          }
        }
        if (last) {
          parser2 = in_body_mode;
          return;
        }
      }
    }
    function parseRawText(name, attrs) {
      insertHTMLElement(name, attrs);
      tokenizer = rawtext_state;
      originalInsertionMode = parser2;
      parser2 = text_mode;
    }
    function parseRCDATA(name, attrs) {
      insertHTMLElement(name, attrs);
      tokenizer = rcdata_state;
      originalInsertionMode = parser2;
      parser2 = text_mode;
    }
    function afeclone(doc2, i) {
      return {
        elt: createHTMLElt(doc2, afe.list[i].localName, afe.attrs[i]),
        attrs: afe.attrs[i]
      };
    }
    function afereconstruct() {
      if (afe.list.length === 0)
        return;
      var entry = afe.list[afe.list.length - 1];
      if (entry === afe.MARKER)
        return;
      if (stack.elements.lastIndexOf(entry) !== -1)
        return;
      for (var i = afe.list.length - 2;i >= 0; i--) {
        entry = afe.list[i];
        if (entry === afe.MARKER)
          break;
        if (stack.elements.lastIndexOf(entry) !== -1)
          break;
      }
      for (i = i + 1;i < afe.list.length; i++) {
        var newelt = insertElement(function(doc2) {
          return afeclone(doc2, i).elt;
        });
        afe.list[i] = newelt;
      }
    }
    var BOOKMARK = { localName: "BM" };
    function adoptionAgency(tag) {
      if (isA(stack.top, tag) && afe.indexOf(stack.top) === -1) {
        stack.pop();
        return true;
      }
      var outer = 0;
      while (outer < 8) {
        outer++;
        var fmtelt = afe.findElementByTag(tag);
        if (!fmtelt) {
          return false;
        }
        var index = stack.elements.lastIndexOf(fmtelt);
        if (index === -1) {
          afe.remove(fmtelt);
          return true;
        }
        if (!stack.elementInScope(fmtelt)) {
          return true;
        }
        var furthestblock = null, furthestblockindex;
        for (var i = index + 1;i < stack.elements.length; i++) {
          if (isA(stack.elements[i], specialSet)) {
            furthestblock = stack.elements[i];
            furthestblockindex = i;
            break;
          }
        }
        if (!furthestblock) {
          stack.popElement(fmtelt);
          afe.remove(fmtelt);
          return true;
        } else {
          var ancestor = stack.elements[index - 1];
          afe.insertAfter(fmtelt, BOOKMARK);
          var node = furthestblock;
          var lastnode = furthestblock;
          var nodeindex = furthestblockindex;
          var nodeafeindex;
          var inner = 0;
          while (true) {
            inner++;
            node = stack.elements[--nodeindex];
            if (node === fmtelt)
              break;
            nodeafeindex = afe.indexOf(node);
            if (inner > 3 && nodeafeindex !== -1) {
              afe.remove(node);
              nodeafeindex = -1;
            }
            if (nodeafeindex === -1) {
              stack.removeElement(node);
              continue;
            }
            var newelt = afeclone(ancestor.ownerDocument, nodeafeindex);
            afe.replace(node, newelt.elt, newelt.attrs);
            stack.elements[nodeindex] = newelt.elt;
            node = newelt.elt;
            if (lastnode === furthestblock) {
              afe.remove(BOOKMARK);
              afe.insertAfter(newelt.elt, BOOKMARK);
            }
            node._appendChild(lastnode);
            lastnode = node;
          }
          if (foster_parent_mode && isA(ancestor, tablesectionrowSet)) {
            fosterParent(function() {
              return lastnode;
            });
          } else if (ancestor instanceof impl.HTMLTemplateElement) {
            ancestor.content._appendChild(lastnode);
          } else {
            ancestor._appendChild(lastnode);
          }
          var newelt2 = afeclone(furthestblock.ownerDocument, afe.indexOf(fmtelt));
          while (furthestblock.hasChildNodes()) {
            newelt2.elt._appendChild(furthestblock.firstChild);
          }
          furthestblock._appendChild(newelt2.elt);
          afe.remove(fmtelt);
          afe.replace(BOOKMARK, newelt2.elt, newelt2.attrs);
          stack.removeElement(fmtelt);
          var pos = stack.elements.lastIndexOf(furthestblock);
          stack.elements.splice(pos + 1, 0, newelt2.elt);
        }
      }
      return true;
    }
    function handleScriptEnd() {
      stack.pop();
      parser2 = originalInsertionMode;
      return;
    }
    function stopParsing() {
      delete doc._parser;
      stack.elements.length = 0;
      if (doc.defaultView) {
        doc.defaultView.dispatchEvent(new impl.Event("load", {}));
      }
    }
    function reconsume(c, new_state) {
      tokenizer = new_state;
      nextchar--;
    }
    function data_state(c) {
      switch (c) {
        case 38:
          return_state = data_state;
          tokenizer = character_reference_state;
          break;
        case 60:
          if (emitSimpleTag())
            break;
          tokenizer = tag_open_state;
          break;
        case 0:
          textrun.push(c);
          textIncludesNUL = true;
          break;
        case -1:
          emitEOF();
          break;
        default:
          emitCharsWhile(DATATEXT) || textrun.push(c);
          break;
      }
    }
    function rcdata_state(c) {
      switch (c) {
        case 38:
          return_state = rcdata_state;
          tokenizer = character_reference_state;
          break;
        case 60:
          tokenizer = rcdata_less_than_sign_state;
          break;
        case 0:
          textrun.push(65533);
          textIncludesNUL = true;
          break;
        case -1:
          emitEOF();
          break;
        default:
          textrun.push(c);
          break;
      }
    }
    function rawtext_state(c) {
      switch (c) {
        case 60:
          tokenizer = rawtext_less_than_sign_state;
          break;
        case 0:
          textrun.push(65533);
          break;
        case -1:
          emitEOF();
          break;
        default:
          emitCharsWhile(RAWTEXT) || textrun.push(c);
          break;
      }
    }
    function script_data_state(c) {
      switch (c) {
        case 60:
          tokenizer = script_data_less_than_sign_state;
          break;
        case 0:
          textrun.push(65533);
          break;
        case -1:
          emitEOF();
          break;
        default:
          emitCharsWhile(RAWTEXT) || textrun.push(c);
          break;
      }
    }
    function plaintext_state(c) {
      switch (c) {
        case 0:
          textrun.push(65533);
          break;
        case -1:
          emitEOF();
          break;
        default:
          emitCharsWhile(PLAINTEXT) || textrun.push(c);
          break;
      }
    }
    function tag_open_state(c) {
      switch (c) {
        case 33:
          tokenizer = markup_declaration_open_state;
          break;
        case 47:
          tokenizer = end_tag_open_state;
          break;
        case 65:
        case 66:
        case 67:
        case 68:
        case 69:
        case 70:
        case 71:
        case 72:
        case 73:
        case 74:
        case 75:
        case 76:
        case 77:
        case 78:
        case 79:
        case 80:
        case 81:
        case 82:
        case 83:
        case 84:
        case 85:
        case 86:
        case 87:
        case 88:
        case 89:
        case 90:
        case 97:
        case 98:
        case 99:
        case 100:
        case 101:
        case 102:
        case 103:
        case 104:
        case 105:
        case 106:
        case 107:
        case 108:
        case 109:
        case 110:
        case 111:
        case 112:
        case 113:
        case 114:
        case 115:
        case 116:
        case 117:
        case 118:
        case 119:
        case 120:
        case 121:
        case 122:
          beginTagName();
          reconsume(c, tag_name_state);
          break;
        case 63:
          reconsume(c, bogus_comment_state);
          break;
        default:
          textrun.push(60);
          reconsume(c, data_state);
          break;
      }
    }
    function end_tag_open_state(c) {
      switch (c) {
        case 65:
        case 66:
        case 67:
        case 68:
        case 69:
        case 70:
        case 71:
        case 72:
        case 73:
        case 74:
        case 75:
        case 76:
        case 77:
        case 78:
        case 79:
        case 80:
        case 81:
        case 82:
        case 83:
        case 84:
        case 85:
        case 86:
        case 87:
        case 88:
        case 89:
        case 90:
        case 97:
        case 98:
        case 99:
        case 100:
        case 101:
        case 102:
        case 103:
        case 104:
        case 105:
        case 106:
        case 107:
        case 108:
        case 109:
        case 110:
        case 111:
        case 112:
        case 113:
        case 114:
        case 115:
        case 116:
        case 117:
        case 118:
        case 119:
        case 120:
        case 121:
        case 122:
          beginEndTagName();
          reconsume(c, tag_name_state);
          break;
        case 62:
          tokenizer = data_state;
          break;
        case -1:
          textrun.push(60);
          textrun.push(47);
          emitEOF();
          break;
        default:
          reconsume(c, bogus_comment_state);
          break;
      }
    }
    function tag_name_state(c) {
      switch (c) {
        case 9:
        case 10:
        case 12:
        case 32:
          tokenizer = before_attribute_name_state;
          break;
        case 47:
          tokenizer = self_closing_start_tag_state;
          break;
        case 62:
          tokenizer = data_state;
          emitTag();
          break;
        case 65:
        case 66:
        case 67:
        case 68:
        case 69:
        case 70:
        case 71:
        case 72:
        case 73:
        case 74:
        case 75:
        case 76:
        case 77:
        case 78:
        case 79:
        case 80:
        case 81:
        case 82:
        case 83:
        case 84:
        case 85:
        case 86:
        case 87:
        case 88:
        case 89:
        case 90:
          tagnamebuf += String.fromCharCode(c + 32);
          break;
        case 0:
          tagnamebuf += String.fromCharCode(65533);
          break;
        case -1:
          emitEOF();
          break;
        default:
          tagnamebuf += getMatchingChars(TAGNAME);
          break;
      }
    }
    function rcdata_less_than_sign_state(c) {
      if (c === 47) {
        beginTempBuf();
        tokenizer = rcdata_end_tag_open_state;
      } else {
        textrun.push(60);
        reconsume(c, rcdata_state);
      }
    }
    function rcdata_end_tag_open_state(c) {
      switch (c) {
        case 65:
        case 66:
        case 67:
        case 68:
        case 69:
        case 70:
        case 71:
        case 72:
        case 73:
        case 74:
        case 75:
        case 76:
        case 77:
        case 78:
        case 79:
        case 80:
        case 81:
        case 82:
        case 83:
        case 84:
        case 85:
        case 86:
        case 87:
        case 88:
        case 89:
        case 90:
        case 97:
        case 98:
        case 99:
        case 100:
        case 101:
        case 102:
        case 103:
        case 104:
        case 105:
        case 106:
        case 107:
        case 108:
        case 109:
        case 110:
        case 111:
        case 112:
        case 113:
        case 114:
        case 115:
        case 116:
        case 117:
        case 118:
        case 119:
        case 120:
        case 121:
        case 122:
          beginEndTagName();
          reconsume(c, rcdata_end_tag_name_state);
          break;
        default:
          textrun.push(60);
          textrun.push(47);
          reconsume(c, rcdata_state);
          break;
      }
    }
    function rcdata_end_tag_name_state(c) {
      switch (c) {
        case 9:
        case 10:
        case 12:
        case 32:
          if (appropriateEndTag(tagnamebuf)) {
            tokenizer = before_attribute_name_state;
            return;
          }
          break;
        case 47:
          if (appropriateEndTag(tagnamebuf)) {
            tokenizer = self_closing_start_tag_state;
            return;
          }
          break;
        case 62:
          if (appropriateEndTag(tagnamebuf)) {
            tokenizer = data_state;
            emitTag();
            return;
          }
          break;
        case 65:
        case 66:
        case 67:
        case 68:
        case 69:
        case 70:
        case 71:
        case 72:
        case 73:
        case 74:
        case 75:
        case 76:
        case 77:
        case 78:
        case 79:
        case 80:
        case 81:
        case 82:
        case 83:
        case 84:
        case 85:
        case 86:
        case 87:
        case 88:
        case 89:
        case 90:
          tagnamebuf += String.fromCharCode(c + 32);
          tempbuf.push(c);
          return;
        case 97:
        case 98:
        case 99:
        case 100:
        case 101:
        case 102:
        case 103:
        case 104:
        case 105:
        case 106:
        case 107:
        case 108:
        case 109:
        case 110:
        case 111:
        case 112:
        case 113:
        case 114:
        case 115:
        case 116:
        case 117:
        case 118:
        case 119:
        case 120:
        case 121:
        case 122:
          tagnamebuf += String.fromCharCode(c);
          tempbuf.push(c);
          return;
        default:
          break;
      }
      textrun.push(60);
      textrun.push(47);
      pushAll(textrun, tempbuf);
      reconsume(c, rcdata_state);
    }
    function rawtext_less_than_sign_state(c) {
      if (c === 47) {
        beginTempBuf();
        tokenizer = rawtext_end_tag_open_state;
      } else {
        textrun.push(60);
        reconsume(c, rawtext_state);
      }
    }
    function rawtext_end_tag_open_state(c) {
      switch (c) {
        case 65:
        case 66:
        case 67:
        case 68:
        case 69:
        case 70:
        case 71:
        case 72:
        case 73:
        case 74:
        case 75:
        case 76:
        case 77:
        case 78:
        case 79:
        case 80:
        case 81:
        case 82:
        case 83:
        case 84:
        case 85:
        case 86:
        case 87:
        case 88:
        case 89:
        case 90:
        case 97:
        case 98:
        case 99:
        case 100:
        case 101:
        case 102:
        case 103:
        case 104:
        case 105:
        case 106:
        case 107:
        case 108:
        case 109:
        case 110:
        case 111:
        case 112:
        case 113:
        case 114:
        case 115:
        case 116:
        case 117:
        case 118:
        case 119:
        case 120:
        case 121:
        case 122:
          beginEndTagName();
          reconsume(c, rawtext_end_tag_name_state);
          break;
        default:
          textrun.push(60);
          textrun.push(47);
          reconsume(c, rawtext_state);
          break;
      }
    }
    function rawtext_end_tag_name_state(c) {
      switch (c) {
        case 9:
        case 10:
        case 12:
        case 32:
          if (appropriateEndTag(tagnamebuf)) {
            tokenizer = before_attribute_name_state;
            return;
          }
          break;
        case 47:
          if (appropriateEndTag(tagnamebuf)) {
            tokenizer = self_closing_start_tag_state;
            return;
          }
          break;
        case 62:
          if (appropriateEndTag(tagnamebuf)) {
            tokenizer = data_state;
            emitTag();
            return;
          }
          break;
        case 65:
        case 66:
        case 67:
        case 68:
        case 69:
        case 70:
        case 71:
        case 72:
        case 73:
        case 74:
        case 75:
        case 76:
        case 77:
        case 78:
        case 79:
        case 80:
        case 81:
        case 82:
        case 83:
        case 84:
        case 85:
        case 86:
        case 87:
        case 88:
        case 89:
        case 90:
          tagnamebuf += String.fromCharCode(c + 32);
          tempbuf.push(c);
          return;
        case 97:
        case 98:
        case 99:
        case 100:
        case 101:
        case 102:
        case 103:
        case 104:
        case 105:
        case 106:
        case 107:
        case 108:
        case 109:
        case 110:
        case 111:
        case 112:
        case 113:
        case 114:
        case 115:
        case 116:
        case 117:
        case 118:
        case 119:
        case 120:
        case 121:
        case 122:
          tagnamebuf += String.fromCharCode(c);
          tempbuf.push(c);
          return;
        default:
          break;
      }
      textrun.push(60);
      textrun.push(47);
      pushAll(textrun, tempbuf);
      reconsume(c, rawtext_state);
    }
    function script_data_less_than_sign_state(c) {
      switch (c) {
        case 47:
          beginTempBuf();
          tokenizer = script_data_end_tag_open_state;
          break;
        case 33:
          tokenizer = script_data_escape_start_state;
          textrun.push(60);
          textrun.push(33);
          break;
        default:
          textrun.push(60);
          reconsume(c, script_data_state);
          break;
      }
    }
    function script_data_end_tag_open_state(c) {
      switch (c) {
        case 65:
        case 66:
        case 67:
        case 68:
        case 69:
        case 70:
        case 71:
        case 72:
        case 73:
        case 74:
        case 75:
        case 76:
        case 77:
        case 78:
        case 79:
        case 80:
        case 81:
        case 82:
        case 83:
        case 84:
        case 85:
        case 86:
        case 87:
        case 88:
        case 89:
        case 90:
        case 97:
        case 98:
        case 99:
        case 100:
        case 101:
        case 102:
        case 103:
        case 104:
        case 105:
        case 106:
        case 107:
        case 108:
        case 109:
        case 110:
        case 111:
        case 112:
        case 113:
        case 114:
        case 115:
        case 116:
        case 117:
        case 118:
        case 119:
        case 120:
        case 121:
        case 122:
          beginEndTagName();
          reconsume(c, script_data_end_tag_name_state);
          break;
        default:
          textrun.push(60);
          textrun.push(47);
          reconsume(c, script_data_state);
          break;
      }
    }
    function script_data_end_tag_name_state(c) {
      switch (c) {
        case 9:
        case 10:
        case 12:
        case 32:
          if (appropriateEndTag(tagnamebuf)) {
            tokenizer = before_attribute_name_state;
            return;
          }
          break;
        case 47:
          if (appropriateEndTag(tagnamebuf)) {
            tokenizer = self_closing_start_tag_state;
            return;
          }
          break;
        case 62:
          if (appropriateEndTag(tagnamebuf)) {
            tokenizer = data_state;
            emitTag();
            return;
          }
          break;
        case 65:
        case 66:
        case 67:
        case 68:
        case 69:
        case 70:
        case 71:
        case 72:
        case 73:
        case 74:
        case 75:
        case 76:
        case 77:
        case 78:
        case 79:
        case 80:
        case 81:
        case 82:
        case 83:
        case 84:
        case 85:
        case 86:
        case 87:
        case 88:
        case 89:
        case 90:
          tagnamebuf += String.fromCharCode(c + 32);
          tempbuf.push(c);
          return;
        case 97:
        case 98:
        case 99:
        case 100:
        case 101:
        case 102:
        case 103:
        case 104:
        case 105:
        case 106:
        case 107:
        case 108:
        case 109:
        case 110:
        case 111:
        case 112:
        case 113:
        case 114:
        case 115:
        case 116:
        case 117:
        case 118:
        case 119:
        case 120:
        case 121:
        case 122:
          tagnamebuf += String.fromCharCode(c);
          tempbuf.push(c);
          return;
        default:
          break;
      }
      textrun.push(60);
      textrun.push(47);
      pushAll(textrun, tempbuf);
      reconsume(c, script_data_state);
    }
    function script_data_escape_start_state(c) {
      if (c === 45) {
        tokenizer = script_data_escape_start_dash_state;
        textrun.push(45);
      } else {
        reconsume(c, script_data_state);
      }
    }
    function script_data_escape_start_dash_state(c) {
      if (c === 45) {
        tokenizer = script_data_escaped_dash_dash_state;
        textrun.push(45);
      } else {
        reconsume(c, script_data_state);
      }
    }
    function script_data_escaped_state(c) {
      switch (c) {
        case 45:
          tokenizer = script_data_escaped_dash_state;
          textrun.push(45);
          break;
        case 60:
          tokenizer = script_data_escaped_less_than_sign_state;
          break;
        case 0:
          textrun.push(65533);
          break;
        case -1:
          emitEOF();
          break;
        default:
          textrun.push(c);
          break;
      }
    }
    function script_data_escaped_dash_state(c) {
      switch (c) {
        case 45:
          tokenizer = script_data_escaped_dash_dash_state;
          textrun.push(45);
          break;
        case 60:
          tokenizer = script_data_escaped_less_than_sign_state;
          break;
        case 0:
          tokenizer = script_data_escaped_state;
          textrun.push(65533);
          break;
        case -1:
          emitEOF();
          break;
        default:
          tokenizer = script_data_escaped_state;
          textrun.push(c);
          break;
      }
    }
    function script_data_escaped_dash_dash_state(c) {
      switch (c) {
        case 45:
          textrun.push(45);
          break;
        case 60:
          tokenizer = script_data_escaped_less_than_sign_state;
          break;
        case 62:
          tokenizer = script_data_state;
          textrun.push(62);
          break;
        case 0:
          tokenizer = script_data_escaped_state;
          textrun.push(65533);
          break;
        case -1:
          emitEOF();
          break;
        default:
          tokenizer = script_data_escaped_state;
          textrun.push(c);
          break;
      }
    }
    function script_data_escaped_less_than_sign_state(c) {
      switch (c) {
        case 47:
          beginTempBuf();
          tokenizer = script_data_escaped_end_tag_open_state;
          break;
        case 65:
        case 66:
        case 67:
        case 68:
        case 69:
        case 70:
        case 71:
        case 72:
        case 73:
        case 74:
        case 75:
        case 76:
        case 77:
        case 78:
        case 79:
        case 80:
        case 81:
        case 82:
        case 83:
        case 84:
        case 85:
        case 86:
        case 87:
        case 88:
        case 89:
        case 90:
        case 97:
        case 98:
        case 99:
        case 100:
        case 101:
        case 102:
        case 103:
        case 104:
        case 105:
        case 106:
        case 107:
        case 108:
        case 109:
        case 110:
        case 111:
        case 112:
        case 113:
        case 114:
        case 115:
        case 116:
        case 117:
        case 118:
        case 119:
        case 120:
        case 121:
        case 122:
          beginTempBuf();
          textrun.push(60);
          reconsume(c, script_data_double_escape_start_state);
          break;
        default:
          textrun.push(60);
          reconsume(c, script_data_escaped_state);
          break;
      }
    }
    function script_data_escaped_end_tag_open_state(c) {
      switch (c) {
        case 65:
        case 66:
        case 67:
        case 68:
        case 69:
        case 70:
        case 71:
        case 72:
        case 73:
        case 74:
        case 75:
        case 76:
        case 77:
        case 78:
        case 79:
        case 80:
        case 81:
        case 82:
        case 83:
        case 84:
        case 85:
        case 86:
        case 87:
        case 88:
        case 89:
        case 90:
        case 97:
        case 98:
        case 99:
        case 100:
        case 101:
        case 102:
        case 103:
        case 104:
        case 105:
        case 106:
        case 107:
        case 108:
        case 109:
        case 110:
        case 111:
        case 112:
        case 113:
        case 114:
        case 115:
        case 116:
        case 117:
        case 118:
        case 119:
        case 120:
        case 121:
        case 122:
          beginEndTagName();
          reconsume(c, script_data_escaped_end_tag_name_state);
          break;
        default:
          textrun.push(60);
          textrun.push(47);
          reconsume(c, script_data_escaped_state);
          break;
      }
    }
    function script_data_escaped_end_tag_name_state(c) {
      switch (c) {
        case 9:
        case 10:
        case 12:
        case 32:
          if (appropriateEndTag(tagnamebuf)) {
            tokenizer = before_attribute_name_state;
            return;
          }
          break;
        case 47:
          if (appropriateEndTag(tagnamebuf)) {
            tokenizer = self_closing_start_tag_state;
            return;
          }
          break;
        case 62:
          if (appropriateEndTag(tagnamebuf)) {
            tokenizer = data_state;
            emitTag();
            return;
          }
          break;
        case 65:
        case 66:
        case 67:
        case 68:
        case 69:
        case 70:
        case 71:
        case 72:
        case 73:
        case 74:
        case 75:
        case 76:
        case 77:
        case 78:
        case 79:
        case 80:
        case 81:
        case 82:
        case 83:
        case 84:
        case 85:
        case 86:
        case 87:
        case 88:
        case 89:
        case 90:
          tagnamebuf += String.fromCharCode(c + 32);
          tempbuf.push(c);
          return;
        case 97:
        case 98:
        case 99:
        case 100:
        case 101:
        case 102:
        case 103:
        case 104:
        case 105:
        case 106:
        case 107:
        case 108:
        case 109:
        case 110:
        case 111:
        case 112:
        case 113:
        case 114:
        case 115:
        case 116:
        case 117:
        case 118:
        case 119:
        case 120:
        case 121:
        case 122:
          tagnamebuf += String.fromCharCode(c);
          tempbuf.push(c);
          return;
        default:
          break;
      }
      textrun.push(60);
      textrun.push(47);
      pushAll(textrun, tempbuf);
      reconsume(c, script_data_escaped_state);
    }
    function script_data_double_escape_start_state(c) {
      switch (c) {
        case 9:
        case 10:
        case 12:
        case 32:
        case 47:
        case 62:
          if (buf2str(tempbuf) === "script") {
            tokenizer = script_data_double_escaped_state;
          } else {
            tokenizer = script_data_escaped_state;
          }
          textrun.push(c);
          break;
        case 65:
        case 66:
        case 67:
        case 68:
        case 69:
        case 70:
        case 71:
        case 72:
        case 73:
        case 74:
        case 75:
        case 76:
        case 77:
        case 78:
        case 79:
        case 80:
        case 81:
        case 82:
        case 83:
        case 84:
        case 85:
        case 86:
        case 87:
        case 88:
        case 89:
        case 90:
          tempbuf.push(c + 32);
          textrun.push(c);
          break;
        case 97:
        case 98:
        case 99:
        case 100:
        case 101:
        case 102:
        case 103:
        case 104:
        case 105:
        case 106:
        case 107:
        case 108:
        case 109:
        case 110:
        case 111:
        case 112:
        case 113:
        case 114:
        case 115:
        case 116:
        case 117:
        case 118:
        case 119:
        case 120:
        case 121:
        case 122:
          tempbuf.push(c);
          textrun.push(c);
          break;
        default:
          reconsume(c, script_data_escaped_state);
          break;
      }
    }
    function script_data_double_escaped_state(c) {
      switch (c) {
        case 45:
          tokenizer = script_data_double_escaped_dash_state;
          textrun.push(45);
          break;
        case 60:
          tokenizer = script_data_double_escaped_less_than_sign_state;
          textrun.push(60);
          break;
        case 0:
          textrun.push(65533);
          break;
        case -1:
          emitEOF();
          break;
        default:
          textrun.push(c);
          break;
      }
    }
    function script_data_double_escaped_dash_state(c) {
      switch (c) {
        case 45:
          tokenizer = script_data_double_escaped_dash_dash_state;
          textrun.push(45);
          break;
        case 60:
          tokenizer = script_data_double_escaped_less_than_sign_state;
          textrun.push(60);
          break;
        case 0:
          tokenizer = script_data_double_escaped_state;
          textrun.push(65533);
          break;
        case -1:
          emitEOF();
          break;
        default:
          tokenizer = script_data_double_escaped_state;
          textrun.push(c);
          break;
      }
    }
    function script_data_double_escaped_dash_dash_state(c) {
      switch (c) {
        case 45:
          textrun.push(45);
          break;
        case 60:
          tokenizer = script_data_double_escaped_less_than_sign_state;
          textrun.push(60);
          break;
        case 62:
          tokenizer = script_data_state;
          textrun.push(62);
          break;
        case 0:
          tokenizer = script_data_double_escaped_state;
          textrun.push(65533);
          break;
        case -1:
          emitEOF();
          break;
        default:
          tokenizer = script_data_double_escaped_state;
          textrun.push(c);
          break;
      }
    }
    function script_data_double_escaped_less_than_sign_state(c) {
      if (c === 47) {
        beginTempBuf();
        tokenizer = script_data_double_escape_end_state;
        textrun.push(47);
      } else {
        reconsume(c, script_data_double_escaped_state);
      }
    }
    function script_data_double_escape_end_state(c) {
      switch (c) {
        case 9:
        case 10:
        case 12:
        case 32:
        case 47:
        case 62:
          if (buf2str(tempbuf) === "script") {
            tokenizer = script_data_escaped_state;
          } else {
            tokenizer = script_data_double_escaped_state;
          }
          textrun.push(c);
          break;
        case 65:
        case 66:
        case 67:
        case 68:
        case 69:
        case 70:
        case 71:
        case 72:
        case 73:
        case 74:
        case 75:
        case 76:
        case 77:
        case 78:
        case 79:
        case 80:
        case 81:
        case 82:
        case 83:
        case 84:
        case 85:
        case 86:
        case 87:
        case 88:
        case 89:
        case 90:
          tempbuf.push(c + 32);
          textrun.push(c);
          break;
        case 97:
        case 98:
        case 99:
        case 100:
        case 101:
        case 102:
        case 103:
        case 104:
        case 105:
        case 106:
        case 107:
        case 108:
        case 109:
        case 110:
        case 111:
        case 112:
        case 113:
        case 114:
        case 115:
        case 116:
        case 117:
        case 118:
        case 119:
        case 120:
        case 121:
        case 122:
          tempbuf.push(c);
          textrun.push(c);
          break;
        default:
          reconsume(c, script_data_double_escaped_state);
          break;
      }
    }
    function before_attribute_name_state(c) {
      switch (c) {
        case 9:
        case 10:
        case 12:
        case 32:
          break;
        case 47:
          tokenizer = self_closing_start_tag_state;
          break;
        case 62:
          tokenizer = data_state;
          emitTag();
          break;
        case -1:
          emitEOF();
          break;
        case 61:
          beginAttrName();
          attrnamebuf += String.fromCharCode(c);
          tokenizer = attribute_name_state;
          break;
        default:
          if (handleSimpleAttribute())
            break;
          beginAttrName();
          reconsume(c, attribute_name_state);
          break;
      }
    }
    function attribute_name_state(c) {
      switch (c) {
        case 9:
        case 10:
        case 12:
        case 32:
        case 47:
        case 62:
        case -1:
          reconsume(c, after_attribute_name_state);
          break;
        case 61:
          tokenizer = before_attribute_value_state;
          break;
        case 65:
        case 66:
        case 67:
        case 68:
        case 69:
        case 70:
        case 71:
        case 72:
        case 73:
        case 74:
        case 75:
        case 76:
        case 77:
        case 78:
        case 79:
        case 80:
        case 81:
        case 82:
        case 83:
        case 84:
        case 85:
        case 86:
        case 87:
        case 88:
        case 89:
        case 90:
          attrnamebuf += String.fromCharCode(c + 32);
          break;
        case 0:
          attrnamebuf += String.fromCharCode(65533);
          break;
        case 34:
        case 39:
        case 60:
        default:
          attrnamebuf += getMatchingChars(ATTRNAME);
          break;
      }
    }
    function after_attribute_name_state(c) {
      switch (c) {
        case 9:
        case 10:
        case 12:
        case 32:
          break;
        case 47:
          addAttribute(attrnamebuf);
          tokenizer = self_closing_start_tag_state;
          break;
        case 61:
          tokenizer = before_attribute_value_state;
          break;
        case 62:
          tokenizer = data_state;
          addAttribute(attrnamebuf);
          emitTag();
          break;
        case -1:
          addAttribute(attrnamebuf);
          emitEOF();
          break;
        default:
          addAttribute(attrnamebuf);
          beginAttrName();
          reconsume(c, attribute_name_state);
          break;
      }
    }
    function before_attribute_value_state(c) {
      switch (c) {
        case 9:
        case 10:
        case 12:
        case 32:
          break;
        case 34:
          beginAttrValue();
          tokenizer = attribute_value_double_quoted_state;
          break;
        case 39:
          beginAttrValue();
          tokenizer = attribute_value_single_quoted_state;
          break;
        case 62:
        default:
          beginAttrValue();
          reconsume(c, attribute_value_unquoted_state);
          break;
      }
    }
    function attribute_value_double_quoted_state(c) {
      switch (c) {
        case 34:
          addAttribute(attrnamebuf, attrvaluebuf);
          tokenizer = after_attribute_value_quoted_state;
          break;
        case 38:
          return_state = attribute_value_double_quoted_state;
          tokenizer = character_reference_state;
          break;
        case 0:
          attrvaluebuf += String.fromCharCode(65533);
          break;
        case -1:
          emitEOF();
          break;
        case 10:
          attrvaluebuf += String.fromCharCode(c);
          break;
        default:
          attrvaluebuf += getMatchingChars(DBLQUOTEATTRVAL);
          break;
      }
    }
    function attribute_value_single_quoted_state(c) {
      switch (c) {
        case 39:
          addAttribute(attrnamebuf, attrvaluebuf);
          tokenizer = after_attribute_value_quoted_state;
          break;
        case 38:
          return_state = attribute_value_single_quoted_state;
          tokenizer = character_reference_state;
          break;
        case 0:
          attrvaluebuf += String.fromCharCode(65533);
          break;
        case -1:
          emitEOF();
          break;
        case 10:
          attrvaluebuf += String.fromCharCode(c);
          break;
        default:
          attrvaluebuf += getMatchingChars(SINGLEQUOTEATTRVAL);
          break;
      }
    }
    function attribute_value_unquoted_state(c) {
      switch (c) {
        case 9:
        case 10:
        case 12:
        case 32:
          addAttribute(attrnamebuf, attrvaluebuf);
          tokenizer = before_attribute_name_state;
          break;
        case 38:
          return_state = attribute_value_unquoted_state;
          tokenizer = character_reference_state;
          break;
        case 62:
          addAttribute(attrnamebuf, attrvaluebuf);
          tokenizer = data_state;
          emitTag();
          break;
        case 0:
          attrvaluebuf += String.fromCharCode(65533);
          break;
        case -1:
          nextchar--;
          tokenizer = data_state;
          break;
        case 34:
        case 39:
        case 60:
        case 61:
        case 96:
        default:
          attrvaluebuf += getMatchingChars(UNQUOTEDATTRVAL);
          break;
      }
    }
    function after_attribute_value_quoted_state(c) {
      switch (c) {
        case 9:
        case 10:
        case 12:
        case 32:
          tokenizer = before_attribute_name_state;
          break;
        case 47:
          tokenizer = self_closing_start_tag_state;
          break;
        case 62:
          tokenizer = data_state;
          emitTag();
          break;
        case -1:
          emitEOF();
          break;
        default:
          reconsume(c, before_attribute_name_state);
          break;
      }
    }
    function self_closing_start_tag_state(c) {
      switch (c) {
        case 62:
          tokenizer = data_state;
          emitSelfClosingTag(true);
          break;
        case -1:
          emitEOF();
          break;
        default:
          reconsume(c, before_attribute_name_state);
          break;
      }
    }
    function bogus_comment_state(c, lookahead, eof) {
      var len = lookahead.length;
      if (eof) {
        nextchar += len - 1;
      } else {
        nextchar += len;
      }
      var comment = lookahead.substring(0, len - 1);
      comment = comment.replace(/\u0000/g, "�");
      comment = comment.replace(/\u000D\u000A/g, `
`);
      comment = comment.replace(/\u000D/g, `
`);
      insertToken(COMMENT, comment);
      tokenizer = data_state;
    }
    bogus_comment_state.lookahead = ">";
    function markup_declaration_open_state(c, lookahead, eof) {
      if (lookahead[0] === "-" && lookahead[1] === "-") {
        nextchar += 2;
        beginComment();
        tokenizer = comment_start_state;
        return;
      }
      if (lookahead.toUpperCase() === "DOCTYPE") {
        nextchar += 7;
        tokenizer = doctype_state;
      } else if (lookahead === "[CDATA[" && cdataAllowed()) {
        nextchar += 7;
        tokenizer = cdata_section_state;
      } else {
        tokenizer = bogus_comment_state;
      }
    }
    markup_declaration_open_state.lookahead = 7;
    function comment_start_state(c) {
      beginComment();
      switch (c) {
        case 45:
          tokenizer = comment_start_dash_state;
          break;
        case 62:
          tokenizer = data_state;
          insertToken(COMMENT, buf2str(commentbuf));
          break;
        default:
          reconsume(c, comment_state);
          break;
      }
    }
    function comment_start_dash_state(c) {
      switch (c) {
        case 45:
          tokenizer = comment_end_state;
          break;
        case 62:
          tokenizer = data_state;
          insertToken(COMMENT, buf2str(commentbuf));
          break;
        case -1:
          insertToken(COMMENT, buf2str(commentbuf));
          emitEOF();
          break;
        default:
          commentbuf.push(45);
          reconsume(c, comment_state);
          break;
      }
    }
    function comment_state(c) {
      switch (c) {
        case 60:
          commentbuf.push(c);
          tokenizer = comment_less_than_sign_state;
          break;
        case 45:
          tokenizer = comment_end_dash_state;
          break;
        case 0:
          commentbuf.push(65533);
          break;
        case -1:
          insertToken(COMMENT, buf2str(commentbuf));
          emitEOF();
          break;
        default:
          commentbuf.push(c);
          break;
      }
    }
    function comment_less_than_sign_state(c) {
      switch (c) {
        case 33:
          commentbuf.push(c);
          tokenizer = comment_less_than_sign_bang_state;
          break;
        case 60:
          commentbuf.push(c);
          break;
        default:
          reconsume(c, comment_state);
          break;
      }
    }
    function comment_less_than_sign_bang_state(c) {
      switch (c) {
        case 45:
          tokenizer = comment_less_than_sign_bang_dash_state;
          break;
        default:
          reconsume(c, comment_state);
          break;
      }
    }
    function comment_less_than_sign_bang_dash_state(c) {
      switch (c) {
        case 45:
          tokenizer = comment_less_than_sign_bang_dash_dash_state;
          break;
        default:
          reconsume(c, comment_end_dash_state);
          break;
      }
    }
    function comment_less_than_sign_bang_dash_dash_state(c) {
      switch (c) {
        case 62:
        case -1:
          reconsume(c, comment_end_state);
          break;
        default:
          reconsume(c, comment_end_state);
          break;
      }
    }
    function comment_end_dash_state(c) {
      switch (c) {
        case 45:
          tokenizer = comment_end_state;
          break;
        case -1:
          insertToken(COMMENT, buf2str(commentbuf));
          emitEOF();
          break;
        default:
          commentbuf.push(45);
          reconsume(c, comment_state);
          break;
      }
    }
    function comment_end_state(c) {
      switch (c) {
        case 62:
          tokenizer = data_state;
          insertToken(COMMENT, buf2str(commentbuf));
          break;
        case 33:
          tokenizer = comment_end_bang_state;
          break;
        case 45:
          commentbuf.push(45);
          break;
        case -1:
          insertToken(COMMENT, buf2str(commentbuf));
          emitEOF();
          break;
        default:
          commentbuf.push(45);
          commentbuf.push(45);
          reconsume(c, comment_state);
          break;
      }
    }
    function comment_end_bang_state(c) {
      switch (c) {
        case 45:
          commentbuf.push(45);
          commentbuf.push(45);
          commentbuf.push(33);
          tokenizer = comment_end_dash_state;
          break;
        case 62:
          tokenizer = data_state;
          insertToken(COMMENT, buf2str(commentbuf));
          break;
        case -1:
          insertToken(COMMENT, buf2str(commentbuf));
          emitEOF();
          break;
        default:
          commentbuf.push(45);
          commentbuf.push(45);
          commentbuf.push(33);
          reconsume(c, comment_state);
          break;
      }
    }
    function doctype_state(c) {
      switch (c) {
        case 9:
        case 10:
        case 12:
        case 32:
          tokenizer = before_doctype_name_state;
          break;
        case -1:
          beginDoctype();
          forcequirks();
          emitDoctype();
          emitEOF();
          break;
        default:
          reconsume(c, before_doctype_name_state);
          break;
      }
    }
    function before_doctype_name_state(c) {
      switch (c) {
        case 9:
        case 10:
        case 12:
        case 32:
          break;
        case 65:
        case 66:
        case 67:
        case 68:
        case 69:
        case 70:
        case 71:
        case 72:
        case 73:
        case 74:
        case 75:
        case 76:
        case 77:
        case 78:
        case 79:
        case 80:
        case 81:
        case 82:
        case 83:
        case 84:
        case 85:
        case 86:
        case 87:
        case 88:
        case 89:
        case 90:
          beginDoctype();
          doctypenamebuf.push(c + 32);
          tokenizer = doctype_name_state;
          break;
        case 0:
          beginDoctype();
          doctypenamebuf.push(65533);
          tokenizer = doctype_name_state;
          break;
        case 62:
          beginDoctype();
          forcequirks();
          tokenizer = data_state;
          emitDoctype();
          break;
        case -1:
          beginDoctype();
          forcequirks();
          emitDoctype();
          emitEOF();
          break;
        default:
          beginDoctype();
          doctypenamebuf.push(c);
          tokenizer = doctype_name_state;
          break;
      }
    }
    function doctype_name_state(c) {
      switch (c) {
        case 9:
        case 10:
        case 12:
        case 32:
          tokenizer = after_doctype_name_state;
          break;
        case 62:
          tokenizer = data_state;
          emitDoctype();
          break;
        case 65:
        case 66:
        case 67:
        case 68:
        case 69:
        case 70:
        case 71:
        case 72:
        case 73:
        case 74:
        case 75:
        case 76:
        case 77:
        case 78:
        case 79:
        case 80:
        case 81:
        case 82:
        case 83:
        case 84:
        case 85:
        case 86:
        case 87:
        case 88:
        case 89:
        case 90:
          doctypenamebuf.push(c + 32);
          break;
        case 0:
          doctypenamebuf.push(65533);
          break;
        case -1:
          forcequirks();
          emitDoctype();
          emitEOF();
          break;
        default:
          doctypenamebuf.push(c);
          break;
      }
    }
    function after_doctype_name_state(c, lookahead, eof) {
      switch (c) {
        case 9:
        case 10:
        case 12:
        case 32:
          nextchar += 1;
          break;
        case 62:
          tokenizer = data_state;
          nextchar += 1;
          emitDoctype();
          break;
        case -1:
          forcequirks();
          emitDoctype();
          emitEOF();
          break;
        default:
          lookahead = lookahead.toUpperCase();
          if (lookahead === "PUBLIC") {
            nextchar += 6;
            tokenizer = after_doctype_public_keyword_state;
          } else if (lookahead === "SYSTEM") {
            nextchar += 6;
            tokenizer = after_doctype_system_keyword_state;
          } else {
            forcequirks();
            tokenizer = bogus_doctype_state;
          }
          break;
      }
    }
    after_doctype_name_state.lookahead = 6;
    function after_doctype_public_keyword_state(c) {
      switch (c) {
        case 9:
        case 10:
        case 12:
        case 32:
          tokenizer = before_doctype_public_identifier_state;
          break;
        case 34:
          beginDoctypePublicId();
          tokenizer = doctype_public_identifier_double_quoted_state;
          break;
        case 39:
          beginDoctypePublicId();
          tokenizer = doctype_public_identifier_single_quoted_state;
          break;
        case 62:
          forcequirks();
          tokenizer = data_state;
          emitDoctype();
          break;
        case -1:
          forcequirks();
          emitDoctype();
          emitEOF();
          break;
        default:
          forcequirks();
          tokenizer = bogus_doctype_state;
          break;
      }
    }
    function before_doctype_public_identifier_state(c) {
      switch (c) {
        case 9:
        case 10:
        case 12:
        case 32:
          break;
        case 34:
          beginDoctypePublicId();
          tokenizer = doctype_public_identifier_double_quoted_state;
          break;
        case 39:
          beginDoctypePublicId();
          tokenizer = doctype_public_identifier_single_quoted_state;
          break;
        case 62:
          forcequirks();
          tokenizer = data_state;
          emitDoctype();
          break;
        case -1:
          forcequirks();
          emitDoctype();
          emitEOF();
          break;
        default:
          forcequirks();
          tokenizer = bogus_doctype_state;
          break;
      }
    }
    function doctype_public_identifier_double_quoted_state(c) {
      switch (c) {
        case 34:
          tokenizer = after_doctype_public_identifier_state;
          break;
        case 0:
          doctypepublicbuf.push(65533);
          break;
        case 62:
          forcequirks();
          tokenizer = data_state;
          emitDoctype();
          break;
        case -1:
          forcequirks();
          emitDoctype();
          emitEOF();
          break;
        default:
          doctypepublicbuf.push(c);
          break;
      }
    }
    function doctype_public_identifier_single_quoted_state(c) {
      switch (c) {
        case 39:
          tokenizer = after_doctype_public_identifier_state;
          break;
        case 0:
          doctypepublicbuf.push(65533);
          break;
        case 62:
          forcequirks();
          tokenizer = data_state;
          emitDoctype();
          break;
        case -1:
          forcequirks();
          emitDoctype();
          emitEOF();
          break;
        default:
          doctypepublicbuf.push(c);
          break;
      }
    }
    function after_doctype_public_identifier_state(c) {
      switch (c) {
        case 9:
        case 10:
        case 12:
        case 32:
          tokenizer = between_doctype_public_and_system_identifiers_state;
          break;
        case 62:
          tokenizer = data_state;
          emitDoctype();
          break;
        case 34:
          beginDoctypeSystemId();
          tokenizer = doctype_system_identifier_double_quoted_state;
          break;
        case 39:
          beginDoctypeSystemId();
          tokenizer = doctype_system_identifier_single_quoted_state;
          break;
        case -1:
          forcequirks();
          emitDoctype();
          emitEOF();
          break;
        default:
          forcequirks();
          tokenizer = bogus_doctype_state;
          break;
      }
    }
    function between_doctype_public_and_system_identifiers_state(c) {
      switch (c) {
        case 9:
        case 10:
        case 12:
        case 32:
          break;
        case 62:
          tokenizer = data_state;
          emitDoctype();
          break;
        case 34:
          beginDoctypeSystemId();
          tokenizer = doctype_system_identifier_double_quoted_state;
          break;
        case 39:
          beginDoctypeSystemId();
          tokenizer = doctype_system_identifier_single_quoted_state;
          break;
        case -1:
          forcequirks();
          emitDoctype();
          emitEOF();
          break;
        default:
          forcequirks();
          tokenizer = bogus_doctype_state;
          break;
      }
    }
    function after_doctype_system_keyword_state(c) {
      switch (c) {
        case 9:
        case 10:
        case 12:
        case 32:
          tokenizer = before_doctype_system_identifier_state;
          break;
        case 34:
          beginDoctypeSystemId();
          tokenizer = doctype_system_identifier_double_quoted_state;
          break;
        case 39:
          beginDoctypeSystemId();
          tokenizer = doctype_system_identifier_single_quoted_state;
          break;
        case 62:
          forcequirks();
          tokenizer = data_state;
          emitDoctype();
          break;
        case -1:
          forcequirks();
          emitDoctype();
          emitEOF();
          break;
        default:
          forcequirks();
          tokenizer = bogus_doctype_state;
          break;
      }
    }
    function before_doctype_system_identifier_state(c) {
      switch (c) {
        case 9:
        case 10:
        case 12:
        case 32:
          break;
        case 34:
          beginDoctypeSystemId();
          tokenizer = doctype_system_identifier_double_quoted_state;
          break;
        case 39:
          beginDoctypeSystemId();
          tokenizer = doctype_system_identifier_single_quoted_state;
          break;
        case 62:
          forcequirks();
          tokenizer = data_state;
          emitDoctype();
          break;
        case -1:
          forcequirks();
          emitDoctype();
          emitEOF();
          break;
        default:
          forcequirks();
          tokenizer = bogus_doctype_state;
          break;
      }
    }
    function doctype_system_identifier_double_quoted_state(c) {
      switch (c) {
        case 34:
          tokenizer = after_doctype_system_identifier_state;
          break;
        case 0:
          doctypesystembuf.push(65533);
          break;
        case 62:
          forcequirks();
          tokenizer = data_state;
          emitDoctype();
          break;
        case -1:
          forcequirks();
          emitDoctype();
          emitEOF();
          break;
        default:
          doctypesystembuf.push(c);
          break;
      }
    }
    function doctype_system_identifier_single_quoted_state(c) {
      switch (c) {
        case 39:
          tokenizer = after_doctype_system_identifier_state;
          break;
        case 0:
          doctypesystembuf.push(65533);
          break;
        case 62:
          forcequirks();
          tokenizer = data_state;
          emitDoctype();
          break;
        case -1:
          forcequirks();
          emitDoctype();
          emitEOF();
          break;
        default:
          doctypesystembuf.push(c);
          break;
      }
    }
    function after_doctype_system_identifier_state(c) {
      switch (c) {
        case 9:
        case 10:
        case 12:
        case 32:
          break;
        case 62:
          tokenizer = data_state;
          emitDoctype();
          break;
        case -1:
          forcequirks();
          emitDoctype();
          emitEOF();
          break;
        default:
          tokenizer = bogus_doctype_state;
          break;
      }
    }
    function bogus_doctype_state(c) {
      switch (c) {
        case 62:
          tokenizer = data_state;
          emitDoctype();
          break;
        case -1:
          emitDoctype();
          emitEOF();
          break;
        default:
          break;
      }
    }
    function cdata_section_state(c) {
      switch (c) {
        case 93:
          tokenizer = cdata_section_bracket_state;
          break;
        case -1:
          emitEOF();
          break;
        case 0:
          textIncludesNUL = true;
        default:
          emitCharsWhile(CDATATEXT) || textrun.push(c);
          break;
      }
    }
    function cdata_section_bracket_state(c) {
      switch (c) {
        case 93:
          tokenizer = cdata_section_end_state;
          break;
        default:
          textrun.push(93);
          reconsume(c, cdata_section_state);
          break;
      }
    }
    function cdata_section_end_state(c) {
      switch (c) {
        case 93:
          textrun.push(93);
          break;
        case 62:
          flushText();
          tokenizer = data_state;
          break;
        default:
          textrun.push(93);
          textrun.push(93);
          reconsume(c, cdata_section_state);
          break;
      }
    }
    function character_reference_state(c) {
      beginTempBuf();
      tempbuf.push(38);
      switch (c) {
        case 9:
        case 10:
        case 12:
        case 32:
        case 60:
        case 38:
        case -1:
          reconsume(c, character_reference_end_state);
          break;
        case 35:
          tempbuf.push(c);
          tokenizer = numeric_character_reference_state;
          break;
        default:
          reconsume(c, named_character_reference_state);
          break;
      }
    }
    function named_character_reference_state(c) {
      NAMEDCHARREF.lastIndex = nextchar;
      var matched = NAMEDCHARREF.exec(chars);
      if (!matched)
        throw new Error("should never happen");
      var name = matched[1];
      if (!name) {
        tokenizer = character_reference_end_state;
        return;
      }
      nextchar += name.length;
      pushAll(tempbuf, str2buf(name));
      switch (return_state) {
        case attribute_value_double_quoted_state:
        case attribute_value_single_quoted_state:
        case attribute_value_unquoted_state:
          if (name[name.length - 1] !== ";") {
            if (/[=A-Za-z0-9]/.test(chars[nextchar])) {
              tokenizer = character_reference_end_state;
              return;
            }
          }
          break;
        default:
          break;
      }
      beginTempBuf();
      var rv = namedCharRefs[name];
      if (typeof rv === "number") {
        tempbuf.push(rv);
      } else {
        pushAll(tempbuf, rv);
      }
      tokenizer = character_reference_end_state;
    }
    named_character_reference_state.lookahead = -NAMEDCHARREF_MAXLEN;
    function numeric_character_reference_state(c) {
      character_reference_code = 0;
      switch (c) {
        case 120:
        case 88:
          tempbuf.push(c);
          tokenizer = hexadecimal_character_reference_start_state;
          break;
        default:
          reconsume(c, decimal_character_reference_start_state);
          break;
      }
    }
    function hexadecimal_character_reference_start_state(c) {
      switch (c) {
        case 48:
        case 49:
        case 50:
        case 51:
        case 52:
        case 53:
        case 54:
        case 55:
        case 56:
        case 57:
        case 65:
        case 66:
        case 67:
        case 68:
        case 69:
        case 70:
        case 97:
        case 98:
        case 99:
        case 100:
        case 101:
        case 102:
          reconsume(c, hexadecimal_character_reference_state);
          break;
        default:
          reconsume(c, character_reference_end_state);
          break;
      }
    }
    function decimal_character_reference_start_state(c) {
      switch (c) {
        case 48:
        case 49:
        case 50:
        case 51:
        case 52:
        case 53:
        case 54:
        case 55:
        case 56:
        case 57:
          reconsume(c, decimal_character_reference_state);
          break;
        default:
          reconsume(c, character_reference_end_state);
          break;
      }
    }
    function hexadecimal_character_reference_state(c) {
      switch (c) {
        case 65:
        case 66:
        case 67:
        case 68:
        case 69:
        case 70:
          character_reference_code *= 16;
          character_reference_code += c - 55;
          break;
        case 97:
        case 98:
        case 99:
        case 100:
        case 101:
        case 102:
          character_reference_code *= 16;
          character_reference_code += c - 87;
          break;
        case 48:
        case 49:
        case 50:
        case 51:
        case 52:
        case 53:
        case 54:
        case 55:
        case 56:
        case 57:
          character_reference_code *= 16;
          character_reference_code += c - 48;
          break;
        case 59:
          tokenizer = numeric_character_reference_end_state;
          break;
        default:
          reconsume(c, numeric_character_reference_end_state);
          break;
      }
    }
    function decimal_character_reference_state(c) {
      switch (c) {
        case 48:
        case 49:
        case 50:
        case 51:
        case 52:
        case 53:
        case 54:
        case 55:
        case 56:
        case 57:
          character_reference_code *= 10;
          character_reference_code += c - 48;
          break;
        case 59:
          tokenizer = numeric_character_reference_end_state;
          break;
        default:
          reconsume(c, numeric_character_reference_end_state);
          break;
      }
    }
    function numeric_character_reference_end_state(c) {
      if (character_reference_code in numericCharRefReplacements) {
        character_reference_code = numericCharRefReplacements[character_reference_code];
      } else if (character_reference_code > 1114111 || character_reference_code >= 55296 && character_reference_code < 57344) {
        character_reference_code = 65533;
      }
      beginTempBuf();
      if (character_reference_code <= 65535) {
        tempbuf.push(character_reference_code);
      } else {
        character_reference_code = character_reference_code - 65536;
        tempbuf.push(55296 + (character_reference_code >> 10));
        tempbuf.push(56320 + (character_reference_code & 1023));
      }
      reconsume(c, character_reference_end_state);
    }
    function character_reference_end_state(c) {
      switch (return_state) {
        case attribute_value_double_quoted_state:
        case attribute_value_single_quoted_state:
        case attribute_value_unquoted_state:
          attrvaluebuf += buf2str(tempbuf);
          break;
        default:
          pushAll(textrun, tempbuf);
          break;
      }
      reconsume(c, return_state);
    }
    function initial_mode(t, value, arg3, arg4) {
      switch (t) {
        case 1:
          value = value.replace(LEADINGWS, "");
          if (value.length === 0)
            return;
          break;
        case 4:
          doc._appendChild(doc.createComment(value));
          return;
        case 5:
          var name = value;
          var publicid = arg3;
          var systemid = arg4;
          doc.appendChild(new DocumentType(doc, name, publicid, systemid));
          if (force_quirks || name.toLowerCase() !== "html" || quirkyPublicIds.test(publicid) || systemid && systemid.toLowerCase() === quirkySystemId || systemid === undefined && conditionallyQuirkyPublicIds.test(publicid))
            doc._quirks = true;
          else if (limitedQuirkyPublicIds.test(publicid) || systemid !== undefined && conditionallyQuirkyPublicIds.test(publicid))
            doc._limitedQuirks = true;
          parser2 = before_html_mode;
          return;
      }
      doc._quirks = true;
      parser2 = before_html_mode;
      parser2(t, value, arg3, arg4);
    }
    function before_html_mode(t, value, arg3, arg4) {
      var elt;
      switch (t) {
        case 1:
          value = value.replace(LEADINGWS, "");
          if (value.length === 0)
            return;
          break;
        case 5:
          return;
        case 4:
          doc._appendChild(doc.createComment(value));
          return;
        case 2:
          if (value === "html") {
            elt = createHTMLElt(doc, value, arg3);
            stack.push(elt);
            doc.appendChild(elt);
            parser2 = before_head_mode;
            return;
          }
          break;
        case 3:
          switch (value) {
            case "html":
            case "head":
            case "body":
            case "br":
              break;
            default:
              return;
          }
      }
      elt = createHTMLElt(doc, "html", null);
      stack.push(elt);
      doc.appendChild(elt);
      parser2 = before_head_mode;
      parser2(t, value, arg3, arg4);
    }
    function before_head_mode(t, value, arg3, arg4) {
      switch (t) {
        case 1:
          value = value.replace(LEADINGWS, "");
          if (value.length === 0)
            return;
          break;
        case 5:
          return;
        case 4:
          insertComment(value);
          return;
        case 2:
          switch (value) {
            case "html":
              in_body_mode(t, value, arg3, arg4);
              return;
            case "head":
              var elt = insertHTMLElement(value, arg3);
              head_element_pointer = elt;
              parser2 = in_head_mode;
              return;
          }
          break;
        case 3:
          switch (value) {
            case "html":
            case "head":
            case "body":
            case "br":
              break;
            default:
              return;
          }
      }
      before_head_mode(TAG, "head", null);
      parser2(t, value, arg3, arg4);
    }
    function in_head_mode(t, value, arg3, arg4) {
      switch (t) {
        case 1:
          var ws = value.match(LEADINGWS);
          if (ws) {
            insertText(ws[0]);
            value = value.substring(ws[0].length);
          }
          if (value.length === 0)
            return;
          break;
        case 4:
          insertComment(value);
          return;
        case 5:
          return;
        case 2:
          switch (value) {
            case "html":
              in_body_mode(t, value, arg3, arg4);
              return;
            case "meta":
            case "base":
            case "basefont":
            case "bgsound":
            case "link":
              insertHTMLElement(value, arg3);
              stack.pop();
              return;
            case "title":
              parseRCDATA(value, arg3);
              return;
            case "noscript":
              if (!scripting_enabled) {
                insertHTMLElement(value, arg3);
                parser2 = in_head_noscript_mode;
                return;
              }
            case "noframes":
            case "style":
              parseRawText(value, arg3);
              return;
            case "script":
              insertElement(function(doc2) {
                var elt = createHTMLElt(doc2, value, arg3);
                elt._parser_inserted = true;
                elt._force_async = false;
                if (fragment)
                  elt._already_started = true;
                flushText();
                return elt;
              });
              tokenizer = script_data_state;
              originalInsertionMode = parser2;
              parser2 = text_mode;
              return;
            case "template":
              insertHTMLElement(value, arg3);
              afe.insertMarker();
              frameset_ok = false;
              parser2 = in_template_mode;
              templateInsertionModes.push(parser2);
              return;
            case "head":
              return;
          }
          break;
        case 3:
          switch (value) {
            case "head":
              stack.pop();
              parser2 = after_head_mode;
              return;
            case "body":
            case "html":
            case "br":
              break;
            case "template":
              if (!stack.contains("template")) {
                return;
              }
              stack.generateImpliedEndTags(null, "thorough");
              stack.popTag("template");
              afe.clearToMarker();
              templateInsertionModes.pop();
              resetInsertionMode();
              return;
            default:
              return;
          }
          break;
      }
      in_head_mode(ENDTAG, "head", null);
      parser2(t, value, arg3, arg4);
    }
    function in_head_noscript_mode(t, value, arg3, arg4) {
      switch (t) {
        case 5:
          return;
        case 4:
          in_head_mode(t, value);
          return;
        case 1:
          var ws = value.match(LEADINGWS);
          if (ws) {
            in_head_mode(t, ws[0]);
            value = value.substring(ws[0].length);
          }
          if (value.length === 0)
            return;
          break;
        case 2:
          switch (value) {
            case "html":
              in_body_mode(t, value, arg3, arg4);
              return;
            case "basefont":
            case "bgsound":
            case "link":
            case "meta":
            case "noframes":
            case "style":
              in_head_mode(t, value, arg3);
              return;
            case "head":
            case "noscript":
              return;
          }
          break;
        case 3:
          switch (value) {
            case "noscript":
              stack.pop();
              parser2 = in_head_mode;
              return;
            case "br":
              break;
            default:
              return;
          }
          break;
      }
      in_head_noscript_mode(ENDTAG, "noscript", null);
      parser2(t, value, arg3, arg4);
    }
    function after_head_mode(t, value, arg3, arg4) {
      switch (t) {
        case 1:
          var ws = value.match(LEADINGWS);
          if (ws) {
            insertText(ws[0]);
            value = value.substring(ws[0].length);
          }
          if (value.length === 0)
            return;
          break;
        case 4:
          insertComment(value);
          return;
        case 5:
          return;
        case 2:
          switch (value) {
            case "html":
              in_body_mode(t, value, arg3, arg4);
              return;
            case "body":
              insertHTMLElement(value, arg3);
              frameset_ok = false;
              parser2 = in_body_mode;
              return;
            case "frameset":
              insertHTMLElement(value, arg3);
              parser2 = in_frameset_mode;
              return;
            case "base":
            case "basefont":
            case "bgsound":
            case "link":
            case "meta":
            case "noframes":
            case "script":
            case "style":
            case "template":
            case "title":
              stack.push(head_element_pointer);
              in_head_mode(TAG, value, arg3);
              stack.removeElement(head_element_pointer);
              return;
            case "head":
              return;
          }
          break;
        case 3:
          switch (value) {
            case "template":
              return in_head_mode(t, value, arg3, arg4);
            case "body":
            case "html":
            case "br":
              break;
            default:
              return;
          }
          break;
      }
      after_head_mode(TAG, "body", null);
      frameset_ok = true;
      parser2(t, value, arg3, arg4);
    }
    function in_body_mode(t, value, arg3, arg4) {
      var body, i, node, elt;
      switch (t) {
        case 1:
          if (textIncludesNUL) {
            value = value.replace(NULCHARS, "");
            if (value.length === 0)
              return;
          }
          if (frameset_ok && NONWS.test(value))
            frameset_ok = false;
          afereconstruct();
          insertText(value);
          return;
        case 5:
          return;
        case 4:
          insertComment(value);
          return;
        case -1:
          if (templateInsertionModes.length) {
            return in_template_mode(t);
          }
          stopParsing();
          return;
        case 2:
          switch (value) {
            case "html":
              if (stack.contains("template")) {
                return;
              }
              transferAttributes(arg3, stack.elements[0]);
              return;
            case "base":
            case "basefont":
            case "bgsound":
            case "link":
            case "meta":
            case "noframes":
            case "script":
            case "style":
            case "template":
            case "title":
              in_head_mode(TAG, value, arg3);
              return;
            case "body":
              body = stack.elements[1];
              if (!body || !(body instanceof impl.HTMLBodyElement) || stack.contains("template"))
                return;
              frameset_ok = false;
              transferAttributes(arg3, body);
              return;
            case "frameset":
              if (!frameset_ok)
                return;
              body = stack.elements[1];
              if (!body || !(body instanceof impl.HTMLBodyElement))
                return;
              if (body.parentNode)
                body.parentNode.removeChild(body);
              while (!(stack.top instanceof impl.HTMLHtmlElement))
                stack.pop();
              insertHTMLElement(value, arg3);
              parser2 = in_frameset_mode;
              return;
            case "address":
            case "article":
            case "aside":
            case "blockquote":
            case "center":
            case "details":
            case "dialog":
            case "dir":
            case "div":
            case "dl":
            case "fieldset":
            case "figcaption":
            case "figure":
            case "footer":
            case "header":
            case "hgroup":
            case "main":
            case "nav":
            case "ol":
            case "p":
            case "section":
            case "summary":
            case "ul":
              if (stack.inButtonScope("p"))
                in_body_mode(ENDTAG, "p");
              insertHTMLElement(value, arg3);
              return;
            case "menu":
              if (stack.inButtonScope("p"))
                in_body_mode(ENDTAG, "p");
              if (isA(stack.top, "menuitem")) {
                stack.pop();
              }
              insertHTMLElement(value, arg3);
              return;
            case "h1":
            case "h2":
            case "h3":
            case "h4":
            case "h5":
            case "h6":
              if (stack.inButtonScope("p"))
                in_body_mode(ENDTAG, "p");
              if (stack.top instanceof impl.HTMLHeadingElement)
                stack.pop();
              insertHTMLElement(value, arg3);
              return;
            case "pre":
            case "listing":
              if (stack.inButtonScope("p"))
                in_body_mode(ENDTAG, "p");
              insertHTMLElement(value, arg3);
              ignore_linefeed = true;
              frameset_ok = false;
              return;
            case "form":
              if (form_element_pointer && !stack.contains("template"))
                return;
              if (stack.inButtonScope("p"))
                in_body_mode(ENDTAG, "p");
              elt = insertHTMLElement(value, arg3);
              if (!stack.contains("template"))
                form_element_pointer = elt;
              return;
            case "li":
              frameset_ok = false;
              for (i = stack.elements.length - 1;i >= 0; i--) {
                node = stack.elements[i];
                if (node instanceof impl.HTMLLIElement) {
                  in_body_mode(ENDTAG, "li");
                  break;
                }
                if (isA(node, specialSet) && !isA(node, addressdivpSet))
                  break;
              }
              if (stack.inButtonScope("p"))
                in_body_mode(ENDTAG, "p");
              insertHTMLElement(value, arg3);
              return;
            case "dd":
            case "dt":
              frameset_ok = false;
              for (i = stack.elements.length - 1;i >= 0; i--) {
                node = stack.elements[i];
                if (isA(node, dddtSet)) {
                  in_body_mode(ENDTAG, node.localName);
                  break;
                }
                if (isA(node, specialSet) && !isA(node, addressdivpSet))
                  break;
              }
              if (stack.inButtonScope("p"))
                in_body_mode(ENDTAG, "p");
              insertHTMLElement(value, arg3);
              return;
            case "plaintext":
              if (stack.inButtonScope("p"))
                in_body_mode(ENDTAG, "p");
              insertHTMLElement(value, arg3);
              tokenizer = plaintext_state;
              return;
            case "button":
              if (stack.inScope("button")) {
                in_body_mode(ENDTAG, "button");
                parser2(t, value, arg3, arg4);
              } else {
                afereconstruct();
                insertHTMLElement(value, arg3);
                frameset_ok = false;
              }
              return;
            case "a":
              var activeElement = afe.findElementByTag("a");
              if (activeElement) {
                in_body_mode(ENDTAG, value);
                afe.remove(activeElement);
                stack.removeElement(activeElement);
              }
            case "b":
            case "big":
            case "code":
            case "em":
            case "font":
            case "i":
            case "s":
            case "small":
            case "strike":
            case "strong":
            case "tt":
            case "u":
              afereconstruct();
              afe.push(insertHTMLElement(value, arg3), arg3);
              return;
            case "nobr":
              afereconstruct();
              if (stack.inScope(value)) {
                in_body_mode(ENDTAG, value);
                afereconstruct();
              }
              afe.push(insertHTMLElement(value, arg3), arg3);
              return;
            case "applet":
            case "marquee":
            case "object":
              afereconstruct();
              insertHTMLElement(value, arg3);
              afe.insertMarker();
              frameset_ok = false;
              return;
            case "table":
              if (!doc._quirks && stack.inButtonScope("p")) {
                in_body_mode(ENDTAG, "p");
              }
              insertHTMLElement(value, arg3);
              frameset_ok = false;
              parser2 = in_table_mode;
              return;
            case "area":
            case "br":
            case "embed":
            case "img":
            case "keygen":
            case "wbr":
              afereconstruct();
              insertHTMLElement(value, arg3);
              stack.pop();
              frameset_ok = false;
              return;
            case "input":
              afereconstruct();
              elt = insertHTMLElement(value, arg3);
              stack.pop();
              var type = elt.getAttribute("type");
              if (!type || type.toLowerCase() !== "hidden")
                frameset_ok = false;
              return;
            case "param":
            case "source":
            case "track":
              insertHTMLElement(value, arg3);
              stack.pop();
              return;
            case "hr":
              if (stack.inButtonScope("p"))
                in_body_mode(ENDTAG, "p");
              if (isA(stack.top, "menuitem")) {
                stack.pop();
              }
              insertHTMLElement(value, arg3);
              stack.pop();
              frameset_ok = false;
              return;
            case "image":
              in_body_mode(TAG, "img", arg3, arg4);
              return;
            case "textarea":
              insertHTMLElement(value, arg3);
              ignore_linefeed = true;
              frameset_ok = false;
              tokenizer = rcdata_state;
              originalInsertionMode = parser2;
              parser2 = text_mode;
              return;
            case "xmp":
              if (stack.inButtonScope("p"))
                in_body_mode(ENDTAG, "p");
              afereconstruct();
              frameset_ok = false;
              parseRawText(value, arg3);
              return;
            case "iframe":
              frameset_ok = false;
              parseRawText(value, arg3);
              return;
            case "noembed":
              parseRawText(value, arg3);
              return;
            case "select":
              afereconstruct();
              insertHTMLElement(value, arg3);
              frameset_ok = false;
              if (parser2 === in_table_mode || parser2 === in_caption_mode || parser2 === in_table_body_mode || parser2 === in_row_mode || parser2 === in_cell_mode)
                parser2 = in_select_in_table_mode;
              else
                parser2 = in_select_mode;
              return;
            case "optgroup":
            case "option":
              if (stack.top instanceof impl.HTMLOptionElement) {
                in_body_mode(ENDTAG, "option");
              }
              afereconstruct();
              insertHTMLElement(value, arg3);
              return;
            case "menuitem":
              if (isA(stack.top, "menuitem")) {
                stack.pop();
              }
              afereconstruct();
              insertHTMLElement(value, arg3);
              return;
            case "rb":
            case "rtc":
              if (stack.inScope("ruby")) {
                stack.generateImpliedEndTags();
              }
              insertHTMLElement(value, arg3);
              return;
            case "rp":
            case "rt":
              if (stack.inScope("ruby")) {
                stack.generateImpliedEndTags("rtc");
              }
              insertHTMLElement(value, arg3);
              return;
            case "math":
              afereconstruct();
              adjustMathMLAttributes(arg3);
              adjustForeignAttributes(arg3);
              insertForeignElement(value, arg3, NAMESPACE.MATHML);
              if (arg4)
                stack.pop();
              return;
            case "svg":
              afereconstruct();
              adjustSVGAttributes(arg3);
              adjustForeignAttributes(arg3);
              insertForeignElement(value, arg3, NAMESPACE.SVG);
              if (arg4)
                stack.pop();
              return;
            case "caption":
            case "col":
            case "colgroup":
            case "frame":
            case "head":
            case "tbody":
            case "td":
            case "tfoot":
            case "th":
            case "thead":
            case "tr":
              return;
          }
          afereconstruct();
          insertHTMLElement(value, arg3);
          return;
        case 3:
          switch (value) {
            case "template":
              in_head_mode(ENDTAG, value, arg3);
              return;
            case "body":
              if (!stack.inScope("body"))
                return;
              parser2 = after_body_mode;
              return;
            case "html":
              if (!stack.inScope("body"))
                return;
              parser2 = after_body_mode;
              parser2(t, value, arg3);
              return;
            case "address":
            case "article":
            case "aside":
            case "blockquote":
            case "button":
            case "center":
            case "details":
            case "dialog":
            case "dir":
            case "div":
            case "dl":
            case "fieldset":
            case "figcaption":
            case "figure":
            case "footer":
            case "header":
            case "hgroup":
            case "listing":
            case "main":
            case "menu":
            case "nav":
            case "ol":
            case "pre":
            case "section":
            case "summary":
            case "ul":
              if (!stack.inScope(value))
                return;
              stack.generateImpliedEndTags();
              stack.popTag(value);
              return;
            case "form":
              if (!stack.contains("template")) {
                var openform = form_element_pointer;
                form_element_pointer = null;
                if (!openform || !stack.elementInScope(openform))
                  return;
                stack.generateImpliedEndTags();
                stack.removeElement(openform);
              } else {
                if (!stack.inScope("form"))
                  return;
                stack.generateImpliedEndTags();
                stack.popTag("form");
              }
              return;
            case "p":
              if (!stack.inButtonScope(value)) {
                in_body_mode(TAG, value, null);
                parser2(t, value, arg3, arg4);
              } else {
                stack.generateImpliedEndTags(value);
                stack.popTag(value);
              }
              return;
            case "li":
              if (!stack.inListItemScope(value))
                return;
              stack.generateImpliedEndTags(value);
              stack.popTag(value);
              return;
            case "dd":
            case "dt":
              if (!stack.inScope(value))
                return;
              stack.generateImpliedEndTags(value);
              stack.popTag(value);
              return;
            case "h1":
            case "h2":
            case "h3":
            case "h4":
            case "h5":
            case "h6":
              if (!stack.elementTypeInScope(impl.HTMLHeadingElement))
                return;
              stack.generateImpliedEndTags();
              stack.popElementType(impl.HTMLHeadingElement);
              return;
            case "sarcasm":
              break;
            case "a":
            case "b":
            case "big":
            case "code":
            case "em":
            case "font":
            case "i":
            case "nobr":
            case "s":
            case "small":
            case "strike":
            case "strong":
            case "tt":
            case "u":
              var result = adoptionAgency(value);
              if (result)
                return;
              break;
            case "applet":
            case "marquee":
            case "object":
              if (!stack.inScope(value))
                return;
              stack.generateImpliedEndTags();
              stack.popTag(value);
              afe.clearToMarker();
              return;
            case "br":
              in_body_mode(TAG, value, null);
              return;
          }
          for (i = stack.elements.length - 1;i >= 0; i--) {
            node = stack.elements[i];
            if (isA(node, value)) {
              stack.generateImpliedEndTags(value);
              stack.popElement(node);
              break;
            } else if (isA(node, specialSet)) {
              return;
            }
          }
          return;
      }
    }
    function text_mode(t, value, arg3, arg4) {
      switch (t) {
        case 1:
          insertText(value);
          return;
        case -1:
          if (stack.top instanceof impl.HTMLScriptElement)
            stack.top._already_started = true;
          stack.pop();
          parser2 = originalInsertionMode;
          parser2(t);
          return;
        case 3:
          if (value === "script") {
            handleScriptEnd();
          } else {
            stack.pop();
            parser2 = originalInsertionMode;
          }
          return;
        default:
          return;
      }
    }
    function in_table_mode(t, value, arg3, arg4) {
      function getTypeAttr(attrs) {
        for (var i = 0, n = attrs.length;i < n; i++) {
          if (attrs[i][0] === "type")
            return attrs[i][1].toLowerCase();
        }
        return null;
      }
      switch (t) {
        case 1:
          if (text_integration_mode) {
            in_body_mode(t, value, arg3, arg4);
            return;
          } else if (isA(stack.top, tablesectionrowSet)) {
            pending_table_text = [];
            originalInsertionMode = parser2;
            parser2 = in_table_text_mode;
            parser2(t, value, arg3, arg4);
            return;
          }
          break;
        case 4:
          insertComment(value);
          return;
        case 5:
          return;
        case 2:
          switch (value) {
            case "caption":
              stack.clearToContext(tableContextSet);
              afe.insertMarker();
              insertHTMLElement(value, arg3);
              parser2 = in_caption_mode;
              return;
            case "colgroup":
              stack.clearToContext(tableContextSet);
              insertHTMLElement(value, arg3);
              parser2 = in_column_group_mode;
              return;
            case "col":
              in_table_mode(TAG, "colgroup", null);
              parser2(t, value, arg3, arg4);
              return;
            case "tbody":
            case "tfoot":
            case "thead":
              stack.clearToContext(tableContextSet);
              insertHTMLElement(value, arg3);
              parser2 = in_table_body_mode;
              return;
            case "td":
            case "th":
            case "tr":
              in_table_mode(TAG, "tbody", null);
              parser2(t, value, arg3, arg4);
              return;
            case "table":
              if (!stack.inTableScope(value)) {
                return;
              }
              in_table_mode(ENDTAG, value);
              parser2(t, value, arg3, arg4);
              return;
            case "style":
            case "script":
            case "template":
              in_head_mode(t, value, arg3, arg4);
              return;
            case "input":
              var type = getTypeAttr(arg3);
              if (type !== "hidden")
                break;
              insertHTMLElement(value, arg3);
              stack.pop();
              return;
            case "form":
              if (form_element_pointer || stack.contains("template"))
                return;
              form_element_pointer = insertHTMLElement(value, arg3);
              stack.popElement(form_element_pointer);
              return;
          }
          break;
        case 3:
          switch (value) {
            case "table":
              if (!stack.inTableScope(value))
                return;
              stack.popTag(value);
              resetInsertionMode();
              return;
            case "body":
            case "caption":
            case "col":
            case "colgroup":
            case "html":
            case "tbody":
            case "td":
            case "tfoot":
            case "th":
            case "thead":
            case "tr":
              return;
            case "template":
              in_head_mode(t, value, arg3, arg4);
              return;
          }
          break;
        case -1:
          in_body_mode(t, value, arg3, arg4);
          return;
      }
      foster_parent_mode = true;
      in_body_mode(t, value, arg3, arg4);
      foster_parent_mode = false;
    }
    function in_table_text_mode(t, value, arg3, arg4) {
      if (t === TEXT) {
        if (textIncludesNUL) {
          value = value.replace(NULCHARS, "");
          if (value.length === 0)
            return;
        }
        pending_table_text.push(value);
      } else {
        var s = pending_table_text.join("");
        pending_table_text.length = 0;
        if (NONWS.test(s)) {
          foster_parent_mode = true;
          in_body_mode(TEXT, s);
          foster_parent_mode = false;
        } else {
          insertText(s);
        }
        parser2 = originalInsertionMode;
        parser2(t, value, arg3, arg4);
      }
    }
    function in_caption_mode(t, value, arg3, arg4) {
      function end_caption() {
        if (!stack.inTableScope("caption"))
          return false;
        stack.generateImpliedEndTags();
        stack.popTag("caption");
        afe.clearToMarker();
        parser2 = in_table_mode;
        return true;
      }
      switch (t) {
        case 2:
          switch (value) {
            case "caption":
            case "col":
            case "colgroup":
            case "tbody":
            case "td":
            case "tfoot":
            case "th":
            case "thead":
            case "tr":
              if (end_caption())
                parser2(t, value, arg3, arg4);
              return;
          }
          break;
        case 3:
          switch (value) {
            case "caption":
              end_caption();
              return;
            case "table":
              if (end_caption())
                parser2(t, value, arg3, arg4);
              return;
            case "body":
            case "col":
            case "colgroup":
            case "html":
            case "tbody":
            case "td":
            case "tfoot":
            case "th":
            case "thead":
            case "tr":
              return;
          }
          break;
      }
      in_body_mode(t, value, arg3, arg4);
    }
    function in_column_group_mode(t, value, arg3, arg4) {
      switch (t) {
        case 1:
          var ws = value.match(LEADINGWS);
          if (ws) {
            insertText(ws[0]);
            value = value.substring(ws[0].length);
          }
          if (value.length === 0)
            return;
          break;
        case 4:
          insertComment(value);
          return;
        case 5:
          return;
        case 2:
          switch (value) {
            case "html":
              in_body_mode(t, value, arg3, arg4);
              return;
            case "col":
              insertHTMLElement(value, arg3);
              stack.pop();
              return;
            case "template":
              in_head_mode(t, value, arg3, arg4);
              return;
          }
          break;
        case 3:
          switch (value) {
            case "colgroup":
              if (!isA(stack.top, "colgroup")) {
                return;
              }
              stack.pop();
              parser2 = in_table_mode;
              return;
            case "col":
              return;
            case "template":
              in_head_mode(t, value, arg3, arg4);
              return;
          }
          break;
        case -1:
          in_body_mode(t, value, arg3, arg4);
          return;
      }
      if (!isA(stack.top, "colgroup")) {
        return;
      }
      in_column_group_mode(ENDTAG, "colgroup");
      parser2(t, value, arg3, arg4);
    }
    function in_table_body_mode(t, value, arg3, arg4) {
      function endsect() {
        if (!stack.inTableScope("tbody") && !stack.inTableScope("thead") && !stack.inTableScope("tfoot"))
          return;
        stack.clearToContext(tableBodyContextSet);
        in_table_body_mode(ENDTAG, stack.top.localName, null);
        parser2(t, value, arg3, arg4);
      }
      switch (t) {
        case 2:
          switch (value) {
            case "tr":
              stack.clearToContext(tableBodyContextSet);
              insertHTMLElement(value, arg3);
              parser2 = in_row_mode;
              return;
            case "th":
            case "td":
              in_table_body_mode(TAG, "tr", null);
              parser2(t, value, arg3, arg4);
              return;
            case "caption":
            case "col":
            case "colgroup":
            case "tbody":
            case "tfoot":
            case "thead":
              endsect();
              return;
          }
          break;
        case 3:
          switch (value) {
            case "table":
              endsect();
              return;
            case "tbody":
            case "tfoot":
            case "thead":
              if (stack.inTableScope(value)) {
                stack.clearToContext(tableBodyContextSet);
                stack.pop();
                parser2 = in_table_mode;
              }
              return;
            case "body":
            case "caption":
            case "col":
            case "colgroup":
            case "html":
            case "td":
            case "th":
            case "tr":
              return;
          }
          break;
      }
      in_table_mode(t, value, arg3, arg4);
    }
    function in_row_mode(t, value, arg3, arg4) {
      function endrow() {
        if (!stack.inTableScope("tr"))
          return false;
        stack.clearToContext(tableRowContextSet);
        stack.pop();
        parser2 = in_table_body_mode;
        return true;
      }
      switch (t) {
        case 2:
          switch (value) {
            case "th":
            case "td":
              stack.clearToContext(tableRowContextSet);
              insertHTMLElement(value, arg3);
              parser2 = in_cell_mode;
              afe.insertMarker();
              return;
            case "caption":
            case "col":
            case "colgroup":
            case "tbody":
            case "tfoot":
            case "thead":
            case "tr":
              if (endrow())
                parser2(t, value, arg3, arg4);
              return;
          }
          break;
        case 3:
          switch (value) {
            case "tr":
              endrow();
              return;
            case "table":
              if (endrow())
                parser2(t, value, arg3, arg4);
              return;
            case "tbody":
            case "tfoot":
            case "thead":
              if (stack.inTableScope(value)) {
                if (endrow())
                  parser2(t, value, arg3, arg4);
              }
              return;
            case "body":
            case "caption":
            case "col":
            case "colgroup":
            case "html":
            case "td":
            case "th":
              return;
          }
          break;
      }
      in_table_mode(t, value, arg3, arg4);
    }
    function in_cell_mode(t, value, arg3, arg4) {
      switch (t) {
        case 2:
          switch (value) {
            case "caption":
            case "col":
            case "colgroup":
            case "tbody":
            case "td":
            case "tfoot":
            case "th":
            case "thead":
            case "tr":
              if (stack.inTableScope("td")) {
                in_cell_mode(ENDTAG, "td");
                parser2(t, value, arg3, arg4);
              } else if (stack.inTableScope("th")) {
                in_cell_mode(ENDTAG, "th");
                parser2(t, value, arg3, arg4);
              }
              return;
          }
          break;
        case 3:
          switch (value) {
            case "td":
            case "th":
              if (!stack.inTableScope(value))
                return;
              stack.generateImpliedEndTags();
              stack.popTag(value);
              afe.clearToMarker();
              parser2 = in_row_mode;
              return;
            case "body":
            case "caption":
            case "col":
            case "colgroup":
            case "html":
              return;
            case "table":
            case "tbody":
            case "tfoot":
            case "thead":
            case "tr":
              if (!stack.inTableScope(value))
                return;
              in_cell_mode(ENDTAG, stack.inTableScope("td") ? "td" : "th");
              parser2(t, value, arg3, arg4);
              return;
          }
          break;
      }
      in_body_mode(t, value, arg3, arg4);
    }
    function in_select_mode(t, value, arg3, arg4) {
      switch (t) {
        case 1:
          if (textIncludesNUL) {
            value = value.replace(NULCHARS, "");
            if (value.length === 0)
              return;
          }
          insertText(value);
          return;
        case 4:
          insertComment(value);
          return;
        case 5:
          return;
        case -1:
          in_body_mode(t, value, arg3, arg4);
          return;
        case 2:
          switch (value) {
            case "html":
              in_body_mode(t, value, arg3, arg4);
              return;
            case "option":
              if (stack.top instanceof impl.HTMLOptionElement)
                in_select_mode(ENDTAG, value);
              insertHTMLElement(value, arg3);
              return;
            case "optgroup":
              if (stack.top instanceof impl.HTMLOptionElement)
                in_select_mode(ENDTAG, "option");
              if (stack.top instanceof impl.HTMLOptGroupElement)
                in_select_mode(ENDTAG, value);
              insertHTMLElement(value, arg3);
              return;
            case "select":
              in_select_mode(ENDTAG, value);
              return;
            case "input":
            case "keygen":
            case "textarea":
              if (!stack.inSelectScope("select"))
                return;
              in_select_mode(ENDTAG, "select");
              parser2(t, value, arg3, arg4);
              return;
            case "script":
            case "template":
              in_head_mode(t, value, arg3, arg4);
              return;
          }
          break;
        case 3:
          switch (value) {
            case "optgroup":
              if (stack.top instanceof impl.HTMLOptionElement && stack.elements[stack.elements.length - 2] instanceof impl.HTMLOptGroupElement) {
                in_select_mode(ENDTAG, "option");
              }
              if (stack.top instanceof impl.HTMLOptGroupElement)
                stack.pop();
              return;
            case "option":
              if (stack.top instanceof impl.HTMLOptionElement)
                stack.pop();
              return;
            case "select":
              if (!stack.inSelectScope(value))
                return;
              stack.popTag(value);
              resetInsertionMode();
              return;
            case "template":
              in_head_mode(t, value, arg3, arg4);
              return;
          }
          break;
      }
    }
    function in_select_in_table_mode(t, value, arg3, arg4) {
      switch (value) {
        case "caption":
        case "table":
        case "tbody":
        case "tfoot":
        case "thead":
        case "tr":
        case "td":
        case "th":
          switch (t) {
            case 2:
              in_select_in_table_mode(ENDTAG, "select");
              parser2(t, value, arg3, arg4);
              return;
            case 3:
              if (stack.inTableScope(value)) {
                in_select_in_table_mode(ENDTAG, "select");
                parser2(t, value, arg3, arg4);
              }
              return;
          }
      }
      in_select_mode(t, value, arg3, arg4);
    }
    function in_template_mode(t, value, arg3, arg4) {
      function switchModeAndReprocess(mode) {
        parser2 = mode;
        templateInsertionModes[templateInsertionModes.length - 1] = parser2;
        parser2(t, value, arg3, arg4);
      }
      switch (t) {
        case 1:
        case 4:
        case 5:
          in_body_mode(t, value, arg3, arg4);
          return;
        case -1:
          if (!stack.contains("template")) {
            stopParsing();
          } else {
            stack.popTag("template");
            afe.clearToMarker();
            templateInsertionModes.pop();
            resetInsertionMode();
            parser2(t, value, arg3, arg4);
          }
          return;
        case 2:
          switch (value) {
            case "base":
            case "basefont":
            case "bgsound":
            case "link":
            case "meta":
            case "noframes":
            case "script":
            case "style":
            case "template":
            case "title":
              in_head_mode(t, value, arg3, arg4);
              return;
            case "caption":
            case "colgroup":
            case "tbody":
            case "tfoot":
            case "thead":
              switchModeAndReprocess(in_table_mode);
              return;
            case "col":
              switchModeAndReprocess(in_column_group_mode);
              return;
            case "tr":
              switchModeAndReprocess(in_table_body_mode);
              return;
            case "td":
            case "th":
              switchModeAndReprocess(in_row_mode);
              return;
          }
          switchModeAndReprocess(in_body_mode);
          return;
        case 3:
          switch (value) {
            case "template":
              in_head_mode(t, value, arg3, arg4);
              return;
            default:
              return;
          }
      }
    }
    function after_body_mode(t, value, arg3, arg4) {
      switch (t) {
        case 1:
          if (NONWS.test(value))
            break;
          in_body_mode(t, value);
          return;
        case 4:
          stack.elements[0]._appendChild(doc.createComment(value));
          return;
        case 5:
          return;
        case -1:
          stopParsing();
          return;
        case 2:
          if (value === "html") {
            in_body_mode(t, value, arg3, arg4);
            return;
          }
          break;
        case 3:
          if (value === "html") {
            if (fragment)
              return;
            parser2 = after_after_body_mode;
            return;
          }
          break;
      }
      parser2 = in_body_mode;
      parser2(t, value, arg3, arg4);
    }
    function in_frameset_mode(t, value, arg3, arg4) {
      switch (t) {
        case 1:
          value = value.replace(ALLNONWS, "");
          if (value.length > 0)
            insertText(value);
          return;
        case 4:
          insertComment(value);
          return;
        case 5:
          return;
        case -1:
          stopParsing();
          return;
        case 2:
          switch (value) {
            case "html":
              in_body_mode(t, value, arg3, arg4);
              return;
            case "frameset":
              insertHTMLElement(value, arg3);
              return;
            case "frame":
              insertHTMLElement(value, arg3);
              stack.pop();
              return;
            case "noframes":
              in_head_mode(t, value, arg3, arg4);
              return;
          }
          break;
        case 3:
          if (value === "frameset") {
            if (fragment && stack.top instanceof impl.HTMLHtmlElement)
              return;
            stack.pop();
            if (!fragment && !(stack.top instanceof impl.HTMLFrameSetElement))
              parser2 = after_frameset_mode;
            return;
          }
          break;
      }
    }
    function after_frameset_mode(t, value, arg3, arg4) {
      switch (t) {
        case 1:
          value = value.replace(ALLNONWS, "");
          if (value.length > 0)
            insertText(value);
          return;
        case 4:
          insertComment(value);
          return;
        case 5:
          return;
        case -1:
          stopParsing();
          return;
        case 2:
          switch (value) {
            case "html":
              in_body_mode(t, value, arg3, arg4);
              return;
            case "noframes":
              in_head_mode(t, value, arg3, arg4);
              return;
          }
          break;
        case 3:
          if (value === "html") {
            parser2 = after_after_frameset_mode;
            return;
          }
          break;
      }
    }
    function after_after_body_mode(t, value, arg3, arg4) {
      switch (t) {
        case 1:
          if (NONWS.test(value))
            break;
          in_body_mode(t, value, arg3, arg4);
          return;
        case 4:
          doc._appendChild(doc.createComment(value));
          return;
        case 5:
          in_body_mode(t, value, arg3, arg4);
          return;
        case -1:
          stopParsing();
          return;
        case 2:
          if (value === "html") {
            in_body_mode(t, value, arg3, arg4);
            return;
          }
          break;
      }
      parser2 = in_body_mode;
      parser2(t, value, arg3, arg4);
    }
    function after_after_frameset_mode(t, value, arg3, arg4) {
      switch (t) {
        case 1:
          value = value.replace(ALLNONWS, "");
          if (value.length > 0)
            in_body_mode(t, value, arg3, arg4);
          return;
        case 4:
          doc._appendChild(doc.createComment(value));
          return;
        case 5:
          in_body_mode(t, value, arg3, arg4);
          return;
        case -1:
          stopParsing();
          return;
        case 2:
          switch (value) {
            case "html":
              in_body_mode(t, value, arg3, arg4);
              return;
            case "noframes":
              in_head_mode(t, value, arg3, arg4);
              return;
          }
          break;
      }
    }
    function insertForeignToken(t, value, arg3, arg4) {
      function isHTMLFont(attrs) {
        for (var i2 = 0, n = attrs.length;i2 < n; i2++) {
          switch (attrs[i2][0]) {
            case "color":
            case "face":
            case "size":
              return true;
          }
        }
        return false;
      }
      var current;
      switch (t) {
        case 1:
          if (frameset_ok && NONWSNONNUL.test(value))
            frameset_ok = false;
          if (textIncludesNUL) {
            value = value.replace(NULCHARS, "�");
          }
          insertText(value);
          return;
        case 4:
          insertComment(value);
          return;
        case 5:
          return;
        case 2:
          switch (value) {
            case "font":
              if (!isHTMLFont(arg3))
                break;
            case "b":
            case "big":
            case "blockquote":
            case "body":
            case "br":
            case "center":
            case "code":
            case "dd":
            case "div":
            case "dl":
            case "dt":
            case "em":
            case "embed":
            case "h1":
            case "h2":
            case "h3":
            case "h4":
            case "h5":
            case "h6":
            case "head":
            case "hr":
            case "i":
            case "img":
            case "li":
            case "listing":
            case "menu":
            case "meta":
            case "nobr":
            case "ol":
            case "p":
            case "pre":
            case "ruby":
            case "s":
            case "small":
            case "span":
            case "strong":
            case "strike":
            case "sub":
            case "sup":
            case "table":
            case "tt":
            case "u":
            case "ul":
            case "var":
              if (fragment) {
                break;
              }
              do {
                stack.pop();
                current = stack.top;
              } while (current.namespaceURI !== NAMESPACE.HTML && !isMathmlTextIntegrationPoint(current) && !isHTMLIntegrationPoint(current));
              insertToken(t, value, arg3, arg4);
              return;
          }
          current = stack.elements.length === 1 && fragment ? fragmentContext : stack.top;
          if (current.namespaceURI === NAMESPACE.MATHML) {
            adjustMathMLAttributes(arg3);
          } else if (current.namespaceURI === NAMESPACE.SVG) {
            value = adjustSVGTagName(value);
            adjustSVGAttributes(arg3);
          }
          adjustForeignAttributes(arg3);
          insertForeignElement(value, arg3, current.namespaceURI);
          if (arg4) {
            if (value === "script" && current.namespaceURI === NAMESPACE.SVG) {}
            stack.pop();
          }
          return;
        case 3:
          current = stack.top;
          if (value === "script" && current.namespaceURI === NAMESPACE.SVG && current.localName === "script") {
            stack.pop();
          } else {
            var i = stack.elements.length - 1;
            var node = stack.elements[i];
            for (;; ) {
              if (node.localName.toLowerCase() === value) {
                stack.popElement(node);
                break;
              }
              node = stack.elements[--i];
              if (node.namespaceURI !== NAMESPACE.HTML)
                continue;
              parser2(t, value, arg3, arg4);
              break;
            }
          }
          return;
      }
    }
    htmlparser.testTokenizer = function(input, initialState, lastStartTag, charbychar) {
      var tokens = [];
      switch (initialState) {
        case "PCDATA state":
          tokenizer = data_state;
          break;
        case "RCDATA state":
          tokenizer = rcdata_state;
          break;
        case "RAWTEXT state":
          tokenizer = rawtext_state;
          break;
        case "PLAINTEXT state":
          tokenizer = plaintext_state;
          break;
      }
      if (lastStartTag) {
        lasttagname = lastStartTag;
      }
      insertToken = function(t, value, arg3, arg4) {
        flushText();
        switch (t) {
          case 1:
            if (tokens.length > 0 && tokens[tokens.length - 1][0] === "Character") {
              tokens[tokens.length - 1][1] += value;
            } else
              tokens.push(["Character", value]);
            break;
          case 4:
            tokens.push(["Comment", value]);
            break;
          case 5:
            tokens.push([
              "DOCTYPE",
              value,
              arg3 === undefined ? null : arg3,
              arg4 === undefined ? null : arg4,
              !force_quirks
            ]);
            break;
          case 2:
            var attrs = Object.create(null);
            for (var i2 = 0;i2 < arg3.length; i2++) {
              var a = arg3[i2];
              if (a.length === 1) {
                attrs[a[0]] = "";
              } else {
                attrs[a[0]] = a[1];
              }
            }
            var token = ["StartTag", value, attrs];
            if (arg4)
              token.push(true);
            tokens.push(token);
            break;
          case 3:
            tokens.push(["EndTag", value]);
            break;
          case -1:
            break;
        }
      };
      if (!charbychar) {
        this.parse(input, true);
      } else {
        for (var i = 0;i < input.length; i++) {
          this.parse(input[i]);
        }
        this.parse("", true);
      }
      return tokens;
    };
    return htmlparser;
  }
});

// node_modules/@mixmark-io/domino/lib/DOMImplementation.js
var require_DOMImplementation = __commonJS((exports, module) => {
  module.exports = DOMImplementation;
  var Document2 = require_Document2();
  var DocumentType = require_DocumentType();
  var HTMLParser = require_HTMLParser();
  var utils = require_utils();
  var xml = require_xmlnames();
  function DOMImplementation(contextObject) {
    this.contextObject = contextObject;
  }
  var supportedFeatures = {
    xml: { "": true, "1.0": true, "2.0": true },
    core: { "": true, "2.0": true },
    html: { "": true, "1.0": true, "2.0": true },
    xhtml: { "": true, "1.0": true, "2.0": true }
  };
  DOMImplementation.prototype = {
    hasFeature: function hasFeature(feature, version) {
      var f = supportedFeatures[(feature || "").toLowerCase()];
      return f && f[version || ""] || false;
    },
    createDocumentType: function createDocumentType(qualifiedName, publicId, systemId) {
      if (!xml.isValidQName(qualifiedName))
        utils.InvalidCharacterError();
      return new DocumentType(this.contextObject, qualifiedName, publicId, systemId);
    },
    createDocument: function createDocument(namespace, qualifiedName, doctype) {
      var d = new Document2(false, null);
      var e;
      if (qualifiedName)
        e = d.createElementNS(namespace, qualifiedName);
      else
        e = null;
      if (doctype) {
        d.appendChild(doctype);
      }
      if (e)
        d.appendChild(e);
      if (namespace === utils.NAMESPACE.HTML) {
        d._contentType = "application/xhtml+xml";
      } else if (namespace === utils.NAMESPACE.SVG) {
        d._contentType = "image/svg+xml";
      } else {
        d._contentType = "application/xml";
      }
      return d;
    },
    createHTMLDocument: function createHTMLDocument(titleText) {
      var d = new Document2(true, null);
      d.appendChild(new DocumentType(d, "html"));
      var html = d.createElement("html");
      d.appendChild(html);
      var head = d.createElement("head");
      html.appendChild(head);
      if (titleText !== undefined) {
        var title = d.createElement("title");
        head.appendChild(title);
        title.appendChild(d.createTextNode(titleText));
      }
      html.appendChild(d.createElement("body"));
      d.modclock = 1;
      return d;
    },
    mozSetOutputMutationHandler: function(doc, handler3) {
      doc.mutationHandler = handler3;
    },
    mozGetInputMutationHandler: function(doc) {
      utils.nyi();
    },
    mozHTMLParser: HTMLParser
  };
});

// node_modules/@mixmark-io/domino/lib/Location.js
var require_Location = __commonJS((exports, module) => {
  var URL2 = require_URL();
  var URLUtils = require_URLUtils();
  module.exports = Location;
  function Location(window2, href) {
    this._window = window2;
    this._href = href;
  }
  Location.prototype = Object.create(URLUtils.prototype, {
    constructor: { value: Location },
    href: {
      get: function() {
        return this._href;
      },
      set: function(v) {
        this.assign(v);
      }
    },
    assign: { value: function(url) {
      var current = new URL2(this._href);
      var newurl = current.resolve(url);
      this._href = newurl;
    } },
    replace: { value: function(url) {
      this.assign(url);
    } },
    reload: { value: function() {
      this.assign(this.href);
    } },
    toString: { value: function() {
      return this.href;
    } }
  });
});

// node_modules/@mixmark-io/domino/lib/NavigatorID.js
var require_NavigatorID = __commonJS((exports, module) => {
  var NavigatorID = Object.create(null, {
    appCodeName: { value: "Mozilla" },
    appName: { value: "Netscape" },
    appVersion: { value: "4.0" },
    platform: { value: "" },
    product: { value: "Gecko" },
    productSub: { value: "20100101" },
    userAgent: { value: "" },
    vendor: { value: "" },
    vendorSub: { value: "" },
    taintEnabled: { value: function() {
      return false;
    } }
  });
  module.exports = NavigatorID;
});

// node_modules/@mixmark-io/domino/lib/WindowTimers.js
var require_WindowTimers = __commonJS((exports, module) => {
  var WindowTimers = {
    setTimeout,
    clearTimeout,
    setInterval,
    clearInterval
  };
  module.exports = WindowTimers;
});

// node_modules/@mixmark-io/domino/lib/impl.js
var require_impl = __commonJS((exports, module) => {
  var utils = require_utils();
  exports = module.exports = {
    CSSStyleDeclaration: require_CSSStyleDeclaration(),
    CharacterData: require_CharacterData(),
    Comment: require_Comment(),
    DOMException: require_DOMException(),
    DOMImplementation: require_DOMImplementation(),
    DOMTokenList: require_DOMTokenList(),
    Document: require_Document2(),
    DocumentFragment: require_DocumentFragment(),
    DocumentType: require_DocumentType(),
    Element: require_Element(),
    HTMLParser: require_HTMLParser(),
    NamedNodeMap: require_NamedNodeMap(),
    Node: require_Node2(),
    NodeList: require_NodeList(),
    NodeFilter: require_NodeFilter(),
    ProcessingInstruction: require_ProcessingInstruction(),
    Text: require_Text(),
    Window: require_Window()
  };
  utils.merge(exports, require_events());
  utils.merge(exports, require_htmlelts().elements);
  utils.merge(exports, require_svg().elements);
});

// node_modules/@mixmark-io/domino/lib/Window.js
var require_Window = __commonJS((exports, module) => {
  var DOMImplementation = require_DOMImplementation();
  var EventTarget = require_EventTarget();
  var Location = require_Location();
  var utils = require_utils();
  module.exports = Window;
  function Window(document) {
    this.document = document || new DOMImplementation(null).createHTMLDocument("");
    this.document._scripting_enabled = true;
    this.document.defaultView = this;
    this.location = new Location(this, this.document._address || "about:blank");
  }
  Window.prototype = Object.create(EventTarget.prototype, {
    console: { value: console },
    history: { value: {
      back: utils.nyi,
      forward: utils.nyi,
      go: utils.nyi
    } },
    navigator: { value: require_NavigatorID() },
    window: { get: function() {
      return this;
    } },
    self: { get: function() {
      return this;
    } },
    frames: { get: function() {
      return this;
    } },
    parent: { get: function() {
      return this;
    } },
    top: { get: function() {
      return this;
    } },
    length: { value: 0 },
    frameElement: { value: null },
    opener: { value: null },
    onload: {
      get: function() {
        return this._getEventHandler("load");
      },
      set: function(v) {
        this._setEventHandler("load", v);
      }
    },
    getComputedStyle: { value: function getComputedStyle(elt) {
      return elt.style;
    } }
  });
  utils.expose(require_WindowTimers(), Window);
  utils.expose(require_impl(), Window);
});

// node_modules/@mixmark-io/domino/lib/index.js
var require_lib = __commonJS((exports) => {
  var DOMImplementation = require_DOMImplementation();
  var HTMLParser = require_HTMLParser();
  var Window = require_Window();
  var impl = require_impl();
  exports.createDOMImplementation = function() {
    return new DOMImplementation(null);
  };
  exports.createDocument = function(html, force) {
    if (html || force) {
      var parser2 = new HTMLParser;
      parser2.parse(html || "", true);
      return parser2.document();
    }
    return new DOMImplementation(null).createHTMLDocument("");
  };
  exports.createIncrementalHTMLParser = function() {
    var parser2 = new HTMLParser;
    return {
      write: function(s) {
        if (s.length > 0) {
          parser2.parse(s, false, function() {
            return true;
          });
        }
      },
      end: function(s) {
        parser2.parse(s || "", true, function() {
          return true;
        });
      },
      process: function(shouldPauseFunc) {
        return parser2.parse("", false, shouldPauseFunc);
      },
      document: function() {
        return parser2.document();
      }
    };
  };
  exports.createWindow = function(html, address) {
    var document = exports.createDocument(html);
    if (address !== undefined) {
      document._address = address;
    }
    return new impl.Window(document);
  };
  exports.impl = impl;
});

// node_modules/turndown/lib/turndown.cjs.js
var require_turndown_cjs = __commonJS((exports, module) => {
  function extend(destination) {
    for (var i = 1;i < arguments.length; i++) {
      var source = arguments[i];
      for (var key in source) {
        if (Object.prototype.hasOwnProperty.call(source, key))
          destination[key] = source[key];
      }
    }
    return destination;
  }
  function repeat(character, count) {
    return Array(count + 1).join(character);
  }
  function trimLeadingNewlines(string) {
    return string.replace(/^\n*/, "");
  }
  function trimTrailingNewlines(string) {
    var indexEnd = string.length;
    while (indexEnd > 0 && string[indexEnd - 1] === `
`)
      indexEnd--;
    return string.substring(0, indexEnd);
  }
  function trimNewlines(string) {
    return trimTrailingNewlines(trimLeadingNewlines(string));
  }
  var blockElements = ["ADDRESS", "ARTICLE", "ASIDE", "AUDIO", "BLOCKQUOTE", "BODY", "CANVAS", "CENTER", "DD", "DIR", "DIV", "DL", "DT", "FIELDSET", "FIGCAPTION", "FIGURE", "FOOTER", "FORM", "FRAMESET", "H1", "H2", "H3", "H4", "H5", "H6", "HEADER", "HGROUP", "HR", "HTML", "ISINDEX", "LI", "MAIN", "MENU", "NAV", "NOFRAMES", "NOSCRIPT", "OL", "OUTPUT", "P", "PRE", "SECTION", "TABLE", "TBODY", "TD", "TFOOT", "TH", "THEAD", "TR", "UL"];
  function isBlock(node) {
    return is(node, blockElements);
  }
  var voidElements = ["AREA", "BASE", "BR", "COL", "COMMAND", "EMBED", "HR", "IMG", "INPUT", "KEYGEN", "LINK", "META", "PARAM", "SOURCE", "TRACK", "WBR"];
  function isVoid(node) {
    return is(node, voidElements);
  }
  function hasVoid(node) {
    return has(node, voidElements);
  }
  var meaningfulWhenBlankElements = ["A", "TABLE", "THEAD", "TBODY", "TFOOT", "TH", "TD", "IFRAME", "SCRIPT", "AUDIO", "VIDEO"];
  function isMeaningfulWhenBlank(node) {
    return is(node, meaningfulWhenBlankElements);
  }
  function hasMeaningfulWhenBlank(node) {
    return has(node, meaningfulWhenBlankElements);
  }
  function is(node, tagNames) {
    return tagNames.indexOf(node.nodeName) >= 0;
  }
  function has(node, tagNames) {
    return node.getElementsByTagName && tagNames.some(function(tagName) {
      return node.getElementsByTagName(tagName).length;
    });
  }
  var markdownEscapes = [[/\\/g, "\\\\"], [/\*/g, "\\*"], [/^-/g, "\\-"], [/^\+ /g, "\\+ "], [/^(=+)/g, "\\$1"], [/^(#{1,6}) /g, "\\$1 "], [/`/g, "\\`"], [/^~~~/g, "\\~~~"], [/\[/g, "\\["], [/\]/g, "\\]"], [/^>/g, "\\>"], [/_/g, "\\_"], [/^(\d+)\. /g, "$1\\. "]];
  function escapeMarkdown(string) {
    return markdownEscapes.reduce(function(accumulator, escape) {
      return accumulator.replace(escape[0], escape[1]);
    }, string);
  }
  var rules = {};
  rules.paragraph = {
    filter: "p",
    replacement: function(content) {
      return `

` + content + `

`;
    }
  };
  rules.lineBreak = {
    filter: "br",
    replacement: function(content, node, options) {
      return options.br + `
`;
    }
  };
  rules.heading = {
    filter: ["h1", "h2", "h3", "h4", "h5", "h6"],
    replacement: function(content, node, options) {
      var hLevel = Number(node.nodeName.charAt(1));
      if (options.headingStyle === "setext" && hLevel < 3) {
        var underline = repeat(hLevel === 1 ? "=" : "-", content.length);
        return `

` + content + `
` + underline + `

`;
      } else {
        return `

` + repeat("#", hLevel) + " " + content + `

`;
      }
    }
  };
  rules.blockquote = {
    filter: "blockquote",
    replacement: function(content) {
      content = trimNewlines(content).replace(/^/gm, "> ");
      return `

` + content + `

`;
    }
  };
  rules.list = {
    filter: ["ul", "ol"],
    replacement: function(content, node) {
      var parent = node.parentNode;
      if (parent.nodeName === "LI" && parent.lastElementChild === node) {
        return `
` + content;
      } else {
        return `

` + content + `

`;
      }
    }
  };
  rules.listItem = {
    filter: "li",
    replacement: function(content, node, options) {
      var prefix = options.bulletListMarker + "   ";
      var parent = node.parentNode;
      if (parent.nodeName === "OL") {
        var start = parent.getAttribute("start");
        var index = Array.prototype.indexOf.call(parent.children, node);
        prefix = (start ? Number(start) + index : index + 1) + ".  ";
      }
      var isParagraph = /\n$/.test(content);
      content = trimNewlines(content) + (isParagraph ? `
` : "");
      content = content.replace(/\n/gm, `
` + " ".repeat(prefix.length));
      return prefix + content + (node.nextSibling ? `
` : "");
    }
  };
  rules.indentedCodeBlock = {
    filter: function(node, options) {
      return options.codeBlockStyle === "indented" && node.nodeName === "PRE" && node.firstChild && node.firstChild.nodeName === "CODE";
    },
    replacement: function(content, node, options) {
      return `

    ` + node.firstChild.textContent.replace(/\n/g, `
    `) + `

`;
    }
  };
  rules.fencedCodeBlock = {
    filter: function(node, options) {
      return options.codeBlockStyle === "fenced" && node.nodeName === "PRE" && node.firstChild && node.firstChild.nodeName === "CODE";
    },
    replacement: function(content, node, options) {
      var className = node.firstChild.getAttribute("class") || "";
      var language = (className.match(/language-(\S+)/) || [null, ""])[1];
      var code = node.firstChild.textContent;
      var fenceChar = options.fence.charAt(0);
      var fenceSize = 3;
      var fenceInCodeRegex = new RegExp("^" + fenceChar + "{3,}", "gm");
      var match;
      while (match = fenceInCodeRegex.exec(code)) {
        if (match[0].length >= fenceSize) {
          fenceSize = match[0].length + 1;
        }
      }
      var fence = repeat(fenceChar, fenceSize);
      return `

` + fence + language + `
` + code.replace(/\n$/, "") + `
` + fence + `

`;
    }
  };
  rules.horizontalRule = {
    filter: "hr",
    replacement: function(content, node, options) {
      return `

` + options.hr + `

`;
    }
  };
  rules.inlineLink = {
    filter: function(node, options) {
      return options.linkStyle === "inlined" && node.nodeName === "A" && node.getAttribute("href");
    },
    replacement: function(content, node) {
      var href = escapeLinkDestination(node.getAttribute("href"));
      var title = escapeLinkTitle(cleanAttribute(node.getAttribute("title")));
      var titlePart = title ? ' "' + title + '"' : "";
      return "[" + content + "](" + href + titlePart + ")";
    }
  };
  rules.referenceLink = {
    filter: function(node, options) {
      return options.linkStyle === "referenced" && node.nodeName === "A" && node.getAttribute("href");
    },
    replacement: function(content, node, options) {
      var href = escapeLinkDestination(node.getAttribute("href"));
      var title = cleanAttribute(node.getAttribute("title"));
      if (title)
        title = ' "' + escapeLinkTitle(title) + '"';
      var replacement;
      var reference;
      switch (options.linkReferenceStyle) {
        case "collapsed":
          replacement = "[" + content + "][]";
          reference = "[" + content + "]: " + href + title;
          break;
        case "shortcut":
          replacement = "[" + content + "]";
          reference = "[" + content + "]: " + href + title;
          break;
        default:
          var id = this.references.length + 1;
          replacement = "[" + content + "][" + id + "]";
          reference = "[" + id + "]: " + href + title;
      }
      this.references.push(reference);
      return replacement;
    },
    references: [],
    append: function(options) {
      var references = "";
      if (this.references.length) {
        references = `

` + this.references.join(`
`) + `

`;
        this.references = [];
      }
      return references;
    }
  };
  rules.emphasis = {
    filter: ["em", "i"],
    replacement: function(content, node, options) {
      if (!content.trim())
        return "";
      return options.emDelimiter + content + options.emDelimiter;
    }
  };
  rules.strong = {
    filter: ["strong", "b"],
    replacement: function(content, node, options) {
      if (!content.trim())
        return "";
      return options.strongDelimiter + content + options.strongDelimiter;
    }
  };
  rules.code = {
    filter: function(node) {
      var hasSiblings = node.previousSibling || node.nextSibling;
      var isCodeBlock = node.parentNode.nodeName === "PRE" && !hasSiblings;
      return node.nodeName === "CODE" && !isCodeBlock;
    },
    replacement: function(content) {
      if (!content)
        return "";
      content = content.replace(/\r?\n|\r/g, " ");
      var extraSpace = /^`|^ .*?[^ ].* $|`$/.test(content) ? " " : "";
      var delimiter = "`";
      var matches = content.match(/`+/gm) || [];
      while (matches.indexOf(delimiter) !== -1)
        delimiter = delimiter + "`";
      return delimiter + extraSpace + content + extraSpace + delimiter;
    }
  };
  rules.image = {
    filter: "img",
    replacement: function(content, node) {
      var alt = escapeMarkdown(cleanAttribute(node.getAttribute("alt")));
      var src = escapeLinkDestination(node.getAttribute("src") || "");
      var title = cleanAttribute(node.getAttribute("title"));
      var titlePart = title ? ' "' + escapeLinkTitle(title) + '"' : "";
      return src ? "![" + alt + "]" + "(" + src + titlePart + ")" : "";
    }
  };
  function cleanAttribute(attribute) {
    return attribute ? attribute.replace(/(\n+\s*)+/g, `
`) : "";
  }
  function escapeLinkDestination(destination) {
    var escaped = destination.replace(/([<>()])/g, "\\$1");
    return escaped.indexOf(" ") >= 0 ? "<" + escaped + ">" : escaped;
  }
  function escapeLinkTitle(title) {
    return title.replace(/"/g, "\\\"");
  }
  function Rules(options) {
    this.options = options;
    this._keep = [];
    this._remove = [];
    this.blankRule = {
      replacement: options.blankReplacement
    };
    this.keepReplacement = options.keepReplacement;
    this.defaultRule = {
      replacement: options.defaultReplacement
    };
    this.array = [];
    for (var key in options.rules)
      this.array.push(options.rules[key]);
  }
  Rules.prototype = {
    add: function(key, rule) {
      this.array.unshift(rule);
    },
    keep: function(filter) {
      this._keep.unshift({
        filter,
        replacement: this.keepReplacement
      });
    },
    remove: function(filter) {
      this._remove.unshift({
        filter,
        replacement: function() {
          return "";
        }
      });
    },
    forNode: function(node) {
      if (node.isBlank)
        return this.blankRule;
      var rule;
      if (rule = findRule(this.array, node, this.options))
        return rule;
      if (rule = findRule(this._keep, node, this.options))
        return rule;
      if (rule = findRule(this._remove, node, this.options))
        return rule;
      return this.defaultRule;
    },
    forEach: function(fn) {
      for (var i = 0;i < this.array.length; i++)
        fn(this.array[i], i);
    }
  };
  function findRule(rules2, node, options) {
    for (var i = 0;i < rules2.length; i++) {
      var rule = rules2[i];
      if (filterValue(rule, node, options))
        return rule;
    }
    return;
  }
  function filterValue(rule, node, options) {
    var filter = rule.filter;
    if (typeof filter === "string") {
      if (filter === node.nodeName.toLowerCase())
        return true;
    } else if (Array.isArray(filter)) {
      if (filter.indexOf(node.nodeName.toLowerCase()) > -1)
        return true;
    } else if (typeof filter === "function") {
      if (filter.call(rule, node, options))
        return true;
    } else {
      throw new TypeError("`filter` needs to be a string, array, or function");
    }
  }
  function collapseWhitespace(options) {
    var element = options.element;
    var isBlock2 = options.isBlock;
    var isVoid2 = options.isVoid;
    var isPre = options.isPre || function(node2) {
      return node2.nodeName === "PRE";
    };
    if (!element.firstChild || isPre(element))
      return;
    var prevText = null;
    var keepLeadingWs = false;
    var prev = null;
    var node = next(prev, element, isPre);
    while (node !== element) {
      if (node.nodeType === 3 || node.nodeType === 4) {
        var text = node.data.replace(/[ \r\n\t]+/g, " ");
        if ((!prevText || / $/.test(prevText.data)) && !keepLeadingWs && text[0] === " ") {
          text = text.substr(1);
        }
        if (!text) {
          node = remove(node);
          continue;
        }
        node.data = text;
        prevText = node;
      } else if (node.nodeType === 1) {
        if (isBlock2(node) || node.nodeName === "BR") {
          if (prevText) {
            prevText.data = prevText.data.replace(/ $/, "");
          }
          prevText = null;
          keepLeadingWs = false;
        } else if (isVoid2(node) || isPre(node)) {
          prevText = null;
          keepLeadingWs = true;
        } else if (prevText) {
          keepLeadingWs = false;
        }
      } else {
        node = remove(node);
        continue;
      }
      var nextNode = next(prev, node, isPre);
      prev = node;
      node = nextNode;
    }
    if (prevText) {
      prevText.data = prevText.data.replace(/ $/, "");
      if (!prevText.data) {
        remove(prevText);
      }
    }
  }
  function remove(node) {
    var next2 = node.nextSibling || node.parentNode;
    node.parentNode.removeChild(node);
    return next2;
  }
  function next(prev, current, isPre) {
    if (prev && prev.parentNode === current || isPre(current)) {
      return current.nextSibling || current.parentNode;
    }
    return current.firstChild || current.nextSibling || current.parentNode;
  }
  var root = typeof window !== "undefined" ? window : {};
  function canParseHTMLNatively() {
    var Parser = root.DOMParser;
    var canParse = false;
    try {
      if (new Parser().parseFromString("", "text/html")) {
        canParse = true;
      }
    } catch (e) {}
    return canParse;
  }
  function createHTMLParser() {
    var Parser = function() {};
    {
      var domino = require_lib();
      Parser.prototype.parseFromString = function(string) {
        return domino.createDocument(string);
      };
    }
    return Parser;
  }
  var HTMLParser = canParseHTMLNatively() ? root.DOMParser : createHTMLParser();
  function RootNode(input, options) {
    var root2;
    if (typeof input === "string") {
      var doc = htmlParser().parseFromString('<x-turndown id="turndown-root">' + input + "</x-turndown>", "text/html");
      root2 = doc.getElementById("turndown-root");
    } else {
      root2 = input.cloneNode(true);
    }
    collapseWhitespace({
      element: root2,
      isBlock,
      isVoid,
      isPre: options.preformattedCode ? isPreOrCode : null
    });
    return root2;
  }
  var _htmlParser;
  function htmlParser() {
    _htmlParser = _htmlParser || new HTMLParser;
    return _htmlParser;
  }
  function isPreOrCode(node) {
    return node.nodeName === "PRE" || node.nodeName === "CODE";
  }
  function Node(node, options) {
    node.isBlock = isBlock(node);
    node.isCode = node.nodeName === "CODE" || node.parentNode.isCode;
    node.isBlank = isBlank(node);
    node.flankingWhitespace = flankingWhitespace(node, options);
    return node;
  }
  function isBlank(node) {
    return !isVoid(node) && !isMeaningfulWhenBlank(node) && /^\s*$/i.test(node.textContent) && !hasVoid(node) && !hasMeaningfulWhenBlank(node);
  }
  function flankingWhitespace(node, options) {
    if (node.isBlock || options.preformattedCode && node.isCode) {
      return {
        leading: "",
        trailing: ""
      };
    }
    var edges = edgeWhitespace(node.textContent);
    if (edges.leadingAscii && isFlankedByWhitespace("left", node, options)) {
      edges.leading = edges.leadingNonAscii;
    }
    if (edges.trailingAscii && isFlankedByWhitespace("right", node, options)) {
      edges.trailing = edges.trailingNonAscii;
    }
    return {
      leading: edges.leading,
      trailing: edges.trailing
    };
  }
  function edgeWhitespace(string) {
    var m = string.match(/^(([ \t\r\n]*)(\s*))(?:(?=\S)[\s\S]*\S)?((\s*?)([ \t\r\n]*))$/);
    return {
      leading: m[1],
      leadingAscii: m[2],
      leadingNonAscii: m[3],
      trailing: m[4],
      trailingNonAscii: m[5],
      trailingAscii: m[6]
    };
  }
  function isFlankedByWhitespace(side, node, options) {
    var sibling;
    var regExp;
    var isFlanked;
    if (side === "left") {
      sibling = node.previousSibling;
      regExp = / $/;
    } else {
      sibling = node.nextSibling;
      regExp = /^ /;
    }
    if (sibling) {
      if (sibling.nodeType === 3) {
        isFlanked = regExp.test(sibling.nodeValue);
      } else if (options.preformattedCode && sibling.nodeName === "CODE") {
        isFlanked = false;
      } else if (sibling.nodeType === 1 && !isBlock(sibling)) {
        isFlanked = regExp.test(sibling.textContent);
      }
    }
    return isFlanked;
  }
  var reduce = Array.prototype.reduce;
  function TurndownService(options) {
    if (!(this instanceof TurndownService))
      return new TurndownService(options);
    var defaults = {
      rules,
      headingStyle: "setext",
      hr: "* * *",
      bulletListMarker: "*",
      codeBlockStyle: "indented",
      fence: "```",
      emDelimiter: "_",
      strongDelimiter: "**",
      linkStyle: "inlined",
      linkReferenceStyle: "full",
      br: "  ",
      preformattedCode: false,
      blankReplacement: function(content, node) {
        return node.isBlock ? `

` : "";
      },
      keepReplacement: function(content, node) {
        return node.isBlock ? `

` + node.outerHTML + `

` : node.outerHTML;
      },
      defaultReplacement: function(content, node) {
        return node.isBlock ? `

` + content + `

` : content;
      }
    };
    this.options = extend({}, defaults, options);
    this.rules = new Rules(this.options);
  }
  TurndownService.prototype = {
    turndown: function(input) {
      if (!canConvert(input)) {
        throw new TypeError(input + " is not a string, or an element/document/fragment node.");
      }
      if (input === "")
        return "";
      var output = process2.call(this, new RootNode(input, this.options));
      return postProcess.call(this, output);
    },
    use: function(plugin) {
      if (Array.isArray(plugin)) {
        for (var i = 0;i < plugin.length; i++)
          this.use(plugin[i]);
      } else if (typeof plugin === "function") {
        plugin(this);
      } else {
        throw new TypeError("plugin must be a Function or an Array of Functions");
      }
      return this;
    },
    addRule: function(key, rule) {
      this.rules.add(key, rule);
      return this;
    },
    keep: function(filter) {
      this.rules.keep(filter);
      return this;
    },
    remove: function(filter) {
      this.rules.remove(filter);
      return this;
    },
    escape: function(string) {
      return escapeMarkdown(string);
    }
  };
  function process2(parentNode) {
    var self = this;
    return reduce.call(parentNode.childNodes, function(output, node) {
      node = new Node(node, self.options);
      var replacement = "";
      if (node.nodeType === 3) {
        replacement = node.isCode ? node.nodeValue : self.escape(node.nodeValue);
      } else if (node.nodeType === 1) {
        replacement = replacementForNode.call(self, node);
      }
      return join(output, replacement);
    }, "");
  }
  function postProcess(output) {
    var self = this;
    this.rules.forEach(function(rule) {
      if (typeof rule.append === "function") {
        output = join(output, rule.append(self.options));
      }
    });
    return output.replace(/^[\t\r\n]+/, "").replace(/[\t\r\n\s]+$/, "");
  }
  function replacementForNode(node) {
    var rule = this.rules.forNode(node);
    var content = process2.call(this, node);
    var whitespace = node.flankingWhitespace;
    if (whitespace.leading || whitespace.trailing)
      content = content.trim();
    return whitespace.leading + rule.replacement(content, node, this.options) + whitespace.trailing;
  }
  function join(output, replacement) {
    var s1 = trimTrailingNewlines(output);
    var s2 = trimLeadingNewlines(replacement);
    var nls = Math.max(output.length - s1.length, replacement.length - s2.length);
    var separator = `

`.substring(0, nls);
    return s1 + separator + s2;
  }
  function canConvert(input) {
    return input != null && (typeof input === "string" || input.nodeType && (input.nodeType === 1 || input.nodeType === 9 || input.nodeType === 11));
  }
  module.exports = TurndownService;
});

// scripts/akm-migrate.ts
import { pathToFileURL as pathToFileURL2 } from "url";

// node_modules/yaml/dist/index.js
var composer = require_composer();
var Document = require_Document();
var Schema = require_Schema();
var errors = require_errors();
var Alias = require_Alias();
var identity = require_identity();
var Pair = require_Pair();
var Scalar = require_Scalar();
var YAMLMap = require_YAMLMap();
var YAMLSeq = require_YAMLSeq();
var cst = require_cst();
var lexer = require_lexer();
var lineCounter = require_line_counter();
var parser = require_parser();
var publicApi = require_public_api();
var visit = require_visit();
var $Composer = composer.Composer;
var $Document = Document.Document;
var $Schema = Schema.Schema;
var $YAMLError = errors.YAMLError;
var $YAMLParseError = errors.YAMLParseError;
var $YAMLWarning = errors.YAMLWarning;
var $Alias = Alias.Alias;
var $isAlias = identity.isAlias;
var $isCollection = identity.isCollection;
var $isDocument = identity.isDocument;
var $isMap = identity.isMap;
var $isNode = identity.isNode;
var $isPair = identity.isPair;
var $isScalar = identity.isScalar;
var $isSeq = identity.isSeq;
var $Pair = Pair.Pair;
var $Scalar = Scalar.Scalar;
var $YAMLMap = YAMLMap.YAMLMap;
var $YAMLSeq = YAMLSeq.YAMLSeq;
var $Lexer = lexer.Lexer;
var $LineCounter = lineCounter.LineCounter;
var $Parser = parser.Parser;
var $parse = publicApi.parse;
var $parseAllDocuments = publicApi.parseAllDocuments;
var $parseDocument = publicApi.parseDocument;
var $stringify = publicApi.stringify;
var $visit = visit.visit;
var $visitAsync = visit.visitAsync;

// src/output/html-render.ts
import path7 from "node:path";
// src/runtime.ts
import { spawn as nodeSpawn, spawnSync as nodeSpawnSync } from "node:child_process";
import { createWriteStream, statfsSync } from "node:fs";
import { createRequire as createRequire2 } from "node:module";
import path6 from "node:path";
import { Readable } from "node:stream";
import { pipeline } from "node:stream/promises";
import { fileURLToPath } from "node:url";

// src/core/common.ts
import crypto2 from "node:crypto";
import fs2 from "node:fs";
import path5 from "node:path";

// src/core/config/legacy-source-shape-shim.ts
import path2 from "node:path";

// src/core/asset/asset-ref.ts
import path from "node:path";

// src/core/errors.ts
var CONFIG_HINTS = {
  STASH_DIR_NOT_FOUND: "Run `akm setup` to create and configure your bundle, or configure a defaultBundle path.",
  STASH_DIR_NOT_A_DIRECTORY: "The configured default bundle path exists but isn't a directory. Update it to point at a folder.",
  STASH_DIR_UNREADABLE: "Check the path exists and your user has read permission, or update the default bundle path.",
  DATA_DIR_UNREADABLE: "The data directory is not readable by the user running akm. Check its owner and mode, or point AKM_DATA_DIR / XDG_DATA_HOME somewhere this user owns.",
  INDEX_SCHEMA_INCOMPATIBLE: "Run `akm index --full` to rebuild the derived index from the currently materialized sources.",
  LLM_NOT_CONFIGURED: 'Run `akm setup` or configure an `engines` entry with `kind: "llm"`, then select it with `defaults.llmEngine`.',
  TEST_ISOLATION_MISSING: "Under bun test, when AKM_BUNDLE_DIR is set you MUST also set XDG_DATA_HOME (or AKM_DATA_DIR) and XDG_STATE_HOME (or AKM_STATE_DIR) to temp directories so the test does not touch the developer's real ~/.local/share/akm or ~/.local/state/akm.",
  UNSAFE_STASH_DIR: "Choose a path inside your home directory (e.g. ~/akm) or another empty workspace. The bundle directory cannot be the filesystem root, your home directory itself, or a sensitive system path like /etc, /var, ~/.config, or ~/.ssh.",
  UNKNOWN_IMPROVE_STRATEGY: "Pass one of the listed strategy names to `--strategy`, or define it under `improve.strategies`. Names are case-sensitive.",
  EXECUTION_NOT_AUTHORIZED: "Change the selected tools or update the machine/user execution policy, then retry.",
  SECRET_REFERENCE_UNRESOLVED: "Check the secret exists (`akm secret list`) and the name after `secret://` matches, or run `akm secret set <name> <value>` to store it.",
  REGISTRY_URL_INVALID: "Registry URLs must be credential-free http(s) URLs. Fix the entry with `akm registry list` / `akm registry add`, or the AKM_REGISTRY_URL / AKM_NPM_REGISTRY variable that supplied it."
};
var COMPOSITION_INVALID_MULTI_JOB_HINT = "AKM workflows support exactly one job per source, with no needs: between jobs. Split the extra job(s) into " + "their own workflow file, and compose them with uses: workflows/<ref> instead.";
var USAGE_HINTS = {
  INVALID_FLAG_VALUE: "Run `akm <command> --help` to see accepted values.",
  INVALID_SOURCE_VALUE: "Pick one of: local, registry, all, or a configured source name.",
  INVALID_FORMAT_VALUE: "Pick one of: json, jsonl, yaml, text, md, html.",
  INVALID_DETAIL_VALUE: "Pick one of: brief, normal, full. For agent/summary projections use --shape.",
  INVALID_SHAPE_VALUE: "Pick one of: human, agent, summary (summary falls back to agent, with a warning, on commands with no summary projection).",
  INVALID_JSON_CONFIG_VALUE: `Quote JSON values in your shell, for example: akm config set embedding '{"endpoint":"http://localhost:11434/v1/embeddings","model":"nomic-embed-text"}'.`,
  MISSING_OR_AMBIGUOUS_TARGET: "Use `akm bundle update --all` or pass a target like `akm bundle update npm:@scope/pkg` (not both).",
  TARGET_NOT_UPDATABLE: "Run `akm bundle list` to view your sources, then retry with one of those values.",
  MISSING_REQUIRED_ARGUMENT: "Refs use the form [bundle//]conceptId, e.g. `akm show knowledge/guide.md` or `akm show skills/deploy`.",
  UNKNOWN_COMMAND: "Run `akm --help` to see available commands.",
  UNKNOWN_FLAG: "Run the command with `--help` to see its accepted flags.",
  COMPOSITION_INVALID: "Remove the with: block, or target a tasks/<ref> whose source declares inputs: — commands/<ref> and scripts/<ref> steps are not binding surfaces.",
  TASK_SOURCE_INVALID: "Fix the task source at the reported path and line, then re-run.",
  TARGET_REF_INVALID: "Targets are canonical asset refs: `commands/review`, `scripts/build.sh`, `tasks/nightly`, `workflows/release`.",
  WORKFLOW_SOURCE_INVALID: "Run `akm lint` to see the failing source location, or `akm workflow plan <ref>` to compile it without writing.",
  INPUT_BINDING_INVALID: "Check the step's with: keys against the target's declared inputs.",
  TASK_TARGET_UNSUPPORTED: "Task definitions support command, script, workflow, and shell (run:) targets; akm/command is layered by callers."
};
var TRANSIENT_HINTS = {
  RUN_LEASE_HELD: "Wait for the akm process driving this run (the named pid) to finish, then retry.",
  STATE_DB_CONTENDED: "Another akm process is writing state.db right now. Wait a few seconds and retry; commands that support --skip-if-locked can skip instead of failing.",
  INDEX_DB_CONTENDED: "Another akm process is writing index.db; retry shortly, or pass --skip-if-locked on scheduled runs.",
  IMPROVE_LOCK_HELD: "Another akm improve run holds the whole-run lock right now. Wait for it to finish and retry, or pass --skip-if-locked on scheduled runs.",
  LOCKFILE_CONTENDED: "Another akm process is updating its bundle lockfile right now. Wait a few seconds and retry.",
  ASSET_MUTATION_LEASE_HELD: "Another akm process is writing bundle content right now. Wait for it to finish and retry.",
  SCHEDULER_LOCK_HELD: "Another `akm task sync`, `add`, `enable`, `disable` or `prune` is writing the scheduler right now. Wait for it to finish and retry.",
  REGISTRY_UNREACHABLE: "The registry did not answer in time. Check the network and the registry URL (`akm registry list`), then retry."
};
var NOT_FOUND_HINTS = {
  ASSET_NOT_FOUND: "Run `akm search <query>` or `akm index` to refresh the index.",
  SOURCE_NOT_FOUND: "Run `akm bundle list` to view your sources, then retry with one of those values.",
  WORKFLOW_NOT_FOUND: "Run `akm workflow list --active` to see runs.",
  PROPOSAL_NOT_FOUND: "Run `akm proposal list` to see pending proposals and their ids.",
  FILE_NOT_FOUND: "Check the path exists and is readable.",
  IMPROVE_RUN_NOT_FOUND: "Run `akm improve` first, or `akm improve report --since 30d` to see recent run ids in `runIds`.",
  REGISTRY_NOT_FOUND: "Check the ref's spelling and version; `akm search <query> --from registry` lists installable refs."
};

class AkmError extends Error {
}

class ConfigError extends AkmError {
  kind = "config";
  code;
  _hint;
  constructor(msg, code = "INVALID_CONFIG_FILE", hint) {
    super(msg);
    this.name = "ConfigError";
    this.code = code;
    this._hint = hint;
    Object.setPrototypeOf(this, new.target.prototype);
  }
  hint() {
    return this._hint ?? CONFIG_HINTS[this.code];
  }
}

class UsageError extends AkmError {
  kind = "usage";
  code;
  _hint;
  constructor(msg, code = "INVALID_FLAG_VALUE", hint) {
    super(msg);
    this.name = "UsageError";
    this.code = code;
    this._hint = hint;
    Object.setPrototypeOf(this, new.target.prototype);
  }
  hint() {
    return this._hint ?? USAGE_HINTS[this.code];
  }
}

class TransientError extends AkmError {
  kind = "transient";
  code;
  _hint;
  constructor(msg, code, hint) {
    super(msg);
    this.name = "TransientError";
    this.code = code;
    this._hint = hint;
    Object.setPrototypeOf(this, new.target.prototype);
  }
  hint() {
    return this._hint ?? TRANSIENT_HINTS[this.code];
  }
}

class NotFoundError extends AkmError {
  kind = "not-found";
  code;
  _hint;
  constructor(msg, code = "ASSET_NOT_FOUND", hint) {
    super(msg);
    this.name = "NotFoundError";
    this.code = code;
    this._hint = hint;
    Object.setPrototypeOf(this, new.target.prototype);
  }
  hint() {
    return this._hint ?? NOT_FOUND_HINTS[this.code];
  }
}
function isTestIsolationError(err) {
  return err instanceof ConfigError && err.code === "TEST_ISOLATION_MISSING";
}
function rethrowIfTestIsolationError(err) {
  if (isTestIsolationError(err)) {
    throw err;
  }
}

// src/core/asset/asset-ref.ts
function validateName(name) {
  if (!name)
    throw new UsageError("Empty asset name.", "MISSING_REQUIRED_ARGUMENT");
  if (name.includes("\x00"))
    throw new UsageError("Null byte in asset name.", "MISSING_REQUIRED_ARGUMENT");
  if (/^[A-Za-z]:/.test(name))
    throw new UsageError("Windows drive path in asset name.", "MISSING_REQUIRED_ARGUMENT");
  const slashName = name.replace(/\\/g, "/");
  if (slashName === ".." || slashName.startsWith("../")) {
    throw new UsageError("Path traversal in asset name.", "MISSING_REQUIRED_ARGUMENT");
  }
  if (slashName.split("/").some((seg) => seg === "." || seg === "..")) {
    throw new UsageError("Asset name cannot contain relative path segments.", "MISSING_REQUIRED_ARGUMENT");
  }
  const normalized = path.posix.normalize(slashName);
  if (path.posix.isAbsolute(normalized))
    throw new UsageError("Absolute path in asset name.", "MISSING_REQUIRED_ARGUMENT");
  if (normalized === ".." || normalized.startsWith("../")) {
    throw new UsageError("Path traversal in asset name.", "MISSING_REQUIRED_ARGUMENT");
  }
}
function normalizeName(name) {
  return path.posix.normalize(name.replace(/\\/g, "/"));
}
var BUNDLE_SLUG_RE = /^[^\s:.#/]+$/;
function isBundleSlug(s) {
  return BUNDLE_SLUG_RE.test(s);
}
function normalizeConceptId(raw) {
  const nfc = raw.normalize("NFC");
  if (nfc.includes("#")) {
    throw new UsageError("`#` is reserved for the export fragment in a concept id.", "MISSING_REQUIRED_ARGUMENT");
  }
  validateName(nfc);
  return normalizeName(nfc);
}
function makeBundleRef(bundle, conceptId, fragment) {
  const normalized = normalizeConceptId(conceptId);
  let out = normalized;
  if (bundle) {
    if (!BUNDLE_SLUG_RE.test(bundle)) {
      throw new UsageError(`Invalid bundle slug "${bundle}". A bundle slug may not contain ':', '.', '#', '/', or whitespace.`, "MISSING_REQUIRED_ARGUMENT");
    }
    out = `${bundle}//${normalized}`;
  }
  if (fragment)
    out = `${out}#${fragment}`;
  return out;
}
function bundleRefToString(ref) {
  return makeBundleRef(ref.bundle, ref.conceptId, ref.fragment);
}
function parseBundleRef(ref) {
  const trimmed = ref.trim();
  if (!trimmed)
    throw new UsageError("Empty ref.", "MISSING_REQUIRED_ARGUMENT");
  let bundle;
  let body = trimmed;
  const boundary = trimmed.indexOf("//");
  if (boundary >= 0) {
    bundle = trimmed.slice(0, boundary);
    body = trimmed.slice(boundary + 2);
    if (!bundle)
      throw new UsageError("Empty bundle in ref.", "MISSING_REQUIRED_ARGUMENT");
    if (!BUNDLE_SLUG_RE.test(bundle)) {
      throw new UsageError(`Invalid bundle slug "${bundle}" in ref "${trimmed}". A bundle slug may not contain ':', '.', '#', '/', or whitespace.`, "MISSING_REQUIRED_ARGUMENT");
    }
  }
  let fragment;
  const hash = body.indexOf("#");
  if (hash >= 0) {
    fragment = body.slice(hash + 1) || undefined;
    body = body.slice(0, hash);
  }
  if (!body) {
    throw new UsageError(`Invalid ref "${trimmed}". Expected [bundle//]conceptId, e.g. knowledge/guide or core//skills/review`, "MISSING_REQUIRED_ARGUMENT");
  }
  const conceptId = normalizeConceptId(body);
  return { bundle: bundle || undefined, conceptId, fragment };
}

// src/core/warn.ts
import fs from "node:fs";
var quiet = false;
var logFilePath;
var sinkOverride;
function appendToLogFile(level, args) {
  if (!logFilePath)
    return;
  const ts = new Date().toISOString();
  const msg = args.map((a) => typeof a === "string" ? a : JSON.stringify(a)).join(" ");
  try {
    fs.appendFileSync(logFilePath, `[${ts}] [${level}] ${msg}
`);
  } catch (e) {
    process.stderr.write(`[akm:warn] log-file write failed (${logFilePath}): ${e}
`);
    process.stderr.write(`[${ts}] [${level}] ${msg}
`);
  }
}
function warn(...args) {
  if (sinkOverride) {
    sinkOverride("warn", args);
    return;
  }
  appendToLogFile("WARN", args);
  if (!quiet) {
    console.warn(...args);
  }
}
var warnedOnceKeys = new Set;
function warnOnce(key, ...args) {
  if (warnedOnceKeys.has(key))
    return;
  warnedOnceKeys.add(key);
  warn(...args);
}

// src/core/config/legacy-source-shape-shim.ts
function isPlainRecord(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}
var DEFAULT_WRITABLE_BY_TYPE = {
  filesystem: true,
  git: false,
  website: false,
  npm: false
};
function bundleFromLegacySource(entry, index) {
  if (!isPlainRecord(entry))
    return;
  const type = typeof entry.type === "string" ? entry.type : undefined;
  const bundle = {};
  switch (type) {
    case "filesystem":
      if (typeof entry.path !== "string" || !entry.path)
        return;
      bundle.path = entry.path;
      break;
    case "git":
      if (typeof entry.url !== "string" || !entry.url)
        return;
      bundle.git = entry.url;
      break;
    case "website":
      if (typeof entry.url !== "string" || !entry.url)
        return;
      bundle.website = { url: entry.url };
      break;
    case "npm": {
      const spec = typeof entry.url === "string" && entry.url ? entry.url : entry.path;
      if (typeof spec !== "string" || !spec)
        return;
      bundle.npm = spec;
      break;
    }
    default:
      return;
  }
  const writable = typeof entry.writable === "boolean" ? entry.writable : DEFAULT_WRITABLE_BY_TYPE[type ?? ""];
  if (writable !== undefined)
    bundle.writable = writable;
  if (typeof entry.enabled === "boolean")
    bundle.enabled = entry.enabled;
  const name = typeof entry.name === "string" ? entry.name : undefined;
  const key = name && isBundleSlug(name) ? name : `source-${index + 1}`;
  return [key, bundle];
}
function filesystemLocator(bundle) {
  if (!isPlainRecord(bundle) || typeof bundle.path !== "string" || bundle.path.length === 0)
    return;
  return path2.resolve(bundle.path);
}
function convertLegacySourceShape(raw) {
  const hasStashDir = "stashDir" in raw;
  const hasSources = "sources" in raw;
  const hasInstalled = "installed" in raw && raw.installed !== undefined;
  if (!hasStashDir && !hasSources && !hasInstalled)
    return { config: raw, converted: [] };
  const { stashDir: _stashDir, sources: _sources, installed: _installed, ...rest } = raw;
  const bundles = isPlainRecord(rest.bundles) ? { ...rest.bundles } : {};
  let defaultBundle = typeof rest.defaultBundle === "string" ? rest.defaultBundle : undefined;
  const usableStashDir = typeof raw.stashDir === "string" && raw.stashDir.trim().length > 0;
  if (usableStashDir) {
    bundles.stash = { path: raw.stashDir, writable: true };
    defaultBundle ??= "stash";
  }
  if (Array.isArray(raw.sources)) {
    raw.sources.forEach((entry, index) => {
      const converted2 = bundleFromLegacySource(entry, index);
      if (!converted2)
        return;
      const [key, bundle] = converted2;
      const locator = filesystemLocator(bundle);
      if (locator && Object.values(bundles).some((candidate) => filesystemLocator(candidate) === locator))
        return;
      bundles[key] = bundle;
      defaultBundle ??= key;
    });
  }
  const converted = [hasStashDir && "stashDir", hasSources && "sources", hasInstalled && "installed"].filter((key) => typeof key === "string");
  const hasBundles = Object.keys(bundles).length > 0 || isPlainRecord(rest.bundles);
  return {
    config: { ...rest, ...hasBundles ? { bundles } : {}, ...defaultBundle !== undefined ? { defaultBundle } : {} },
    converted
  };
}
function migrateLegacySourceShape(raw, sourcePath) {
  const { config, converted } = convertLegacySourceShape(raw);
  if (converted.length === 0)
    return config;
  const where = sourcePath ? ` at ${sourcePath}` : "";
  warnOnce(`legacy-source-shape${sourcePath ? `:${sourcePath}` : ""}`, `Config${where} uses the retired ${converted.join("/")} shape — auto-migrated in memory to \`bundles\`/\`defaultBundle\`. Run \`akm migrate apply\` to rewrite the config file and silence this warning.`);
  return config;
}

// src/core/paths.ts
import os from "node:os";
import path4 from "node:path";

// src/core/bundle-id.ts
import crypto from "node:crypto";
import path3 from "node:path";
function slugForPath(sourcePath) {
  const resolved = path3.resolve(sourcePath);
  const base = slugify(path3.basename(resolved));
  if (base.length > 0)
    return base;
  return `bundle-${shortHash(resolved)}`;
}
function slugify(name) {
  return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
}
function deriveBundleId(registryId, sourcePath, usedIds) {
  const preferred = registryId && registryId.length > 0 && isBundleSlug(registryId) ? registryId : slugForPath(sourcePath);
  const id = ensureUniqueId(preferred, sourcePath, usedIds);
  usedIds.add(id);
  return id;
}
function ensureUniqueId(preferred, sourcePath, used) {
  if (!used.has(preferred))
    return preferred;
  const suffixed = `${preferred}-${shortHash(path3.resolve(sourcePath))}`;
  if (!used.has(suffixed))
    return suffixed;
  let n = 2;
  while (used.has(`${suffixed}-${n}`))
    n++;
  return `${suffixed}-${n}`;
}
function shortHash(input) {
  return crypto.createHash("sha256").update(input).digest("hex").slice(0, 8);
}

// src/core/platform.ts
var IS_WINDOWS = process.platform === "win32";

// src/core/paths.ts
function isUnderBunTest(env) {
  return env.BUN_TEST === "1" || env.NODE_ENV === "test";
}
function isTransientStashPath(p) {
  return p.startsWith("/tmp/") || p === "/tmp" || p.startsWith("/var/tmp/") || p === "/var/tmp" || p.startsWith("/private/tmp/") || p.startsWith("/private/var/folders/") || p.startsWith("/var/folders/");
}
function testIsolationError() {
  return new ConfigError("Refusing to resolve data directory under bun test: neither XDG_DATA_HOME nor AKM_DATA_DIR is set. " + "This guards against tests writing into the developer's real ~/.local/share/akm. " + "Set XDG_DATA_HOME (or AKM_DATA_DIR) to a mktemp-d directory in this test's env block.", "TEST_ISOLATION_MISSING");
}
function getConfigDir(env = process.env, platform = process.platform) {
  const override = env.AKM_CONFIG_DIR?.trim();
  if (override)
    return override;
  if (platform === "win32") {
    const appData = env.APPDATA?.trim();
    if (appData)
      return path4.join(appData, "akm");
  } else {
    const xdgConfigHome2 = env.XDG_CONFIG_HOME?.trim();
    if (xdgConfigHome2)
      return path4.join(xdgConfigHome2, "akm");
  }
  const stashOverride = env.AKM_BUNDLE_DIR?.trim();
  if (stashOverride && isTransientStashPath(stashOverride)) {
    return path4.join(stashOverride, ".akm");
  }
  if (platform === "win32") {
    const appData = env.APPDATA?.trim();
    if (appData)
      return path4.join(appData, "akm");
    const userProfile = env.USERPROFILE?.trim();
    if (!userProfile) {
      throw new ConfigError("Unable to determine config directory. Set APPDATA or USERPROFILE.", "CONFIG_DIR_UNRESOLVABLE");
    }
    return path4.join(userProfile, "AppData", "Roaming", "akm");
  }
  const xdgConfigHome = env.XDG_CONFIG_HOME?.trim();
  if (xdgConfigHome)
    return path4.join(xdgConfigHome, "akm");
  const home = env.HOME?.trim();
  if (!home) {
    throw new ConfigError("Unable to determine config directory. Set XDG_CONFIG_HOME or HOME.", "CONFIG_DIR_UNRESOLVABLE");
  }
  return path4.join(home, ".config", "akm");
}
function getConfigPath(env = process.env) {
  return path4.join(getConfigDir(env), "config.json");
}
function getCacheDir(env = process.env) {
  const override = env.AKM_CACHE_DIR?.trim();
  if (override)
    return override;
  if (IS_WINDOWS) {
    const localAppData = env.LOCALAPPDATA?.trim();
    if (localAppData)
      return path4.join(localAppData, "akm");
    const userProfile = env.USERPROFILE?.trim();
    if (userProfile)
      return path4.join(userProfile, "AppData", "Local", "akm");
    const appData = env.APPDATA?.trim();
    if (appData) {
      return path4.join(appData, "..", "Local", "akm");
    }
  } else {
    const xdgCacheHome = env.XDG_CACHE_HOME?.trim();
    if (xdgCacheHome)
      return path4.join(xdgCacheHome, "akm");
  }
  const stashOverride = env.AKM_BUNDLE_DIR?.trim();
  if (stashOverride && isTransientStashPath(stashOverride)) {
    return path4.join(stashOverride, ".akm", "cache");
  }
  if (IS_WINDOWS) {
    throw new ConfigError("Unable to determine cache directory. Set LOCALAPPDATA, USERPROFILE, or APPDATA.", "CONFIG_DIR_UNRESOLVABLE");
  }
  const home = env.HOME?.trim();
  if (!home)
    return homelessFallbackDir("akm-cache");
  return path4.join(home, ".cache", "akm");
}
function homelessFallbackDir(kind) {
  const uid = typeof process.getuid === "function" ? process.getuid() : undefined;
  return path4.join(os.tmpdir(), uid === undefined ? kind : `${kind}-${uid}`);
}
function getDataDir(env = process.env, platform = process.platform) {
  const override = env.AKM_DATA_DIR?.trim();
  if (override)
    return override;
  if (isUnderBunTest(env) && !env.XDG_DATA_HOME?.trim()) {
    throw testIsolationError();
  }
  if (platform === "win32") {
    const localAppData = env.LOCALAPPDATA?.trim();
    if (localAppData)
      return path4.join(localAppData, "akm", "data");
    const userProfile = env.USERPROFILE?.trim();
    if (userProfile)
      return path4.join(userProfile, "AppData", "Local", "akm", "data");
    const appData = env.APPDATA?.trim();
    if (!appData) {
      throw new ConfigError("Unable to determine data directory. Set LOCALAPPDATA, USERPROFILE, or APPDATA.", "CONFIG_DIR_UNRESOLVABLE");
    }
    return path4.join(appData, "..", "Local", "akm", "data");
  }
  const xdgDataHome = env.XDG_DATA_HOME?.trim();
  if (xdgDataHome)
    return path4.join(xdgDataHome, "akm");
  const home = env.HOME?.trim();
  if (!home)
    return homelessFallbackDir("akm-data");
  return path4.join(home, ".local", "share", "akm");
}
function getLockfilePath() {
  return path4.join(getDataDir(), "akm.lock");
}
function getRegistryCacheDir() {
  return path4.join(getCacheDir(), "registry");
}
function getRegistryIndexCacheDir() {
  return path4.join(getCacheDir(), "registry-index");
}
function getStateDir(env = process.env, platform = process.platform) {
  const override = env.AKM_STATE_DIR?.trim();
  if (override)
    return override;
  if (platform === "win32") {
    const localAppData = env.LOCALAPPDATA?.trim();
    if (localAppData)
      return path4.join(localAppData, "akm", "state");
    const userProfile = env.USERPROFILE?.trim();
    if (userProfile)
      return path4.join(userProfile, "AppData", "Local", "akm", "state");
    const appData = env.APPDATA?.trim();
    if (!appData) {
      throw new ConfigError("Unable to determine state directory. Set LOCALAPPDATA, USERPROFILE, or APPDATA.", "CONFIG_DIR_UNRESOLVABLE");
    }
    return path4.join(appData, "..", "Local", "akm", "state");
  }
  const xdgStateHome = env.XDG_STATE_HOME?.trim();
  if (xdgStateHome)
    return path4.join(xdgStateHome, "akm");
  const home = env.HOME?.trim();
  if (!home)
    return homelessFallbackDir("akm-state");
  return path4.join(home, ".local", "state", "akm");
}
function getDefaultStashDir(env = process.env) {
  const override = env.AKM_BUNDLE_DIR?.trim();
  if (override)
    return override;
  if (IS_WINDOWS) {
    const userProfile = env.USERPROFILE?.trim();
    if (userProfile)
      return path4.join(userProfile, "Documents", "akm");
    return path4.join("C:\\", "akm");
  }
  const home = env.HOME?.trim();
  if (!home) {
    throw new ConfigError("Unable to determine default bundle directory. Set HOME.", "STASH_DIR_NOT_FOUND");
  }
  return path4.join(home, "akm");
}

// src/core/common.ts
var MAX_LOCK_METADATA_BYTES = 64 * 1024;
function readTextFileDescriptorWithLimit(fd, maxBytes, label = "File", displayPath = "(open file)") {
  const stat = fs2.fstatSync(fd);
  if (!stat.isFile())
    throw new ConfigError(`${label} is not a regular file: ${displayPath}.`, "INVALID_CONFIG_FILE");
  if (stat.size > maxBytes) {
    throw new ConfigError(`${label} exceeds the ${maxBytes}-byte limit: ${displayPath}.`, "INVALID_CONFIG_FILE");
  }
  const buffer = Buffer.allocUnsafe(maxBytes + 1);
  let total = 0;
  while (total <= maxBytes) {
    const bytesRead = fs2.readSync(fd, buffer, total, maxBytes + 1 - total, null);
    if (bytesRead === 0)
      break;
    total += bytesRead;
  }
  if (total > maxBytes) {
    throw new ConfigError(`${label} exceeds the ${maxBytes}-byte limit: ${displayPath}.`, "INVALID_CONFIG_FILE");
  }
  return buffer.subarray(0, total).toString("utf8");
}
function readTextFile(filePath, label = "File") {
  const fd = fs2.openSync(filePath, "r");
  try {
    const stat = fs2.fstatSync(fd);
    if (!stat.isFile())
      throw new ConfigError(`${label} is not a regular file: ${filePath}.`, "INVALID_CONFIG_FILE");
    return fs2.readFileSync(fd, "utf8");
  } finally {
    fs2.closeSync(fd);
  }
}
function stripJsonComments(text) {
  let result = "";
  let i = 0;
  let inString = false;
  while (i < text.length) {
    if (inString) {
      if (text[i] === "\\") {
        result += text[i] + (text[i + 1] ?? "");
        i += 2;
        continue;
      }
      if (text[i] === '"') {
        inString = false;
      }
      result += text[i];
      i++;
      continue;
    }
    if (text[i] === '"') {
      inString = true;
      result += text[i];
      i++;
      continue;
    }
    if (text[i] === "/" && text[i + 1] === "/") {
      while (i < text.length && text[i] !== `
`)
        i++;
      continue;
    }
    if (text[i] === "/" && text[i + 1] === "*") {
      i += 2;
      while (i < text.length && !(text[i] === "*" && text[i + 1] === "/"))
        i++;
      i += 2;
      continue;
    }
    result += text[i];
    i++;
  }
  return result;
}
function writeFileAtomic(target, content, mode) {
  const tmp = `${target}.tmp.${process.pid}.${crypto2.randomBytes(8).toString("hex")}`;
  const data = typeof content === "string" ? Buffer.from(content) : content;
  const fileMode = mode ?? 384;
  let fd;
  let tempOwned = false;
  let renamed = false;
  let failed = false;
  let failure;
  try {
    fd = fs2.openSync(tmp, "wx", fileMode);
    tempOwned = true;
    if (process.platform !== "win32")
      fs2.fchmodSync(fd, fileMode);
    let offset = 0;
    while (offset < data.byteLength) {
      const written = fs2.writeSync(fd, data, offset, data.byteLength - offset);
      if (written <= 0)
        throw new Error(`Could not make progress writing atomic temp file ${tmp}.`);
      offset += written;
    }
    fs2.fdatasyncSync(fd);
    fs2.closeSync(fd);
    fd = undefined;
    fs2.renameSync(tmp, target);
    renamed = true;
  } catch (error) {
    failed = true;
    failure = error;
  } finally {
    if (fd !== undefined) {
      try {
        fs2.closeSync(fd);
      } catch (error) {
        if (!failed) {
          failed = true;
          failure = error;
        }
      }
    }
    if (tempOwned && !renamed) {
      try {
        fs2.unlinkSync(tmp);
      } catch (error) {
        if (!failed && !hasErrnoCode(error, "ENOENT")) {
          failed = true;
          failure = error;
        }
      }
    }
  }
  if (failed)
    throw failure;
  if (process.platform !== "win32") {
    let dirFd;
    try {
      dirFd = fs2.openSync(path5.dirname(target), "r");
    } catch (error) {
      if (hasErrnoCode(error, "EINVAL") || hasErrnoCode(error, "ENOTSUP"))
        return;
      throw error;
    }
    try {
      try {
        fs2.fsyncSync(dirFd);
      } catch (error) {
        if (!hasErrnoCode(error, "EINVAL") && !hasErrnoCode(error, "ENOTSUP"))
          throw error;
      }
    } finally {
      fs2.closeSync(dirFd);
    }
  }
}
function resolveStashDir(env = process.env) {
  const envDir = env.AKM_BUNDLE_DIR?.trim();
  if (envDir) {
    return validateStashDir(envDir);
  }
  const configStashDir = readStashDirFromConfig();
  if (configStashDir)
    return validateStashDir(configStashDir);
  const defaultDir = getDefaultStashDir(env);
  if (isValidDirectory(defaultDir)) {
    return defaultDir;
  }
  throw new ConfigError(`No bundle directory found. Run "akm bundle create" to create one at ${defaultDir}.`, "STASH_DIR_NOT_FOUND");
}
function validateStashDir(raw) {
  const stashDir = path5.resolve(raw);
  let stat;
  try {
    stat = fs2.statSync(stashDir);
  } catch {
    throw new ConfigError(`Unable to read bundle directory at "${stashDir}".`, "STASH_DIR_UNREADABLE");
  }
  if (!stat.isDirectory()) {
    throw new ConfigError(`Bundle path must point to a directory: "${stashDir}".`, "STASH_DIR_NOT_A_DIRECTORY");
  }
  return stashDir;
}
function isValidDirectory(dir) {
  try {
    return fs2.statSync(dir).isDirectory();
  } catch (error) {
    if (hasErrnoCode(error, "ENOENT"))
      return false;
    throw new ConfigError(`Unable to read bundle directory at "${dir}".`, "STASH_DIR_UNREADABLE");
  }
}
function readStashDirFromConfig() {
  try {
    const configPath = getConfigPath();
    const text = readTextFile(configPath, "Config file");
    const parsed = JSON.parse(stripJsonComments(text));
    if (typeof parsed !== "object" || parsed === null)
      return;
    const raw = migrateLegacySourceShape(parsed, configPath);
    const bundles = raw.bundles;
    const defaultBundle = raw.defaultBundle;
    const selectedBundle = typeof defaultBundle === "string" ? bundles?.[defaultBundle] : undefined;
    const selectedBundlePath = typeof selectedBundle?.path === "string" ? selectedBundle.path : undefined;
    if (bundles && typeof bundles === "object" && typeof defaultBundle === "string" && selectedBundlePath?.trim()) {
      const bundle = selectedBundle;
      const bundlePath = bundle.path.trim();
      if (bundle.components !== undefined) {
        if (typeof bundle.components !== "object" || bundle.components === null) {
          throw new ConfigError("A bundle components map must contain exactly one component.", "INVALID_CONFIG_FILE");
        }
        const components = Object.values(bundle.components);
        if (components.length !== 1) {
          throw new ConfigError("A bundle components map must contain exactly one component.", "INVALID_CONFIG_FILE");
        }
        const component = components[0];
        if (typeof component === "object" && component !== null) {
          const componentConfig = component;
          if (typeof componentConfig.root !== "string")
            return bundlePath;
          const bundleRoot = path5.resolve(bundlePath);
          const componentRoot = path5.resolve(bundleRoot, componentConfig.root);
          if (!isWithin(componentRoot, bundleRoot)) {
            throw new ConfigError(`Component root "${componentConfig.root}" escapes bundle "${defaultBundle}".`, "INVALID_CONFIG_FILE");
          }
          return componentRoot;
        }
      }
      return bundlePath;
    }
  } catch (err) {
    if (err instanceof ConfigError)
      throw err;
  }
  return;
}
function toPosix(input) {
  return input.replace(/\\/g, "/");
}
function compareCodePoints(left, right) {
  return left < right ? -1 : left > right ? 1 : 0;
}
function hasErrnoCode(error, code) {
  if (typeof error !== "object" || error === null || !("code" in error))
    return false;
  return error.code === code;
}
function isContainedRelativePath(value) {
  if (value === "" || value.startsWith("/") || value.startsWith("\\") || value.startsWith("~"))
    return false;
  if (/^[A-Za-z]:/.test(value))
    return false;
  return !value.split(/[/\\]+/).includes("..");
}
function isWithin(candidate, root) {
  return isContainedResolvedPath(safeRealpath(candidate), safeRealpath(root));
}
function isAkmRegistryCachePath(filePath) {
  return isWithin(filePath, getRegistryCacheDir()) || isWithin(filePath, getRegistryIndexCacheDir());
}
function isContainedResolvedPath(resolvedCandidate, resolvedRoot) {
  const rel = path5.relative(normalizeFsPathForComparison(resolvedRoot), normalizeFsPathForComparison(resolvedCandidate));
  if (rel === "")
    return true;
  if (path5.isAbsolute(rel))
    return false;
  return rel.split(/[/\\]+/)[0] !== "..";
}
function safeRealpath(p) {
  const resolved = path5.resolve(p);
  try {
    return fs2.realpathSync(resolved);
  } catch {
    const suffix = [];
    let current = resolved;
    for (;; ) {
      const parent = path5.dirname(current);
      if (parent === current) {
        return resolved;
      }
      suffix.unshift(path5.basename(current));
      current = parent;
      try {
        const realParent = fs2.realpathSync(current);
        return path5.join(realParent, ...suffix);
      } catch {}
    }
  }
}
function normalizeFsPathForComparison(value) {
  return process.platform === "win32" ? value.toLowerCase() : value;
}
var DEFAULT_RETRY_MAX_DELAY_MS = 30000;
function shouldRetry(status) {
  return status === 429 || status >= 500;
}
function backoffDelay(attempt, baseDelay = 500, maxDelayMs = DEFAULT_RETRY_MAX_DELAY_MS) {
  return Math.min(maxDelayMs, baseDelay * 2 ** attempt * (0.5 + Math.random() * 0.5));
}
function computeRetryDelay(response, attempt, options) {
  const maxDelayMs = options?.maxDelayMs ?? DEFAULT_RETRY_MAX_DELAY_MS;
  const baseDelay = options?.baseDelay ?? 500;
  const retryAfter = response.headers.get("retry-after");
  if (retryAfter) {
    const seconds = Number(retryAfter);
    if (Number.isFinite(seconds)) {
      return seconds >= 0 ? Math.min(maxDelayMs, seconds * 1000) : backoffDelay(attempt, baseDelay, maxDelayMs);
    }
    const date = Date.parse(retryAfter);
    if (Number.isFinite(date))
      return Math.min(maxDelayMs, Math.max(0, date - Date.now()));
  }
  return backoffDelay(attempt, baseDelay, maxDelayMs);
}
function abortableDelay(ms, signal, abortMessage = "Aborted") {
  if (!signal)
    return new Promise((resolve) => setTimeout(resolve, ms));
  if (signal.aborted)
    return Promise.reject(signal.reason ?? new Error(abortMessage));
  return new Promise((resolve, reject) => {
    const onAbort = () => {
      clearTimeout(timer);
      reject(signal.reason ?? new Error(abortMessage));
    };
    const timer = setTimeout(() => {
      signal.removeEventListener("abort", onAbort);
      resolve();
    }, ms);
    signal.addEventListener("abort", onAbort, { once: true });
  });
}
var DEFAULT_RESPONSE_BYTE_CAP = 10 * 1024 * 1024;

class ResponseTooLargeError extends Error {
  url;
  maxBytes;
  observedBytes;
  constructor(url, maxBytes, observedBytes) {
    const observed = observedBytes === null ? "unknown" : `${observedBytes} bytes`;
    super(`Response body exceeded ${maxBytes} bytes (observed: ${observed}): ${url}`);
    this.name = "ResponseTooLargeError";
    this.url = url;
    this.maxBytes = maxBytes;
    this.observedBytes = observedBytes;
  }
}

class BodyReadTimeoutError extends Error {
  url;
  timeoutMs;
  constructor(url, timeoutMs) {
    super(`Response body read exceeded ${timeoutMs}ms: ${url}`);
    this.name = "BodyReadTimeoutError";
    this.url = url;
    this.timeoutMs = timeoutMs;
  }
}
function bodyAbortError(signal, url) {
  const reason = signal?.reason;
  return reason instanceof Error ? reason : new Error(`Response body read aborted: ${url}`);
}
async function readChunkWithDeadline(reader, deadlineAt, signal, url, timeoutMs) {
  if (signal?.aborted)
    throw bodyAbortError(signal, url);
  const remaining = deadlineAt === null ? null : deadlineAt - Date.now();
  if (remaining !== null && remaining <= 0)
    throw new BodyReadTimeoutError(url, timeoutMs);
  if (remaining === null && !signal)
    return reader.read();
  return new Promise((resolve, reject) => {
    let timer;
    const cleanup = () => {
      if (timer)
        clearTimeout(timer);
      signal?.removeEventListener("abort", onAbort);
    };
    const onAbort = () => {
      cleanup();
      reject(bodyAbortError(signal, url));
    };
    if (remaining !== null) {
      timer = setTimeout(() => {
        cleanup();
        reject(new BodyReadTimeoutError(url, timeoutMs));
      }, remaining);
    }
    signal?.addEventListener("abort", onAbort, { once: true });
    reader.read().then((result) => {
      cleanup();
      resolve(result);
    }, (err) => {
      cleanup();
      reject(err);
    });
  });
}
async function readBodyWithByteCap(response, maxBytes = DEFAULT_RESPONSE_BYTE_CAP, limits) {
  const url = response.url || "(unknown URL)";
  const contentLengthHeader = response.headers.get("content-length");
  if (contentLengthHeader) {
    const declared = Number(contentLengthHeader);
    if (Number.isFinite(declared) && declared > maxBytes) {
      await response.body?.cancel?.().catch(() => {
        return;
      });
      throw new ResponseTooLargeError(url, maxBytes, declared);
    }
  }
  const body = response.body;
  if (!body) {
    const text = await response.text();
    const byteLength = Buffer.byteLength(text, "utf8");
    if (byteLength > maxBytes)
      throw new ResponseTooLargeError(url, maxBytes, byteLength);
    return text;
  }
  const reader = body.getReader();
  const chunks = [];
  let total = 0;
  const bodyTimeoutMs = limits?.bodyTimeoutMs;
  const deadlineAt = bodyTimeoutMs != null ? Date.now() + bodyTimeoutMs : null;
  try {
    while (true) {
      const { done, value } = await readChunkWithDeadline(reader, deadlineAt, limits?.signal, url, bodyTimeoutMs ?? 0);
      if (done)
        break;
      if (!value)
        continue;
      total += value.byteLength;
      if (total > maxBytes)
        throw new ResponseTooLargeError(url, maxBytes, total);
      chunks.push(value);
    }
  } catch (err) {
    await reader.cancel().catch(() => {
      return;
    });
    throw err;
  } finally {
    reader.releaseLock?.();
  }
  if (chunks.length === 0)
    return "";
  if (chunks.length === 1)
    return new TextDecoder().decode(chunks[0]);
  const combined = new Uint8Array(total);
  let offset = 0;
  for (const chunk of chunks) {
    combined.set(chunk, offset);
    offset += chunk.byteLength;
  }
  return new TextDecoder().decode(combined);
}
async function jsonWithByteCap(response, maxBytes = DEFAULT_RESPONSE_BYTE_CAP, limits) {
  const text = await readBodyWithByteCap(response, maxBytes, limits);
  return JSON.parse(text);
}
function toErrorMessage(error) {
  return error instanceof Error ? error.message : String(error);
}
function asNonEmptyString(value) {
  if (typeof value !== "string")
    return;
  const trimmed = value.trim();
  return trimmed.length > 0 ? trimmed : undefined;
}
var ENV_ASSIGN_LINE_RE = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/;
function scanEnvKeyNames(text) {
  const keys = [];
  const seen = new Set;
  for (const line of text.split(/\r?\n/)) {
    const m = line.match(ENV_ASSIGN_LINE_RE);
    if (!m)
      continue;
    const key = m[1];
    if (!key)
      continue;
    if (seen.has(key))
      continue;
    seen.add(key);
    keys.push(key);
  }
  return keys;
}
function wellFormedUnicode(value) {
  for (let index = 0;index < value.length; index += 1) {
    const code = value.charCodeAt(index);
    if (code >= 55296 && code <= 56319) {
      const next = value.charCodeAt(index + 1);
      if (!(next >= 56320 && next <= 57343))
        return false;
      index += 1;
    } else if (code >= 56320 && code <= 57343)
      return false;
  }
  return true;
}
function isRecord(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}
function tryParseJson(raw) {
  try {
    return JSON.parse(raw);
  } catch {
    return;
  }
}
function isProcessAlive(pid) {
  if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0)
    return false;
  try {
    process.kill(pid, 0);
    return true;
  } catch (err) {
    return err?.code === "EPERM";
  }
}

// src/runtime.ts
var isBun = !!process.versions?.bun;
var nodeRequire = createRequire2(import.meta.url);
function spawnSync(cmd, options = {}) {
  if (isBun) {
    const r2 = bunGlobal().spawnSync(cmd, options);
    return {
      success: r2.success,
      exitCode: r2.exitCode ?? null,
      stdout: toBuffer(r2.stdout),
      stderr: toBuffer(r2.stderr)
    };
  }
  const [bin, ...args] = cmd;
  const r = nodeSpawnSync(bin, args, { cwd: options.cwd, env: options.env ?? process.env });
  const exitCode = r.status;
  return {
    success: r.error === undefined && exitCode === 0,
    exitCode: exitCode ?? null,
    stdout: toBuffer(r.stdout),
    stderr: toBuffer(r.stderr)
  };
}
var MAX_STREAMED_DOWNLOAD_BYTES = 1024 * 1024 * 1024;
var STREAMED_DOWNLOAD_BODY_TIMEOUT_MS = 5 * 60000;
function writeStreamChunk(out, chunk) {
  return new Promise((resolve, reject) => {
    out.write(chunk, (err) => err ? reject(err) : resolve());
  });
}
function endWriteStream(out) {
  return new Promise((resolve, reject) => {
    out.once("error", reject);
    out.end(() => resolve());
  });
}
async function writeResponseToFileCapped(filePath, res, options) {
  const maxBytes = options?.maxBytes ?? MAX_STREAMED_DOWNLOAD_BYTES;
  const bodyTimeoutMs = options?.bodyTimeoutMs ?? STREAMED_DOWNLOAD_BODY_TIMEOUT_MS;
  const url = res.url || filePath;
  const declared = Number(res.headers.get("content-length"));
  if (Number.isFinite(declared) && declared > maxBytes) {
    await res.body?.cancel?.().catch(() => {
      return;
    });
    throw new ResponseTooLargeError(url, maxBytes, declared);
  }
  const body = res.body;
  if (!body) {
    const buf = Buffer.from(await res.arrayBuffer());
    if (buf.byteLength > maxBytes)
      throw new ResponseTooLargeError(url, maxBytes, buf.byteLength);
    await pipeline(Readable.from(buf), createWriteStream(filePath));
    return;
  }
  const reader = body.getReader();
  const out = createWriteStream(filePath);
  const deadlineAt = Date.now() + bodyTimeoutMs;
  let total = 0;
  try {
    while (true) {
      const { done, value } = await readChunkWithDeadline(reader, deadlineAt, options?.signal, url, bodyTimeoutMs);
      if (done)
        break;
      if (!value)
        continue;
      total += value.byteLength;
      if (total > maxBytes)
        throw new ResponseTooLargeError(url, maxBytes, total);
      await writeStreamChunk(out, value);
    }
    await endWriteStream(out);
  } catch (err) {
    out.destroy();
    await reader.cancel().catch(() => {
      return;
    });
    throw err;
  } finally {
    reader.releaseLock?.();
  }
}
function getDirname(importMetaUrl) {
  return path6.dirname(fileURLToPath(importMetaUrl));
}
function statfsType(path7) {
  try {
    return statfsSync(path7).type;
  } catch {
    return;
  }
}
function sleepSync(ms) {
  if (isBun) {
    bunGlobal().sleepSync(ms);
    return;
  }
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
}
var mainPath = isBun ? bunGlobal().main : process.argv[1];
function bunGlobal() {
  return globalThis.Bun;
}
function toBuffer(data) {
  if (data == null)
    return Buffer.alloc(0);
  if (Buffer.isBuffer(data))
    return data;
  if (typeof data === "string")
    return Buffer.from(data, "utf8");
  return Buffer.from(data);
}

// src/output/html-render.ts
var TEMPLATES_DIR = path7.join(getDirname(import.meta.url), "../assets/templates/html");

// src/output/render-registry.ts
var mdRenderers = new Map;
function registerMdRenderer(command, handler) {
  mdRenderers.set(command, handler);
}

// src/version.ts
import fs3 from "node:fs";
import path8 from "node:path";
var pkgVersion = (() => {
  if (typeof AKM_VERSION !== "undefined")
    return AKM_VERSION;
  try {
    const pkgPath = path8.resolve(getDirname(import.meta.url), "../package.json");
    if (fs3.existsSync(pkgPath)) {
      const pkg = JSON.parse(fs3.readFileSync(pkgPath, "utf-8"));
      if (typeof pkg.version === "string")
        return pkg.version;
    }
  } catch {}
  return "0.0.0-dev";
})();
// src/commands/health/types-result.ts
var ACTIVE_RUN_WARN_MS = 15 * 60 * 1000;
// src/commands/health/report-view-model.ts
var DISTILL_REASONS_HIDDEN = new Set(["no new signal since last proposal"]);

// src/storage/database.ts
import { createRequire as createRequire3 } from "node:module";
var isBun2 = !!process.versions?.bun;
var nodeRequire2 = createRequire3(import.meta.url);
function openDatabase(path9, opts) {
  return isBun2 ? openBunDatabase(path9, opts) : openNodeDatabase(path9, opts);
}
function openDatabaseFinalizing(path9, opts) {
  const db = openDatabase(path9, opts);
  const tracked = new Set;
  const origPrepare = db.prepare.bind(db);
  const origClose = db.close.bind(db);
  db.prepare = (sql, ...rest) => {
    const stmt = origPrepare(sql, ...rest);
    tracked.add(stmt);
    return stmt;
  };
  db.close = (...args) => {
    for (const stmt of tracked) {
      try {
        stmt.finalize?.();
      } catch {}
    }
    tracked.clear();
    return origClose(...args);
  };
  return db;
}
function openBunDatabase(path9, opts) {
  const { Database: BunDatabase } = loadBunSqlite();
  const db = opts ? new BunDatabase(path9, bunOptions(opts)) : new BunDatabase(path9);
  return db;
}
function bunOptions(opts) {
  const out = {};
  if (opts.readonly !== undefined)
    out.readonly = opts.readonly;
  if (opts.create !== undefined)
    out.create = opts.create;
  if (!out.readonly)
    out.readwrite = true;
  return out;
}
var bunSqliteModule;
function loadBunSqlite() {
  if (!bunSqliteModule) {
    bunSqliteModule = nodeRequire2("bun:sqlite");
  }
  return bunSqliteModule;
}
var betterSqlite3Ctor;
var MISSING_BINDING_REMEDY = `akm could not load 'better-sqlite3', the SQLite driver it needs on Node.js.
` + `  • Reinstall akm with a working C/C++ build toolchain so its optional
` + "    'better-sqlite3' native binding builds (a global `npm i -g better-sqlite3`\n" + `    will NOT be resolved — Node loads it from akm's own node_modules).
` + "  • Or run akm under Bun, which has a built-in SQLite driver and needs no native build.";
function abiMismatchRemedy(message) {
  const ABI_MISMATCH_SHAPES = [
    "did not self-register",
    "NODE_MODULE_VERSION",
    "was compiled against a different",
    "invalid ELF header"
  ];
  if (!ABI_MISMATCH_SHAPES.some((shape) => message.includes(shape)))
    return;
  return `akm could not load 'better-sqlite3': its native binding was built for a different
` + `Node.js version than the one now running (this Node is ABI ${process.versions.modules}).
` + `This is what happens when Node is upgraded after akm is installed. It is NOT a
` + `broken install, and reinstalling akm is not required.
` + `  Fix: npm rebuild better-sqlite3        # in akm's install directory
` + `  Or:  npm install -g akm-cli            # reinstall, rebuilding against this Node
` + "  Or:  run akm under Bun, whose built-in SQLite driver needs no native binding.";
}
function loadBetterSqlite3() {
  if (!betterSqlite3Ctor) {
    let mod;
    try {
      mod = nodeRequire2("better-sqlite3");
    } catch (err) {
      const raw = err instanceof Error ? err.message : String(err);
      throw new Error(`${abiMismatchRemedy(raw) ?? MISSING_BINDING_REMEDY}
  Underlying load error: ${raw}`);
    }
    betterSqlite3Ctor = mod.default ?? mod;
  }
  return betterSqlite3Ctor;
}
function openNodeDatabase(path9, opts) {
  const BetterSqlite3 = loadBetterSqlite3();
  const options = {};
  if (opts?.readonly !== undefined)
    options.readonly = opts.readonly;
  if (opts?.create === false)
    options.fileMustExist = true;
  let db;
  try {
    db = opts ? new BetterSqlite3(path9, options) : new BetterSqlite3(path9);
  } catch (err) {
    const raw = err instanceof Error ? err.message : String(err);
    const remedy = abiMismatchRemedy(raw);
    if (!remedy)
      throw err;
    throw new Error(`${remedy}
  Underlying error: ${raw}`);
  }
  return {
    prepare: db.prepare.bind(db),
    exec: db.exec.bind(db),
    run: (sql, ...params) => db.prepare(sql).run(...params),
    loadExtension: db.loadExtension.bind(db),
    transaction: db.transaction.bind(db),
    get inTransaction() {
      return db.inTransaction;
    },
    close: db.close.bind(db)
  };
}

// src/core/state-db.ts
import fs5 from "node:fs";
import path10 from "node:path";

// src/storage/managed-db.ts
import fs4 from "node:fs";
import path9 from "node:path";

// src/storage/sqlite-pragmas.ts
var VALID_MODES = new Set(["WAL", "DELETE", "TRUNCATE"]);
var warnedInvalid = false;
var warnedNetworkFallback = false;
function resolveJournalMode(raw) {
  if (raw === undefined)
    return "WAL";
  const normalized = raw.trim().toUpperCase();
  if (normalized === "")
    return "WAL";
  if (VALID_MODES.has(normalized)) {
    return normalized;
  }
  warnInvalidJournalModeOnce(raw);
  return "WAL";
}
function resolveConfiguredJournalMode(env = process.env) {
  return resolveJournalMode(env.AKM_SQLITE_JOURNAL_MODE);
}
function warnInvalidJournalModeOnce(raw) {
  if (warnedInvalid)
    return;
  warnedInvalid = true;
  warn(`[akm] invalid AKM_SQLITE_JOURNAL_MODE=${JSON.stringify(raw)} — using WAL (valid: WAL, DELETE, TRUNCATE)`);
}
var FS_MAGIC_NFS = 26985;
var FS_MAGIC_SMB = 20859;
var FS_MAGIC_CIFS = 4283649346;
var FS_MAGIC_SMB2 = 4266872130;
var FS_MAGIC_FUSE = 1702057286;
var NETWORK_FS_MAGICS = new Set([
  FS_MAGIC_NFS,
  FS_MAGIC_SMB,
  FS_MAGIC_CIFS,
  FS_MAGIC_SMB2,
  FS_MAGIC_FUSE
]);
function isNetworkFilesystem(fsType) {
  if (fsType === undefined)
    return false;
  return NETWORK_FS_MAGICS.has(fsType);
}
var SQLITE_BUSY_TIMEOUT_MS = 30000;
function applyReadonlyPragmas(db) {
  db.exec(`PRAGMA busy_timeout = ${SQLITE_BUSY_TIMEOUT_MS}`);
}
function applyStandardPragmas(db, opts = {}) {
  let mode = resolveConfiguredJournalMode(opts.env);
  if (mode === "WAL" && opts.dataDir) {
    const probe = opts.fsTypeProbe ?? statfsType;
    if (isNetworkFilesystem(probe(opts.dataDir))) {
      mode = "DELETE";
      warnNetworkFallbackOnce(opts.dataDir);
    }
  }
  db.exec(`PRAGMA busy_timeout = ${SQLITE_BUSY_TIMEOUT_MS}`);
  db.exec(`PRAGMA journal_mode = ${mode}`);
  if (opts.foreignKeys !== false) {
    db.exec("PRAGMA foreign_keys = ON");
  }
  if (mode !== "WAL") {
    db.exec("PRAGMA synchronous = FULL");
  }
  return mode;
}
function warnNetworkFallbackOnce(dataDir) {
  if (warnedNetworkFallback)
    return;
  warnedNetworkFallback = true;
  warn(`[akm] network filesystem detected at ${dataDir} — WAL unsupported, using DELETE journal mode`);
}

// src/storage/managed-db.ts
function openManagedDatabase(spec) {
  const dir = path9.dirname(spec.path);
  if (spec.create !== false && !fs4.existsSync(dir)) {
    fs4.mkdirSync(dir, { recursive: true });
  }
  const db = spec.create === false ? openDatabase(spec.path, { create: false }) : openDatabase(spec.path);
  try {
    applyStandardPragmas(db, spec.pragmas ?? { dataDir: dir });
    spec.init?.(db);
    return db;
  } catch (error2) {
    try {
      if (db.inTransaction)
        db.exec("ROLLBACK");
    } catch {}
    try {
      db.close();
    } catch {}
    throw error2;
  }
}

// src/storage/sqlite-transaction.ts
function isSqliteContentionError(err) {
  const code = err?.code;
  if (code === "SQLITE_BUSY" || code === "SQLITE_LOCKED")
    return true;
  const msg = (err instanceof Error ? err.message : String(err)).toLowerCase();
  return msg.includes("database is locked") || msg.includes("database table is locked") || msg.includes("did not open a transaction");
}
var WITH_IMMEDIATE_TX_MAX_ATTEMPTS = 5;
function throwBeginFailure(err) {
  if (isSqliteContentionError(err)) {
    const contended = new TransientError("akm's state database is busy (another akm process is writing it); retry shortly.", "STATE_DB_CONTENDED");
    contended.cause = err;
    throw contended;
  }
  throw err;
}
function beginImmediateTransaction(db) {
  if (db.inTransaction) {
    throw new Error("beginImmediateTransaction requires a connection with no active transaction");
  }
  let lastBeginErr;
  for (let attempt = 1;attempt <= WITH_IMMEDIATE_TX_MAX_ATTEMPTS; attempt++) {
    try {
      db.exec("BEGIN IMMEDIATE");
      if (!db.inTransaction) {
        throw new Error("BEGIN IMMEDIATE did not open a transaction (phantom contention state)");
      }
      return;
    } catch (err) {
      lastBeginErr = err;
      if (isSqliteContentionError(err) && attempt < WITH_IMMEDIATE_TX_MAX_ATTEMPTS) {
        if (db.inTransaction) {
          try {
            db.exec("ROLLBACK");
          } catch {}
        }
        sleepSync(2 ** (attempt - 1));
        continue;
      }
      throwBeginFailure(err);
    }
  }
  throwBeginFailure(lastBeginErr);
}
function withImmediateTransaction(db, fn) {
  if (db.inTransaction) {
    return fn();
  }
  beginImmediateTransaction(db);
  try {
    const result = fn();
    if (!db.inTransaction) {
      throw new Error("withImmediateTransaction invariant violated: transaction opened by BEGIN IMMEDIATE was no longer active after the transaction body ran; refusing to COMMIT (writes may have escaped serialization)");
    }
    db.exec("COMMIT");
    return result;
  } catch (err) {
    if (db.inTransaction) {
      try {
        db.exec("ROLLBACK");
      } catch {}
    }
    throw err;
  }
}

// src/storage/sqlite-migrations.ts
function assertMigrationRegistry(migrations) {
  const seen = new Set;
  for (const migration of migrations) {
    if (seen.has(migration.id))
      throw new Error(`Migration registry contains duplicate ID ${migration.id}.`);
    seen.add(migration.id);
  }
}
function migrationLedgerExists(db) {
  return !!db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'schema_migrations'").get();
}
function inspectLedgerAgainst(db, registryIds) {
  if (!migrationLedgerExists(db))
    return { status: registryIds.length === 0 ? "current" : "old", migrationIds: [] };
  const rows = db.prepare("SELECT id FROM schema_migrations ORDER BY rowid").all();
  const migrationIds = rows.map((row) => row.id);
  for (const [index, row] of rows.entries()) {
    const expectedId = registryIds[index];
    if (!expectedId) {
      return {
        status: "newer",
        migrationIds,
        detail: `applied migration ID${rows.length - registryIds.length === 1 ? "" : "s"} ${migrationIds.slice(registryIds.length).join(", ")} unknown to this akm`
      };
    }
    if (row.id !== expectedId) {
      return {
        status: "inconsistent",
        migrationIds,
        detail: `migration ledger is not an exact ordered prefix at position ${index + 1} (found '${row.id}', expected '${expectedId}'). ` + `Applied, in order: [${migrationIds.join(", ")}]. This akm's expected order: [${registryIds.join(", ")}].`
      };
    }
  }
  return {
    status: rows.length === registryIds.length ? "current" : "old",
    migrationIds
  };
}
function inspectMigrationLedger(db, migrations) {
  return inspectLedgerAgainst(db, migrations.map((migration) => migration.id));
}
function assertMigrationLedger(db, migrations) {
  const state = inspectMigrationLedger(db, migrations);
  if (state.status === "inconsistent") {
    throw new Error(`Refusing a database whose migrations are not an exact ordered prefix: ${state.detail} ` + "Applying this binary's missing migration now could run it against a schema a later migration already " + "changed underneath it, which is a real risk of producing a wrong schema — not something akm can guess " + "its way out of safely. This usually means the database was migrated by an incompatible akm build or " + "fork, or schema_migrations was edited by hand. Restore this file from a backup taken before the " + "divergence, or — if there is no backup and the data is not needed — delete it and let akm rebuild it " + "from scratch (a derived index.db regenerates from your sources on the next 'akm index'; state.db loses " + "durable history such as improve/proposal state and must be treated as a last resort).");
  }
  return state;
}
function ensureMigrationsTable(db) {
  db.exec(`
    CREATE TABLE IF NOT EXISTS schema_migrations (
      id         TEXT    PRIMARY KEY,
      applied_at TEXT    NOT NULL DEFAULT (datetime('now'))
    );
  `);
}
function pendingMigrations(db, migrations) {
  return migrations.slice(assertMigrationLedger(db, migrations).migrationIds.length);
}
function runMigrations(db, migrations) {
  if (pendingMigrations(db, migrations).length === 0)
    return [];
  return withImmediateTransaction(db, () => {
    ensureMigrationsTable(db);
    const applied = [];
    for (const migration of pendingMigrations(db, migrations)) {
      db.exec(migration.up);
      db.prepare("INSERT INTO schema_migrations (id) VALUES (?)").run(migration.id);
      applied.push(migration.id);
    }
    return applied;
  });
}

// src/core/state/migrations.ts
var STATE_MIGRATION_SAFETY_BY_ID = Object.freeze({
  "001-initial-schema": "additive",
  "002-task-history-per-run": "data-preserving-rebuild",
  "003-improve-runs": "additive",
  "004-extract-sessions-seen": "additive",
  "005-proposal-fs-imports": "additive",
  "006-proposals-pending-ref-source": "additive",
  "007-consolidation-judged": "additive",
  "008-body-embeddings": "additive",
  "009-asset-salience": "additive",
  "010-asset-outcome": "additive",
  "011-asset-salience-homeostatic-demoted-at": "additive",
  "012-improve-gate-thresholds": "additive",
  "013-extract-sessions-content-hash": "additive",
  "014-recombine-hypotheses": "additive",
  "015-asset-salience-encoding-source": "additive",
  "016-collapse-churn-detector": "additive",
  "017-improve-run-strategy": "additive",
  "018-drop-dead-lane-schema": "historical-destructive",
  "019-proposal-fingerprints": "additive",
  "020-three-db-cutover": "additive",
  "021-asset-state-missing-since": "additive",
  "022-workflow-unit-attempts": "additive",
  "023-child-workflow-runs": "additive",
  "024-workflow-run-outputs": "additive",
  "025-task-history-vocabulary-backfill": "data-preserving-rebuild",
  "026-proposals-strip-legacy-fragment-refs": "data-preserving-rebuild",
  "027-extract-sessions-seen-harness-rename": "data-preserving-rebuild",
  "028-improve-ledger": "historical-destructive",
  "029-improve-ledger-content-hash": "additive"
});
var STATE_MIGRATIONS = [
  {
    id: "001-initial-schema",
    up: `
      -- ── events ──────────────────────────────────────────────────────────────
      --
      -- Replaces events.jsonl. Indexed (query) columns:
      --   id          INTEGER PK — monotonic rowid; replaces byte-offset cursor.
      --                            Callers store this as "sinceId" for resume.
      --   event_type  TEXT        — indexed; replaces the type filter in readEvents().
      --   ts          TEXT        — ISO-8601 UTC ms; indexed for range queries.
      --   ref         TEXT        — nullable asset ref; indexed for ref-scoped queries.
      --
      -- Extensible (metadata_json) columns:
      --   metadata_json TEXT      — JSON object storing all non-indexed payload
      --                             fields (tags, any future structured fields).
      --                             Maps directly to EventEnvelope.metadata.
      --
      -- schema_version mirrors EventEnvelope.schemaVersion — always 1 for v1
      -- rows. Stored as a column (not in the JSON blob) so future schema
      -- changes can be detected and migrated row-by-row if ever needed.
      --
      -- TTL: rows where ts < NOW() - 90 days can be deleted by a maintenance job.
      -- No automatic deletion occurs here — callers call purgeOldEvents().
      --
      -- ADD COLUMN extension points (future migrations):
      --   ALTER TABLE events ADD COLUMN stash_dir TEXT DEFAULT NULL;
      --   ALTER TABLE events ADD COLUMN correlation_id TEXT DEFAULT NULL;
      --   ALTER TABLE events ADD COLUMN schema_version INTEGER NOT NULL DEFAULT 1;
      --
      CREATE TABLE IF NOT EXISTS events (
        id             INTEGER PRIMARY KEY AUTOINCREMENT,
        event_type     TEXT    NOT NULL,
        ts             TEXT    NOT NULL,
        ref            TEXT,
        metadata_json  TEXT    NOT NULL DEFAULT '{}'
      );

      -- Query patterns supported by these indexes:
      --   SELECT … WHERE event_type = ?                 → idx_events_type
      --   SELECT … WHERE ref = ?                        → idx_events_ref
      --   SELECT … WHERE ts >= ? AND ts <= ?            → idx_events_ts
      --   SELECT … WHERE event_type = ? AND ref = ?     → idx_events_type (prefix scan) + filter
      --   SELECT … WHERE id > ?                         → PK (rowid) — no extra index needed
      CREATE INDEX IF NOT EXISTS idx_events_type ON events(event_type);
      CREATE INDEX IF NOT EXISTS idx_events_ref  ON events(ref);
      CREATE INDEX IF NOT EXISTS idx_events_ts   ON events(ts);

      -- ── proposals ────────────────────────────────────────────────────────────
      --
      -- Replaces per-uuid JSON directories under <stashDir>/.akm/proposals/.
      --
      -- Indexed (query) columns:
      --   id          TEXT PK     — UUID (crypto.randomUUID()); stable directory name.
      --   stash_dir   TEXT        — absolute stash root; multi-stash installs need
      --                             this to partition proposal lists per stash.
      --   ref         TEXT        — target asset ref (e.g. "lessons/alpha");
      --                             indexed for ref-scoped queue views.
      --   status      TEXT        — "pending" | "accepted" | "rejected"; indexed
      --                             so pending-queue queries are fast.
      --   source      TEXT        — human-readable origin tag (e.g. "reflect").
      --   created_at  TEXT        — ISO-8601; used for ORDER BY created_at ASC.
      --   updated_at  TEXT        — ISO-8601; updated on accept/reject.
      --
      -- Large payload columns (NOT indexed):
      --   content     TEXT        — full markdown text; the proposal payload body.
      --   frontmatter_json TEXT   — JSON of parsed frontmatter (may be NULL when
      --                             the content has no frontmatter block).
      --
      -- Extensible (metadata_json) columns:
      --   metadata_json TEXT      — JSON object for future proposal fields.
      --                             Current fields stored here: sourceRun,
      --                             review, confidence, gateDecision (#577),
      --                             backupContent.
      --
      -- ADD COLUMN extension points (future migrations):
      --   ALTER TABLE proposals ADD COLUMN source_run TEXT DEFAULT NULL;
      --   ALTER TABLE proposals ADD COLUMN review_outcome TEXT DEFAULT NULL;
      --   ALTER TABLE proposals ADD COLUMN review_reason TEXT DEFAULT NULL;
      --   ALTER TABLE proposals ADD COLUMN review_decided_at TEXT DEFAULT NULL;
      --   ALTER TABLE proposals ADD COLUMN archived INTEGER NOT NULL DEFAULT 0;
      --
      CREATE TABLE IF NOT EXISTS proposals (
        id               TEXT    PRIMARY KEY,
        stash_dir        TEXT    NOT NULL,
        ref              TEXT    NOT NULL,
        status           TEXT    NOT NULL DEFAULT 'pending',
        source           TEXT    NOT NULL,
        created_at       TEXT    NOT NULL,
        updated_at       TEXT    NOT NULL,
        content          TEXT    NOT NULL DEFAULT '',
        frontmatter_json TEXT,
        metadata_json    TEXT    NOT NULL DEFAULT '{}'
      );

      -- Query patterns:
      --   SELECT … WHERE stash_dir = ? AND status = ?   → idx_proposals_stash_status
      --   SELECT … WHERE ref = ? AND status = ?         → idx_proposals_ref_status
      --   SELECT … WHERE id = ?                         → PK
      CREATE INDEX IF NOT EXISTS idx_proposals_stash_status
        ON proposals(stash_dir, status);
      CREATE INDEX IF NOT EXISTS idx_proposals_ref_status
        ON proposals(ref, status);

      -- ── task_history ─────────────────────────────────────────────────────────
      --
      -- Replaces per-task JSONL files under <cacheDir>/tasks/history/.
      --
      -- Indexed (query) columns:
      --   task_id     TEXT PK     — stable task identifier string.
      --   status      TEXT        — terminal status (e.g. "completed", "failed",
      --                             "cancelled"); indexed for status-scoped queries.
      --   started_at  TEXT        — ISO-8601; indexed for time-range queries.
      --   target_kind TEXT        — kind of the target entity (e.g. "issue",
      --                             "workflow", "agent"); indexed for kind-scoped queries.
      --   target_ref  TEXT        — stable ref of the target entity; indexed for
      --                             per-target history lookups.
      --
      -- Non-indexed time columns:
      --   completed_at TEXT       — ISO-8601 or NULL if still running.
      --   failed_at    TEXT       — ISO-8601 or NULL.
      --
      -- Non-indexed diagnostic columns:
      --   log_path     TEXT       — absolute path to the task log file, if any.
      --
      -- Extensible (metadata_json) columns:
      --   metadata_json TEXT      — JSON object for future task fields (exit_code,
      --                             runner, priority, parent_task_id, …).
      --
      -- ADD COLUMN extension points (future migrations):
      --   ALTER TABLE task_history ADD COLUMN exit_code INTEGER DEFAULT NULL;
      --   ALTER TABLE task_history ADD COLUMN runner TEXT DEFAULT NULL;
      --   ALTER TABLE task_history ADD COLUMN parent_task_id TEXT DEFAULT NULL;
      --   ALTER TABLE task_history ADD COLUMN priority INTEGER NOT NULL DEFAULT 0;
      --
      CREATE TABLE IF NOT EXISTS task_history (
        task_id       TEXT    PRIMARY KEY,
        status        TEXT    NOT NULL,
        started_at    TEXT    NOT NULL,
        completed_at  TEXT,
        failed_at     TEXT,
        log_path      TEXT,
        target_kind   TEXT,
        target_ref    TEXT,
        metadata_json TEXT    NOT NULL DEFAULT '{}'
      );

      -- Query patterns:
      --   SELECT … WHERE task_id = ?                    → PK
      --   SELECT … WHERE started_at >= ? AND started_at <= ? → idx_task_history_started
      --   SELECT … WHERE target_kind = ? AND target_ref = ?  → idx_task_history_target
      --   SELECT … WHERE status = ?                     → idx_task_history_status
      CREATE INDEX IF NOT EXISTS idx_task_history_started
        ON task_history(started_at);
      CREATE INDEX IF NOT EXISTS idx_task_history_target
        ON task_history(target_kind, target_ref);
      CREATE INDEX IF NOT EXISTS idx_task_history_status
        ON task_history(status);
    `
  },
  {
    id: "002-task-history-per-run",
    up: `
      ALTER TABLE task_history RENAME TO task_history_v1;

      CREATE TABLE task_history (
        id            INTEGER PRIMARY KEY AUTOINCREMENT,
        task_id       TEXT    NOT NULL,
        status        TEXT    NOT NULL,
        started_at    TEXT    NOT NULL,
        completed_at  TEXT,
        failed_at     TEXT,
        log_path      TEXT,
        target_kind   TEXT,
        target_ref    TEXT,
        metadata_json TEXT    NOT NULL DEFAULT '{}'
      );

      INSERT INTO task_history
        (task_id, status, started_at, completed_at, failed_at,
         log_path, target_kind, target_ref, metadata_json)
      SELECT task_id, status, started_at, completed_at, failed_at,
             log_path, target_kind, target_ref, metadata_json
      FROM task_history_v1;

      DROP TABLE task_history_v1;

      -- Unique constraint: same task cannot have two runs with the same start time.
      CREATE UNIQUE INDEX IF NOT EXISTS idx_task_history_run
        ON task_history(task_id, started_at);
      CREATE INDEX IF NOT EXISTS idx_task_history_task_id
        ON task_history(task_id);
      CREATE INDEX IF NOT EXISTS idx_task_history_started
        ON task_history(started_at);
      CREATE INDEX IF NOT EXISTS idx_task_history_target
        ON task_history(target_kind, target_ref);
      CREATE INDEX IF NOT EXISTS idx_task_history_status
        ON task_history(status);
    `
  },
  {
    id: "003-improve-runs",
    up: `
      CREATE TABLE IF NOT EXISTS improve_runs (
        id            TEXT    PRIMARY KEY,
        started_at    TEXT    NOT NULL,
        completed_at  TEXT,
        stash_dir     TEXT    NOT NULL,
        dry_run       INTEGER NOT NULL DEFAULT 0,
        profile       TEXT,
        scope_mode    TEXT    NOT NULL,
        scope_value   TEXT,
        guidance      TEXT,
        ok            INTEGER NOT NULL,
        result_json   TEXT    NOT NULL,
        metrics_json  TEXT,
        metadata_json TEXT    NOT NULL DEFAULT '{}'
      );

      -- Query patterns supported:
      --   SELECT … WHERE started_at >= ? AND started_at <= ?
      --     → idx_improve_runs_started
      --   SELECT … WHERE dry_run = 0
      --     → idx_improve_runs_dry_run (productivity audits filter trap)
      --   SELECT … WHERE stash_dir = ? AND scope_mode = ?
      --     → idx_improve_runs_stash_scope
      CREATE INDEX IF NOT EXISTS idx_improve_runs_started
        ON improve_runs(started_at);
      CREATE INDEX IF NOT EXISTS idx_improve_runs_dry_run
        ON improve_runs(dry_run);
      CREATE INDEX IF NOT EXISTS idx_improve_runs_stash_scope
        ON improve_runs(stash_dir, scope_mode);
    `
  },
  {
    id: "004-extract-sessions-seen",
    up: `
      CREATE TABLE IF NOT EXISTS extract_sessions_seen (
        harness          TEXT    NOT NULL,
        session_id       TEXT    NOT NULL,
        processed_at     TEXT    NOT NULL,
        session_ended_at TEXT,
        outcome          TEXT    NOT NULL,
        candidate_count  INTEGER NOT NULL DEFAULT 0,
        proposal_count   INTEGER NOT NULL DEFAULT 0,
        rationale        TEXT,
        source_run       TEXT,
        metadata_json    TEXT    NOT NULL DEFAULT '{}',
        PRIMARY KEY (harness, session_id)
      );

      -- Query patterns:
      --   SELECT … WHERE harness = ?                       → idx_extract_sessions_harness
      --   SELECT … WHERE processed_at >= ?                 → idx_extract_sessions_processed
      --   SELECT … WHERE harness = ? AND session_id = ?    → PK
      CREATE INDEX IF NOT EXISTS idx_extract_sessions_harness
        ON extract_sessions_seen(harness);
      CREATE INDEX IF NOT EXISTS idx_extract_sessions_processed
        ON extract_sessions_seen(processed_at);
    `
  },
  {
    id: "005-proposal-fs-imports",
    up: `
      CREATE TABLE IF NOT EXISTS proposal_fs_imports (
        stash_dir      TEXT    PRIMARY KEY,
        imported_at    TEXT    NOT NULL,
        imported_count INTEGER NOT NULL DEFAULT 0
      );
    `
  },
  {
    id: "006-proposals-pending-ref-source",
    up: `
      CREATE INDEX IF NOT EXISTS idx_proposals_stash_status_ref_source
        ON proposals(stash_dir, status, ref, source);
    `
  },
  {
    id: "007-consolidation-judged",
    up: `
      CREATE TABLE IF NOT EXISTS consolidation_judged (
        entry_key    TEXT    PRIMARY KEY,
        content_hash TEXT    NOT NULL,
        judged_at    TEXT    NOT NULL,
        outcome      TEXT    NOT NULL
      );
    `
  },
  {
    id: "008-body-embeddings",
    up: `
      CREATE TABLE IF NOT EXISTS body_embeddings (
        content_hash TEXT    PRIMARY KEY,
        embedding    BLOB    NOT NULL,
        model_id     TEXT    NOT NULL,
        created_at   INTEGER NOT NULL
      );
    `
  },
  {
    id: "009-asset-salience",
    up: `
      CREATE TABLE IF NOT EXISTS asset_salience (
        asset_ref          TEXT    PRIMARY KEY,
        encoding_salience  REAL    NOT NULL DEFAULT 0.5,
        outcome_salience   REAL    NOT NULL DEFAULT 0.0,
        retrieval_salience REAL    NOT NULL DEFAULT 0.0,
        rank_score         REAL    NOT NULL DEFAULT 0.0,
        consecutive_no_ops INTEGER NOT NULL DEFAULT 0,
        updated_at         INTEGER NOT NULL DEFAULT 0
      );

      -- Hot path: sort / filter by rank_score for selector queries.
      CREATE INDEX IF NOT EXISTS idx_asset_salience_rank
        ON asset_salience(rank_score DESC);
    `
  },
  {
    id: "010-asset-outcome",
    up: `
      CREATE TABLE IF NOT EXISTS asset_outcome (
        asset_ref                TEXT    PRIMARY KEY,
        last_retrieved_at        INTEGER NOT NULL DEFAULT 0,
        retrieval_count          INTEGER NOT NULL DEFAULT 0,
        expected_retrieval_rate  REAL    NOT NULL DEFAULT 0.0,
        negative_feedback_count  INTEGER NOT NULL DEFAULT 0,
        accepted_change_count    INTEGER NOT NULL DEFAULT 0,
        review_pressure          INTEGER NOT NULL DEFAULT 0,
        outcome_score            REAL    NOT NULL DEFAULT 0.0,
        updated_at               INTEGER NOT NULL DEFAULT 0
      );

      -- Hot path: sort assets by review_pressure DESC for #613 admission.
      CREATE INDEX IF NOT EXISTS idx_asset_outcome_review_pressure
        ON asset_outcome(review_pressure DESC);

      -- Secondary: sort by outcome_score DESC for outcomeSalience reads.
      CREATE INDEX IF NOT EXISTS idx_asset_outcome_score
        ON asset_outcome(outcome_score DESC);
    `
  },
  {
    id: "011-asset-salience-homeostatic-demoted-at",
    up: `
      ALTER TABLE asset_salience ADD COLUMN homeostatic_demoted_at INTEGER DEFAULT NULL;
    `
  },
  {
    id: "012-improve-gate-thresholds",
    up: `
      CREATE TABLE IF NOT EXISTS improve_gate_thresholds (
        phase       TEXT    NOT NULL PRIMARY KEY,
        threshold   INTEGER NOT NULL,
        updated_at  INTEGER NOT NULL
      );
    `
  },
  {
    id: "013-extract-sessions-content-hash",
    up: `
      ALTER TABLE extract_sessions_seen ADD COLUMN content_hash TEXT DEFAULT NULL;
    `
  },
  {
    id: "014-recombine-hypotheses",
    up: `
      CREATE TABLE IF NOT EXISTS recombine_hypotheses (
        hypothesis_ref    TEXT PRIMARY KEY,
        signature         TEXT NOT NULL,
        member_key        TEXT NOT NULL,
        consecutive_count INTEGER NOT NULL DEFAULT 0,
        first_seen_at     TEXT NOT NULL,
        last_seen_at      TEXT NOT NULL,
        last_run          TEXT,
        promoted_at       TEXT,
        metadata_json     TEXT NOT NULL DEFAULT '{}'
      );
      CREATE INDEX IF NOT EXISTS idx_recombine_hypotheses_last_seen
        ON recombine_hypotheses(last_seen_at);
    `
  },
  {
    id: "015-asset-salience-encoding-source",
    up: `
      ALTER TABLE asset_salience ADD COLUMN encoding_source TEXT DEFAULT NULL;
    `
  },
  {
    id: "016-collapse-churn-detector",
    up: `
      CREATE TABLE IF NOT EXISTS canary_queries (
        id            INTEGER PRIMARY KEY AUTOINCREMENT,
        canary_set_id TEXT    NOT NULL,
        anchor_ref    TEXT    NOT NULL,
        query         TEXT    NOT NULL,
        source        TEXT    NOT NULL DEFAULT 'auto',
        active        INTEGER NOT NULL DEFAULT 1,
        created_at    TEXT    NOT NULL
      );
      CREATE INDEX IF NOT EXISTS idx_canary_queries_active
        ON canary_queries(active, canary_set_id);

      CREATE TABLE IF NOT EXISTS improve_cycle_metrics (
        id                      INTEGER PRIMARY KEY AUTOINCREMENT,
        run_id                  TEXT    NOT NULL,
        ts                      TEXT    NOT NULL,
        pass                    TEXT    NOT NULL,
        canary_set_id           TEXT    NOT NULL,
        mean_recall             REAL    NOT NULL,
        mean_ndcg               REAL    NOT NULL,
        mean_mrr                REAL    NOT NULL,
        canary_ranks_json       TEXT    NOT NULL,
        store_total             INTEGER NOT NULL,
        store_by_type_json      TEXT    NOT NULL,
        distinct_content_ratio  REAL    NOT NULL,
        mean_bigram_diversity   REAL    NOT NULL,
        over_generation_count   INTEGER NOT NULL,
        accepted_actions        INTEGER NOT NULL,
        merge_floor_violations  INTEGER NOT NULL DEFAULT 0,
        alerts_json             TEXT    NOT NULL DEFAULT '[]'
      );
      CREATE INDEX IF NOT EXISTS idx_improve_cycle_metrics_ts
        ON improve_cycle_metrics(ts);
    `
  },
  {
    id: "017-improve-run-strategy",
    up: `
      ALTER TABLE improve_runs ADD COLUMN strategy TEXT;
      CREATE INDEX IF NOT EXISTS idx_improve_runs_strategy_started ON improve_runs(strategy, started_at);
    `
  },
  {
    id: "018-drop-dead-lane-schema",
    up: `
      DROP INDEX IF EXISTS idx_recombine_hypotheses_last_seen;
      DROP TABLE IF EXISTS recombine_hypotheses;

      DROP TABLE IF EXISTS consolidation_judged;

      DROP INDEX IF EXISTS idx_asset_outcome_review_pressure;
      ALTER TABLE asset_outcome DROP COLUMN review_pressure;
    `
  },
  {
    id: "019-proposal-fingerprints",
    up: `
      CREATE TABLE IF NOT EXISTS proposal_fingerprints (
        stash_dir TEXT NOT NULL,
        fingerprint TEXT NOT NULL,
        ref TEXT NOT NULL,
        source TEXT NOT NULL,
        model_id TEXT NOT NULL DEFAULT '',
        proposal_id TEXT,
        created_at TEXT NOT NULL,
        PRIMARY KEY (stash_dir, fingerprint)
      );
      CREATE INDEX IF NOT EXISTS idx_proposal_fingerprints_ref
        ON proposal_fingerprints(stash_dir, ref);
    `
  },
  {
    id: "020-three-db-cutover",
    up: `
      -- ── workflow_runs (workflows/db.ts base + migrations 001/002/003/006/010) ──
      CREATE TABLE IF NOT EXISTS workflow_runs (
        id                  TEXT PRIMARY KEY,
        workflow_ref        TEXT NOT NULL,
        workflow_entry_id   INTEGER,
        workflow_title      TEXT NOT NULL,
        status              TEXT NOT NULL CHECK (status IN ('active', 'completed', 'blocked', 'failed')),
        params_json         TEXT NOT NULL DEFAULT '{}',
        current_step_id     TEXT,
        created_at          TEXT NOT NULL,
        updated_at          TEXT NOT NULL,
        completed_at        TEXT,
        scope_key           TEXT,
        agent_harness       TEXT,
        agent_session_id    TEXT,
        checkin_armed_at    TEXT,
        plan_json           TEXT,
        plan_hash           TEXT,
        engine_lease_until  TEXT,
        engine_lease_holder TEXT,
        plan_ir_version     INTEGER
      );
      CREATE INDEX IF NOT EXISTS idx_workflow_runs_ref ON workflow_runs(workflow_ref);
      CREATE INDEX IF NOT EXISTS idx_workflow_runs_status ON workflow_runs(status);
      CREATE INDEX IF NOT EXISTS idx_workflow_runs_scope_ref_status
        ON workflow_runs(scope_key, workflow_ref, status);
      CREATE INDEX IF NOT EXISTS idx_workflow_runs_agent_session
        ON workflow_runs(agent_harness, agent_session_id);

      -- ── workflow_run_steps (base + migration 003 summary) ─────────────────────
      CREATE TABLE IF NOT EXISTS workflow_run_steps (
        run_id          TEXT NOT NULL,
        step_id         TEXT NOT NULL,
        step_title      TEXT NOT NULL,
        instructions    TEXT NOT NULL,
        completion_json TEXT,
        sequence_index  INTEGER NOT NULL,
        status          TEXT NOT NULL CHECK (status IN ('pending', 'completed', 'blocked', 'failed', 'skipped')),
        notes           TEXT,
        evidence_json   TEXT,
        completed_at    TEXT,
        summary         TEXT,
        PRIMARY KEY (run_id, step_id),
        FOREIGN KEY (run_id) REFERENCES workflow_runs(id) ON DELETE CASCADE
      );
      CREATE INDEX IF NOT EXISTS idx_workflow_run_steps_run_sequence
        ON workflow_run_steps(run_id, sequence_index);

      -- ── workflow_run_units (migration 004 + 005/007/008/009/010 columns) ──────
      CREATE TABLE IF NOT EXISTS workflow_run_units (
        run_id           TEXT NOT NULL,
        unit_id          TEXT NOT NULL,
        step_id          TEXT,
        node_id          TEXT NOT NULL,
        parent_unit_id   TEXT,
        phase            TEXT,
        runner           TEXT,
        model            TEXT,
        status           TEXT NOT NULL CHECK (status IN ('pending', 'running', 'completed', 'failed', 'skipped')),
        input_hash       TEXT,
        result_json      TEXT,
        tokens           INTEGER,
        failure_reason   TEXT,
        worktree_path    TEXT,
        started_at       TEXT,
        finished_at      TEXT,
        session_id       TEXT,
        last_checkin_at  TEXT,
        attempts         INTEGER NOT NULL DEFAULT 1,
        claim_holder     TEXT,
        claim_expires_at TEXT,
        engine           TEXT,
        PRIMARY KEY (run_id, unit_id),
        FOREIGN KEY (run_id) REFERENCES workflow_runs(id) ON DELETE CASCADE
      );
      CREATE INDEX IF NOT EXISTS idx_workflow_run_units_run_step
        ON workflow_run_units(run_id, step_id);

      -- ── usage_events (index.db ensureUsageEventsSchema — the durable new home) ─
      CREATE TABLE IF NOT EXISTS usage_events (
        id         INTEGER PRIMARY KEY AUTOINCREMENT,
        event_type TEXT NOT NULL,
        query      TEXT,
        entry_id   INTEGER,
        entry_ref  TEXT,
        signal     TEXT,
        metadata   TEXT,
        source     TEXT NOT NULL DEFAULT 'user',
        created_at TEXT NOT NULL DEFAULT (datetime('now'))
      );
      CREATE INDEX IF NOT EXISTS idx_usage_events_entry ON usage_events(entry_id);
      CREATE INDEX IF NOT EXISTS idx_usage_events_type ON usage_events(event_type);
      CREATE INDEX IF NOT EXISTS idx_usage_events_ref ON usage_events(entry_ref);
      CREATE INDEX IF NOT EXISTS idx_usage_events_source ON usage_events(source);

      -- ── legacy_state (ensureLegacyStateTable — the orphan quarantine archive) ──
      CREATE TABLE IF NOT EXISTS legacy_state (
        surface        TEXT NOT NULL,
        old_ref        TEXT NOT NULL,
        row_count      INTEGER NOT NULL DEFAULT 0,
        reason         TEXT NOT NULL,
        quarantined_at TEXT NOT NULL DEFAULT (datetime('now')),
        PRIMARY KEY (surface, old_ref)
      );
    `
  },
  {
    id: "021-asset-state-missing-since",
    up: `
      ALTER TABLE asset_salience ADD COLUMN missing_since INTEGER DEFAULT NULL;
      ALTER TABLE asset_outcome ADD COLUMN missing_since INTEGER DEFAULT NULL;
    `
  },
  {
    id: "022-workflow-unit-attempts",
    up: `
      CREATE TABLE workflow_run_unit_attempts (
        run_id           TEXT NOT NULL,
        unit_id          TEXT NOT NULL,
        attempt          INTEGER NOT NULL CHECK (attempt >= 1),
        dispatch_id      TEXT NOT NULL,
        step_id          TEXT NOT NULL,
        node_id          TEXT NOT NULL,
        phase            TEXT NOT NULL CHECK (phase IN ('unit', 'gate')),
        runner           TEXT,
        engine           TEXT,
        model            TEXT,
        input_hash       TEXT NOT NULL,
        status           TEXT NOT NULL CHECK (status IN ('running', 'completed', 'failed', 'skipped')),
        result_json      TEXT,
        tokens           INTEGER,
        failure_reason   TEXT,
        session_id       TEXT,
        worktree_path    TEXT,
        started_at       TEXT NOT NULL,
        finished_at      TEXT,
        claim_holder     TEXT NOT NULL,
        claim_expires_at TEXT NOT NULL,
        PRIMARY KEY (run_id, unit_id, attempt),
        FOREIGN KEY (run_id) REFERENCES workflow_runs(id) ON DELETE CASCADE
      );
      CREATE UNIQUE INDEX idx_workflow_run_unit_attempts_dispatch
        ON workflow_run_unit_attempts(dispatch_id);
      CREATE INDEX idx_workflow_run_unit_attempts_run_step
        ON workflow_run_unit_attempts(run_id, step_id, unit_id, attempt);
      CREATE INDEX idx_workflow_run_unit_attempts_running_claim
        ON workflow_run_unit_attempts(run_id, status, claim_expires_at);
    `
  },
  {
    id: "023-child-workflow-runs",
    up: `
      ALTER TABLE workflow_runs ADD COLUMN parent_run_id  TEXT;
      ALTER TABLE workflow_runs ADD COLUMN parent_unit_id TEXT;
      ALTER TABLE workflow_runs ADD COLUMN invocation_key TEXT;
      CREATE INDEX idx_workflow_runs_parent ON workflow_runs(parent_run_id);
      CREATE UNIQUE INDEX idx_workflow_runs_invocation_key
        ON workflow_runs(parent_run_id, invocation_key)
        WHERE parent_run_id IS NOT NULL;
    `
  },
  {
    id: "024-workflow-run-outputs",
    up: `
      ALTER TABLE workflow_runs ADD COLUMN outputs_json TEXT;
    `
  },
  {
    id: "025-task-history-vocabulary-backfill",
    up: `
      UPDATE task_history
      SET target_kind = 'command',
          metadata_json = json_set(metadata_json, '$.targetVocab', 2)
      WHERE target_kind = 'prompt'
        AND json_valid(metadata_json)
        AND json_extract(metadata_json, '$.targetVocab') IS NULL;

      UPDATE task_history
      SET target_kind = 'shell',
          metadata_json = json_set(metadata_json, '$.targetVocab', 2)
      WHERE target_kind = 'command'
        AND json_valid(metadata_json)
        AND json_extract(metadata_json, '$.targetVocab') IS NULL;
    `
  },
  {
    id: "026-proposals-strip-legacy-fragment-refs",
    up: `
      UPDATE proposals
      SET ref = substr(ref, 1, instr(ref, '#') - 1)
      WHERE ref LIKE '%#%';
    `
  },
  {
    id: "027-extract-sessions-seen-harness-rename",
    up: `
      UPDATE OR IGNORE extract_sessions_seen SET harness = 'claude' WHERE harness = 'claude-code';
      DELETE FROM extract_sessions_seen WHERE harness = 'claude-code';
      UPDATE workflow_runs SET agent_harness = 'claude' WHERE agent_harness = 'claude-code';
    `
  },
  {
    id: "028-improve-ledger",
    up: `
      CREATE TABLE IF NOT EXISTS improve_ledger (
        stash_dir TEXT NOT NULL,
        ref TEXT NOT NULL,
        source TEXT NOT NULL,
        last_attempt_at TEXT NOT NULL,
        outcome TEXT NOT NULL,
        next_eligible_at TEXT,
        proposal_id TEXT,
        detail TEXT,
        PRIMARY KEY (stash_dir, ref, source)
      );

      INSERT OR REPLACE INTO improve_ledger
        (stash_dir, ref, source, last_attempt_at, outcome, next_eligible_at, proposal_id, detail)
      SELECT
        p.stash_dir,
        p.ref,
        p.source,
        p.updated_at,
        o.outcome,
        CASE o.outcome
          WHEN 'rejected' THEN strftime('%Y-%m-%dT%H:%M:%fZ', p.updated_at,
            CASE p.source WHEN 'reflect' THEN '+14 days' WHEN 'distill' THEN '+30 days' ELSE '+7 days' END)
          WHEN 'expired' THEN strftime('%Y-%m-%dT%H:%M:%fZ', p.updated_at, '+1 days')
          WHEN 'proposed' THEN strftime('%Y-%m-%dT%H:%M:%fZ', p.updated_at, '+7 days')
          ELSE NULL
        END,
        p.id,
        CASE WHEN json_valid(p.metadata_json)
          THEN json_extract(p.metadata_json, '$.review.reason') ELSE NULL END
      FROM proposals p
      JOIN (
        SELECT stash_dir, ref, source, MAX(updated_at) AS latest_updated_at
        FROM proposals GROUP BY stash_dir, ref, source
      ) latest
        ON latest.stash_dir = p.stash_dir AND latest.ref = p.ref AND latest.source = p.source
       AND latest.latest_updated_at = p.updated_at
      JOIN (
        SELECT rowid AS proposal_rowid,
          CASE status
            WHEN 'pending' THEN 'proposed'
            WHEN 'accepted' THEN 'accepted'
            WHEN 'reverted' THEN 'rejected'
            WHEN 'rejected' THEN
              CASE WHEN json_valid(metadata_json) THEN
                CASE
                  WHEN json_extract(metadata_json, '$.review.reason') LIKE 'expired:%' THEN 'expired'
                  WHEN json_extract(metadata_json, '$.gateDecision.reason') = 'stale-target' THEN 'failed'
                  WHEN json_extract(metadata_json, '$.review.reason') = 'Asset no longer exists on disk' THEN 'failed'
                  ELSE 'rejected'
                END
              ELSE 'rejected' END
            ELSE NULL
          END AS outcome
        FROM proposals
      ) o ON o.proposal_rowid = p.rowid
      WHERE o.outcome IS NOT NULL
      ORDER BY p.rowid ASC;

      DROP INDEX IF EXISTS idx_proposal_fingerprints_ref;
      DROP TABLE IF EXISTS proposal_fingerprints;
      DROP TABLE IF EXISTS improve_gate_thresholds;
      DROP TABLE IF EXISTS proposal_fs_imports;
      DROP TABLE IF EXISTS consolidation_judged;
      DROP TABLE IF EXISTS improve_cycle_metrics;
      DROP TABLE IF EXISTS canary_queries;
    `
  },
  {
    id: "029-improve-ledger-content-hash",
    up: `
      ALTER TABLE improve_ledger ADD COLUMN content_hash TEXT DEFAULT NULL;
    `
  }
];
assertMigrationRegistry(STATE_MIGRATIONS);
function assertStateMigrationSafetyRegistry() {
  const migrationIds = STATE_MIGRATIONS.map((migration) => migration.id);
  const classifiedIds = Object.keys(STATE_MIGRATION_SAFETY_BY_ID);
  if (migrationIds.length !== classifiedIds.length || migrationIds.some((migrationId, index) => classifiedIds[index] !== migrationId)) {
    throw new Error("State migration safety classifications must match the exact ordered migration registry.");
  }
}
assertStateMigrationSafetyRegistry();
function getStateMigrationSafety(migrationId) {
  const safety = STATE_MIGRATION_SAFETY_BY_ID[migrationId];
  if (!safety)
    throw new Error(`State migration ${migrationId} has no safety classification.`);
  return safety;
}

// src/core/state-db.ts
function getStateDbPath() {
  return path10.join(getDataDir(), "state.db");
}
function warnNewerStateLedger(ledger) {
  if (ledger.status !== "newer")
    return;
  warnOnce("state-db-newer-ledger", `[state.db] This akm (v${pkgVersion}) is older than the state database: ${ledger.detail}. ` + "Continuing with the schema this version knows; upgrade akm if its output looks incomplete.");
}
function backupBeforeDestructiveMigration(db, dbPath, pending) {
  const destructive = pending.find((migration) => getStateMigrationSafety(migration.id) === "historical-destructive");
  if (!destructive)
    return;
  const backupPath = `${dbPath}.pre-${destructive.id}.bak`;
  const partialPath = `${backupPath}.tmp`;
  fs5.rmSync(partialPath, { force: true });
  db.prepare("VACUUM INTO ?").run(partialPath);
  fs5.renameSync(partialPath, backupPath);
  return backupPath;
}
function migrateStateDatabase(db, dbPath) {
  const ledger = assertMigrationLedger(db, STATE_MIGRATIONS);
  warnNewerStateLedger(ledger);
  const pending = STATE_MIGRATIONS.slice(ledger.migrationIds.length);
  if (pending.length === 0)
    return { applied: [] };
  const fresh = ledger.migrationIds.length === 0;
  const backupPath = fresh ? undefined : backupBeforeDestructiveMigration(db, dbPath, pending);
  const applied = runMigrations(db, STATE_MIGRATIONS);
  if (fresh && applied.length > 0)
    db.exec("VACUUM");
  return backupPath ? { applied, backupPath } : { applied };
}
function openAndMigrate(dbPath) {
  let report = { applied: [] };
  const db = openManagedDatabase({
    path: dbPath,
    pragmas: { dataDir: path10.dirname(dbPath) },
    init: (handle) => {
      report = migrateStateDatabase(handle, dbPath);
    }
  });
  return { db, ...report };
}
function listPendingStateMigrations(dbPath = getStateDbPath()) {
  if (!fs5.existsSync(dbPath))
    return [];
  const db = openDatabase(dbPath, { readonly: true, create: false });
  try {
    applyReadonlyPragmas(db);
    const ledger = assertMigrationLedger(db, STATE_MIGRATIONS);
    return STATE_MIGRATIONS.slice(ledger.migrationIds.length).map((migration) => migration.id);
  } finally {
    db.close();
  }
}
function upgradeHistoricalStateDatabase(dbPath = getStateDbPath()) {
  const pending = listPendingStateMigrations(dbPath);
  if (pending.length === 0)
    return { upgraded: false, applied: [] };
  const { db, backupPath } = openAndMigrate(dbPath);
  db.close();
  return backupPath ? { upgraded: true, applied: pending, safetyCopyPath: backupPath } : { upgraded: true, applied: pending };
}

// src/core/state-db-scope.ts
import { AsyncLocalStorage } from "node:async_hooks";
var scopeStorage = new AsyncLocalStorage;
var liveScopes = new Set;

// src/core/time.ts
var MINUTE_MS = 60 * 1000;
var HOUR_MS = 60 * 60 * 1000;
var DAY_MS = 24 * 60 * 60 * 1000;
var MONTH_MS = 30 * DAY_MS;
var DURATION_UNITS = {
  m: MINUTE_MS,
  M: MONTH_MS,
  h: HOUR_MS,
  d: DAY_MS
};
function parseDuration(spec, units = DURATION_UNITS) {
  const match = spec.trim().match(/^(\d+)([a-zA-Z])$/);
  if (!match)
    return null;
  const amount = Number.parseInt(match[1] ?? "", 10);
  if (!Number.isFinite(amount))
    return null;
  const multiplier = units[match[2] ?? ""];
  if (multiplier === undefined)
    return null;
  return amount * multiplier;
}

// src/execution/record.ts
function snapshotStrictRecord(value, path11, options = {}) {
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
    throw new TypeError(`${path11} must be an object`);
  }
  const prototype = Object.getPrototypeOf(value);
  if (prototype !== Object.prototype && prototype !== null) {
    throw new TypeError(`${path11} must use a plain or null prototype`);
  }
  const out = Object.create(null);
  for (const key of Reflect.ownKeys(value)) {
    const descriptor = Reflect.getOwnPropertyDescriptor(value, key);
    if (!descriptor)
      throw new TypeError(`${path11}.${String(key)} must have a stable own descriptor`);
    if (typeof key === "symbol" && !options.allowedSymbols?.has(key)) {
      throw new TypeError(`${path11} contains unsupported symbol field: ${String(key)}`);
    }
    if (!("value" in descriptor)) {
      throw new TypeError(`${path11}.${String(key)} must be an enumerable data property, not an accessor`);
    }
    if (typeof key === "string" && !descriptor.enumerable) {
      throw new TypeError(`${path11}.${key} must be an enumerable data property, not a non-enumerable field`);
    }
    Object.defineProperty(out, key, {
      value: descriptor.value,
      enumerable: descriptor.enumerable,
      configurable: false,
      writable: false
    });
  }
  return Object.freeze(out);
}
function assertSnapshotKeys(value, allowed, path11, allowedSymbols = new Set) {
  const allowedKeys = new Set(allowed);
  for (const key of Reflect.ownKeys(value)) {
    if (typeof key === "symbol") {
      if (!allowedSymbols.has(key))
        throw new TypeError(`${path11} contains unsupported field: ${String(key)}`);
    } else if (!allowedKeys.has(key)) {
      throw new TypeError(`${path11} contains unsupported field: ${key}`);
    }
  }
}

// src/execution/json.ts
function fail(path11, detail) {
  throw new TypeError(`${path11} ${detail}`);
}
function cloneExecutionJson(value, path11 = "execution value", ancestors = new Set) {
  if (value === null || typeof value === "string" || typeof value === "boolean")
    return value;
  if (typeof value === "number") {
    if (!Number.isFinite(value))
      fail(path11, "must contain only finite numbers");
    return value;
  }
  if (value === undefined)
    fail(path11, "must be omitted rather than set to undefined");
  if (typeof value !== "object")
    fail(path11, "must be JSON-safe");
  if (ancestors.has(value))
    fail(path11, "must not contain a cycle");
  const nextAncestors = new Set(ancestors);
  nextAncestors.add(value);
  if (Array.isArray(value)) {
    if (Object.getPrototypeOf(value) !== Array.prototype)
      fail(path11, "array must use the standard Array prototype");
    const ownKeys = Reflect.ownKeys(value);
    const lengthDescriptor = Reflect.getOwnPropertyDescriptor(value, "length");
    if (!lengthDescriptor || !("value" in lengthDescriptor) || typeof lengthDescriptor.value !== "number" || !Number.isInteger(lengthDescriptor.value) || lengthDescriptor.value < 0) {
      fail(path11, "array length must be a stable nonnegative integer data property");
    }
    const length = lengthDescriptor.value;
    if (ownKeys.length !== length + 1) {
      fail(path11, "array must be dense and contain no non-index properties");
    }
    for (const key of ownKeys) {
      if (key === "length")
        continue;
      if (typeof key !== "string" || !/^(?:0|[1-9]\d*)$/.test(key) || Number(key) >= length) {
        fail(path11, "array must contain only canonical index properties");
      }
    }
    const cloned2 = [];
    for (let index = 0;index < length; index++) {
      const descriptor = Reflect.getOwnPropertyDescriptor(value, String(index));
      if (!descriptor || !("value" in descriptor) || !descriptor.enumerable) {
        fail(path11, "array must be dense enumerable data properties");
      }
      cloned2.push(cloneExecutionJson(descriptor.value, `${path11}[${index}]`, nextAncestors));
    }
    return Object.freeze(cloned2);
  }
  const snapshot = snapshotStrictRecord(value, path11);
  const cloned = Object.create(null);
  for (const [key, child] of Object.entries(snapshot)) {
    Object.defineProperty(cloned, key, {
      value: cloneExecutionJson(child, `${path11}.${key}`, nextAncestors),
      enumerable: true,
      configurable: false,
      writable: false
    });
  }
  return Object.freeze(cloned);
}
function cloneExecutionJsonObject(value, path11) {
  const cloned = cloneExecutionJson(value, path11);
  if (cloned === null || Array.isArray(cloned) || typeof cloned !== "object") {
    fail(path11, "must be a JSON object");
  }
  return cloned;
}

// src/core/config/engine-semantics.ts
var ENGINE_NAME_PATTERN_SOURCE = "^(?!akm-)[a-z][a-z0-9]*(?:-[a-z0-9]+)*$";
var BUILTIN_IMPROVE_STRATEGY_NAMES = [
  "default",
  "quick",
  "thorough",
  "consolidate",
  "catchup",
  "reflect-distill",
  "proactive-maintenance"
];
var IMPROVE_ENGINE_PROCESSES = [
  "reflect",
  "distill",
  "consolidate",
  "memoryInference",
  "extract",
  "validation",
  "triage"
];
var IMPROVE_PROCESS_NAMES = [...IMPROVE_ENGINE_PROCESSES, "proactiveMaintenance"];

// src/core/improve-result.ts
var COMMON_FIELDS = [
  "schemaVersion",
  "ok",
  "scope",
  "dryRun",
  "notices",
  "skipped",
  "guidance",
  "memorySummary",
  "memoryCleanup",
  "cyclesRun",
  "plannedRefs",
  "plan",
  "actions",
  "skippedProcesses",
  "engineProbe",
  "distillSkipped",
  "validationFailures",
  "schemaRepairs",
  "consolidation",
  "extract",
  "lintSummary",
  "memoryIndexHealth",
  "coverageGaps",
  "evalCasesWritten",
  "deadUrls",
  "deadUrlCoverage",
  "reflectsWithErrorContext",
  "memoryInference",
  "graphExtraction",
  "memoryInferenceDurationMs",
  "graphExtractionDurationMs",
  "ensureIndexDurationMs",
  "orphansPurged",
  "proposalsExpired",
  "reflectCooldownActions",
  "reflectSkippedActions",
  "reflectGuardRejectedActions",
  "gateAutoAcceptedCount",
  "gateAutoAcceptFailedCount",
  "triage",
  "proactiveMaintenance",
  "cycleMetrics",
  "runId",
  "sync",
  "writtenPaths",
  "terminated",
  "usageReport"
];
var V2_FIELDS = new Set([...COMMON_FIELDS, "strategy", "strategyFilteredRefs"]);

// src/core/assert.ts
function assertNever(x, context) {
  let serialized;
  try {
    serialized = JSON.stringify(x);
  } catch {
    serialized = String(x);
  }
  if (serialized === undefined) {
    serialized = String(x);
  }
  const where = context ? ` (${context})` : "";
  throw new Error(`Unexpected value reached assertNever${where}: ${serialized}`);
}

// src/llm/usage-telemetry.ts
import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
var attributionStorage = new AsyncLocalStorage2;

// src/commands/health/windows.ts
var INTERESTING_DELTA_PATHS = [
  "improve.actions.reflect.failed",
  "improve.actions.distill.queued",
  "improve.actions.distill.llmFailed",
  "improve.consolidation.promoted",
  "improve.memoryInference.written",
  "improve.memoryInference.yieldRate",
  "improve.memoryInference.skippedNoFacts",
  "improve.autoAccept.promoted",
  "improve.autoAccept.validationFailed",
  "improve.coverage.acceptedProposals",
  "improve.coverage.distinctRefs",
  "improve.wallTime.medianMs",
  "improve.wallTime.p95Ms",
  "metrics.llmUsage.calls",
  "metrics.llmUsage.totalTokens",
  "metrics.llmUsage.totalDurationMs",
  "metrics.llmUsage.failures"
];
function readNumericPath(obj, path11) {
  const parts = path11.split(".");
  let cursor = obj;
  for (const part of parts) {
    if (typeof cursor !== "object" || cursor === null)
      return 0;
    cursor = cursor[part];
  }
  return typeof cursor === "number" && Number.isFinite(cursor) ? cursor : 0;
}

// src/commands/health/md-report.ts
function padRight(s, width) {
  return s.length >= width ? s : s + " ".repeat(width - s.length);
}
function renderTable(headers, rows) {
  const widths = headers.map((h, i) => Math.max(h.length, ...rows.map((r) => (r[i] ?? "").length)));
  const lines = [];
  lines.push(headers.map((h, i) => padRight(h, widths[i] ?? 0)).join("  "));
  for (const row of rows) {
    lines.push(row.map((cell, i) => padRight(cell ?? "", widths[i] ?? 0)).join("  "));
  }
  return lines.join(`
`);
}
function renderRunsDetailMd(runs) {
  const headers = [
    "ts",
    "ok",
    "strategy",
    "actions",
    "refl_ok/fail/cd/skip",
    "distill_q/llm-fail/judge/validator/cfg/skip",
    "cons_proc/promo/merge/del",
    "mem_cons/written/skip",
    "orphans",
    "lint_f/fl",
    "result_status"
  ];
  const rows = runs.map((r) => {
    const totalActions = r.actions.reflect.ok + r.actions.reflect.failed + r.actions.reflect.cooldown + r.actions.reflect.skipped + r.actions.distill.queued + r.actions.distill.llmFailed + r.actions.distill.judgeRejected + r.actions.distill.validatorRejected + r.actions.distill.configDisabled + r.actions.distill.skipped + r.actions.memoryPrune + r.actions.memoryInference + r.actions.error;
    return [
      r.startedAt,
      String(r.ok),
      r.strategy ?? "",
      String(totalActions),
      `${r.actions.reflect.ok}/${r.actions.reflect.failed}/${r.actions.reflect.cooldown}/${r.actions.reflect.skipped}`,
      `${r.actions.distill.queued}/${r.actions.distill.llmFailed}/${r.actions.distill.judgeRejected}/${r.actions.distill.validatorRejected}/${r.actions.distill.configDisabled}/${r.actions.distill.skipped}`,
      `${r.consolidation.processed}/${r.consolidation.promoted}/${r.consolidation.merged}/${r.consolidation.deleted}`,
      `${r.memoryInference.considered}/${r.memoryInference.written}/${r.memoryInference.skippedNoFacts}`,
      String(r.orphansPurged),
      `${r.lintFixed}/${r.lintFlagged}`,
      r.resultStatus ?? "valid"
    ];
  });
  return renderTable(headers, rows);
}
function renderWindowCompareMd(windows, deltas) {
  if (windows.length === 0)
    return "";
  const headers = ["metric", ...windows.map((w) => w.name), "delta"];
  const badIfPositive = new Set([
    "improve.actions.reflect.failed",
    "improve.actions.distill.llmFailed",
    "improve.wallTime.medianMs",
    "improve.wallTime.p95Ms",
    "improve.memoryInference.skippedNoFacts"
  ]);
  const rows = [];
  const paths = [
    "runs",
    "improve.resultRows.included",
    "improve.resultRows.skipped.invalid",
    ...INTERESTING_DELTA_PATHS
  ];
  for (const path11 of paths) {
    const values = windows.map((w) => String(readNumericPath(w, path11)));
    const delta = deltas?.[path11];
    let deltaStr = "—";
    if (delta) {
      const pct = delta.pctChange;
      const num2 = typeof pct === "number" ? pct : pct;
      const sign = typeof num2 === "number" && num2 > 0 ? "+" : "";
      const formatted = typeof num2 === "number" ? `${sign}${num2}%` : String(num2);
      const marker = badIfPositive.has(path11) && typeof num2 === "number" && num2 > 0 ? "!" : "";
      deltaStr = marker + formatted;
    }
    rows.push([path11, ...values, deltaStr]);
  }
  return renderTable(headers, rows);
}

// src/commands/health/renderers.ts
function isHealthResult(value) {
  return value !== null && typeof value === "object" && "status" in value;
}
registerMdRenderer("health", (result) => {
  if (!isHealthResult(result))
    return null;
  if (result.windows && result.windows.length > 0) {
    return renderWindowCompareMd(result.windows, result.deltas);
  }
  if (result.runs)
    return renderRunsDetailMd(result.runs);
  return null;
});

// src/output/generic-render.ts
var ENVELOPE_META_KEYS = new Set(["shape", "schemaVersion"]);
function flattenForText(value, path11, lines) {
  if (value === null || value === undefined) {
    lines.push(`${path11}=`);
  } else if (Array.isArray(value)) {
    lines.push(`${path11}=${JSON.stringify(value)}`);
  } else if (typeof value === "object") {
    const entries = Object.entries(value);
    if (entries.length === 0) {
      lines.push(`${path11}={}`);
      return;
    }
    for (const [key, nested] of entries) {
      flattenForText(nested, `${path11}.${key}`, lines);
    }
  } else {
    lines.push(`${path11}=${String(value)}`);
  }
}

// src/output/shapes/helpers.ts
var NORMAL_DESCRIPTION_LIMIT = 250;
var FRAGMENT_PROVENANCE_FIELDS = [
  "selectedRef",
  "parentRef",
  "fragmentOrdinal",
  "fragmentCount",
  "startLine",
  "endLine",
  "previousRef",
  "nextRef",
  "fragmentChars",
  "fragmentEstimatedTokens",
  "parentChars",
  "parentEstimatedTokens"
];
var FRAGMENT_CONTEXT_FIELDS = ["contextMode", "contextMaxChars", "contextTruncated"];
function shapeProposalProducerOutput(result, detail) {
  if (result.ok === false) {
    const base2 = {
      ok: false,
      reason: result.reason,
      error: result.error,
      ...result.ref !== undefined ? { ref: result.ref } : {},
      ...result.type !== undefined ? { type: result.type } : {},
      ...result.name !== undefined ? { name: result.name } : {},
      ...result.engine !== undefined ? { engine: result.engine } : {},
      ...result.exitCode !== undefined ? { exitCode: result.exitCode } : {},
      ...Array.isArray(result.notices) ? { notices: result.notices } : {}
    };
    if (detail === "full") {
      return {
        schemaVersion: result.schemaVersion,
        ...base2,
        ...result.stdout !== undefined ? { stdout: result.stdout } : {},
        ...result.stderr !== undefined ? { stderr: result.stderr } : {}
      };
    }
    return base2;
  }
  const proposal = result.proposal;
  const base = {
    ok: result.ok,
    ref: result.ref,
    ...result.engine !== undefined ? { engine: result.engine } : {},
    ...typeof result.durationMs === "number" ? { durationMs: result.durationMs } : {},
    ...Array.isArray(result.notices) ? { notices: result.notices } : {},
    proposal: shapeProposalEntry(proposal, detail === "brief" ? "normal" : detail)
  };
  if (detail === "full") {
    return { schemaVersion: result.schemaVersion, ...base };
  }
  return base;
}
function shapeProposalEntry(entry, detail) {
  if (detail === "brief") {
    const retirement = entry.retirement;
    return {
      ...pickFields(entry, ["id", "ref", "status", "source", "createdAt"]),
      ...retirement?.continuityRisk ? { continuityRisk: true } : {}
    };
  }
  if (detail === "normal") {
    return pickFields(entry, [
      "id",
      "ref",
      "status",
      "source",
      "sourceRun",
      "createdAt",
      "updatedAt",
      "confidence",
      "gateDecision",
      "review",
      "reviewHistory",
      "retirement"
    ]);
  }
  return pickFields(entry, [
    "id",
    "ref",
    "status",
    "source",
    "sourceRun",
    "createdAt",
    "updatedAt",
    "confidence",
    "gateDecision",
    "payload",
    "review",
    "reviewHistory",
    "retirement",
    "retiredArchive",
    "promotionSource",
    "promotionSourceHash"
  ]);
}
function shapeProposalListOutput(result, detail) {
  const proposals = result.proposals;
  const shaped = proposals.map((p) => shapeProposalEntry(p, detail));
  const base = {
    totalCount: result.totalCount,
    proposals: shaped
  };
  if (detail === "full") {
    return { schemaVersion: result.schemaVersion, ...base };
  }
  return base;
}
function shapeProposalShowOutput(result, detail) {
  const proposal = result.proposal;
  const validation = result.validation;
  const base = {
    proposal: shapeProposalEntry(proposal, detail === "brief" ? "normal" : detail),
    ...validation ? { validation } : {}
  };
  if (detail === "full") {
    return { schemaVersion: result.schemaVersion, ...base };
  }
  return base;
}
function shapeProposalAcceptOutput(result, detail) {
  const proposal = result.proposal;
  const base = {
    ok: result.ok,
    id: result.id,
    ref: result.ref,
    assetPath: result.assetPath,
    proposal: shapeProposalEntry(proposal, detail === "brief" ? "normal" : detail)
  };
  if (detail === "full") {
    return { schemaVersion: result.schemaVersion, ...base };
  }
  return base;
}
function shapeProposalRejectOutput(result, detail) {
  const proposal = result.proposal;
  const base = {
    ok: result.ok,
    id: result.id,
    ref: result.ref,
    ...result.reason !== undefined ? { reason: result.reason } : {},
    proposal: shapeProposalEntry(proposal, detail === "brief" ? "normal" : detail)
  };
  if (detail === "full") {
    return { schemaVersion: result.schemaVersion, ...base };
  }
  return base;
}
function shapeProposalDiffOutput(result, detail) {
  const base = {
    id: result.id,
    ref: result.ref,
    isNew: result.isNew,
    unified: result.unified,
    ...result.targetPath !== undefined ? { targetPath: result.targetPath } : {},
    ...result.op !== undefined ? { op: result.op } : {},
    ...result.retirement !== undefined ? { retirement: result.retirement } : {},
    ...result.note !== undefined ? { note: result.note } : {}
  };
  if (detail === "full") {
    return { schemaVersion: result.schemaVersion, ...base };
  }
  return base;
}
function shapeEventsOutput(result, detail) {
  const events = Array.isArray(result.events) ? result.events : [];
  const shapedEvents = events.map((event) => shapeEventEntry(event, detail));
  const base = {
    ...result.ref !== undefined ? { ref: result.ref } : {},
    ...result.type !== undefined ? { type: result.type } : {},
    ...result.run !== undefined ? { run: result.run } : {},
    ...result.since !== undefined ? { since: result.since } : {},
    ...typeof result.sinceOffset === "number" ? { sinceOffset: result.sinceOffset } : {},
    ...typeof result.limit === "number" ? { limit: result.limit } : {},
    totalCount: result.totalCount ?? shapedEvents.length,
    events: shapedEvents
  };
  if (typeof result.nextOffset === "number") {
    base.nextOffset = result.nextOffset;
  }
  if (typeof result.reason === "string") {
    base.reason = result.reason;
  }
  if (detail === "full") {
    return { schemaVersion: result.schemaVersion ?? 1, ...base };
  }
  return base;
}
function shapeEventEntry(entry, detail) {
  if (detail === "brief") {
    return pickFields(entry, ["eventType", "ref", "ts"]);
  }
  if (detail === "normal") {
    return pickFields(entry, ["eventType", "ref", "ts"]);
  }
  return pickFields(entry, ["id", "schemaVersion", "eventType", "ref", "ts", "metadata"]);
}
function shapeSearchOutput(result, detail, shape = "human") {
  const forAgent = shape === "agent";
  const hits = Array.isArray(result.hits) ? result.hits : [];
  const registryHits = Array.isArray(result.registryHits) ? result.registryHits : [];
  const shapedHits = forAgent ? hits.map((hit) => shapeSearchHitForAgent(hit)) : hits.map((hit) => shapeSearchHit(hit, detail));
  const shapedRegistryHits = forAgent ? registryHits.map((hit) => shapeSearchHitForAgent(hit)) : registryHits.map((hit) => shapeSearchHit(hit, detail));
  const searchMode = typeof result.searchMode === "string" ? result.searchMode : undefined;
  const warnings = Array.isArray(result.warnings) && result.warnings.length > 0 ? result.warnings : undefined;
  if (forAgent) {
    return {
      hits: shapedHits,
      ...shapedRegistryHits.length > 0 ? { registryHits: shapedRegistryHits } : {},
      ...searchMode ? { searchMode } : {},
      ...warnings ? { warnings } : {},
      ...result.tip ? { tip: result.tip } : {}
    };
  }
  if (detail === "full") {
    return {
      schemaVersion: result.schemaVersion,
      bundleDir: result.bundleDir,
      source: result.source,
      hits: shapedHits,
      ...shapedRegistryHits.length > 0 ? { registryHits: shapedRegistryHits } : {},
      ...result.tip ? { tip: result.tip } : {},
      ...searchMode ? { searchMode } : {},
      ...warnings ? { warnings } : {},
      ...result.timing ? { timing: result.timing } : {}
    };
  }
  return {
    hits: shapedHits,
    ...shapedRegistryHits.length > 0 ? { registryHits: shapedRegistryHits } : {},
    ...searchMode ? { searchMode } : {},
    ...warnings ? { warnings } : {},
    ...result.tip ? { tip: result.tip } : {}
  };
}
function shapeRegistrySearchOutput(result, detail) {
  const hits = Array.isArray(result.hits) ? result.hits : [];
  const assetHits = Array.isArray(result.assetHits) ? result.assetHits : [];
  const shapedKitHits = hits.map((hit) => shapeSearchHit({ ...hit, type: "registry" }, detail));
  const shapedAssetHits = assetHits.map((hit) => shapeAssetHit(hit, detail));
  const shaped = {
    hits: shapedKitHits,
    ...shapedAssetHits.length > 0 ? { assetHits: shapedAssetHits } : {},
    ...Array.isArray(result.warnings) && result.warnings.length > 0 ? { warnings: result.warnings } : {}
  };
  if (detail === "full") {
    shaped.query = result.query;
  }
  return shaped;
}
function shapeAssetHit(hit, detail) {
  if (detail === "brief")
    return pickFields(hit, ["assetName", "assetType", "action", "estimatedTokens"]);
  if (detail === "normal") {
    return capDescription(pickFields(hit, ["assetName", "assetType", "description", "stash", "action", "estimatedTokens"]), NORMAL_DESCRIPTION_LIMIT);
  }
  return hit;
}
function shapeSearchHit(hit, detail) {
  if (hit.type === "registry") {
    if (detail === "brief") {
      const out = pickFields(hit, ["title", "name", "installRef", "score"]);
      if (out.title && !out.name)
        out.name = out.title;
      return out;
    }
    if (detail === "normal") {
      const out = capDescription(pickFields(hit, ["title", "name", "description", "action", "installRef", "score", "warnings"]), NORMAL_DESCRIPTION_LIMIT);
      if (out.title && !out.name)
        out.name = out.title;
      return out;
    }
    return hit;
  }
  if (detail === "brief") {
    return pickFields(hit, ["type", "name", "ref", "action", "estimatedTokens", "keys"]);
  }
  if (detail === "normal") {
    const shaped = capDescription(pickFields(hit, ["type", "name", "description", "action", "score", "estimatedTokens", "warnings", "quality"]), NORMAL_DESCRIPTION_LIMIT);
    if (Array.isArray(hit.keys) && hit.keys.length > 0)
      shaped.keys = hit.keys;
    return shaped;
  }
  return hit;
}
function shapeSearchHitForAgent(hit) {
  const picked = pickFields(hit, [
    "name",
    "ref",
    "type",
    "path",
    "editable",
    "editHint",
    "description",
    "action",
    "score",
    "estimatedTokens",
    "keys"
  ]);
  if (picked.editable !== false)
    delete picked.editHint;
  return capDescription(picked, NORMAL_DESCRIPTION_LIMIT);
}
function capDescription(hit, limit) {
  if (typeof hit.description !== "string")
    return hit;
  return { ...hit, description: truncateDescription(hit.description, limit) };
}
function truncateDescription(description, limit) {
  const normalized = description.replace(/\s+/g, " ").trim();
  if (normalized.length <= limit)
    return normalized;
  const truncated = normalized.slice(0, limit - 1);
  const lastSpace = truncated.lastIndexOf(" ");
  const safe = lastSpace >= Math.floor(limit * 0.6) ? truncated.slice(0, lastSpace) : truncated;
  return `${safe.trimEnd()}...`;
}
function shapeShowOutput(result, detail, shape = "human") {
  if (shape === "agent") {
    const shaped = pickFields(result, [
      "type",
      "name",
      "ref",
      "path",
      "editable",
      "editHint",
      "description",
      "action",
      "content",
      "template",
      "prompt",
      "run",
      "setup",
      "cwd",
      "activeRun",
      "toolPolicy",
      "modelHint",
      "agent",
      "parameters",
      "workflowTitle",
      "workflowParameters",
      "steps",
      "keys",
      "links",
      ...FRAGMENT_PROVENANCE_FIELDS,
      ...FRAGMENT_CONTEXT_FIELDS
    ]);
    if (shaped.editable !== false)
      delete shaped.editHint;
    return shaped;
  }
  if (shape === "summary") {
    return pickFields(result, [
      "type",
      "name",
      "ref",
      "description",
      "tags",
      "parameters",
      "workflowTitle",
      "action",
      "run",
      "origin",
      "keys",
      "links",
      ...FRAGMENT_PROVENANCE_FIELDS,
      ...FRAGMENT_CONTEXT_FIELDS
    ]);
  }
  const base = pickFields(result, [
    "type",
    "name",
    "ref",
    "origin",
    "action",
    "description",
    "tags",
    "content",
    "template",
    "prompt",
    "toolPolicy",
    "modelHint",
    "agent",
    "parameters",
    "workflowTitle",
    "workflowParameters",
    "steps",
    "run",
    "setup",
    "cwd",
    "activeRun",
    "keys",
    "links",
    ...FRAGMENT_PROVENANCE_FIELDS,
    ...FRAGMENT_CONTEXT_FIELDS,
    "path",
    "editable"
  ]);
  if (detail !== "full") {
    return base;
  }
  return {
    schemaVersion: 1,
    ...base,
    ...pickFields(result, ["editHint"])
  };
}
function pickFields(source, fields) {
  const result = {};
  for (const field of fields) {
    if (source[field] !== undefined) {
      result[field] = source[field];
    }
  }
  return result;
}

// src/output/shapes/curate.ts
var BRIEF_FIELDS = ["source", "type", "name", "ref", "id", "supportRefs", "followUp", "reason"];
var NORMAL_FIELDS = [
  "source",
  "type",
  "name",
  "ref",
  "path",
  "editable",
  "editHint",
  "id",
  "description",
  "preview",
  "keys",
  "parameters",
  "run",
  "supportRefs",
  "followUp",
  "reason",
  "score"
];
var AGENT_FIELDS = [
  "source",
  "type",
  "name",
  "ref",
  "path",
  "editable",
  "editHint",
  "id",
  "description",
  "supportRefs",
  "followUp",
  "reason",
  "score"
];
function shapeCurateItem(item, detail, shape) {
  if (shape === "agent") {
    const shaped = pickFields(item, AGENT_FIELDS);
    if (shaped.editable !== false)
      delete shaped.editHint;
    return capDescription(shaped, NORMAL_DESCRIPTION_LIMIT);
  }
  if (detail === "brief") {
    return pickFields(item, BRIEF_FIELDS);
  }
  if (detail === "normal") {
    return capDescription(pickFields(item, NORMAL_FIELDS), NORMAL_DESCRIPTION_LIMIT);
  }
  return item;
}
function shapeCurateOutput(result, detail, shape) {
  const items = Array.isArray(result.items) ? result.items : [];
  const shapedItems = items.map((item) => shapeCurateItem(item, detail, shape));
  const base = {
    schemaVersion: typeof result.schemaVersion === "number" ? result.schemaVersion : 1,
    shape: "curate",
    query: result.query,
    summary: result.summary,
    items: shapedItems,
    ...typeof result.searchMode === "string" ? { searchMode: result.searchMode } : {},
    ...Array.isArray(result.warnings) && result.warnings.length > 0 ? { warnings: result.warnings } : {},
    ...result.tip ? { tip: result.tip } : {}
  };
  return base;
}
var curateShapes = [
  {
    command: "curate",
    handler: (result, detail, shape) => shapeCurateOutput(result, detail, shape)
  }
];

// src/output/shapes/env-list.ts
var envListShapes = [
  {
    command: "env-list",
    handler: (result) => {
      const r = result;
      const envs = Array.isArray(r.envs) ? r.envs : [];
      return {
        ...r,
        shape: r.shape ?? "env-list",
        schemaVersion: r.schemaVersion ?? 1,
        envs: envs.map((v) => {
          const { path: _path, ...rest } = v;
          return rest;
        })
      };
    }
  }
];

// src/output/shapes/events.ts
var handler = (result, detail) => shapeEventsOutput(result, detail);
var eventsShapes = [{ command: "log-list", handler }];

// src/output/shapes/migrate.ts
var identity2 = (result) => result;
var migrateShapes = [
  { command: "migrate-status", handler: identity2 },
  { command: "migrate-apply", handler: identity2 }
];

// src/output/shapes/models-list.ts
var modelsListShapes = [
  {
    command: "models-list",
    handler: (result) => {
      const r = result;
      return {
        ...r,
        shape: r.shape ?? "models-list",
        schemaVersion: r.schemaVersion ?? 1
      };
    }
  }
];

// src/output/shapes/passthrough.ts
function makeStampHandler(command) {
  return (result) => {
    if (result === null || result === undefined)
      return result;
    if (typeof result !== "object" || Array.isArray(result))
      return result;
    const obj = result;
    return {
      ok: obj.ok ?? true,
      ...obj,
      shape: obj.shape ?? command,
      schemaVersion: obj.schemaVersion ?? 1
    };
  };
}
var PASSTHROUGH_COMMANDS = [
  "add",
  "agent-result",
  "bundle-create",
  "bundle-rename",
  "bundle-show",
  "clone",
  "command-dry-run",
  "config",
  "config-diff",
  "env-create",
  "env-export",
  "env-remove",
  "feedback",
  "extract",
  "health",
  "improve",
  "improve-judge",
  "improve-report",
  "import",
  "index",
  "info",
  "lint",
  "list",
  "models",
  "proposal-accept-batch",
  "proposal-drain",
  "proposal-reject-batch",
  "proposal-reopen-batch",
  "proposal-revert",
  "registry-add",
  "registry-list",
  "registry-remove",
  "remember",
  "remove",
  "secret-set",
  "setup",
  "sync",
  "task-add",
  "task-disable",
  "task-doctor",
  "task-enable",
  "task-explain",
  "task-history",
  "task-prune",
  "task-run",
  "task-sync",
  "task-sync-dry-run",
  "task-validate",
  "update",
  "upgrade",
  "workflow-abandon",
  "workflow-create",
  "workflow-list",
  "workflow-plan",
  "workflow-resume",
  "workflow-run",
  "workflow-status"
];
var passthroughShapes = PASSTHROUGH_COMMANDS.map((command) => ({
  command,
  handler: makeStampHandler(command)
}));

// src/output/shapes/proposal/accept.ts
var proposalAcceptShapes = [
  {
    command: "proposal-accept",
    handler: (result, detail) => shapeProposalAcceptOutput(result, detail)
  }
];

// src/output/shapes/proposal/diff.ts
var proposalDiffShapes = [
  {
    command: "proposal-diff",
    handler: (result, detail) => shapeProposalDiffOutput(result, detail)
  }
];

// src/output/shapes/proposal/list.ts
var proposalListShapes = [
  {
    command: "proposal-list",
    handler: (result, detail) => shapeProposalListOutput(result, detail)
  }
];

// src/output/shapes/proposal/producer.ts
var handler2 = (result, detail) => shapeProposalProducerOutput(result, detail);
var proposalProducerShapes = [{ command: "proposal-new", handler: handler2 }];

// src/output/shapes/proposal/reject.ts
var proposalRejectShapes = [
  {
    command: "proposal-reject",
    handler: (result, detail) => shapeProposalRejectOutput(result, detail)
  }
];

// src/output/shapes/proposal/reopen.ts
var proposalReopenShapes = [
  {
    command: "proposal-reopen",
    handler: (result, detail) => shapeProposalRejectOutput(result, detail)
  }
];

// src/output/shapes/proposal/show.ts
var proposalShowShapes = [
  {
    command: "proposal-show",
    handler: (result, detail) => shapeProposalShowOutput(result, detail)
  }
];

// src/output/command-registry.ts
function createCommandRegistry() {
  const handlers = new Map;
  return {
    register(command, handler3) {
      handlers.set(command, handler3);
    },
    registerAll(entries) {
      for (const { command, handler: handler3 } of entries) {
        handlers.set(command, handler3);
      }
    },
    deregister(command) {
      handlers.delete(command);
    },
    get(command) {
      return handlers.get(command);
    }
  };
}

// src/output/shapes/registry.ts
var OUTPUT_SHAPE_REGISTRY = createCommandRegistry();
function registerOutputShapes(entries) {
  OUTPUT_SHAPE_REGISTRY.registerAll(entries);
}

// src/output/shapes/registry-search.ts
var registrySearchShapes = [
  {
    command: "registry-search",
    handler: (result, detail) => shapeRegistrySearchOutput(result, detail)
  }
];

// src/output/shapes/search.ts
var searchShapes = [
  {
    command: "search",
    handler: (result, detail, shape) => shapeSearchOutput(result, detail, shape)
  }
];

// src/output/shapes/secret-list.ts
var secretListShapes = [
  {
    command: "secret-list",
    handler: (result) => {
      const r = result;
      const secrets = Array.isArray(r.secrets) ? r.secrets : [];
      return {
        ...r,
        shape: r.shape ?? "secret-list",
        schemaVersion: r.schemaVersion ?? 1,
        secrets: secrets.map((s) => {
          const { path: _path, ...rest } = s;
          return rest;
        })
      };
    }
  }
];

// src/output/shapes/show.ts
var showShapes = [
  {
    command: "show",
    handler: (result, detail, shape) => shapeShowOutput(result, detail, shape)
  }
];

// src/output/shapes.ts
var BUILT_IN_OUTPUT_SHAPES = [
  ...searchShapes,
  ...curateShapes,
  ...registrySearchShapes,
  ...showShapes,
  ...eventsShapes,
  ...proposalListShapes,
  ...proposalShowShapes,
  ...proposalAcceptShapes,
  ...proposalRejectShapes,
  ...proposalReopenShapes,
  ...proposalDiffShapes,
  ...proposalProducerShapes,
  ...envListShapes,
  ...secretListShapes,
  ...migrateShapes,
  ...modelsListShapes,
  ...passthroughShapes
];
registerOutputShapes(BUILT_IN_OUTPUT_SHAPES);
var SHAPE_SUMMARY_COMMANDS = new Set(["show"]);

// src/core/registry-url.ts
var INVALID_REGISTRY_URL_LABEL = "(invalid registry URL)";
var HTTP_SCHEME_START = /h[\t\r\n]*t[\t\r\n]*t[\t\r\n]*p[\t\r\n]*(?:s[\t\r\n]*)?:/giu;
var AUTHORITY_PREFIX_SEPARATOR = new Set(["\t", "\r", `
`, "\\", "/"]);
var AUTHORITY_STRUCTURAL_BOUNDARY = new Set(["\\", "/", "?", "#"]);
var AUTHORITY_AMBIGUOUS_BOUNDARY = new Set(["&", ",", ";", ")"]);
var AUTHORITY_SOFT_BOUNDARY = new Set(["\t", "\r", `
`, " ", '"', "'", "`", "<", ">"]);
var STRICT_MAX_DEPTH = 8;
var STRICT_MAX_CANDIDATES = 128;
var STRICT_MAX_DECODED_BYTES = 65536;
var HTTP_SCHEME_EVIDENCE = /h[\t\r\n]*t[\t\r\n]*t[\t\r\n]*p[\t\r\n]*(?:s[\t\r\n]*)?:/iu;
function formatRegistryUrl(raw) {
  const parsed = parseWholeHttpUrl(raw);
  const inspection = inspectStrictRegistryUrl(raw);
  if (parsed) {
    if (!inspection.unsafe)
      return raw;
    let candidate = raw;
    if (parsed.username || parsed.password) {
      parsed.username = "";
      parsed.password = "";
      candidate = parsed.toString();
    }
    candidate = redactDetectedUserinfo(candidate, "strict");
    return inspectStrictRegistryUrl(candidate).unsafe ? INVALID_REGISTRY_URL_LABEL : candidate;
  }
  const formatted = redactDetectedUserinfo(raw, "strict");
  if (inspection.unsafe && registryUrlStarts(raw)[0]?.start === 0 && formatted !== raw && !inspectStrictRegistryUrl(formatted).unsafe) {
    return formatted;
  }
  return INVALID_REGISTRY_URL_LABEL;
}
function inspectStrictRegistryUrl(raw) {
  const state = { candidates: 0, decodedBytes: 0 };
  const parsed = parseWholeHttpUrl(raw);
  if (!parsed) {
    inspectStrictComponent(raw, state, 0);
    return state.reason ? { unsafe: true, reason: state.reason } : { unsafe: false };
  }
  inspectParsedStrictUrl(parsed, state, 0);
  return state.reason ? { unsafe: true, reason: state.reason } : { unsafe: false };
}
function inspectParsedStrictUrl(parsed, state, depth) {
  if (state.reason)
    return;
  if (parsed.username || parsed.password) {
    state.reason = "credentials";
    return;
  }
  inspectAuthoredStrictComponent(parsed.pathname, state, depth, false);
  if (state.reason)
    return;
  const rawQuery = parsed.search.startsWith("?") ? parsed.search.slice(1) : parsed.search;
  for (const pair of rawQuery.split("&")) {
    const equals = pair.indexOf("=");
    const rawKey = equals >= 0 ? pair.slice(0, equals) : pair;
    const rawValue = equals >= 0 ? pair.slice(equals + 1) : "";
    inspectAuthoredStrictComponent(rawKey, state, depth, true);
    inspectAuthoredStrictComponent(rawValue, state, depth, true);
    if (state.reason)
      return;
  }
  const fragment = parsed.hash.startsWith("#") ? parsed.hash.slice(1) : parsed.hash;
  inspectAuthoredStrictComponent(fragment, state, depth, false);
}
function inspectAuthoredStrictComponent(raw, state, depth, queryEncoded) {
  for (const authoredPart of splitAuthoredFieldComponents(raw)) {
    let component = authoredPart;
    if (queryEncoded) {
      const decoded = decodePercentSafely(authoredPart, "query");
      if (!decoded.valid && hasCredentialLikeUrlEvidence(authoredPart)) {
        state.reason = "malformed-encoding";
        return;
      }
      component = decoded.value;
    }
    inspectStrictComponent(component, state, depth);
    if (state.reason)
      return;
  }
}
function inspectStrictComponent(raw, state, depth) {
  if (state.reason || raw.length === 0)
    return;
  let decoded = raw;
  let currentDepth = depth;
  const seenCandidateKeys = new Set;
  while (true) {
    const starts = registryUrlStarts(decoded);
    if (starts.length > 0) {
      const unseenIndices = unseenCandidateIndices(decoded, starts, seenCandidateKeys);
      const percentFullyCovered = inspectStrictUrlCandidates(decoded, starts, unseenIndices, state, currentDepth);
      if (state.reason)
        return;
      if (percentFullyCovered)
        return;
    }
    if (!decoded.includes("%"))
      return;
    if (currentDepth >= STRICT_MAX_DEPTH) {
      if (looksLikeStrictUrlComponent(decoded))
        state.reason = "inspection-limit";
      return;
    }
    const next = decodePercentSafely(decoded, "component");
    if (!next.valid) {
      if (hasCredentialLikeUrlEvidence(decoded))
        state.reason = "malformed-encoding";
      return;
    }
    if (next.value === decoded)
      return;
    decoded = next.value;
    currentDepth++;
  }
}
function unseenCandidateIndices(decoded, starts, seenCandidateKeys) {
  const occurrences = new Map;
  const unseen = new Set;
  for (let index = 0;index < starts.length; index++) {
    const start = starts[index];
    if (!start)
      continue;
    const authority = strictAuthoritySlice(decoded.slice(start.start));
    const occurrence = (occurrences.get(authority) ?? 0) + 1;
    occurrences.set(authority, occurrence);
    const key = `${authority}\x00${occurrence}`;
    if (seenCandidateKeys.has(key))
      continue;
    seenCandidateKeys.add(key);
    unseen.add(index);
  }
  return unseen;
}
function inspectStrictUrlCandidates(decoded, starts, unseenIndices, state, depth) {
  const recursivelyInspectedRanges = [];
  const bytes = new TextEncoder().encode(decoded).byteLength;
  if (bytes > STRICT_MAX_DECODED_BYTES - state.decodedBytes) {
    state.reason = "inspection-limit";
    return false;
  }
  state.decodedBytes += bytes;
  if (unseenIndices.size > STRICT_MAX_CANDIDATES - state.candidates) {
    state.reason = "inspection-limit";
    return false;
  }
  state.candidates += unseenIndices.size;
  for (const start of starts) {
    if (findStrictComponentUserinfoSpan(decoded, start)) {
      state.reason = "credentials";
      return false;
    }
  }
  for (let index = 0;index < starts.length; index++) {
    if (!unseenIndices.has(index))
      continue;
    const start = starts[index];
    if (!start)
      continue;
    const nextStart = starts[index + 1]?.start ?? decoded.length;
    const candidate = trimStrictCandidateSuffix(decoded.slice(start.start, nextStart));
    const candidateDepth = inspectDecodedCandidateUserinfo(candidate, state, depth);
    if (state.reason)
      return false;
    if (candidateDepth >= STRICT_MAX_DEPTH) {
      state.reason = "inspection-limit";
      return false;
    }
    const parsed = parseWholeHttpUrl(candidate);
    if (!parsed)
      continue;
    if (parsed.username || parsed.password)
      continue;
    inspectParsedStrictUrl(parsed, state, candidateDepth + 1);
    if (state.reason)
      return false;
    recursivelyInspectedRanges.push({ start: start.start, end: nextStart });
  }
  return everyPercentEscapeIsCovered(decoded, recursivelyInspectedRanges);
}
function everyPercentEscapeIsCovered(raw, ranges) {
  for (let cursor = raw.indexOf("%");cursor >= 0; cursor = raw.indexOf("%", cursor + 1)) {
    if (!ranges.some((range) => cursor >= range.start && cursor < range.end))
      return false;
  }
  return true;
}
function inspectDecodedCandidateUserinfo(raw, state, depth) {
  let decoded = strictAuthoritySlice(raw);
  let currentDepth = depth;
  while (true) {
    if (registryUrlStarts(decoded).some((start) => findStrictComponentUserinfoSpan(decoded, start))) {
      state.reason = "credentials";
      return currentDepth;
    }
    if (!decoded.includes("%"))
      return currentDepth;
    if (currentDepth >= STRICT_MAX_DEPTH) {
      state.reason = "inspection-limit";
      return currentDepth;
    }
    const next = decodePercentSafely(decoded, "component");
    if (!next.valid) {
      if (hasCredentialLikeUrlEvidence(decoded))
        state.reason = "malformed-encoding";
      return currentDepth;
    }
    if (next.value === decoded)
      return currentDepth;
    decoded = strictAuthoritySlice(next.value);
    currentDepth++;
  }
}
function strictAuthoritySlice(raw) {
  const start = registryUrlStarts(raw)[0];
  if (!start)
    return raw;
  let end = raw.length;
  for (let cursor = start.authorityStart;cursor < raw.length; cursor++) {
    const char = raw[cursor];
    if (char && AUTHORITY_STRUCTURAL_BOUNDARY.has(char)) {
      end = cursor;
      break;
    }
  }
  return raw.slice(start.start, end);
}
function decodePercentSafely(raw, mode) {
  const input = mode === "query" ? raw.replaceAll("+", "%20") : raw;
  let valid = true;
  let value = raw;
  try {
    value = decodeURIComponent(input);
  } catch {
    valid = false;
  }
  if (mode === "query") {
    return { value: new URLSearchParams(`value=${raw}`).get("value") ?? "", valid };
  }
  if (!valid)
    return { value: raw, valid: false };
  return { value, valid: true };
}
function splitAuthoredFieldComponents(raw) {
  const parts = [];
  let partStart = 0;
  for (let cursor = 0;cursor < raw.length; cursor++) {
    const delimiter = raw[cursor];
    if (!delimiter || !AUTHORITY_AMBIGUOUS_BOUNDARY.has(delimiter))
      continue;
    if (!/^[a-z0-9_.-]+=/iu.test(raw.slice(cursor + 1)))
      continue;
    const prefix = raw.slice(partStart, cursor);
    const starts = registryUrlStarts(prefix);
    const lastStart = starts.at(-1);
    if (!lastStart)
      continue;
    const candidate = trimStrictCandidateSuffix(prefix.slice(lastStart.start));
    const parsed = parseWholeHttpUrl(candidate);
    if (!parsed || parsed.username || parsed.password || !looksLikeDiagnosticHostPrefix(parsed.hostname))
      continue;
    parts.push(raw.slice(partStart, cursor));
    partStart = cursor + 1;
  }
  parts.push(raw.slice(partStart));
  return parts;
}
function findStrictComponentUserinfoSpan(raw, urlStart) {
  const conventional = findUserinfoSpan(raw, urlStart, "strict");
  if (conventional)
    return conventional;
  const { authorityStart } = urlStart;
  let lastAt = -1;
  for (let cursor = authorityStart;cursor < raw.length; cursor++) {
    const char = raw[cursor];
    if (char === undefined || AUTHORITY_STRUCTURAL_BOUNDARY.has(char))
      break;
    if (char === "@" && cursor > authorityStart)
      lastAt = cursor;
  }
  if (lastAt <= authorityStart)
    return;
  const prefix = raw.slice(authorityStart, lastAt);
  const ambiguousBoundary = Array.from(prefix).findIndex((char) => AUTHORITY_AMBIGUOUS_BOUNDARY.has(char));
  if (ambiguousBoundary < 0)
    return;
  return { start: authorityStart, end: lastAt + 1 };
}
function trimStrictCandidateSuffix(raw) {
  return raw.replace(/[\t\r\n ]+$/u, "").replace(/[,&;]+$/u, "");
}
function hasCredentialLikeUrlEvidence(raw) {
  const evidence = decodePercentForEvidence(raw);
  return HTTP_SCHEME_EVIDENCE.test(stripMalformedPercentForEvidence(evidence)) && evidence.includes("@");
}
function looksLikeStrictUrlComponent(raw) {
  const evidence = decodePercentForEvidence(raw);
  return HTTP_SCHEME_EVIDENCE.test(stripMalformedPercentForEvidence(evidence));
}
function decodePercentForEvidence(raw) {
  let decoded = raw;
  for (let layer = 0;layer <= STRICT_MAX_DEPTH; layer++) {
    const next = decoded.replace(/%([0-9a-f]{2})/giu, (_match, hex) => String.fromCharCode(Number.parseInt(hex, 16)));
    if (next === decoded)
      break;
    decoded = next;
  }
  return decoded;
}
function stripMalformedPercentForEvidence(raw) {
  return raw.replace(/%[^%]{0,2}/gu, "");
}
function redactDetectedUserinfo(raw, mode) {
  let formatted = raw;
  const starts = registryUrlStarts(raw);
  for (let i = starts.length - 1;i >= 0; i--) {
    const start = starts[i];
    if (start === undefined)
      continue;
    const span = findUserinfoSpan(formatted, start, mode);
    if (!span)
      continue;
    formatted = `${formatted.slice(0, span.start)}${formatted.slice(span.end)}`;
  }
  return formatted;
}
function registryUrlStarts(raw) {
  return Array.from(raw.matchAll(HTTP_SCHEME_START), (match) => {
    let authorityStart = match.index + match[0].length;
    while (authorityStart < raw.length && AUTHORITY_PREFIX_SEPARATOR.has(raw[authorityStart] ?? "")) {
      authorityStart++;
    }
    return { start: match.index, authorityStart };
  });
}
function findUserinfoSpan(raw, urlStart, mode) {
  const { authorityStart } = urlStart;
  let crossedAmbiguousBoundary = false;
  let lastAt = -1;
  for (let cursor = authorityStart;cursor < raw.length; cursor++) {
    const char = raw[cursor];
    if (char === undefined)
      return;
    if (char === "@") {
      if (cursor > authorityStart)
        lastAt = cursor;
      continue;
    }
    if (AUTHORITY_STRUCTURAL_BOUNDARY.has(char))
      return userinfoSpan(authorityStart, lastAt);
    const isSoftBoundary = AUTHORITY_SOFT_BOUNDARY.has(char);
    const isAmbiguousBoundary = AUTHORITY_AMBIGUOUS_BOUNDARY.has(char);
    if (!isSoftBoundary && !isAmbiguousBoundary)
      continue;
    if (mode === "diagnostic" && cursor === authorityStart && isSoftBoundary)
      return;
    if (lastAt >= 0 && mode === "diagnostic") {
      const apparentHost = raw.slice(lastAt + 1, cursor);
      if (looksLikeDiagnosticHostPrefix(apparentHost))
        return userinfoSpan(authorityStart, lastAt);
    }
    if (crossedAmbiguousBoundary)
      continue;
    const prefix = raw.slice(authorityStart, cursor);
    if (mode === "diagnostic" && looksLikeDiagnosticHostPrefix(prefix) || isAmbiguousBoundary && !prefix.includes(":")) {
      return userinfoSpan(authorityStart, lastAt);
    }
    crossedAmbiguousBoundary = true;
  }
  return userinfoSpan(authorityStart, lastAt);
}
function userinfoSpan(authorityStart, lastAt) {
  return lastAt > authorityStart ? { start: authorityStart, end: lastAt + 1 } : undefined;
}
function looksLikeDiagnosticHostPrefix(raw) {
  if (raw.startsWith("["))
    return true;
  const hostname = raw.split(":", 1)[0]?.toLowerCase() ?? "";
  return hostname === "localhost" || hostname.startsWith("xn--") || hostname.includes(".");
}
function parseWholeHttpUrl(raw) {
  try {
    const parsed = new URL(raw);
    return parsed.protocol === "http:" || parsed.protocol === "https:" ? parsed : undefined;
  } catch {
    return;
  }
}

// src/output/text/command-format.ts
function formatInfoPlain(r) {
  const lines = [];
  if (r.version)
    lines.push(`version: ${String(r.version)}`);
  if (typeof r.error === "string")
    lines.push(`error: ${r.error}`);
  if (r.bundleDir)
    lines.push(`bundleDir: ${String(r.bundleDir)}`);
  if (r.defaultBundle !== undefined) {
    lines.push(`defaultBundle: ${r.defaultBundle === null ? "(none)" : String(r.defaultBundle)}`);
  }
  if (typeof r.configError === "string")
    lines.push(`configError: ${r.configError}`);
  if (typeof r.bundleDirError === "string")
    lines.push(`bundleDirError: ${r.bundleDirError}`);
  if (Array.isArray(r.assetTypes) && r.assetTypes.length > 0) {
    lines.push(`assetTypes: ${r.assetTypes.join(", ")}`);
  }
  if (Array.isArray(r.searchModes) && r.searchModes.length > 0) {
    lines.push(`searchModes: ${r.searchModes.join(", ")}`);
  }
  const semanticSearch = r.semanticSearch;
  if (semanticSearch) {
    lines.push("semanticSearch:");
    for (const [k, v] of Object.entries(semanticSearch)) {
      lines.push(`  ${k}: ${String(v)}`);
    }
  }
  const registries = Array.isArray(r.registries) ? r.registries : undefined;
  if (registries) {
    lines.push(`registries (${registries.length}):`);
    for (const reg of registries) {
      const name = typeof reg.name === "string" ? `${reg.name}: ` : "";
      const provider = typeof reg.provider === "string" ? ` (${reg.provider})` : "";
      const disabled = reg.enabled === false ? " [disabled]" : "";
      const url = typeof reg.url === "string" ? formatRegistryUrl(reg.url) : "?";
      lines.push(`  ${name}${url}${provider}${disabled}`);
    }
  }
  const sourceProviders = Array.isArray(r.sourceProviders) ? r.sourceProviders : undefined;
  if (sourceProviders) {
    lines.push(`sourceProviders (${sourceProviders.length}):`);
    for (const source of sourceProviders) {
      const label = source.name ?? source.path ?? source.url ?? source.type ?? "?";
      const disabled = source.enabled === false ? " [disabled]" : "";
      lines.push(`  [${String(source.type ?? "?")}] ${String(label)}${disabled}`);
    }
  }
  const indexStats = r.indexStats;
  if (indexStats) {
    lines.push("indexStats:");
    for (const [k, v] of Object.entries(indexStats)) {
      lines.push(`  ${k}: ${typeof v === "object" && v !== null ? JSON.stringify(v) : String(v)}`);
    }
  }
  if (lines.length === 0)
    return JSON.stringify(r, null, 2);
  return lines.join(`
`);
}
function formatConfigPlain(r) {
  const lines = [];
  const walk = (obj, prefix) => {
    for (const [k, v] of Object.entries(obj)) {
      const path11 = prefix ? `${prefix}.${k}` : k;
      if (v === null || v === undefined) {
        lines.push(`${path11}=`);
      } else if (Array.isArray(v)) {
        lines.push(`${path11}=${JSON.stringify(v)}`);
      } else if (typeof v === "object") {
        walk(v, path11);
      } else {
        const rendered = typeof v === "string" && /^registries\.\d+\.url$/u.test(path11) ? formatRegistryUrl(v) : String(v);
        lines.push(`${path11}=${rendered}`);
      }
    }
  };
  walk(r, "");
  if (lines.length === 0)
    return "(empty config)";
  return lines.join(`
`);
}
function formatFeedbackPlain(r) {
  const ref = String(r.ref ?? "?");
  const signal = String(r.signal ?? "?");
  const note = typeof r.note === "string" && r.note ? ` — ${r.note}` : "";
  return `Recorded ${signal} feedback for ${ref}${note}`;
}
function formatRememberPlain(r) {
  const ref = String(r.ref ?? "?");
  const pathValue = String(r.path ?? "?");
  return `Saved ${ref} at ${pathValue}`;
}
function formatImportPlain(r) {
  const ref = String(r.ref ?? "?");
  const source = String(r.source ?? "?");
  const pathValue = String(r.path ?? "?");
  return `Imported ${source} → ${ref} at ${pathValue}`;
}
function formatSyncPlain(r) {
  if (r.ok === false) {
    const reason = typeof r.reason === "string" ? r.reason : "unknown";
    return `sync: failed (${reason})`;
  }
  const name = typeof r.name === "string" ? r.name : "primary bundle";
  const committed = r.committed === true;
  const pushed = r.pushed === true;
  const parts = [`sync: ${name}`];
  parts.push(committed ? "committed" : "no changes");
  if (pushed)
    parts.push("pushed");
  return parts.join(" — ");
}
function formatRegistryListPlain(r) {
  const registries = Array.isArray(r.registries) ? r.registries : [];
  if (registries.length === 0) {
    return "No registries configured. Add one with `akm registry add <url>`.";
  }
  const lines = [];
  for (const reg of registries) {
    const url = typeof reg.url === "string" ? formatRegistryUrl(reg.url) : "?";
    const name = typeof reg.name === "string" ? reg.name : "";
    const provider = typeof reg.provider === "string" ? ` (${reg.provider})` : "";
    const enabled = reg.enabled === false ? " [disabled]" : "";
    const head = name ? `${name}: ${url}` : url;
    lines.push(`${head}${provider}${enabled}`);
  }
  return lines.join(`
`);
}
function formatRegistryAddPlain(r) {
  if (r.added === false) {
    return typeof r.message === "string" ? r.message : "Registry already configured.";
  }
  const registries = Array.isArray(r.registries) ? r.registries.length : 0;
  return `Registry added (${registries} total).`;
}
function formatRegistryRemovePlain(r) {
  if (r.removed === false) {
    return typeof r.message === "string" ? r.message : "No matching registry found.";
  }
  const entry = r.entry;
  const url = entry ? typeof entry.url === "string" ? formatRegistryUrl(entry.url) : String(entry.name ?? "?") : "?";
  return `Removed registry ${url}`;
}
function formatRegistrySearchPlain(r, detail) {
  return formatSearchPlain(r, detail);
}
function formatEnvListPlain(r) {
  const envs = Array.isArray(r.envs) ? r.envs : [];
  if (envs.length === 0) {
    return "No env files. Create one with `akm env create <name>`, then edit the .env file directly.";
  }
  const lines = [];
  for (const v of envs) {
    const ref = String(v.ref ?? "?");
    const keys = Array.isArray(v.keys) ? v.keys.map(String) : [];
    if (lines.length > 0)
      lines.push("");
    lines.push(`## ${ref}`);
    if (keys.length === 0) {
      lines.push("- (no keys)");
      continue;
    }
    for (const key of keys) {
      lines.push(`- ${key}`);
    }
  }
  return lines.join(`
`);
}
function formatEnvCreatePlain(r) {
  return `Created env ${String(r.ref ?? "?")}`;
}
function formatEnvExportPlain(r) {
  return `Wrote ${String(r.ref ?? "?")} export script → ${String(r.out ?? "?")} (mode 0600; source it, then delete)`;
}
function formatEnvRemovePlain(r) {
  const removed = r.removed === true;
  return removed ? `Removed env ${String(r.ref ?? "?")}` : `Env ${String(r.ref ?? "?")} was not present`;
}
function formatEventsPlain(r) {
  const events = Array.isArray(r.events) ? r.events : [];
  const headerParts = [];
  if (typeof r.ref === "string" && r.ref)
    headerParts.push(`ref: ${r.ref}`);
  if (typeof r.type === "string" && r.type)
    headerParts.push(`type: ${r.type}`);
  if (typeof r.since === "string" && r.since)
    headerParts.push(`since: ${r.since}`);
  const totalCount = typeof r.totalCount === "number" ? r.totalCount : events.length;
  headerParts.push(`${totalCount} event(s)`);
  const header = headerParts.join("  ");
  if (events.length === 0) {
    return `${header}
No events.`;
  }
  const lines = [header, ""];
  for (const event of events) {
    lines.push(formatEventLine(event));
  }
  return lines.join(`
`).trimEnd();
}
function formatEventLine(event) {
  const ts = String(event.ts ?? "?");
  const eventType = String(event.eventType ?? "?");
  const ref = event.ref ? String(event.ref) : null;
  const head = ref ? `${ts}  [${eventType}] ${ref}` : `${ts}  [${eventType}]`;
  if (event.metadata != null && event.metadata !== "") {
    const meta = typeof event.metadata === "string" ? event.metadata : JSON.stringify(event.metadata);
    return `${head}
  metadata: ${meta}`;
  }
  return head;
}
function formatSearchPlain(r, detail) {
  const hits = r.hits ?? [];
  const registryHits = r.registryHits ?? [];
  const allHits = [...hits, ...registryHits];
  if (allHits.length === 0) {
    const warnings = Array.isArray(r.warnings) ? r.warnings : [];
    const hasSetupWarning = warnings.some((w) => String(w).toLowerCase().includes("no bundle") || String(w).toLowerCase().includes("not configured"));
    if (hasSetupWarning) {
      return "No bundle configured. Run `akm bundle create` to create your working bundle, then `akm index` to build the search index.";
    }
    const base = r.tip ? String(r.tip) : "No matches found.";
    return `${base}
Try:
  akm search '<broader-term>'          # fewer keywords
  akm bundle list                      # see all configured sources
  akm curate '<query>'                 # let akm select the best match`;
  }
  const lines = [];
  for (const hit of allHits) {
    const type = hit.type ?? "unknown";
    const name = hit.name ?? "unnamed";
    const score = hit.score != null ? ` (score: ${hit.score})` : "";
    const desc = hit.description ? `  ${hit.description}` : "";
    lines.push(`${type}: ${name}${score}`);
    if (desc)
      lines.push(desc);
    if (hit.id)
      lines.push(`  id: ${String(hit.id)}`);
    if (hit.ref)
      lines.push(`  ref: ${String(hit.ref)}`);
    if (hit.origin !== undefined)
      lines.push(`  origin: ${String(hit.origin)}`);
    if (Array.isArray(hit.keys) && hit.keys.length > 0)
      lines.push(`  keys: ${hit.keys.join(", ")}`);
    if (hit.size)
      lines.push(`  size: ${String(hit.size)}`);
    if (hit.action)
      lines.push(`  action: ${String(hit.action)}`);
    if (hit.run)
      lines.push(`  run: ${String(hit.run)}`);
    if (Array.isArray(hit.tags) && hit.tags.length > 0)
      lines.push(`  tags: ${hit.tags.join(", ")}`);
    if (typeof hit.quality === "string" && hit.quality)
      lines.push(`  quality: ${hit.quality}`);
    if (Array.isArray(hit.warnings) && hit.warnings.length > 0) {
      lines.push(`  warnings: ${hit.warnings.join("; ")}`);
    }
    if (detail === "full") {
      if (hit.path)
        lines.push(`  path: ${String(hit.path)}`);
      if (hit.editable != null)
        lines.push(`  editable: ${String(hit.editable)}`);
      if (hit.editHint)
        lines.push(`  editHint: ${String(hit.editHint)}`);
      const whyMatched = hit.whyMatched;
      if (whyMatched && whyMatched.length > 0) {
        lines.push(`  whyMatched: ${whyMatched.join(", ")}`);
      }
    }
    lines.push("");
  }
  if (detail === "full" && r.timing) {
    const timing = r.timing;
    const parts = [];
    if (timing.totalMs != null)
      parts.push(`total: ${timing.totalMs}ms`);
    if (timing.rankMs != null)
      parts.push(`rank: ${timing.rankMs}ms`);
    if (timing.embedMs != null)
      parts.push(`embed: ${timing.embedMs}ms`);
    if (parts.length > 0)
      lines.push(`timing: ${parts.join(", ")}`);
  }
  if (hits.length >= 1) {
    const preferredHit = hits.find((h) => h.type === "skill" || h.type === "command" || h.type === "agent") ?? hits[0];
    const topRef = typeof preferredHit.ref === "string" ? preferredHit.ref : null;
    const hasWorkflowHit = hits.some((h) => h.type === "workflow");
    if (topRef) {
      if (hasWorkflowHit) {
        const workflowRef = hits.find((h) => h.type === "workflow");
        const wfRef = workflowRef && typeof workflowRef.ref === "string" ? workflowRef.ref : topRef;
        lines.push(`Next: akm show '${topRef}'  |  To execute a workflow: akm workflow run '${wfRef}'`);
        lines.push("Inspect the workflow before running it; `workflow run` executes and verifies its steps automatically.");
      } else {
        lines.push(`Next: akm show '${topRef}'`);
        lines.push("After reading the asset: check whether a workflow applies before editing — if so, inspect it and use `akm workflow run`.");
      }
    }
  }
  return lines.join(`
`).trimEnd();
}
function formatCuratePlain(r, detail) {
  const query = typeof r.query === "string" ? r.query : "";
  const summary = typeof r.summary === "string" ? r.summary : "";
  const items = Array.isArray(r.items) ? r.items : [];
  const lines = [`Curated results for "${query}"`];
  if (summary)
    lines.push(summary);
  if (items.length === 0) {
    if (r.tip)
      lines.push(String(r.tip));
    return lines.join(`
`);
  }
  for (const item of items) {
    const type = typeof item.type === "string" ? item.type : "unknown";
    const name = typeof item.name === "string" ? item.name : "unnamed";
    lines.push("");
    lines.push(`[${type}] ${name}`);
    if (item.description)
      lines.push(`  ${String(item.description)}`);
    if (item.preview)
      lines.push(`  preview: ${String(item.preview)}`);
    if (item.ref)
      lines.push(`  ref: ${String(item.ref)}`);
    if (item.id)
      lines.push(`  id: ${String(item.id)}`);
    if (Array.isArray(item.keys) && item.keys.length > 0) {
      lines.push(`  keys: ${item.keys.join(", ")}`);
    }
    if (Array.isArray(item.parameters) && item.parameters.length > 0) {
      lines.push(`  parameters: ${item.parameters.join(", ")}`);
    }
    if (item.run)
      lines.push(`  run: ${String(item.run)}`);
    if (item.followUp)
      lines.push(`  show: ${String(item.followUp)}`);
    if (Array.isArray(item.supportRefs) && item.supportRefs.length > 0) {
      for (const support of item.supportRefs) {
        if (!support.ref)
          continue;
        const label = typeof support.type === "string" ? `[${support.type}] ` : "";
        const why = typeof support.reason === "string" ? ` — ${support.reason}` : "";
        lines.push(`  support: ${label}${String(support.ref)}${why}`);
      }
    }
    if (detail !== "brief" && item.reason)
      lines.push(`  why: ${String(item.reason)}`);
  }
  const warnings = Array.isArray(r.warnings) ? r.warnings : [];
  if (warnings.length > 0) {
    lines.push("");
    lines.push("Warnings:");
    for (const warning of warnings) {
      lines.push(`- ${String(warning)}`);
    }
  }
  lines.push("");
  lines.push("Next steps:");
  lines.push("  1. Run `akm show <ref>` for the best result above to read the full schema.");
  lines.push("  2. Edit the workspace file using the schema field names and your task-specific values.");
  lines.push("  3. Run `akm feedback <ref> --positive` when the task succeeds.");
  lines.push("To search further: akm search '<query>'");
  return lines.join(`
`);
}
function formatInitPlain(r) {
  let out = `Bundle initialized at ${r.bundleDir ?? "unknown"}`;
  if (r.defaultBundleUpdated === false && typeof r.previousBundleDir === "string" && r.previousBundleDir) {
    out += `
Your default bundle is unchanged (${r.previousBundleDir}). Re-run with --set-default to make ${r.bundleDir} the default.`;
  } else if (r.configPath) {
    out += `
Config saved to ${r.configPath}`;
  }
  return out;
}
function formatIndexPlain(r) {
  const indexResult = r;
  let out = `Indexed ${indexResult.totalEntries ?? 0} entries from ${indexResult.directoriesScanned ?? 0} directories (mode: ${indexResult.mode ?? "unknown"})`;
  const warnings = indexResult.warnings;
  if (Array.isArray(warnings) && warnings.length > 0) {
    out += `
Warnings (${warnings.length}):`;
    for (const message of warnings)
      out += `
  - ${String(message)}`;
  }
  const verification = indexResult.verification;
  if (verification?.ok === false && verification.message) {
    out += `
Verification: ${String(verification.message)}`;
  }
  const timing = indexResult.timing;
  if (timing) {
    out += `
Timing: total ${timing.totalMs}ms` + `, preflight ${timing.preflightMs}ms` + `, walk ${timing.walkMs}ms` + `, llm ${timing.llmMs}ms` + `, embeddings ${timing.embedMs}ms` + `, fts ${timing.ftsMs}ms` + `, finalize ${timing.finalizeMs}ms` + `, clean ${timing.cleanMs}ms` + `, end-to-end ${timing.endToEndMs}ms`;
  }
  return out;
}
function formatListPlain(r) {
  const sources = Array.isArray(r.sources) ? r.sources : [];
  if (sources.length === 0)
    return "No sources configured. Use `akm bundle add` to add a source.";
  const lines = [];
  for (const src of sources) {
    const kind = typeof src.kind === "string" ? src.kind : "unknown";
    const name = typeof src.name === "string" ? src.name : "unnamed";
    const ver = typeof src.version === "string" ? ` v${src.version}` : "";
    const prov = typeof src.provider === "string" ? ` (${src.provider})` : "";
    const flags = [];
    if (src.default === true)
      flags.push("default");
    if (src.writable === true)
      flags.push("writable");
    const flagText = flags.length > 0 ? ` [${flags.join(", ")}]` : "";
    lines.push(`[${kind}] ${name}${ver}${prov}${flagText}`);
  }
  lines.push("");
  lines.push("To search: akm search '<query>'  |  To view an asset: akm show <ref>");
  return lines.join(`
`);
}
function formatModelsListPlain(r) {
  const rows = Array.isArray(r.rows) ? r.rows : [];
  if (rows.length === 0)
    return "No model aliases configured.";
  const headers = ["ALIAS", "COLUMN", "MODEL", "SOURCE", "VIA", "ENGINE"];
  const cells = rows.map((row) => [
    String(row.alias ?? "?"),
    String(row.column ?? "?"),
    String(row.model ?? "?"),
    String(row.source ?? "?"),
    String(row.via ?? "?"),
    row.engine !== undefined ? String(row.engine) : "-"
  ]);
  const widths = headers.map((header, i) => {
    let width = header.length;
    for (const cols of cells) {
      const cell = cols[i];
      if (cell !== undefined && cell.length > width)
        width = cell.length;
    }
    return width;
  });
  const renderRow = (cols) => cols.map((cell, i) => cell.padEnd(widths[i] ?? cell.length)).join("  ").trimEnd();
  return [renderRow(headers), ...cells.map(renderRow)].join(`
`);
}
function formatBundleShowPlain(r) {
  const name = typeof r.name === "string" ? r.name : "unknown";
  const kind = typeof r.kind === "string" ? r.kind : "unknown";
  const lines = [`${name} [${kind}]`];
  if (r.default === true)
    lines.push("  default: true");
  if (r.writable === true)
    lines.push("  writable: true");
  if (typeof r.version === "string")
    lines.push(`  version: ${r.version}`);
  if (typeof r.provider === "string")
    lines.push(`  provider: ${r.provider}`);
  if (typeof r.path === "string")
    lines.push(`  path: ${r.path}`);
  if (typeof r.ref === "string")
    lines.push(`  ref: ${r.ref}`);
  if (typeof r.registryId === "string")
    lines.push(`  registryId: ${r.registryId}`);
  lines.push(`  items: ${typeof r.itemCount === "number" ? r.itemCount : 0}`);
  const byType = r.byType;
  if (byType && Object.keys(byType).length > 0) {
    lines.push(`  byType: ${Object.entries(byType).map(([t, n]) => `${t}=${n}`).join(", ")}`);
  }
  const status = r.status;
  if (status?.exists === false)
    lines.push("  status: MISSING on disk");
  return lines.join(`
`);
}
function formatAddPlain(r) {
  if (!("index" in r))
    return formatDeclarativeAddPlain(r);
  const index = r.index;
  const scanned = index?.directoriesScanned ?? 0;
  const total = index?.totalEntries ?? 0;
  const bundleSuffix = typeof r.bundleId === "string" && r.bundleId.length > 0 ? ` as bundle "${r.bundleId}"` : "";
  const lines = [`Installed ${r.ref}${bundleSuffix} (${scanned} directories scanned, ${total} total assets indexed)`];
  const warnings = index?.warnings;
  if (Array.isArray(warnings) && warnings.length > 0) {
    lines.push(`Warnings (${warnings.length}):`);
    for (const message of warnings)
      lines.push(`  - ${String(message)}`);
  }
  return lines.join(`
`);
}
function formatDeclarativeAddPlain(r) {
  if (r.added !== true) {
    return typeof r.message === "string" ? r.message : "add: no changes";
  }
  const entry = r.entry;
  const kind = typeof entry?.type === "string" ? entry.type : "source";
  const name = typeof entry?.name === "string" && entry.name || typeof entry?.path === "string" && entry.path || typeof entry?.url === "string" && entry.url || "source";
  if (kind === "filesystem") {
    return `Added ${name} (filesystem) — run \`akm index\` to index it.`;
  }
  return `Added ${name} (${kind}) — not yet synced; run \`akm bundle update ${name}\` to fetch it.`;
}
function formatRemovePlain(r) {
  const target = r.target ?? r.ref ?? "";
  const ok = r.ok !== false ? "OK" : "FAILED";
  return `remove: ${target} ${ok}`;
}
function formatBundleRenamePlain(r) {
  const oldId = String(r.oldId ?? "?");
  const newId = String(r.newId ?? "?");
  const applied = r.applied === true;
  const config = r.config ?? {};
  const state = r.state ?? {};
  const index = r.index ?? {};
  const schedulerRefs = Array.isArray(config.schedulerRefs) ? config.schedulerRefs.length : 0;
  const proposalRefs = Number(state.proposalRefs ?? 0);
  const proposalTargets = Number(state.proposalTargets ?? 0);
  const taskHistoryRefs = Number(state.taskHistoryRefs ?? 0);
  const entries = Number(index.entries ?? 0);
  const contentRefs = Array.isArray(r.contentRefs) ? r.contentRefs : [];
  const nativeSchedulerRows = Array.isArray(r.nativeSchedulerRows) ? r.nativeSchedulerRows : [];
  const verb = applied ? "Renamed" : "Would rename";
  const lines = [
    `${verb} bundle "${oldId}" to "${newId}" (${entries} index entries, ${schedulerRefs} scheduler ref(s), ` + `${proposalRefs + proposalTargets} proposal reference(s), ${taskHistoryRefs} task-history row(s)).`
  ];
  if (!applied) {
    lines.push("Re-run without --dry-run to apply. It also re-syncs native scheduler bindings under the new name.");
    if (nativeSchedulerRows.length > 0) {
      lines.push(`Native scheduler rows naming "${oldId}//" that the sync would replace:`);
      for (const row of nativeSchedulerRows)
        lines.push(`  - ${String(row)}`);
    }
  } else {
    const taskSync = r.taskSync;
    const syncResult = taskSync?.result;
    if (syncResult) {
      const installed = Array.isArray(syncResult.installed) ? syncResult.installed.length : 0;
      const updated = Array.isArray(syncResult.updated) ? syncResult.updated.length : 0;
      const removed = Array.isArray(syncResult.removed) ? syncResult.removed.length : 0;
      const failures = Array.isArray(syncResult.failures) ? syncResult.failures : [];
      if (failures.length === 0) {
        lines.push(`Native scheduler bindings re-synced under the new name (${installed} installed, ${updated} updated, ${removed} removed).`);
      } else {
        lines.push(`Native scheduler sync after rename: ${installed} installed, ${updated} updated, ${removed} removed, ${failures.length} failed.`);
        for (const failure of failures)
          lines.push(`  - ${failure.ref ?? failure.path}: ${failure.reason}`);
        lines.push("Run `akm task sync` to retry.");
      }
    } else if (taskSync?.ok === false && taskSync.error) {
      lines.push(`Re-syncing native scheduler bindings failed: ${taskSync.error}. Run \`akm task sync\` to retry.`);
    }
  }
  if (contentRefs.length > 0) {
    lines.push(`Content still spelling "${oldId}//" (not rewritten — edit these by hand):`);
    for (const file of contentRefs)
      lines.push(`  - ${String(file)}`);
  }
  return lines.join(`
`);
}
function formatUpdatePlain(r) {
  const processed = r.processed;
  const plainSynced = r.plainSynced;
  const skipped = r.skipped;
  const lines = [];
  for (const item of processed ?? []) {
    const changed = item.changed;
    const installed = item.installed;
    const previous = item.previous;
    if (changed?.any) {
      const prev = previous?.resolvedVersion ?? "unknown";
      const next = installed?.resolvedVersion ?? "unknown";
      lines.push(`update: ${item.id} v${prev} → v${next}`);
    } else {
      lines.push(`update: ${item.id} (unchanged)`);
    }
  }
  for (const item of plainSynced ?? []) {
    lines.push(item.kind === "filesystem" ? `update: ${item.id} reconciled (filesystem)` : `update: ${item.id} synced (${item.kind})`);
  }
  for (const item of skipped ?? []) {
    lines.push(`update: ${item.id} skipped — ${item.reason}`);
  }
  return lines.length > 0 ? lines.join(`
`) : `update: nothing to update`;
}
function formatUpgradePlain(r) {
  if (r.upgraded === true) {
    return `akm upgraded: v${r.currentVersion} → v${r.newVersion}`;
  }
  if (r.updateAvailable === true) {
    return `akm v${r.currentVersion} → v${r.latestVersion} available (run 'akm upgrade' to install)`;
  }
  if (r.updateAvailable === false && r.latestVersion) {
    return `akm v${r.currentVersion} is already the latest version`;
  }
  if (r.message)
    return String(r.message);
  return null;
}
function formatClonePlain(r) {
  const dst = r.destination?.path ?? "unknown";
  const remote = r.remoteFetched ? " (fetched from remote)" : "";
  const over = r.overwritten ? " (overwritten)" : "";
  return `Cloned${remote} → ${dst}${over}`;
}
// src/output/text/status-list.ts
function renderStatusEntries(entries) {
  const ordered = entries.map((entry, index) => ({ entry, index })).sort((a, b) => a.entry.severityRank - b.entry.severityRank || a.index - b.index).map(({ entry }) => entry);
  const lines = [];
  for (const entry of ordered) {
    lines.push(`${entry.glyph} ${entry.headline}`);
    for (const detail of entry.detailLines ?? []) {
      lines.push(`    ${detail}`);
    }
  }
  return lines;
}
function summarizeCounts(counts, order) {
  return order.filter((status) => (counts[status] ?? 0) > 0).map((status) => `${counts[status]} ${status}`).join(", ");
}

// src/output/text/health-format.ts
var STATUS_GLYPH = { fail: "✗", warn: "⚠", unknown: "?", pass: "✓" };
var STATUS_RANK = { fail: 0, warn: 1, unknown: 2, pass: 3 };
var STATUS_ORDER = ["fail", "warn", "unknown", "pass"];
function evidenceLines(evidence) {
  if (!evidence)
    return [];
  return Object.entries(evidence).map(([key, value]) => `${key}: ${value !== null && typeof value === "object" ? JSON.stringify(value) : String(value)}`);
}
function checkStatusEntry(check, detail) {
  const status = check.status ?? "unknown";
  const meta = [check.kind, check.confidence].filter((v) => !!v).join(", ");
  return {
    severityRank: STATUS_RANK[status] ?? 9,
    glyph: STATUS_GLYPH[status] ?? "?",
    headline: `${check.name}  [${status}${meta ? `, ${meta}` : ""}]  ${check.message ?? ""}`.trimEnd(),
    detailLines: detail === "brief" ? [] : evidenceLines(check.evidence)
  };
}
function renderCheckSection(title, checks, detail) {
  if (checks.length === 0)
    return [`${title}: (none)`];
  const counts = {};
  for (const check of checks) {
    const status = check.status ?? "unknown";
    counts[status] = (counts[status] ?? 0) + 1;
  }
  const summary = summarizeCounts(counts, STATUS_ORDER);
  const header = `${title} (${checks.length}${summary ? ` — ${summary}` : ""})`;
  return [header, ...renderStatusEntries(checks.map((check) => checkStatusEntry(check, detail)))];
}
var HANDLED_KEYS = new Set(["ok", "status", "since", "hardChecks", "advisories", "shape", "schemaVersion"]);
function formatHealthPlain(r, detail) {
  if (r === null || typeof r !== "object")
    return null;
  const lines = [];
  if (typeof r.ok === "boolean")
    lines.push(`ok: ${r.ok}`);
  if (typeof r.status === "string")
    lines.push(`status: ${r.status}`);
  if (typeof r.since === "string")
    lines.push(`since: ${r.since}`);
  const hardChecks = Array.isArray(r.hardChecks) ? r.hardChecks : [];
  const advisories = Array.isArray(r.advisories) ? r.advisories : [];
  lines.push("", ...renderCheckSection("hardChecks", hardChecks, detail));
  lines.push("", ...renderCheckSection("advisories", advisories, detail));
  if (detail === "brief" && [...hardChecks, ...advisories].some((c) => c.evidence && Object.keys(c.evidence).length > 0)) {
    lines.push("", "(evidence omitted at --detail brief; re-run with --detail normal or --detail full to see it)");
  }
  for (const [key, value] of Object.entries(r)) {
    if (HANDLED_KEYS.has(key) || value === undefined)
      continue;
    const fieldLines = [];
    flattenForText(value, key, fieldLines);
    if (fieldLines.length > 0)
      lines.push("", ...fieldLines);
  }
  return lines.join(`
`).trim();
}
// src/output/text/lint-format.ts
function glyphFor(fixed) {
  if (fixed === "failed")
    return { glyph: "✗", severityRank: 0 };
  if (fixed === true)
    return { glyph: "✓", severityRank: 2 };
  return { glyph: "⚠", severityRank: 1 };
}
function locationOf(issue) {
  return typeof issue.line === "number" ? `${issue.file}:${issue.line}` : issue.file;
}
function issueEntry(issue) {
  const { glyph, severityRank } = glyphFor(issue.fixed);
  return { severityRank, glyph, headline: `${locationOf(issue)}  [${issue.issue}]  ${issue.detail}` };
}
function renderIssueSection(title, issues) {
  if (issues.length === 0)
    return [`${title}: (none)`];
  return [`${title} (${issues.length})`, ...renderStatusEntries(issues.map(issueEntry))];
}
function formatLintPlain(r) {
  if (r === null || typeof r !== "object")
    return null;
  const fixed = Array.isArray(r.fixed) ? r.fixed : [];
  const flagged = Array.isArray(r.flagged) ? r.flagged : [];
  const warnings = Array.isArray(r.warnings) ? r.warnings : [];
  const summary = r.summary;
  const lines = [];
  if (typeof r.ok === "boolean")
    lines.push(`ok: ${r.ok}`);
  lines.push(`summary: fixed=${summary?.fixed ?? fixed.length} flagged=${summary?.flagged ?? flagged.length}` + ` warnings=${summary?.warnings ?? warnings.length}`);
  lines.push("", ...renderIssueSection("flagged", flagged));
  lines.push("", ...renderIssueSection("warnings", warnings));
  lines.push("", ...renderIssueSection("fixed", fixed));
  return lines.join(`
`).trim();
}
// src/output/text/proposal-format.ts
function appendLoweringNotices(lines, result) {
  const notices = Array.isArray(result.notices) ? result.notices : [];
  for (const notice of notices) {
    const severity = notice.severity === "info" ? "info" : "warning";
    const code = typeof notice.code === "string" ? notice.code : "lowering-notice";
    const adapter = typeof notice.adapter === "string" ? ` adapter=${notice.adapter}` : "";
    const field = typeof notice.field === "string" ? ` field=${notice.field}` : "";
    const message = typeof notice.message === "string" ? `: ${notice.message}` : "";
    lines.push(`  notice[${severity}] ${code}${adapter}${field}${message}`);
  }
}
function formatProposalProducerPlain(command, r) {
  if (r.ok === false) {
    const reason = String(r.reason);
    const error2 = typeof r.error === "string" ? r.error : "";
    const lines2 = [`${command}: failed (${reason})`];
    if (error2)
      lines2.push(`  error: ${error2}`);
    if (r.ref)
      lines2.push(`  ref: ${String(r.ref)}`);
    if (r.exitCode !== undefined && r.exitCode !== null) {
      lines2.push(`  exitCode: ${String(r.exitCode)}`);
    }
    appendLoweringNotices(lines2, r);
    return lines2.join(`
`);
  }
  const proposal = r.proposal;
  const id = String(proposal.id);
  const ref = String(r.ref);
  const status = String(proposal.status);
  const lines = [`${command}: queued proposal ${id} (${ref}) [${status}]`];
  appendLoweringNotices(lines, r);
  return lines.join(`
`);
}
function formatGateDecisionSummary(raw) {
  if (typeof raw !== "object" || raw === null)
    return "";
  const d = raw;
  const outcome = typeof d.outcome === "string" ? d.outcome : undefined;
  if (!outcome)
    return "";
  const reason = typeof d.reason === "string" && d.reason.length > 0 ? `:${d.reason}` : "";
  const cmp = formatGateThresholdComparison(d);
  return `gate=${outcome}${reason}${cmp ? ` (${cmp})` : ""}`;
}
function formatGateThresholdComparison(d) {
  const thresholds = typeof d.thresholds === "object" && d.thresholds !== null ? d.thresholds : {};
  const measured = typeof d.measured === "number" ? d.measured : undefined;
  if (measured === undefined)
    return "";
  if (typeof thresholds.maxDiffLines === "number") {
    return `${measured} > ${thresholds.maxDiffLines}`;
  }
  if (typeof thresholds.minContentLines === "number") {
    return `${measured} < ${thresholds.minContentLines}`;
  }
  return "";
}
function formatProposalListPlain(r) {
  const proposals = r.proposals;
  const total = r.totalCount;
  if (proposals.length === 0) {
    return `${total} proposal(s).
No proposals.
Generate one with \`akm improve <ref>\` or \`akm proposal new <type> <name> --task ...\`.`;
  }
  const lines = [`${total} proposal(s)`, ""];
  for (const p of proposals) {
    const id = String(p.id);
    const ref = String(p.ref);
    const status = String(p.status);
    const source = String(p.source);
    const created = String(p.createdAt);
    const gate = formatGateDecisionSummary(p.gateDecision);
    const gateSuffix = gate ? `  ${gate}` : "";
    const retirement = p.retirement;
    const flagged = p.continuityRisk === true || Boolean(retirement?.continuityRisk);
    const continuitySuffix = flagged ? "  ⚠ continuity-risk" : "";
    lines.push(`${id}  [${status}] ${ref}  source=${source}  ${created}${gateSuffix}${continuitySuffix}`);
  }
  return lines.join(`
`).trimEnd();
}
function retireVerdictLines(retirement) {
  const lines = [
    `retire.label: ${String(retirement.judgeLabel)} (cosine=${String(retirement.cosine)})`,
    `retire.reason: ${String(retirement.judgeReason)}`
  ];
  const continuityRisk = retirement.continuityRisk;
  if (continuityRisk) {
    const failingQueries = typeof continuityRisk.failingQueries === "number" ? continuityRisk.failingQueries : 0;
    const unverifiedQueries = typeof continuityRisk.unverifiedQueries === "number" ? continuityRisk.unverifiedQueries : 0;
    const summary = [];
    if (failingQueries > 0) {
      summary.push(`${failingQueries} of the retired asset's own quer${failingQueries === 1 ? "y" : "ies"} would not have found the successor top 10`);
    }
    if (unverifiedQueries > 0) {
      summary.push(`${unverifiedQueries} quer${unverifiedQueries === 1 ? "y" : "ies"} unverified (search failed or used the keyword-only fallback)`);
    }
    lines.push(`retire.continuityRisk: ${summary.join("; ")} — excluded from bulk accept`);
    const ranks = Array.isArray(continuityRisk.ranks) ? continuityRisk.ranks : [];
    for (const rank of ranks) {
      const successorRank = rank.successorRank === null || rank.successorRank === undefined ? "absent from top 10" : `#${String(rank.successorRank)}`;
      lines.push(`  - "${String(rank.query)}": retired #${String(rank.retiredRank)}, successor ${successorRank}`);
    }
  }
  return lines;
}
function formatProposalShowPlain(r) {
  const p = r.proposal;
  const lines = [];
  lines.push(`# proposal ${String(p.id)}`);
  lines.push(`ref: ${String(p.ref)}`);
  lines.push(`status: ${String(p.status)}`);
  lines.push(`source: ${String(p.source)}`);
  if (p.sourceRun)
    lines.push(`sourceRun: ${String(p.sourceRun)}`);
  if (p.createdAt)
    lines.push(`createdAt: ${String(p.createdAt)}`);
  if (p.updatedAt)
    lines.push(`updatedAt: ${String(p.updatedAt)}`);
  if (typeof p.confidence === "number")
    lines.push(`confidence: ${p.confidence.toFixed(2)}`);
  const gate = p.gateDecision;
  if (gate && typeof gate.outcome === "string") {
    lines.push(`gate.decision: ${String(gate.outcome)}`);
    lines.push(`gate.reason: ${String(gate.reason)}`);
    const cmp = formatGateThresholdComparison(gate);
    if (cmp)
      lines.push(`gate.thresholds: ${cmp}`);
    if (gate.gate)
      lines.push(`gate.by: ${String(gate.gate)}`);
    if (gate.decidedAt)
      lines.push(`gate.decidedAt: ${String(gate.decidedAt)}`);
  }
  const review = p.review;
  if (review) {
    lines.push(`review.outcome: ${String(review.outcome ?? "?")}`);
    if (review.reason)
      lines.push(`review.reason: ${String(review.reason)}`);
    if (review.decidedAt)
      lines.push(`review.decidedAt: ${String(review.decidedAt)}`);
  }
  const history = Array.isArray(p.reviewHistory) ? p.reviewHistory : [];
  for (const entry of history) {
    const undone = entry.review;
    const was = undone ? `${String(undone.outcome ?? "?")}${undone.reason ? `: ${String(undone.reason)}` : ""} (${String(undone.decidedAt ?? "?")})` : "an unrecorded review";
    const why = entry.reopenReason ? ` (${String(entry.reopenReason)})` : "";
    lines.push(`reopened: ${String(entry.reopenedAt)}${why}, undoing ${was}`);
  }
  const retirement = p.retirement;
  if (retirement) {
    lines.push(`retire: ${String(retirement.retiredRef)} -> ${String(retirement.successorRef)}`);
    lines.push(...retireVerdictLines(retirement));
  }
  const validation = r.validation;
  if (validation) {
    const findings = Array.isArray(validation.findings) ? validation.findings : [];
    const warnings = findings.filter((f) => f.severity === "warn");
    const errors2 = findings.filter((f) => f.severity !== "warn");
    lines.push("");
    if (errors2.length > 0) {
      const warnSuffix = warnings.length > 0 ? `, ${warnings.length} warning(s)` : "";
      lines.push(`✗ invalid (${errors2.length} error(s)${warnSuffix})`);
    } else if (warnings.length > 0) {
      lines.push(`✓ valid (${warnings.length} warning(s))`);
    } else {
      lines.push("✓ valid");
    }
    for (const f of errors2) {
      lines.push(`  ✗ error  [${String(f.kind)}] ${String(f.message)}`);
    }
    for (const f of warnings) {
      lines.push(`  ⚠ warning  [${String(f.kind)}] ${String(f.message)} (non-blocking)`);
    }
  }
  const payload = p.payload;
  if (!retirement && payload && typeof payload.content === "string") {
    lines.push("");
    lines.push("payload:");
    lines.push(payload.content);
  }
  return lines.join(`
`).trimEnd();
}
function formatProposalAcceptPlain(r) {
  return `Accepted proposal ${String(r.id)} → ${String(r.ref)} at ${String(r.assetPath)}`;
}
function formatProposalRejectPlain(r) {
  const reason = r.reason ? ` (${String(r.reason)})` : "";
  return `Rejected proposal ${String(r.id)} (${String(r.ref)})${reason}`;
}
function formatProposalReopenPlain(r) {
  const reason = r.reason ? ` (${String(r.reason)})` : "";
  return `Reopened proposal ${String(r.id)} (${String(r.ref)}) [pending]${reason}`;
}
function formatProposalReopenBatchPlain(r) {
  const results = Array.isArray(r.results) ? r.results : [];
  const reason = results[0]?.reason ? ` (${String(results[0].reason)})` : "";
  return [
    `Reopened ${results.length} proposal(s) [pending]${reason}`,
    ...results.map((result) => `  ${String(result.id)}  ${String(result.ref)}`)
  ].join(`
`);
}
function formatProposalDrainPlain(r) {
  const applyMode = String(r.applyMode ?? "queue");
  const promoted = Array.isArray(r.promoted) ? r.promoted : [];
  const rejected = Array.isArray(r.rejected) ? r.rejected : [];
  const deferred = Array.isArray(r.deferred) ? r.deferred : [];
  const skippedByCap = Array.isArray(r.skippedByCap) ? r.skippedByCap : [];
  const staged = Array.isArray(r.staged) ? r.staged : [];
  const failed = Array.isArray(r.failed) ? r.failed : [];
  const prefix = r.dryRun === true ? "[dry-run] " : "";
  const lines = [
    `${prefix}Drained proposal queue (strategy=${String(r.strategy ?? "?")}, applyMode=${applyMode})`,
    `  promoted: ${promoted.length}`,
    `  rejected: ${rejected.length}`,
    `  deferred: ${deferred.length}`,
    `  skippedByCap: ${skippedByCap.length}`,
    `  staged: ${staged.length}`,
    `  failed: ${failed.length}`
  ];
  for (const d of deferred) {
    lines.push(`    - ${String(d.id ?? "?")} (${String(d.reason ?? "?")})`);
  }
  for (const f of failed) {
    lines.push(`    ! ${String(f.id ?? "?")} (${String(f.reason ?? "?")}): ${String(f.detail ?? "?")}`);
  }
  appendLoweringNotices(lines, r);
  return lines.join(`
`).trimEnd();
}
function formatProposalDiffPlain(r) {
  const unified = typeof r.unified === "string" ? r.unified : "";
  if (r.op === "delete") {
    const retirement = r.retirement;
    const subject = retirement ? `${String(retirement.retiredRef)} -> ${String(retirement.successorRef)}` : String(r.ref);
    const lines = [`# proposal ${String(r.id)} (retire: ${subject})`];
    if (retirement)
      lines.push(...retireVerdictLines(retirement));
    if (typeof r.note === "string")
      lines.push(`note: ${r.note}`);
    if (unified)
      lines.push(unified);
    return lines.join(`
`);
  }
  const header = r.isNew ? `# proposal ${String(r.id)} (new asset: ${String(r.ref)})` : `# proposal ${String(r.id)} (update: ${String(r.ref)})`;
  if (!unified)
    return `${header}
(no changes)`;
  return `${header}
${unified}`;
}
// src/core/asset/asset-placement.ts
import fs6 from "node:fs";
import path11 from "node:path";

// src/core/recognition-util.ts
var SCRIPT_EXTENSIONS = new Set([
  ".sh",
  ".ts",
  ".js",
  ".ps1",
  ".cmd",
  ".bat",
  ".py",
  ".rb",
  ".go",
  ".pl",
  ".php",
  ".lua",
  ".r",
  ".swift",
  ".kt",
  ".kts"
]);
var WORKFLOW_EXTENSIONS = [".md", ".yml"];
var KNOWN_TYPES = [
  "skill",
  "command",
  "agent",
  "knowledge",
  "workflow",
  "script",
  "memory",
  "env",
  "secret",
  "lesson",
  "task",
  "session",
  "fact",
  "instruction"
];
function isKnownType(type) {
  return KNOWN_TYPES.includes(type);
}
var DEPRECATED_REJECTED_TYPES = new Set(["tool", "vault"]);

// src/core/asset/asset-placement.ts
var workflowSpec = {
  isRelevantFile: (fileName) => WORKFLOW_EXTENSIONS.includes(path11.extname(fileName).toLowerCase()),
  toCanonicalName: (typeRoot, filePath) => {
    const rel = toPosix(path11.relative(typeRoot, filePath));
    for (const ext of WORKFLOW_EXTENSIONS) {
      if (rel.toLowerCase().endsWith(ext))
        return rel.slice(0, -ext.length);
    }
    return rel;
  },
  toAssetPath: (typeRoot, name) => {
    const lower = name.toLowerCase();
    for (const ext of WORKFLOW_EXTENSIONS) {
      if (lower.endsWith(ext))
        return path11.join(typeRoot, name);
    }
    for (const ext of WORKFLOW_EXTENSIONS) {
      const candidate = path11.join(typeRoot, `${name}${ext}`);
      if (fs6.existsSync(candidate))
        return candidate;
    }
    return path11.join(typeRoot, `${name}.md`);
  }
};
var markdownSpec = {
  isRelevantFile: (fileName) => path11.extname(fileName).toLowerCase() === ".md",
  toCanonicalName: (typeRoot, filePath) => {
    const rel = toPosix(path11.relative(typeRoot, filePath));
    return rel.endsWith(".md") ? rel.slice(0, -3) : rel;
  },
  toAssetPath: (typeRoot, name) => {
    const withExt = name.endsWith(".md") ? name : `${name}.md`;
    return path11.join(typeRoot, withExt);
  }
};
var scriptSpec = {
  isRelevantFile: (fileName) => SCRIPT_EXTENSIONS.has(path11.extname(fileName).toLowerCase()),
  toCanonicalName: (typeRoot, filePath) => toPosix(path11.relative(typeRoot, filePath)),
  toAssetPath: (typeRoot, name) => path11.join(typeRoot, name)
};
var BUILTIN_PLACEMENT_SPECS = {
  skill: {
    stashDir: "skills",
    isRelevantFile: (fileName) => fileName === "SKILL.md",
    toCanonicalName: (typeRoot, filePath) => {
      const relDir = toPosix(path11.dirname(path11.relative(typeRoot, filePath)));
      if (!relDir || relDir === ".")
        return;
      return relDir;
    },
    toAssetPath: (typeRoot, name) => path11.join(typeRoot, name, "SKILL.md")
  },
  command: { stashDir: "commands", ...markdownSpec },
  agent: { stashDir: "agents", ...markdownSpec },
  knowledge: { stashDir: "knowledge", ...markdownSpec },
  instruction: { stashDir: "instructions", ...markdownSpec },
  workflow: { stashDir: "workflows", ...workflowSpec },
  script: { stashDir: "scripts", ...scriptSpec },
  memory: { stashDir: "memories", ...markdownSpec },
  env: {
    stashDir: "env",
    isRelevantFile: (fileName) => fileName === ".env" || fileName.endsWith(".env"),
    toCanonicalName: (typeRoot, filePath) => {
      const rel = toPosix(path11.relative(typeRoot, filePath));
      const fileName = path11.basename(rel);
      if (fileName === ".env") {
        const dir = path11.dirname(rel);
        return dir === "." || dir === "" ? "default" : `${dir}/default`;
      }
      const stripped = rel.endsWith(".env") ? rel.slice(0, -4) : rel;
      return stripped;
    },
    toAssetPath: (typeRoot, name) => {
      if (name === "default")
        return path11.join(typeRoot, ".env");
      return path11.join(typeRoot, name.endsWith(".env") ? name : `${name}.env`);
    }
  },
  secret: {
    stashDir: "secrets",
    isRelevantFile: (fileName) => !fileName.endsWith(".lock") && !fileName.endsWith(".sensitive"),
    toCanonicalName: (typeRoot, filePath) => toPosix(path11.relative(typeRoot, filePath)),
    toAssetPath: (typeRoot, name) => path11.join(typeRoot, name)
  },
  lesson: { stashDir: "lessons", ...markdownSpec },
  task: {
    stashDir: "tasks",
    isRelevantFile: (fileName) => path11.extname(fileName).toLowerCase() === ".yml",
    toCanonicalName: (typeRoot, filePath) => {
      const rel = toPosix(path11.relative(typeRoot, filePath));
      return rel.toLowerCase().endsWith(".yml") ? rel.slice(0, -4) : rel;
    },
    toAssetPath: (typeRoot, name) => {
      const withExt = name.toLowerCase().endsWith(".yml") ? name : `${name}.yml`;
      return path11.join(typeRoot, withExt);
    }
  },
  session: { stashDir: "sessions", ...markdownSpec },
  fact: { stashDir: "facts", ...markdownSpec }
};
var PLACEMENT_SPECS = { ...BUILTIN_PLACEMENT_SPECS };
function placementTypes() {
  return Object.keys(PLACEMENT_SPECS);
}
function stashDirFor(type) {
  return PLACEMENT_SPECS[type]?.stashDir;
}
function typeForStashDir(stashDir) {
  for (const [type, spec] of Object.entries(PLACEMENT_SPECS)) {
    if (spec.stashDir === stashDir)
      return type;
  }
  return;
}
function stashDirNames() {
  return Object.values(PLACEMENT_SPECS).map((spec) => spec.stashDir);
}
function deriveCanonicalAssetName(assetType, typeRoot, filePath) {
  return PLACEMENT_SPECS[assetType]?.toCanonicalName(typeRoot, filePath);
}
function deriveCanonicalAssetNameFromStashRoot(assetType, stashRoot, filePath) {
  const relPath = toPosix(path11.relative(stashRoot, filePath));
  const segments = relPath.split("/").filter(Boolean);
  const firstSegment = segments[0];
  const typeRoot = firstSegment !== undefined && firstSegment === stashDirFor(assetType) ? path11.join(stashRoot, firstSegment) : stashRoot;
  return deriveCanonicalAssetName(assetType, typeRoot, filePath);
}
function assetPathForName(assetType, typeRoot, name) {
  const spec = PLACEMENT_SPECS[assetType];
  if (!spec)
    throw new Error(`Unknown asset type: "${assetType}"`);
  return spec.toAssetPath(typeRoot, name);
}
function assetPathCandidatesForName(assetType, typeRoot, name) {
  const primary = assetPathForName(assetType, typeRoot, name);
  if (assetType !== "env")
    return [primary];
  const base = name === "default" ? "" : name.endsWith("/default") ? name.slice(0, -"default".length) : undefined;
  if (base === undefined)
    return [primary];
  const dotForm = path11.join(typeRoot, base, ".env");
  const namedForm = path11.join(typeRoot, base, "default.env");
  return [...new Set([primary, dotForm, namedForm])];
}

// src/core/asset/resolve-ref.ts
function conceptIdFromTypeName(type, name) {
  const stashDir = stashDirFor(type);
  return stashDir !== undefined ? `${stashDir}/${name}` : name;
}
function conceptIdForStashFile(type, stashRoot, filePath) {
  const name = deriveCanonicalAssetNameFromStashRoot(type, stashRoot, filePath);
  return name === undefined ? filePath : conceptIdFromTypeName(type, name);
}

// src/output/text/show-directives.ts
function appendShowDirectives(lines, r) {
  const assetType = typeof r.type === "string" ? r.type : null;
  const assetRef = typeof r.ref === "string" ? r.ref : typeof r.name === "string" && assetType ? conceptIdFromTypeName(assetType, r.name) : null;
  const showLoopCount = typeof r.showLoopWarning === "number" ? r.showLoopWarning : 0;
  if (showLoopCount >= 3) {
    lines.push("");
    lines.push(`WARNING: You have shown this asset ${showLoopCount} times without completing the task.`);
    lines.push("Stop re-reading — you have the information you need. Act on it now:");
    lines.push("  - Write your output file using the content above.");
    lines.push(`  - If this asset does not contain what you need, run \`akm feedback '${assetRef ?? "<ref>"}' --negative\` and search for a different asset.`);
  }
  if (assetType === "skill" || assetType === "knowledge") {
    const activeRun = r.activeRun;
    if (activeRun) {
      lines.unshift("Read this reference, follow the active unit's instructions, and return the result to the workflow runner. Step completion is automatic.");
      lines.unshift(`WORKFLOW ACTIVE — schema shown as reference (run: ${activeRun.runId})`);
      lines.unshift("---");
      lines.unshift("");
      lines.push("");
      lines.push(`Run \`akm feedback ${assetRef ? `'${assetRef}'` : "<ref>"} --positive\` if the step succeeds, or \`--negative\` if this schema did not help.`);
    } else {
      const preApplyLines = [...lines];
      lines.push("");
      lines.push("---");
      if (isCommandOutputSkill(preApplyLines)) {
        lines.push("APPLY (only if no workflow step is required for this task):");
        lines.push("  1. Identify the output file from README.md (typically commands.txt).");
        lines.push("  2. Write the exact command syntax from the code blocks above — replace every placeholder (`<name>`, `<value>`) with a real, concrete value from your task context. Do not write placeholder text.");
        lines.push("  3. Each command should be on a single line (no backslash line continuation unless the verifier expects it).");
        lines.push(`Run \`akm feedback ${assetRef ? `'${assetRef}'` : "<ref>"} --positive\` after the task succeeds, or \`--negative\` if this reference did not contain the needed command syntax.`);
      } else {
        lines.push("APPLY (only if no workflow step is required for this task):");
        lines.push("  1. Identify the target file from README.md — write or edit it. If the file does not yet exist, CREATE it with the full structure from this schema.");
        lines.push("  2. Add/edit the fields shown above using the exact field names from this schema.");
        lines.push("  3. COPY the exact YAML structure and field names from the code blocks above — do not substitute synonyms or invent nesting. Replace every placeholder value with a real, concrete value from your task context. Do not leave any field as null, empty, or a placeholder.");
        lines.push(`Run \`akm feedback ${assetRef ? `'${assetRef}'` : "<ref>"} --positive\` after the task succeeds, or \`--negative\` if the task fails after following this guidance.`);
      }
    }
  } else if (assetType === "workflow") {
    const workflowName = typeof r.name === "string" ? r.name : null;
    const workflowRef = workflowName ? `workflows/${workflowName}` : "<ref>";
    const separatorIdx = lines.indexOf("---");
    const insertIdx = separatorIdx >= 0 ? separatorIdx + 1 : r.type || r.name ? 1 : 0;
    const actionDirective = [
      `ACTION REQUIRED: Do not execute steps manually from this output.`,
      `Run \`akm workflow run '${workflowRef}'\` to execute the workflow through its declared gates.`,
      "---"
    ];
    lines.splice(insertIdx, 0, "", ...actionDirective);
    lines.push("");
    lines.push("---");
    lines.push(`NEXT STEP: Run \`akm workflow run '${workflowRef}'\` to execute the workflow.`);
    lines.push("Inspect the workflow first; the runner dispatches and completes each step automatically.");
  }
}
function isCommandOutputSkill(lines) {
  const codeLines = lines.filter((l) => l.startsWith("  ") || l.startsWith("\t") || /^`/.test(l));
  const cliPattern = /^(az |kubectl |docker |git |helm |terraform |aws |gcloud )/;
  const yamlPattern = /^\s+\w+:/;
  const cliCount = codeLines.filter((l) => cliPattern.test(l.trim())).length;
  const yamlCount = codeLines.filter((l) => yamlPattern.test(l)).length;
  return cliCount > yamlCount && cliCount > 0;
}

// src/output/text/show-format.ts
function formatShowPlain(r, detail) {
  const lines = [];
  if (r.type || r.name) {
    lines.push(`# ${String(r.type ?? "asset")}: ${String(r.name ?? "unknown")}`);
  }
  if (r.path && r.editable !== false) {
    lines.push(`file: ${String(r.path)}`);
  }
  if (r.origin !== undefined)
    lines.push(`# origin: ${String(r.origin)}`);
  if (r.action)
    lines.push(`# ${String(r.action)}`);
  if (Array.isArray(r.keys)) {
    const keys = r.keys.map(String);
    lines.push(keys.length > 0 ? `keys: ${keys.join(", ")}` : "(no keys)");
  }
  if (r.description)
    lines.push(`description: ${String(r.description)}`);
  if (r.workflowTitle)
    lines.push(`workflowTitle: ${String(r.workflowTitle)}`);
  if (r.agent)
    lines.push(`agent: ${String(r.agent)}`);
  if (Array.isArray(r.parameters) && r.parameters.length > 0)
    lines.push(`parameters: ${r.parameters.join(", ")}`);
  if (Array.isArray(r.workflowParameters) && r.workflowParameters.length > 0) {
    lines.push("workflowParameters:");
    for (const parameter of r.workflowParameters) {
      const name = typeof parameter.name === "string" ? parameter.name : "unknown";
      const description = typeof parameter.description === "string" && parameter.description.trim() ? `: ${parameter.description}` : "";
      lines.push(`  - ${name}${description}`);
    }
  }
  if (r.modelHint != null)
    lines.push(`modelHint: ${String(r.modelHint)}`);
  if (r.toolPolicy != null)
    lines.push(`toolPolicy: ${JSON.stringify(r.toolPolicy)}`);
  if (r.run)
    lines.push(`run: ${String(r.run)}`);
  if (r.setup)
    lines.push(`setup: ${String(r.setup)}`);
  if (r.cwd)
    lines.push(`cwd: ${String(r.cwd)}`);
  if (detail === "full") {
    if (r.path)
      lines.push(`path: ${String(r.path)}`);
    if (r.editable !== undefined)
      lines.push(`editable: ${String(r.editable)}`);
    if (r.editHint)
      lines.push(`editHint: ${String(r.editHint)}`);
    if (r.schemaVersion !== undefined)
      lines.push(`schemaVersion: ${String(r.schemaVersion)}`);
  }
  const links = typeof r.links === "object" && r.links !== null ? r.links : undefined;
  if (links) {
    lines.push("");
    lines.push("links:");
    for (const part of ["outgoing", "incoming", "unresolved"]) {
      const groups = links[part];
      if (typeof groups !== "object" || groups === null)
        continue;
      lines.push(`  ${part}:`);
      for (const [kind, group] of Object.entries(groups)) {
        const refs = Array.isArray(group.refs) ? group.refs.map(String) : [];
        const more = (group.total ?? refs.length) > refs.length ? ` (+${(group.total ?? 0) - refs.length} more)` : "";
        lines.push(`    ${kind}: ${refs.join(", ")}${more}`);
      }
    }
  }
  const payloads = [r.content, r.template, r.prompt].filter((value) => value != null).map(String);
  if (Array.isArray(r.steps) && r.steps.length > 0) {
    if (lines.length > 0)
      lines.push("");
    lines.push("steps:");
    for (const [index, step] of r.steps.entries()) {
      const title = typeof step.title === "string" ? step.title : "Untitled step";
      const id = typeof step.id === "string" ? step.id : "unknown";
      lines.push(`  ${index + 1}. ${title} [${id}]`);
      if (typeof step.instructions === "string" && step.instructions.trim()) {
        const instrLines = step.instructions.trim().split(`
`);
        lines.push(`     instructions: ${instrLines[0]}`);
        for (const instrLine of instrLines.slice(1))
          lines.push(`       ${instrLine}`);
      }
      if (Array.isArray(step.completionCriteria) && step.completionCriteria.length > 0) {
        lines.push("     completion:");
        for (const criterion of step.completionCriteria) {
          lines.push(`       - ${String(criterion)}`);
        }
      }
    }
  }
  if (payloads.length > 0) {
    if (lines.length > 0)
      lines.push("");
    lines.push(...payloads);
  }
  appendShowDirectives(lines, r);
  return lines.length > 0 ? lines.join(`
`) : null;
}
// src/output/text/workflow-format.ts
function formatWorkflowListPlain(result) {
  const runs = Array.isArray(result.runs) ? result.runs : [];
  if (runs.length === 0) {
    return "No workflow runs in the current working scope. Start one with `akm workflow run workflows/<name>` or author one with `akm workflow create <name>`.";
  }
  return runs.map((run) => {
    const id = typeof run.id === "string" ? run.id : "unknown";
    const ref = typeof run.workflowRef === "string" ? run.workflowRef : "unknown";
    const status = typeof run.status === "string" ? run.status : "unknown";
    const currentStep = typeof run.currentStepId === "string" ? ` (current: ${run.currentStepId})` : "";
    return `${id} ${ref} [${status}]${currentStep}`;
  }).join(`
`);
}
var CHILD_STATUS_GLYPHS = {
  completed: "✓",
  active: "→",
  blocked: "⚠",
  failed: "✗"
};
function renderChildNode(child, depth, lines) {
  const indent = "  ".repeat(depth + 1);
  const runId = typeof child.runId === "string" ? child.runId : "unknown";
  const ref = typeof child.workflowRef === "string" ? child.workflowRef : "unknown";
  const status = typeof child.status === "string" ? child.status : "unknown";
  const glyph = CHILD_STATUS_GLYPHS[status] ?? "?";
  const stepId = typeof child.stepId === "string" ? ` (step "${child.stepId}")` : "";
  lines.push(`${indent}- ${glyph} ${runId} ${ref} [${status}]${stepId}`);
  const resume = typeof child.resume === "object" && child.resume !== null ? child.resume : undefined;
  if (resume) {
    lines.push(`${indent}    resume: ${typeof resume.command === "string" ? resume.command : ""}`);
    lines.push(`${indent}    then:   ${typeof resume.then === "string" ? resume.then : ""}`);
  }
  const nested = Array.isArray(child.children) ? child.children : [];
  for (const grandchild of nested)
    renderChildNode(grandchild, depth + 1, lines);
}
function formatWorkflowStatusPlain(result) {
  const run = typeof result.run === "object" && result.run !== null ? result.run : undefined;
  const workflow = typeof result.workflow === "object" && result.workflow !== null ? result.workflow : undefined;
  if (!run || !workflow)
    return null;
  const lines = [
    `workflow: ${String(workflow.ref ?? "unknown")}`,
    `run: ${String(run.id ?? "unknown")}`,
    `title: ${String(run.workflowTitle ?? workflow.title ?? "Workflow")}`,
    `status: ${String(run.status ?? "unknown")}`
  ];
  if (run.currentStepId)
    lines.push(`currentStep: ${String(run.currentStepId)}`);
  const steps = Array.isArray(workflow.steps) ? workflow.steps : [];
  if (steps.length > 0) {
    lines.push("steps:");
    for (const step of steps) {
      const title = typeof step.title === "string" ? step.title : "Untitled step";
      const id = typeof step.id === "string" ? step.id : "unknown";
      const status = typeof step.status === "string" ? step.status : "unknown";
      lines.push(`  - ${title} [${id}] (${status})`);
      if (typeof step.notes === "string" && step.notes.trim()) {
        lines.push(`    notes: ${step.notes}`);
      }
    }
  }
  const children = Array.isArray(result.children) ? result.children : undefined;
  if (children && children.length > 0) {
    lines.push("children:");
    for (const child of children)
      renderChildNode(child, 0, lines);
  }
  const units = Array.isArray(result.units) ? result.units : undefined;
  if (units) {
    lines.push("");
    lines.push(units.length > 0 ? "units:" : "units: (none journaled)");
    for (const unit of units) {
      const id = typeof unit.unitId === "string" ? unit.unitId : "unknown";
      const status = typeof unit.status === "string" ? unit.status : "unknown";
      const node = typeof unit.nodeId === "string" ? unit.nodeId : "";
      const attempts = typeof unit.attempts === "number" ? unit.attempts : undefined;
      const suffix = attempts !== undefined && attempts > 1 ? `, attempt ${attempts}` : "";
      lines.push(`  - ${id} [${node}] (${status}${suffix})`);
      if (typeof unit.failureReason === "string" && unit.failureReason.trim()) {
        lines.push(`    failure_reason: ${unit.failureReason}`);
      }
      if (typeof unit.diagnostic === "string" && unit.diagnostic.trim()) {
        const diagLines = unit.diagnostic.split(`
`);
        lines.push(`    diagnostic: ${diagLines[0]}`);
        for (const diagLine of diagLines.slice(1))
          lines.push(`      ${diagLine}`);
      }
    }
  }
  return lines.join(`
`);
}
function renderLoweringNoticeLine(value) {
  if (typeof value !== "object" || value === null)
    return null;
  const notice = value;
  if (typeof notice.code !== "string" || typeof notice.severity !== "string" || typeof notice.adapter !== "string" || typeof notice.message !== "string") {
    return null;
  }
  const field = typeof notice.field === "string" && notice.field ? `; ${notice.field}` : "";
  return `! lowering[${notice.severity}] ${notice.code} (${notice.adapter}${field}): ${notice.message}`;
}
function formatWorkflowRunPlain(result) {
  const run = typeof result.run === "object" && result.run !== null ? result.run : undefined;
  if (!run)
    return null;
  const lines = [];
  if (result.resumed === true) {
    lines.push(`resuming existing run ${String(run.id ?? "unknown")} for ${String(run.workflowRef ?? "this ref")}; ` + `pass --new to start a fresh run`);
  }
  lines.push(`run: ${String(run.id ?? "unknown")}`, `status: ${String(run.status ?? "unknown")}`);
  for (const warning of Array.isArray(result.warnings) ? result.warnings : [])
    lines.push(`! ${String(warning)}`);
  for (const value of Array.isArray(result.notices) ? result.notices : []) {
    const line = renderLoweringNoticeLine(value);
    if (line)
      lines.push(line);
  }
  const executed = Array.isArray(result.executed) ? result.executed : [];
  if (executed.length === 0) {
    lines.push("executed: (no steps — run was already done or blocked)");
  } else {
    lines.push("executed:");
    for (const step of executed) {
      const marker = step.ok === true ? "ok" : "FAILED";
      lines.push(`  - ${String(step.stepId ?? "?")} [${marker}] units: ${String(step.unitCount ?? 0)}` + (Number(step.failedUnits ?? 0) > 0 ? ` (${String(step.failedUnits)} failed)` : ""));
      if (typeof step.summary === "string" && step.summary.trim()) {
        lines.push(`    ${step.summary}`);
      }
    }
  }
  const gate = typeof result.gateRejection === "object" && result.gateRejection !== null ? result.gateRejection : undefined;
  if (gate) {
    lines.push(`gate rejected step ${String(gate.stepId ?? "?")}: ${String(gate.feedback ?? "")}`);
    const missing = Array.isArray(gate.missing) ? gate.missing : [];
    for (const item of missing)
      lines.push(`  missing: ${String(item)}`);
  }
  if (result.aborted === true) {
    lines.push(result.timedOut === true ? "workflow timed out; the run remains resumable." : "workflow interrupted; the run remains resumable.");
  }
  if (result.done === true)
    lines.push("workflow completed.");
  return lines.join(`
`);
}
function formatWorkflowCreatePlain(r) {
  if (typeof r.template === "string")
    return r.template;
  if (r.ref && r.path) {
    return `Created ${String(r.ref)} at ${String(r.path)}`;
  }
  return null;
}
function formatWorkflowResumePlain(r) {
  return formatWorkflowStatusPlain(r) ?? `Resumed workflow run ${String(r.id ?? r.runId ?? "?")}`;
}
function formatInputBindingsList(bindings) {
  return bindings.map((binding) => {
    const name = String(binding.name ?? "");
    return binding.kind === "literal" ? `${name}=${JSON.stringify(binding.value)} (literal)` : `${name} <- ${String(binding.from ?? "")} (reference)`;
  }).join(", ");
}
function renderPlanStepLines(step, ordinal, lines, prefix = "  ") {
  const stepId = typeof step.stepId === "string" ? step.stepId : "unknown";
  const targetKind = typeof step.targetKind === "string" ? `[${step.targetKind}]` : "";
  const expansion = typeof step.expansion === "object" && step.expansion !== null ? step.expansion : {};
  const via = typeof expansion.via === "string" ? expansion.via : "direct";
  const childPlanHash = typeof expansion.childPlanHash === "string" ? expansion.childPlanHash : undefined;
  const viaText = via === "task" ? `via ${String(expansion.taskRef ?? "")}` : via === "child" ? `-> ${String(expansion.childRef ?? "")}${childPlanHash ? ` (plan ${childPlanHash})` : ""}` : "direct";
  lines.push(`${prefix}${ordinal}. ${stepId} ${targetKind} ${viaText}`.replace(/ +/g, " ").trimEnd());
  const detailPrefix = `${prefix}  `;
  const inputBindings = Array.isArray(step.inputBindings) ? step.inputBindings : [];
  if (inputBindings.length > 0) {
    lines.push(`${detailPrefix}with: ${formatInputBindingsList(inputBindings)}`);
  }
  if (via === "child") {
    const childOutputs = Array.isArray(expansion.childOutputs) ? expansion.childOutputs : [];
    if (childOutputs.length > 0) {
      lines.push(`${detailPrefix}exports: ${childOutputs.map(String).join(", ")}`);
    }
    const childSteps = Array.isArray(expansion.steps) ? expansion.steps : [];
    for (const [index, childStep] of childSteps.entries()) {
      renderPlanStepLines(childStep, index + 1, lines, `${prefix}  ${ordinal}.`);
    }
  }
}
function formatWorkflowPlanPlain(result) {
  if (typeof result.ref !== "string")
    return null;
  const sourceFormat = typeof result.sourceFormat === "string" ? result.sourceFormat : "unknown";
  const irVersion = typeof result.irVersion === "number" ? result.irVersion : "unknown";
  const planHash = typeof result.planHash === "string" ? result.planHash : "unknown";
  const execution = typeof result.execution === "object" && result.execution !== null ? result.execution : {};
  const budget = typeof result.budget === "object" && result.budget !== null ? result.budget : undefined;
  const lines = [
    `workflow: ${result.ref} (${sourceFormat})`,
    `source:   ${typeof result.sourcePath === "string" ? result.sourcePath : "unknown"}`,
    `plan:     irVersion ${irVersion}, hash ${planHash} (not published)`
  ];
  const limitsParts = [
    `maxConcurrency ${typeof execution.maxConcurrency === "number" ? execution.maxConcurrency : "?"}`
  ];
  if (budget) {
    const budgetParts = [];
    if (typeof budget.maxUnits === "number")
      budgetParts.push(`max_units ${budget.maxUnits}`);
    if (typeof budget.maxTokens === "number")
      budgetParts.push(`max_tokens ${budget.maxTokens}`);
    if (budgetParts.length > 0)
      limitsParts.push(`budget ${budgetParts.join(", ")}`);
  }
  lines.push(`limits:   ${limitsParts.join("; ")}`);
  const params = Array.isArray(result.params) ? result.params : undefined;
  if (params && params.length > 0)
    lines.push(`params:   ${params.join(", ")}`);
  const outputs = typeof result.outputs === "object" && result.outputs !== null ? result.outputs : undefined;
  if (outputs) {
    for (const [name, declaration] of Object.entries(outputs)) {
      const from = typeof declaration === "object" && declaration !== null ? String(declaration.from ?? "") : "";
      lines.push(`outputs:  ${name} <- ${from}`);
    }
  }
  const steps = Array.isArray(result.steps) ? result.steps : [];
  lines.push("steps:");
  for (const [index, step] of steps.entries()) {
    renderPlanStepLines(step, index + 1, lines);
  }
  const notices = Array.isArray(result.notices) ? result.notices : [];
  if (notices.length > 0) {
    lines.push("notices:");
    for (const value of notices) {
      const line = renderLoweringNoticeLine(value);
      if (line)
        lines.push(`  ${line}`);
    }
  }
  const warnings = Array.isArray(result.warnings) ? result.warnings : [];
  if (warnings.length > 0) {
    lines.push("warnings:");
    for (const warning of warnings)
      lines.push(`  ! ${String(warning)}`);
  }
  return lines.join(`
`);
}
// src/output/text/add.ts
var addFormatters = [{ command: "add", handler: (r) => formatAddPlain(r) }];

// src/output/text/bundle-create.ts
var bundleCreateFormatters = [
  { command: "bundle-create", handler: (r) => formatInitPlain(r) }
];

// src/output/text/bundle-rename.ts
var bundleRenameFormatters = [
  { command: "bundle-rename", handler: (r) => formatBundleRenamePlain(r) }
];

// src/output/text/bundle-show.ts
var bundleShowFormatters = [
  { command: "bundle-show", handler: (r) => formatBundleShowPlain(r) }
];

// src/output/text/clone.ts
var cloneFormatters = [{ command: "clone", handler: (r) => formatClonePlain(r) }];

// src/output/text/config.ts
var configFormatters = [{ command: "config", handler: (r) => formatConfigPlain(r) }];

// src/output/text/curate.ts
var curateFormatters = [
  { command: "curate", handler: (r, detail) => formatCuratePlain(r, detail) }
];

// src/output/text/env.ts
var envFormatters = [
  { command: "env-list", handler: (r) => formatEnvListPlain(r) },
  { command: "env-create", handler: (r) => formatEnvCreatePlain(r) },
  { command: "env-export", handler: (r) => formatEnvExportPlain(r) },
  { command: "env-remove", handler: (r) => formatEnvRemovePlain(r) }
];

// src/output/text/events.ts
var eventsFormatters = [{ command: "log-list", handler: (r) => formatEventsPlain(r) }];

// src/output/text/feedback.ts
var feedbackFormatters = [
  { command: "feedback", handler: (r) => formatFeedbackPlain(r) }
];

// src/output/text/health.ts
var healthFormatters = [
  { command: "health", handler: (r, detail) => formatHealthPlain(r, detail) }
];

// src/output/text/import.ts
var importFormatters = [{ command: "import", handler: (r) => formatImportPlain(r) }];
// src/assets/improve-strategies/catchup.json
var catchup_default = {
  description: "Manual catch-up — consolidation plus a judged triage drain (up to 100 accepts) with no interval minimum. Auto-accepts only when improve autonomy is enabled; otherwise proposals queue for review.",
  processes: {
    reflect: {
      enabled: false
    },
    distill: {
      enabled: false
    },
    consolidate: {
      enabled: true,
      allowedTypes: ["memory"],
      maxChunkSize: 50,
      minPoolSize: 0
    },
    memoryInference: {
      enabled: false
    },
    extract: {
      enabled: false
    },
    triage: {
      enabled: true,
      applyMode: "promote",
      policy: "personal-stash",
      maxAcceptsPerRun: 100,
      judgment: true,
      maxDiffLines: 200
    },
    validation: {
      enabled: false
    },
    proactiveMaintenance: {
      enabled: false
    }
  },
  sync: {
    enabled: true,
    push: true
  }
};
// src/assets/improve-strategies/consolidate.json
var consolidate_default = {
  description: "Consolidation-only pass — merges, deduplicates, and prunes memories every 4h.",
  processes: {
    reflect: { enabled: false },
    distill: { enabled: false },
    consolidate: { enabled: true, allowedTypes: ["memory"], maxChunkSize: 25 },
    memoryInference: { enabled: false },
    extract: { enabled: false },
    triage: { enabled: false },
    validation: { enabled: false },
    proactiveMaintenance: { enabled: false }
  },
  sync: { enabled: true, push: true }
};
// src/assets/improve-strategies/default.json
var default_default = {
  description: "Standard improve pass — reflect (rewrites only from negative feedback), distill, consolidation (promotion plus the reviewed pair-pass retire/supersede proposals), and validation. Memory inference is listed below but only runs when experimental.improveAutonomy is set; improve-stage extract and proactive maintenance off.",
  processes: {
    reflect: {
      enabled: true,
      limit: 25,
      allowedTypes: ["agent", "command", "knowledge", "lesson", "memory", "skill", "workflow"]
    },
    distill: { enabled: true, allowedTypes: ["memory"], requirePlannedRefs: false },
    consolidate: { enabled: true, allowedTypes: ["memory"] },
    memoryInference: { enabled: true },
    extract: { enabled: false, triage: { enabled: true, minScore: 2 } },
    validation: { enabled: true },
    proactiveMaintenance: { enabled: false, dueDays: 30, maxPerRun: 15 },
    triage: { enabled: false, applyMode: "queue", policy: "personal-stash" }
  },
  sync: { enabled: true, push: true }
};
// src/assets/improve-strategies/proactive-maintenance.json
var proactive_maintenance_default = {
  description: "Opt-in proactive-maintenance pass — reflect (on negative feedback), distill, proposal triage (promote, high budget), and the proactive-maintenance lane (maxPerRun 100), which picks due assets for scoring but plans no rewrite; consolidate/memoryInference/extract off. Sync disabled: an interrupted run would otherwise leave an uncommitted backlog.",
  processes: {
    reflect: {
      enabled: true,
      allowedTypes: ["agent", "command", "knowledge", "lesson", "memory", "skill", "workflow"]
    },
    distill: { enabled: true, allowedTypes: ["memory"] },
    consolidate: { enabled: false },
    memoryInference: { enabled: false },
    extract: { enabled: false },
    validation: { enabled: false },
    triage: {
      enabled: true,
      applyMode: "promote",
      policy: "personal-stash",
      maxAcceptsPerRun: 100,
      maxDiffLines: 200,
      judgment: true
    },
    proactiveMaintenance: { enabled: true, dueDays: 30, maxPerRun: 100 }
  },
  sync: { enabled: false }
};
// src/assets/improve-strategies/quick.json
var quick_default = {
  description: "Reflect-only pass — no extract, distill, consolidate, or memoryInference.",
  processes: {
    reflect: {
      enabled: true,
      allowedTypes: ["agent", "command", "knowledge", "lesson", "memory", "skill", "workflow"]
    },
    extract: { enabled: false },
    distill: { enabled: false },
    consolidate: { enabled: false },
    memoryInference: { enabled: false },
    triage: { enabled: false },
    validation: { enabled: false },
    proactiveMaintenance: { enabled: false }
  },
  sync: { enabled: true, push: true }
};
// src/assets/improve-strategies/reflect-distill.json
var reflect_distill_default = {
  description: "Reflect + distill pass — reflect, distill, memoryInference, and proposal triage (promote); proactiveMaintenance/consolidate/extract off. Sync disabled: an interrupted run would otherwise leave an uncommitted backlog.",
  processes: {
    reflect: {
      enabled: true,
      allowedTypes: ["agent", "command", "knowledge", "lesson", "memory", "skill", "workflow"]
    },
    distill: { enabled: true, allowedTypes: ["memory"], requirePlannedRefs: false },
    consolidate: { enabled: false },
    memoryInference: { enabled: true },
    extract: {
      enabled: false,
      timeoutMs: 300000,
      triage: { enabled: true, minScore: 2 },
      minNewSessions: 1
    },
    validation: { enabled: false },
    triage: {
      enabled: true,
      applyMode: "promote",
      policy: "personal-stash",
      maxAcceptsPerRun: 15,
      maxDiffLines: 200,
      judgment: true
    },
    proactiveMaintenance: { enabled: false, dueDays: 30, maxPerRun: 15 }
  },
  sync: { enabled: false }
};
// src/assets/improve-strategies/thorough.json
var thorough_default = {
  description: "Everything default runs, plus a judged triage drain of the pending-proposal backlog (up to 25 accepts per run). Auto-accepts only when improve autonomy is enabled; otherwise proposals queue for review. Identical tuning to default; improve-stage extract and proactive maintenance stay off.",
  processes: {
    reflect: {
      enabled: true,
      limit: 25,
      allowedTypes: ["agent", "command", "knowledge", "lesson", "memory", "skill", "workflow"]
    },
    distill: {
      enabled: true,
      allowedTypes: ["memory"],
      requirePlannedRefs: false
    },
    consolidate: {
      enabled: true,
      allowedTypes: ["memory"]
    },
    memoryInference: {
      enabled: true
    },
    extract: {
      enabled: false,
      triage: {
        enabled: true,
        minScore: 2
      }
    },
    validation: {
      enabled: true
    },
    proactiveMaintenance: {
      enabled: false,
      dueDays: 30,
      maxPerRun: 15
    },
    triage: {
      enabled: true,
      applyMode: "promote",
      policy: "personal-stash",
      maxAcceptsPerRun: 25,
      maxDiffLines: 200,
      judgment: true
    }
  },
  sync: {
    enabled: true,
    push: true
  }
};

// node_modules/zod/v3/external.js
var exports_external = {};
__export(exports_external, {
  void: () => voidType,
  util: () => util,
  unknown: () => unknownType,
  union: () => unionType,
  undefined: () => undefinedType,
  tuple: () => tupleType,
  transformer: () => effectsType,
  symbol: () => symbolType,
  string: () => stringType,
  strictObject: () => strictObjectType,
  setErrorMap: () => setErrorMap,
  set: () => setType,
  record: () => recordType,
  quotelessJson: () => quotelessJson,
  promise: () => promiseType,
  preprocess: () => preprocessType,
  pipeline: () => pipelineType,
  ostring: () => ostring,
  optional: () => optionalType,
  onumber: () => onumber,
  oboolean: () => oboolean,
  objectUtil: () => objectUtil,
  object: () => objectType,
  number: () => numberType,
  nullable: () => nullableType,
  null: () => nullType,
  never: () => neverType,
  nativeEnum: () => nativeEnumType,
  nan: () => nanType,
  map: () => mapType,
  makeIssue: () => makeIssue,
  literal: () => literalType,
  lazy: () => lazyType,
  late: () => late,
  isValid: () => isValid,
  isDirty: () => isDirty,
  isAsync: () => isAsync,
  isAborted: () => isAborted,
  intersection: () => intersectionType,
  instanceof: () => instanceOfType,
  getParsedType: () => getParsedType,
  getErrorMap: () => getErrorMap,
  function: () => functionType,
  enum: () => enumType,
  effect: () => effectsType,
  discriminatedUnion: () => discriminatedUnionType,
  defaultErrorMap: () => en_default,
  datetimeRegex: () => datetimeRegex,
  date: () => dateType,
  custom: () => custom,
  coerce: () => coerce,
  boolean: () => booleanType,
  bigint: () => bigIntType,
  array: () => arrayType,
  any: () => anyType,
  addIssueToContext: () => addIssueToContext,
  ZodVoid: () => ZodVoid,
  ZodUnknown: () => ZodUnknown,
  ZodUnion: () => ZodUnion,
  ZodUndefined: () => ZodUndefined,
  ZodType: () => ZodType,
  ZodTuple: () => ZodTuple,
  ZodTransformer: () => ZodEffects,
  ZodSymbol: () => ZodSymbol,
  ZodString: () => ZodString,
  ZodSet: () => ZodSet,
  ZodSchema: () => ZodType,
  ZodRecord: () => ZodRecord,
  ZodReadonly: () => ZodReadonly,
  ZodPromise: () => ZodPromise,
  ZodPipeline: () => ZodPipeline,
  ZodParsedType: () => ZodParsedType,
  ZodOptional: () => ZodOptional,
  ZodObject: () => ZodObject,
  ZodNumber: () => ZodNumber,
  ZodNullable: () => ZodNullable,
  ZodNull: () => ZodNull,
  ZodNever: () => ZodNever,
  ZodNativeEnum: () => ZodNativeEnum,
  ZodNaN: () => ZodNaN,
  ZodMap: () => ZodMap,
  ZodLiteral: () => ZodLiteral,
  ZodLazy: () => ZodLazy,
  ZodIssueCode: () => ZodIssueCode,
  ZodIntersection: () => ZodIntersection,
  ZodFunction: () => ZodFunction,
  ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,
  ZodError: () => ZodError,
  ZodEnum: () => ZodEnum,
  ZodEffects: () => ZodEffects,
  ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
  ZodDefault: () => ZodDefault,
  ZodDate: () => ZodDate,
  ZodCatch: () => ZodCatch,
  ZodBranded: () => ZodBranded,
  ZodBoolean: () => ZodBoolean,
  ZodBigInt: () => ZodBigInt,
  ZodArray: () => ZodArray,
  ZodAny: () => ZodAny,
  Schema: () => ZodType,
  ParseStatus: () => ParseStatus,
  OK: () => OK,
  NEVER: () => NEVER,
  INVALID: () => INVALID,
  EMPTY_PATH: () => EMPTY_PATH,
  DIRTY: () => DIRTY,
  BRAND: () => BRAND
});

// node_modules/zod/v3/helpers/util.js
var util;
(function(util2) {
  util2.assertEqual = (_) => {};
  function assertIs(_arg) {}
  util2.assertIs = assertIs;
  function assertNever2(_x) {
    throw new Error;
  }
  util2.assertNever = assertNever2;
  util2.arrayToEnum = (items) => {
    const obj = {};
    for (const item of items) {
      obj[item] = item;
    }
    return obj;
  };
  util2.getValidEnumValues = (obj) => {
    const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
    const filtered = {};
    for (const k of validKeys) {
      filtered[k] = obj[k];
    }
    return util2.objectValues(filtered);
  };
  util2.objectValues = (obj) => {
    return util2.objectKeys(obj).map(function(e) {
      return obj[e];
    });
  };
  util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
    const keys = [];
    for (const key in object) {
      if (Object.prototype.hasOwnProperty.call(object, key)) {
        keys.push(key);
      }
    }
    return keys;
  };
  util2.find = (arr, checker) => {
    for (const item of arr) {
      if (checker(item))
        return item;
    }
    return;
  };
  util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
  function joinValues(array, separator = " | ") {
    return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
  }
  util2.joinValues = joinValues;
  util2.jsonStringifyReplacer = (_, value) => {
    if (typeof value === "bigint") {
      return value.toString();
    }
    return value;
  };
})(util || (util = {}));
var objectUtil;
(function(objectUtil2) {
  objectUtil2.mergeShapes = (first, second) => {
    return {
      ...first,
      ...second
    };
  };
})(objectUtil || (objectUtil = {}));
var ZodParsedType = util.arrayToEnum([
  "string",
  "nan",
  "number",
  "integer",
  "float",
  "boolean",
  "date",
  "bigint",
  "symbol",
  "function",
  "undefined",
  "null",
  "array",
  "object",
  "unknown",
  "promise",
  "void",
  "never",
  "map",
  "set"
]);
var getParsedType = (data) => {
  const t = typeof data;
  switch (t) {
    case "undefined":
      return ZodParsedType.undefined;
    case "string":
      return ZodParsedType.string;
    case "number":
      return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
    case "boolean":
      return ZodParsedType.boolean;
    case "function":
      return ZodParsedType.function;
    case "bigint":
      return ZodParsedType.bigint;
    case "symbol":
      return ZodParsedType.symbol;
    case "object":
      if (Array.isArray(data)) {
        return ZodParsedType.array;
      }
      if (data === null) {
        return ZodParsedType.null;
      }
      if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
        return ZodParsedType.promise;
      }
      if (typeof Map !== "undefined" && data instanceof Map) {
        return ZodParsedType.map;
      }
      if (typeof Set !== "undefined" && data instanceof Set) {
        return ZodParsedType.set;
      }
      if (typeof Date !== "undefined" && data instanceof Date) {
        return ZodParsedType.date;
      }
      return ZodParsedType.object;
    default:
      return ZodParsedType.unknown;
  }
};

// node_modules/zod/v3/ZodError.js
var ZodIssueCode = util.arrayToEnum([
  "invalid_type",
  "invalid_literal",
  "custom",
  "invalid_union",
  "invalid_union_discriminator",
  "invalid_enum_value",
  "unrecognized_keys",
  "invalid_arguments",
  "invalid_return_type",
  "invalid_date",
  "invalid_string",
  "too_small",
  "too_big",
  "invalid_intersection_types",
  "not_multiple_of",
  "not_finite"
]);
var quotelessJson = (obj) => {
  const json = JSON.stringify(obj, null, 2);
  return json.replace(/"([^"]+)":/g, "$1:");
};

class ZodError extends Error {
  get errors() {
    return this.issues;
  }
  constructor(issues) {
    super();
    this.issues = [];
    this.addIssue = (sub) => {
      this.issues = [...this.issues, sub];
    };
    this.addIssues = (subs = []) => {
      this.issues = [...this.issues, ...subs];
    };
    const actualProto = new.target.prototype;
    if (Object.setPrototypeOf) {
      Object.setPrototypeOf(this, actualProto);
    } else {
      this.__proto__ = actualProto;
    }
    this.name = "ZodError";
    this.issues = issues;
  }
  format(_mapper) {
    const mapper = _mapper || function(issue) {
      return issue.message;
    };
    const fieldErrors = { _errors: [] };
    const processError = (error2) => {
      for (const issue of error2.issues) {
        if (issue.code === "invalid_union") {
          issue.unionErrors.map(processError);
        } else if (issue.code === "invalid_return_type") {
          processError(issue.returnTypeError);
        } else if (issue.code === "invalid_arguments") {
          processError(issue.argumentsError);
        } else if (issue.path.length === 0) {
          fieldErrors._errors.push(mapper(issue));
        } else {
          let curr = fieldErrors;
          let i = 0;
          while (i < issue.path.length) {
            const el = issue.path[i];
            const terminal = i === issue.path.length - 1;
            if (!terminal) {
              curr[el] = curr[el] || { _errors: [] };
            } else {
              curr[el] = curr[el] || { _errors: [] };
              curr[el]._errors.push(mapper(issue));
            }
            curr = curr[el];
            i++;
          }
        }
      }
    };
    processError(this);
    return fieldErrors;
  }
  static assert(value) {
    if (!(value instanceof ZodError)) {
      throw new Error(`Not a ZodError: ${value}`);
    }
  }
  toString() {
    return this.message;
  }
  get message() {
    return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
  }
  get isEmpty() {
    return this.issues.length === 0;
  }
  flatten(mapper = (issue) => issue.message) {
    const fieldErrors = {};
    const formErrors = [];
    for (const sub of this.issues) {
      if (sub.path.length > 0) {
        const firstEl = sub.path[0];
        fieldErrors[firstEl] = fieldErrors[firstEl] || [];
        fieldErrors[firstEl].push(mapper(sub));
      } else {
        formErrors.push(mapper(sub));
      }
    }
    return { formErrors, fieldErrors };
  }
  get formErrors() {
    return this.flatten();
  }
}
ZodError.create = (issues) => {
  const error2 = new ZodError(issues);
  return error2;
};

// node_modules/zod/v3/locales/en.js
var errorMap = (issue, _ctx) => {
  let message;
  switch (issue.code) {
    case ZodIssueCode.invalid_type:
      if (issue.received === ZodParsedType.undefined) {
        message = "Required";
      } else {
        message = `Expected ${issue.expected}, received ${issue.received}`;
      }
      break;
    case ZodIssueCode.invalid_literal:
      message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
      break;
    case ZodIssueCode.unrecognized_keys:
      message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
      break;
    case ZodIssueCode.invalid_union:
      message = `Invalid input`;
      break;
    case ZodIssueCode.invalid_union_discriminator:
      message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
      break;
    case ZodIssueCode.invalid_enum_value:
      message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
      break;
    case ZodIssueCode.invalid_arguments:
      message = `Invalid function arguments`;
      break;
    case ZodIssueCode.invalid_return_type:
      message = `Invalid function return type`;
      break;
    case ZodIssueCode.invalid_date:
      message = `Invalid date`;
      break;
    case ZodIssueCode.invalid_string:
      if (typeof issue.validation === "object") {
        if ("includes" in issue.validation) {
          message = `Invalid input: must include "${issue.validation.includes}"`;
          if (typeof issue.validation.position === "number") {
            message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
          }
        } else if ("startsWith" in issue.validation) {
          message = `Invalid input: must start with "${issue.validation.startsWith}"`;
        } else if ("endsWith" in issue.validation) {
          message = `Invalid input: must end with "${issue.validation.endsWith}"`;
        } else {
          util.assertNever(issue.validation);
        }
      } else if (issue.validation !== "regex") {
        message = `Invalid ${issue.validation}`;
      } else {
        message = "Invalid";
      }
      break;
    case ZodIssueCode.too_small:
      if (issue.type === "array")
        message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
      else if (issue.type === "string")
        message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
      else if (issue.type === "number")
        message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
      else if (issue.type === "bigint")
        message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
      else if (issue.type === "date")
        message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
      else
        message = "Invalid input";
      break;
    case ZodIssueCode.too_big:
      if (issue.type === "array")
        message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
      else if (issue.type === "string")
        message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
      else if (issue.type === "number")
        message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
      else if (issue.type === "bigint")
        message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
      else if (issue.type === "date")
        message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
      else
        message = "Invalid input";
      break;
    case ZodIssueCode.custom:
      message = `Invalid input`;
      break;
    case ZodIssueCode.invalid_intersection_types:
      message = `Intersection results could not be merged`;
      break;
    case ZodIssueCode.not_multiple_of:
      message = `Number must be a multiple of ${issue.multipleOf}`;
      break;
    case ZodIssueCode.not_finite:
      message = "Number must be finite";
      break;
    default:
      message = _ctx.defaultError;
      util.assertNever(issue);
  }
  return { message };
};
var en_default = errorMap;

// node_modules/zod/v3/errors.js
var overrideErrorMap = en_default;
function setErrorMap(map) {
  overrideErrorMap = map;
}
function getErrorMap() {
  return overrideErrorMap;
}
// node_modules/zod/v3/helpers/parseUtil.js
var makeIssue = (params) => {
  const { data, path: path12, errorMaps, issueData } = params;
  const fullPath = [...path12, ...issueData.path || []];
  const fullIssue = {
    ...issueData,
    path: fullPath
  };
  if (issueData.message !== undefined) {
    return {
      ...issueData,
      path: fullPath,
      message: issueData.message
    };
  }
  let errorMessage = "";
  const maps = errorMaps.filter((m) => !!m).slice().reverse();
  for (const map of maps) {
    errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
  }
  return {
    ...issueData,
    path: fullPath,
    message: errorMessage
  };
};
var EMPTY_PATH = [];
function addIssueToContext(ctx, issueData) {
  const overrideMap = getErrorMap();
  const issue = makeIssue({
    issueData,
    data: ctx.data,
    path: ctx.path,
    errorMaps: [
      ctx.common.contextualErrorMap,
      ctx.schemaErrorMap,
      overrideMap,
      overrideMap === en_default ? undefined : en_default
    ].filter((x) => !!x)
  });
  ctx.common.issues.push(issue);
}

class ParseStatus {
  constructor() {
    this.value = "valid";
  }
  dirty() {
    if (this.value === "valid")
      this.value = "dirty";
  }
  abort() {
    if (this.value !== "aborted")
      this.value = "aborted";
  }
  static mergeArray(status, results) {
    const arrayValue = [];
    for (const s of results) {
      if (s.status === "aborted")
        return INVALID;
      if (s.status === "dirty")
        status.dirty();
      arrayValue.push(s.value);
    }
    return { status: status.value, value: arrayValue };
  }
  static async mergeObjectAsync(status, pairs) {
    const syncPairs = [];
    for (const pair of pairs) {
      const key = await pair.key;
      const value = await pair.value;
      syncPairs.push({
        key,
        value
      });
    }
    return ParseStatus.mergeObjectSync(status, syncPairs);
  }
  static mergeObjectSync(status, pairs) {
    const finalObject = {};
    for (const pair of pairs) {
      const { key, value } = pair;
      if (key.status === "aborted")
        return INVALID;
      if (value.status === "aborted")
        return INVALID;
      if (key.status === "dirty")
        status.dirty();
      if (value.status === "dirty")
        status.dirty();
      if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
        finalObject[key.value] = value.value;
      }
    }
    return { status: status.value, value: finalObject };
  }
}
var INVALID = Object.freeze({
  status: "aborted"
});
var DIRTY = (value) => ({ status: "dirty", value });
var OK = (value) => ({ status: "valid", value });
var isAborted = (x) => x.status === "aborted";
var isDirty = (x) => x.status === "dirty";
var isValid = (x) => x.status === "valid";
var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
// node_modules/zod/v3/helpers/errorUtil.js
var errorUtil;
(function(errorUtil2) {
  errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
  errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
})(errorUtil || (errorUtil = {}));

// node_modules/zod/v3/types.js
class ParseInputLazyPath {
  constructor(parent, value, path12, key) {
    this._cachedPath = [];
    this.parent = parent;
    this.data = value;
    this._path = path12;
    this._key = key;
  }
  get path() {
    if (!this._cachedPath.length) {
      if (Array.isArray(this._key)) {
        this._cachedPath.push(...this._path, ...this._key);
      } else {
        this._cachedPath.push(...this._path, this._key);
      }
    }
    return this._cachedPath;
  }
}
var handleResult = (ctx, result) => {
  if (isValid(result)) {
    return { success: true, data: result.value };
  } else {
    if (!ctx.common.issues.length) {
      throw new Error("Validation failed but no issues detected.");
    }
    return {
      success: false,
      get error() {
        if (this._error)
          return this._error;
        const error2 = new ZodError(ctx.common.issues);
        this._error = error2;
        return this._error;
      }
    };
  }
};
function processCreateParams(params) {
  if (!params)
    return {};
  const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
  if (errorMap2 && (invalid_type_error || required_error)) {
    throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
  }
  if (errorMap2)
    return { errorMap: errorMap2, description };
  const customMap = (iss, ctx) => {
    const { message } = params;
    if (iss.code === "invalid_enum_value") {
      return { message: message ?? ctx.defaultError };
    }
    if (typeof ctx.data === "undefined") {
      return { message: message ?? required_error ?? ctx.defaultError };
    }
    if (iss.code !== "invalid_type")
      return { message: ctx.defaultError };
    return { message: message ?? invalid_type_error ?? ctx.defaultError };
  };
  return { errorMap: customMap, description };
}

class ZodType {
  get description() {
    return this._def.description;
  }
  _getType(input) {
    return getParsedType(input.data);
  }
  _getOrReturnCtx(input, ctx) {
    return ctx || {
      common: input.parent.common,
      data: input.data,
      parsedType: getParsedType(input.data),
      schemaErrorMap: this._def.errorMap,
      path: input.path,
      parent: input.parent
    };
  }
  _processInputParams(input) {
    return {
      status: new ParseStatus,
      ctx: {
        common: input.parent.common,
        data: input.data,
        parsedType: getParsedType(input.data),
        schemaErrorMap: this._def.errorMap,
        path: input.path,
        parent: input.parent
      }
    };
  }
  _parseSync(input) {
    const result = this._parse(input);
    if (isAsync(result)) {
      throw new Error("Synchronous parse encountered promise.");
    }
    return result;
  }
  _parseAsync(input) {
    const result = this._parse(input);
    return Promise.resolve(result);
  }
  parse(data, params) {
    const result = this.safeParse(data, params);
    if (result.success)
      return result.data;
    throw result.error;
  }
  safeParse(data, params) {
    const ctx = {
      common: {
        issues: [],
        async: params?.async ?? false,
        contextualErrorMap: params?.errorMap
      },
      path: params?.path || [],
      schemaErrorMap: this._def.errorMap,
      parent: null,
      data,
      parsedType: getParsedType(data)
    };
    const result = this._parseSync({ data, path: ctx.path, parent: ctx });
    return handleResult(ctx, result);
  }
  "~validate"(data) {
    const ctx = {
      common: {
        issues: [],
        async: !!this["~standard"].async
      },
      path: [],
      schemaErrorMap: this._def.errorMap,
      parent: null,
      data,
      parsedType: getParsedType(data)
    };
    if (!this["~standard"].async) {
      try {
        const result = this._parseSync({ data, path: [], parent: ctx });
        return isValid(result) ? {
          value: result.value
        } : {
          issues: ctx.common.issues
        };
      } catch (err) {
        if (err?.message?.toLowerCase()?.includes("encountered")) {
          this["~standard"].async = true;
        }
        ctx.common = {
          issues: [],
          async: true
        };
      }
    }
    return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
      value: result.value
    } : {
      issues: ctx.common.issues
    });
  }
  async parseAsync(data, params) {
    const result = await this.safeParseAsync(data, params);
    if (result.success)
      return result.data;
    throw result.error;
  }
  async safeParseAsync(data, params) {
    const ctx = {
      common: {
        issues: [],
        contextualErrorMap: params?.errorMap,
        async: true
      },
      path: params?.path || [],
      schemaErrorMap: this._def.errorMap,
      parent: null,
      data,
      parsedType: getParsedType(data)
    };
    const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
    const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
    return handleResult(ctx, result);
  }
  refine(check, message) {
    const getIssueProperties = (val) => {
      if (typeof message === "string" || typeof message === "undefined") {
        return { message };
      } else if (typeof message === "function") {
        return message(val);
      } else {
        return message;
      }
    };
    return this._refinement((val, ctx) => {
      const result = check(val);
      const setError = () => ctx.addIssue({
        code: ZodIssueCode.custom,
        ...getIssueProperties(val)
      });
      if (typeof Promise !== "undefined" && result instanceof Promise) {
        return result.then((data) => {
          if (!data) {
            setError();
            return false;
          } else {
            return true;
          }
        });
      }
      if (!result) {
        setError();
        return false;
      } else {
        return true;
      }
    });
  }
  refinement(check, refinementData) {
    return this._refinement((val, ctx) => {
      if (!check(val)) {
        ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
        return false;
      } else {
        return true;
      }
    });
  }
  _refinement(refinement) {
    return new ZodEffects({
      schema: this,
      typeName: ZodFirstPartyTypeKind.ZodEffects,
      effect: { type: "refinement", refinement }
    });
  }
  superRefine(refinement) {
    return this._refinement(refinement);
  }
  constructor(def) {
    this.spa = this.safeParseAsync;
    this._def = def;
    this.parse = this.parse.bind(this);
    this.safeParse = this.safeParse.bind(this);
    this.parseAsync = this.parseAsync.bind(this);
    this.safeParseAsync = this.safeParseAsync.bind(this);
    this.spa = this.spa.bind(this);
    this.refine = this.refine.bind(this);
    this.refinement = this.refinement.bind(this);
    this.superRefine = this.superRefine.bind(this);
    this.optional = this.optional.bind(this);
    this.nullable = this.nullable.bind(this);
    this.nullish = this.nullish.bind(this);
    this.array = this.array.bind(this);
    this.promise = this.promise.bind(this);
    this.or = this.or.bind(this);
    this.and = this.and.bind(this);
    this.transform = this.transform.bind(this);
    this.brand = this.brand.bind(this);
    this.default = this.default.bind(this);
    this.catch = this.catch.bind(this);
    this.describe = this.describe.bind(this);
    this.pipe = this.pipe.bind(this);
    this.readonly = this.readonly.bind(this);
    this.isNullable = this.isNullable.bind(this);
    this.isOptional = this.isOptional.bind(this);
    this["~standard"] = {
      version: 1,
      vendor: "zod",
      validate: (data) => this["~validate"](data)
    };
  }
  optional() {
    return ZodOptional.create(this, this._def);
  }
  nullable() {
    return ZodNullable.create(this, this._def);
  }
  nullish() {
    return this.nullable().optional();
  }
  array() {
    return ZodArray.create(this);
  }
  promise() {
    return ZodPromise.create(this, this._def);
  }
  or(option) {
    return ZodUnion.create([this, option], this._def);
  }
  and(incoming) {
    return ZodIntersection.create(this, incoming, this._def);
  }
  transform(transform) {
    return new ZodEffects({
      ...processCreateParams(this._def),
      schema: this,
      typeName: ZodFirstPartyTypeKind.ZodEffects,
      effect: { type: "transform", transform }
    });
  }
  default(def) {
    const defaultValueFunc = typeof def === "function" ? def : () => def;
    return new ZodDefault({
      ...processCreateParams(this._def),
      innerType: this,
      defaultValue: defaultValueFunc,
      typeName: ZodFirstPartyTypeKind.ZodDefault
    });
  }
  brand() {
    return new ZodBranded({
      typeName: ZodFirstPartyTypeKind.ZodBranded,
      type: this,
      ...processCreateParams(this._def)
    });
  }
  catch(def) {
    const catchValueFunc = typeof def === "function" ? def : () => def;
    return new ZodCatch({
      ...processCreateParams(this._def),
      innerType: this,
      catchValue: catchValueFunc,
      typeName: ZodFirstPartyTypeKind.ZodCatch
    });
  }
  describe(description) {
    const This = this.constructor;
    return new This({
      ...this._def,
      description
    });
  }
  pipe(target) {
    return ZodPipeline.create(this, target);
  }
  readonly() {
    return ZodReadonly.create(this);
  }
  isOptional() {
    return this.safeParse(undefined).success;
  }
  isNullable() {
    return this.safeParse(null).success;
  }
}
var cuidRegex = /^c[^\s-]{8,}$/i;
var cuid2Regex = /^[0-9a-z]+$/;
var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
var nanoidRegex = /^[a-z0-9_-]{21}$/i;
var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
var durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
var emojiRegex;
var ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
var ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
var ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
var ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
var dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
var dateRegex = new RegExp(`^${dateRegexSource}$`);
function timeRegexSource(args) {
  let secondsRegexSource = `[0-5]\\d`;
  if (args.precision) {
    secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
  } else if (args.precision == null) {
    secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
  }
  const secondsQuantifier = args.precision ? "+" : "?";
  return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
}
function timeRegex(args) {
  return new RegExp(`^${timeRegexSource(args)}$`);
}
function datetimeRegex(args) {
  let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
  const opts = [];
  opts.push(args.local ? `Z?` : `Z`);
  if (args.offset)
    opts.push(`([+-]\\d{2}:?\\d{2})`);
  regex = `${regex}(${opts.join("|")})`;
  return new RegExp(`^${regex}$`);
}
function isValidIP(ip, version) {
  if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
    return true;
  }
  if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
    return true;
  }
  return false;
}
function isValidJWT(jwt, alg) {
  if (!jwtRegex.test(jwt))
    return false;
  try {
    const [header] = jwt.split(".");
    if (!header)
      return false;
    const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
    const decoded = JSON.parse(atob(base64));
    if (typeof decoded !== "object" || decoded === null)
      return false;
    if ("typ" in decoded && decoded?.typ !== "JWT")
      return false;
    if (!decoded.alg)
      return false;
    if (alg && decoded.alg !== alg)
      return false;
    return true;
  } catch {
    return false;
  }
}
function isValidCidr(ip, version) {
  if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
    return true;
  }
  if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
    return true;
  }
  return false;
}

class ZodString extends ZodType {
  _parse(input) {
    if (this._def.coerce) {
      input.data = String(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.string) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.string,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    const status = new ParseStatus;
    let ctx = undefined;
    for (const check of this._def.checks) {
      if (check.kind === "min") {
        if (input.data.length < check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            minimum: check.value,
            type: "string",
            inclusive: true,
            exact: false,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "max") {
        if (input.data.length > check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            maximum: check.value,
            type: "string",
            inclusive: true,
            exact: false,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "length") {
        const tooBig = input.data.length > check.value;
        const tooSmall = input.data.length < check.value;
        if (tooBig || tooSmall) {
          ctx = this._getOrReturnCtx(input, ctx);
          if (tooBig) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_big,
              maximum: check.value,
              type: "string",
              inclusive: true,
              exact: true,
              message: check.message
            });
          } else if (tooSmall) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_small,
              minimum: check.value,
              type: "string",
              inclusive: true,
              exact: true,
              message: check.message
            });
          }
          status.dirty();
        }
      } else if (check.kind === "email") {
        if (!emailRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "email",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "emoji") {
        if (!emojiRegex) {
          emojiRegex = new RegExp(_emojiRegex, "u");
        }
        if (!emojiRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "emoji",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "uuid") {
        if (!uuidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "uuid",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "nanoid") {
        if (!nanoidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "nanoid",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "cuid") {
        if (!cuidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "cuid",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "cuid2") {
        if (!cuid2Regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "cuid2",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "ulid") {
        if (!ulidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "ulid",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "url") {
        try {
          new URL(input.data);
        } catch {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "url",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "regex") {
        check.regex.lastIndex = 0;
        const testResult = check.regex.test(input.data);
        if (!testResult) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "regex",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "trim") {
        input.data = input.data.trim();
      } else if (check.kind === "includes") {
        if (!input.data.includes(check.value, check.position)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: { includes: check.value, position: check.position },
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "toLowerCase") {
        input.data = input.data.toLowerCase();
      } else if (check.kind === "toUpperCase") {
        input.data = input.data.toUpperCase();
      } else if (check.kind === "startsWith") {
        if (!input.data.startsWith(check.value)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: { startsWith: check.value },
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "endsWith") {
        if (!input.data.endsWith(check.value)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: { endsWith: check.value },
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "datetime") {
        const regex = datetimeRegex(check);
        if (!regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: "datetime",
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "date") {
        const regex = dateRegex;
        if (!regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: "date",
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "time") {
        const regex = timeRegex(check);
        if (!regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: "time",
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "duration") {
        if (!durationRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "duration",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "ip") {
        if (!isValidIP(input.data, check.version)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "ip",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "jwt") {
        if (!isValidJWT(input.data, check.alg)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "jwt",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "cidr") {
        if (!isValidCidr(input.data, check.version)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "cidr",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "base64") {
        if (!base64Regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "base64",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "base64url") {
        if (!base64urlRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "base64url",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else {
        util.assertNever(check);
      }
    }
    return { status: status.value, value: input.data };
  }
  _regex(regex, validation, message) {
    return this.refinement((data) => regex.test(data), {
      validation,
      code: ZodIssueCode.invalid_string,
      ...errorUtil.errToObj(message)
    });
  }
  _addCheck(check) {
    return new ZodString({
      ...this._def,
      checks: [...this._def.checks, check]
    });
  }
  email(message) {
    return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
  }
  url(message) {
    return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
  }
  emoji(message) {
    return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
  }
  uuid(message) {
    return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
  }
  nanoid(message) {
    return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
  }
  cuid(message) {
    return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
  }
  cuid2(message) {
    return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
  }
  ulid(message) {
    return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
  }
  base64(message) {
    return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
  }
  base64url(message) {
    return this._addCheck({
      kind: "base64url",
      ...errorUtil.errToObj(message)
    });
  }
  jwt(options) {
    return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
  }
  ip(options) {
    return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
  }
  cidr(options) {
    return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
  }
  datetime(options) {
    if (typeof options === "string") {
      return this._addCheck({
        kind: "datetime",
        precision: null,
        offset: false,
        local: false,
        message: options
      });
    }
    return this._addCheck({
      kind: "datetime",
      precision: typeof options?.precision === "undefined" ? null : options?.precision,
      offset: options?.offset ?? false,
      local: options?.local ?? false,
      ...errorUtil.errToObj(options?.message)
    });
  }
  date(message) {
    return this._addCheck({ kind: "date", message });
  }
  time(options) {
    if (typeof options === "string") {
      return this._addCheck({
        kind: "time",
        precision: null,
        message: options
      });
    }
    return this._addCheck({
      kind: "time",
      precision: typeof options?.precision === "undefined" ? null : options?.precision,
      ...errorUtil.errToObj(options?.message)
    });
  }
  duration(message) {
    return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
  }
  regex(regex, message) {
    return this._addCheck({
      kind: "regex",
      regex,
      ...errorUtil.errToObj(message)
    });
  }
  includes(value, options) {
    return this._addCheck({
      kind: "includes",
      value,
      position: options?.position,
      ...errorUtil.errToObj(options?.message)
    });
  }
  startsWith(value, message) {
    return this._addCheck({
      kind: "startsWith",
      value,
      ...errorUtil.errToObj(message)
    });
  }
  endsWith(value, message) {
    return this._addCheck({
      kind: "endsWith",
      value,
      ...errorUtil.errToObj(message)
    });
  }
  min(minLength, message) {
    return this._addCheck({
      kind: "min",
      value: minLength,
      ...errorUtil.errToObj(message)
    });
  }
  max(maxLength, message) {
    return this._addCheck({
      kind: "max",
      value: maxLength,
      ...errorUtil.errToObj(message)
    });
  }
  length(len, message) {
    return this._addCheck({
      kind: "length",
      value: len,
      ...errorUtil.errToObj(message)
    });
  }
  nonempty(message) {
    return this.min(1, errorUtil.errToObj(message));
  }
  trim() {
    return new ZodString({
      ...this._def,
      checks: [...this._def.checks, { kind: "trim" }]
    });
  }
  toLowerCase() {
    return new ZodString({
      ...this._def,
      checks: [...this._def.checks, { kind: "toLowerCase" }]
    });
  }
  toUpperCase() {
    return new ZodString({
      ...this._def,
      checks: [...this._def.checks, { kind: "toUpperCase" }]
    });
  }
  get isDatetime() {
    return !!this._def.checks.find((ch) => ch.kind === "datetime");
  }
  get isDate() {
    return !!this._def.checks.find((ch) => ch.kind === "date");
  }
  get isTime() {
    return !!this._def.checks.find((ch) => ch.kind === "time");
  }
  get isDuration() {
    return !!this._def.checks.find((ch) => ch.kind === "duration");
  }
  get isEmail() {
    return !!this._def.checks.find((ch) => ch.kind === "email");
  }
  get isURL() {
    return !!this._def.checks.find((ch) => ch.kind === "url");
  }
  get isEmoji() {
    return !!this._def.checks.find((ch) => ch.kind === "emoji");
  }
  get isUUID() {
    return !!this._def.checks.find((ch) => ch.kind === "uuid");
  }
  get isNANOID() {
    return !!this._def.checks.find((ch) => ch.kind === "nanoid");
  }
  get isCUID() {
    return !!this._def.checks.find((ch) => ch.kind === "cuid");
  }
  get isCUID2() {
    return !!this._def.checks.find((ch) => ch.kind === "cuid2");
  }
  get isULID() {
    return !!this._def.checks.find((ch) => ch.kind === "ulid");
  }
  get isIP() {
    return !!this._def.checks.find((ch) => ch.kind === "ip");
  }
  get isCIDR() {
    return !!this._def.checks.find((ch) => ch.kind === "cidr");
  }
  get isBase64() {
    return !!this._def.checks.find((ch) => ch.kind === "base64");
  }
  get isBase64url() {
    return !!this._def.checks.find((ch) => ch.kind === "base64url");
  }
  get minLength() {
    let min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min === null || ch.value > min)
          min = ch.value;
      }
    }
    return min;
  }
  get maxLength() {
    let max = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max === null || ch.value < max)
          max = ch.value;
      }
    }
    return max;
  }
}
ZodString.create = (params) => {
  return new ZodString({
    checks: [],
    typeName: ZodFirstPartyTypeKind.ZodString,
    coerce: params?.coerce ?? false,
    ...processCreateParams(params)
  });
};
function floatSafeRemainder(val, step) {
  const valDecCount = (val.toString().split(".")[1] || "").length;
  const stepDecCount = (step.toString().split(".")[1] || "").length;
  const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
  const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
  const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
  return valInt % stepInt / 10 ** decCount;
}

class ZodNumber extends ZodType {
  constructor() {
    super(...arguments);
    this.min = this.gte;
    this.max = this.lte;
    this.step = this.multipleOf;
  }
  _parse(input) {
    if (this._def.coerce) {
      input.data = Number(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.number) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.number,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    let ctx = undefined;
    const status = new ParseStatus;
    for (const check of this._def.checks) {
      if (check.kind === "int") {
        if (!util.isInteger(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: "integer",
            received: "float",
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "min") {
        const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
        if (tooSmall) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            minimum: check.value,
            type: "number",
            inclusive: check.inclusive,
            exact: false,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "max") {
        const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
        if (tooBig) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            maximum: check.value,
            type: "number",
            inclusive: check.inclusive,
            exact: false,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "multipleOf") {
        if (floatSafeRemainder(input.data, check.value) !== 0) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.not_multiple_of,
            multipleOf: check.value,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "finite") {
        if (!Number.isFinite(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.not_finite,
            message: check.message
          });
          status.dirty();
        }
      } else {
        util.assertNever(check);
      }
    }
    return { status: status.value, value: input.data };
  }
  gte(value, message) {
    return this.setLimit("min", value, true, errorUtil.toString(message));
  }
  gt(value, message) {
    return this.setLimit("min", value, false, errorUtil.toString(message));
  }
  lte(value, message) {
    return this.setLimit("max", value, true, errorUtil.toString(message));
  }
  lt(value, message) {
    return this.setLimit("max", value, false, errorUtil.toString(message));
  }
  setLimit(kind, value, inclusive, message) {
    return new ZodNumber({
      ...this._def,
      checks: [
        ...this._def.checks,
        {
          kind,
          value,
          inclusive,
          message: errorUtil.toString(message)
        }
      ]
    });
  }
  _addCheck(check) {
    return new ZodNumber({
      ...this._def,
      checks: [...this._def.checks, check]
    });
  }
  int(message) {
    return this._addCheck({
      kind: "int",
      message: errorUtil.toString(message)
    });
  }
  positive(message) {
    return this._addCheck({
      kind: "min",
      value: 0,
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  negative(message) {
    return this._addCheck({
      kind: "max",
      value: 0,
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  nonpositive(message) {
    return this._addCheck({
      kind: "max",
      value: 0,
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  nonnegative(message) {
    return this._addCheck({
      kind: "min",
      value: 0,
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  multipleOf(value, message) {
    return this._addCheck({
      kind: "multipleOf",
      value,
      message: errorUtil.toString(message)
    });
  }
  finite(message) {
    return this._addCheck({
      kind: "finite",
      message: errorUtil.toString(message)
    });
  }
  safe(message) {
    return this._addCheck({
      kind: "min",
      inclusive: true,
      value: Number.MIN_SAFE_INTEGER,
      message: errorUtil.toString(message)
    })._addCheck({
      kind: "max",
      inclusive: true,
      value: Number.MAX_SAFE_INTEGER,
      message: errorUtil.toString(message)
    });
  }
  get minValue() {
    let min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min === null || ch.value > min)
          min = ch.value;
      }
    }
    return min;
  }
  get maxValue() {
    let max = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max === null || ch.value < max)
          max = ch.value;
      }
    }
    return max;
  }
  get isInt() {
    return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
  }
  get isFinite() {
    let max = null;
    let min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
        return true;
      } else if (ch.kind === "min") {
        if (min === null || ch.value > min)
          min = ch.value;
      } else if (ch.kind === "max") {
        if (max === null || ch.value < max)
          max = ch.value;
      }
    }
    return Number.isFinite(min) && Number.isFinite(max);
  }
}
ZodNumber.create = (params) => {
  return new ZodNumber({
    checks: [],
    typeName: ZodFirstPartyTypeKind.ZodNumber,
    coerce: params?.coerce || false,
    ...processCreateParams(params)
  });
};

class ZodBigInt extends ZodType {
  constructor() {
    super(...arguments);
    this.min = this.gte;
    this.max = this.lte;
  }
  _parse(input) {
    if (this._def.coerce) {
      try {
        input.data = BigInt(input.data);
      } catch {
        return this._getInvalidInput(input);
      }
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.bigint) {
      return this._getInvalidInput(input);
    }
    let ctx = undefined;
    const status = new ParseStatus;
    for (const check of this._def.checks) {
      if (check.kind === "min") {
        const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
        if (tooSmall) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            type: "bigint",
            minimum: check.value,
            inclusive: check.inclusive,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "max") {
        const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
        if (tooBig) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            type: "bigint",
            maximum: check.value,
            inclusive: check.inclusive,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "multipleOf") {
        if (input.data % check.value !== BigInt(0)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.not_multiple_of,
            multipleOf: check.value,
            message: check.message
          });
          status.dirty();
        }
      } else {
        util.assertNever(check);
      }
    }
    return { status: status.value, value: input.data };
  }
  _getInvalidInput(input) {
    const ctx = this._getOrReturnCtx(input);
    addIssueToContext(ctx, {
      code: ZodIssueCode.invalid_type,
      expected: ZodParsedType.bigint,
      received: ctx.parsedType
    });
    return INVALID;
  }
  gte(value, message) {
    return this.setLimit("min", value, true, errorUtil.toString(message));
  }
  gt(value, message) {
    return this.setLimit("min", value, false, errorUtil.toString(message));
  }
  lte(value, message) {
    return this.setLimit("max", value, true, errorUtil.toString(message));
  }
  lt(value, message) {
    return this.setLimit("max", value, false, errorUtil.toString(message));
  }
  setLimit(kind, value, inclusive, message) {
    return new ZodBigInt({
      ...this._def,
      checks: [
        ...this._def.checks,
        {
          kind,
          value,
          inclusive,
          message: errorUtil.toString(message)
        }
      ]
    });
  }
  _addCheck(check) {
    return new ZodBigInt({
      ...this._def,
      checks: [...this._def.checks, check]
    });
  }
  positive(message) {
    return this._addCheck({
      kind: "min",
      value: BigInt(0),
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  negative(message) {
    return this._addCheck({
      kind: "max",
      value: BigInt(0),
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  nonpositive(message) {
    return this._addCheck({
      kind: "max",
      value: BigInt(0),
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  nonnegative(message) {
    return this._addCheck({
      kind: "min",
      value: BigInt(0),
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  multipleOf(value, message) {
    return this._addCheck({
      kind: "multipleOf",
      value,
      message: errorUtil.toString(message)
    });
  }
  get minValue() {
    let min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min === null || ch.value > min)
          min = ch.value;
      }
    }
    return min;
  }
  get maxValue() {
    let max = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max === null || ch.value < max)
          max = ch.value;
      }
    }
    return max;
  }
}
ZodBigInt.create = (params) => {
  return new ZodBigInt({
    checks: [],
    typeName: ZodFirstPartyTypeKind.ZodBigInt,
    coerce: params?.coerce ?? false,
    ...processCreateParams(params)
  });
};

class ZodBoolean extends ZodType {
  _parse(input) {
    if (this._def.coerce) {
      input.data = Boolean(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.boolean) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.boolean,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
}
ZodBoolean.create = (params) => {
  return new ZodBoolean({
    typeName: ZodFirstPartyTypeKind.ZodBoolean,
    coerce: params?.coerce || false,
    ...processCreateParams(params)
  });
};

class ZodDate extends ZodType {
  _parse(input) {
    if (this._def.coerce) {
      input.data = new Date(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.date) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.date,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    if (Number.isNaN(input.data.getTime())) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_date
      });
      return INVALID;
    }
    const status = new ParseStatus;
    let ctx = undefined;
    for (const check of this._def.checks) {
      if (check.kind === "min") {
        if (input.data.getTime() < check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            message: check.message,
            inclusive: true,
            exact: false,
            minimum: check.value,
            type: "date"
          });
          status.dirty();
        }
      } else if (check.kind === "max") {
        if (input.data.getTime() > check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            message: check.message,
            inclusive: true,
            exact: false,
            maximum: check.value,
            type: "date"
          });
          status.dirty();
        }
      } else {
        util.assertNever(check);
      }
    }
    return {
      status: status.value,
      value: new Date(input.data.getTime())
    };
  }
  _addCheck(check) {
    return new ZodDate({
      ...this._def,
      checks: [...this._def.checks, check]
    });
  }
  min(minDate, message) {
    return this._addCheck({
      kind: "min",
      value: minDate.getTime(),
      message: errorUtil.toString(message)
    });
  }
  max(maxDate, message) {
    return this._addCheck({
      kind: "max",
      value: maxDate.getTime(),
      message: errorUtil.toString(message)
    });
  }
  get minDate() {
    let min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min === null || ch.value > min)
          min = ch.value;
      }
    }
    return min != null ? new Date(min) : null;
  }
  get maxDate() {
    let max = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max === null || ch.value < max)
          max = ch.value;
      }
    }
    return max != null ? new Date(max) : null;
  }
}
ZodDate.create = (params) => {
  return new ZodDate({
    checks: [],
    coerce: params?.coerce || false,
    typeName: ZodFirstPartyTypeKind.ZodDate,
    ...processCreateParams(params)
  });
};

class ZodSymbol extends ZodType {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.symbol) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.symbol,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
}
ZodSymbol.create = (params) => {
  return new ZodSymbol({
    typeName: ZodFirstPartyTypeKind.ZodSymbol,
    ...processCreateParams(params)
  });
};

class ZodUndefined extends ZodType {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.undefined) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.undefined,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
}
ZodUndefined.create = (params) => {
  return new ZodUndefined({
    typeName: ZodFirstPartyTypeKind.ZodUndefined,
    ...processCreateParams(params)
  });
};

class ZodNull extends ZodType {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.null) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.null,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
}
ZodNull.create = (params) => {
  return new ZodNull({
    typeName: ZodFirstPartyTypeKind.ZodNull,
    ...processCreateParams(params)
  });
};

class ZodAny extends ZodType {
  constructor() {
    super(...arguments);
    this._any = true;
  }
  _parse(input) {
    return OK(input.data);
  }
}
ZodAny.create = (params) => {
  return new ZodAny({
    typeName: ZodFirstPartyTypeKind.ZodAny,
    ...processCreateParams(params)
  });
};

class ZodUnknown extends ZodType {
  constructor() {
    super(...arguments);
    this._unknown = true;
  }
  _parse(input) {
    return OK(input.data);
  }
}
ZodUnknown.create = (params) => {
  return new ZodUnknown({
    typeName: ZodFirstPartyTypeKind.ZodUnknown,
    ...processCreateParams(params)
  });
};

class ZodNever extends ZodType {
  _parse(input) {
    const ctx = this._getOrReturnCtx(input);
    addIssueToContext(ctx, {
      code: ZodIssueCode.invalid_type,
      expected: ZodParsedType.never,
      received: ctx.parsedType
    });
    return INVALID;
  }
}
ZodNever.create = (params) => {
  return new ZodNever({
    typeName: ZodFirstPartyTypeKind.ZodNever,
    ...processCreateParams(params)
  });
};

class ZodVoid extends ZodType {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.undefined) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.void,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
}
ZodVoid.create = (params) => {
  return new ZodVoid({
    typeName: ZodFirstPartyTypeKind.ZodVoid,
    ...processCreateParams(params)
  });
};

class ZodArray extends ZodType {
  _parse(input) {
    const { ctx, status } = this._processInputParams(input);
    const def = this._def;
    if (ctx.parsedType !== ZodParsedType.array) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.array,
        received: ctx.parsedType
      });
      return INVALID;
    }
    if (def.exactLength !== null) {
      const tooBig = ctx.data.length > def.exactLength.value;
      const tooSmall = ctx.data.length < def.exactLength.value;
      if (tooBig || tooSmall) {
        addIssueToContext(ctx, {
          code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
          minimum: tooSmall ? def.exactLength.value : undefined,
          maximum: tooBig ? def.exactLength.value : undefined,
          type: "array",
          inclusive: true,
          exact: true,
          message: def.exactLength.message
        });
        status.dirty();
      }
    }
    if (def.minLength !== null) {
      if (ctx.data.length < def.minLength.value) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.too_small,
          minimum: def.minLength.value,
          type: "array",
          inclusive: true,
          exact: false,
          message: def.minLength.message
        });
        status.dirty();
      }
    }
    if (def.maxLength !== null) {
      if (ctx.data.length > def.maxLength.value) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.too_big,
          maximum: def.maxLength.value,
          type: "array",
          inclusive: true,
          exact: false,
          message: def.maxLength.message
        });
        status.dirty();
      }
    }
    if (ctx.common.async) {
      return Promise.all([...ctx.data].map((item, i) => {
        return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
      })).then((result2) => {
        return ParseStatus.mergeArray(status, result2);
      });
    }
    const result = [...ctx.data].map((item, i) => {
      return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
    });
    return ParseStatus.mergeArray(status, result);
  }
  get element() {
    return this._def.type;
  }
  min(minLength, message) {
    return new ZodArray({
      ...this._def,
      minLength: { value: minLength, message: errorUtil.toString(message) }
    });
  }
  max(maxLength, message) {
    return new ZodArray({
      ...this._def,
      maxLength: { value: maxLength, message: errorUtil.toString(message) }
    });
  }
  length(len, message) {
    return new ZodArray({
      ...this._def,
      exactLength: { value: len, message: errorUtil.toString(message) }
    });
  }
  nonempty(message) {
    return this.min(1, message);
  }
}
ZodArray.create = (schema, params) => {
  return new ZodArray({
    type: schema,
    minLength: null,
    maxLength: null,
    exactLength: null,
    typeName: ZodFirstPartyTypeKind.ZodArray,
    ...processCreateParams(params)
  });
};
function deepPartialify(schema) {
  if (schema instanceof ZodObject) {
    const newShape = {};
    for (const key in schema.shape) {
      const fieldSchema = schema.shape[key];
      newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
    }
    return new ZodObject({
      ...schema._def,
      shape: () => newShape
    });
  } else if (schema instanceof ZodArray) {
    return new ZodArray({
      ...schema._def,
      type: deepPartialify(schema.element)
    });
  } else if (schema instanceof ZodOptional) {
    return ZodOptional.create(deepPartialify(schema.unwrap()));
  } else if (schema instanceof ZodNullable) {
    return ZodNullable.create(deepPartialify(schema.unwrap()));
  } else if (schema instanceof ZodTuple) {
    return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
  } else {
    return schema;
  }
}

class ZodObject extends ZodType {
  constructor() {
    super(...arguments);
    this._cached = null;
    this.nonstrict = this.passthrough;
    this.augment = this.extend;
  }
  _getCached() {
    if (this._cached !== null)
      return this._cached;
    const shape = this._def.shape();
    const keys = util.objectKeys(shape);
    this._cached = { shape, keys };
    return this._cached;
  }
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.object) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.object,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    const { status, ctx } = this._processInputParams(input);
    const { shape, keys: shapeKeys } = this._getCached();
    const extraKeys = [];
    if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
      for (const key in ctx.data) {
        if (!shapeKeys.includes(key)) {
          extraKeys.push(key);
        }
      }
    }
    const pairs = [];
    for (const key of shapeKeys) {
      const keyValidator = shape[key];
      const value = ctx.data[key];
      pairs.push({
        key: { status: "valid", value: key },
        value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
        alwaysSet: key in ctx.data
      });
    }
    if (this._def.catchall instanceof ZodNever) {
      const unknownKeys = this._def.unknownKeys;
      if (unknownKeys === "passthrough") {
        for (const key of extraKeys) {
          pairs.push({
            key: { status: "valid", value: key },
            value: { status: "valid", value: ctx.data[key] }
          });
        }
      } else if (unknownKeys === "strict") {
        if (extraKeys.length > 0) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.unrecognized_keys,
            keys: extraKeys
          });
          status.dirty();
        }
      } else if (unknownKeys === "strip") {} else {
        throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
      }
    } else {
      const catchall = this._def.catchall;
      for (const key of extraKeys) {
        const value = ctx.data[key];
        pairs.push({
          key: { status: "valid", value: key },
          value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
          alwaysSet: key in ctx.data
        });
      }
    }
    if (ctx.common.async) {
      return Promise.resolve().then(async () => {
        const syncPairs = [];
        for (const pair of pairs) {
          const key = await pair.key;
          const value = await pair.value;
          syncPairs.push({
            key,
            value,
            alwaysSet: pair.alwaysSet
          });
        }
        return syncPairs;
      }).then((syncPairs) => {
        return ParseStatus.mergeObjectSync(status, syncPairs);
      });
    } else {
      return ParseStatus.mergeObjectSync(status, pairs);
    }
  }
  get shape() {
    return this._def.shape();
  }
  strict(message) {
    errorUtil.errToObj;
    return new ZodObject({
      ...this._def,
      unknownKeys: "strict",
      ...message !== undefined ? {
        errorMap: (issue, ctx) => {
          const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
          if (issue.code === "unrecognized_keys")
            return {
              message: errorUtil.errToObj(message).message ?? defaultError
            };
          return {
            message: defaultError
          };
        }
      } : {}
    });
  }
  strip() {
    return new ZodObject({
      ...this._def,
      unknownKeys: "strip"
    });
  }
  passthrough() {
    return new ZodObject({
      ...this._def,
      unknownKeys: "passthrough"
    });
  }
  extend(augmentation) {
    return new ZodObject({
      ...this._def,
      shape: () => ({
        ...this._def.shape(),
        ...augmentation
      })
    });
  }
  merge(merging) {
    const merged = new ZodObject({
      unknownKeys: merging._def.unknownKeys,
      catchall: merging._def.catchall,
      shape: () => ({
        ...this._def.shape(),
        ...merging._def.shape()
      }),
      typeName: ZodFirstPartyTypeKind.ZodObject
    });
    return merged;
  }
  setKey(key, schema) {
    return this.augment({ [key]: schema });
  }
  catchall(index) {
    return new ZodObject({
      ...this._def,
      catchall: index
    });
  }
  pick(mask) {
    const shape = {};
    for (const key of util.objectKeys(mask)) {
      if (mask[key] && this.shape[key]) {
        shape[key] = this.shape[key];
      }
    }
    return new ZodObject({
      ...this._def,
      shape: () => shape
    });
  }
  omit(mask) {
    const shape = {};
    for (const key of util.objectKeys(this.shape)) {
      if (!mask[key]) {
        shape[key] = this.shape[key];
      }
    }
    return new ZodObject({
      ...this._def,
      shape: () => shape
    });
  }
  deepPartial() {
    return deepPartialify(this);
  }
  partial(mask) {
    const newShape = {};
    for (const key of util.objectKeys(this.shape)) {
      const fieldSchema = this.shape[key];
      if (mask && !mask[key]) {
        newShape[key] = fieldSchema;
      } else {
        newShape[key] = fieldSchema.optional();
      }
    }
    return new ZodObject({
      ...this._def,
      shape: () => newShape
    });
  }
  required(mask) {
    const newShape = {};
    for (const key of util.objectKeys(this.shape)) {
      if (mask && !mask[key]) {
        newShape[key] = this.shape[key];
      } else {
        const fieldSchema = this.shape[key];
        let newField = fieldSchema;
        while (newField instanceof ZodOptional) {
          newField = newField._def.innerType;
        }
        newShape[key] = newField;
      }
    }
    return new ZodObject({
      ...this._def,
      shape: () => newShape
    });
  }
  keyof() {
    return createZodEnum(util.objectKeys(this.shape));
  }
}
ZodObject.create = (shape, params) => {
  return new ZodObject({
    shape: () => shape,
    unknownKeys: "strip",
    catchall: ZodNever.create(),
    typeName: ZodFirstPartyTypeKind.ZodObject,
    ...processCreateParams(params)
  });
};
ZodObject.strictCreate = (shape, params) => {
  return new ZodObject({
    shape: () => shape,
    unknownKeys: "strict",
    catchall: ZodNever.create(),
    typeName: ZodFirstPartyTypeKind.ZodObject,
    ...processCreateParams(params)
  });
};
ZodObject.lazycreate = (shape, params) => {
  return new ZodObject({
    shape,
    unknownKeys: "strip",
    catchall: ZodNever.create(),
    typeName: ZodFirstPartyTypeKind.ZodObject,
    ...processCreateParams(params)
  });
};

class ZodUnion extends ZodType {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const options = this._def.options;
    function handleResults(results) {
      for (const result of results) {
        if (result.result.status === "valid") {
          return result.result;
        }
      }
      for (const result of results) {
        if (result.result.status === "dirty") {
          ctx.common.issues.push(...result.ctx.common.issues);
          return result.result;
        }
      }
      const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_union,
        unionErrors
      });
      return INVALID;
    }
    if (ctx.common.async) {
      return Promise.all(options.map(async (option) => {
        const childCtx = {
          ...ctx,
          common: {
            ...ctx.common,
            issues: []
          },
          parent: null
        };
        return {
          result: await option._parseAsync({
            data: ctx.data,
            path: ctx.path,
            parent: childCtx
          }),
          ctx: childCtx
        };
      })).then(handleResults);
    } else {
      let dirty = undefined;
      const issues = [];
      for (const option of options) {
        const childCtx = {
          ...ctx,
          common: {
            ...ctx.common,
            issues: []
          },
          parent: null
        };
        const result = option._parseSync({
          data: ctx.data,
          path: ctx.path,
          parent: childCtx
        });
        if (result.status === "valid") {
          return result;
        } else if (result.status === "dirty" && !dirty) {
          dirty = { result, ctx: childCtx };
        }
        if (childCtx.common.issues.length) {
          issues.push(childCtx.common.issues);
        }
      }
      if (dirty) {
        ctx.common.issues.push(...dirty.ctx.common.issues);
        return dirty.result;
      }
      const unionErrors = issues.map((issues2) => new ZodError(issues2));
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_union,
        unionErrors
      });
      return INVALID;
    }
  }
  get options() {
    return this._def.options;
  }
}
ZodUnion.create = (types, params) => {
  return new ZodUnion({
    options: types,
    typeName: ZodFirstPartyTypeKind.ZodUnion,
    ...processCreateParams(params)
  });
};
var getDiscriminator = (type) => {
  if (type instanceof ZodLazy) {
    return getDiscriminator(type.schema);
  } else if (type instanceof ZodEffects) {
    return getDiscriminator(type.innerType());
  } else if (type instanceof ZodLiteral) {
    return [type.value];
  } else if (type instanceof ZodEnum) {
    return type.options;
  } else if (type instanceof ZodNativeEnum) {
    return util.objectValues(type.enum);
  } else if (type instanceof ZodDefault) {
    return getDiscriminator(type._def.innerType);
  } else if (type instanceof ZodUndefined) {
    return [undefined];
  } else if (type instanceof ZodNull) {
    return [null];
  } else if (type instanceof ZodOptional) {
    return [undefined, ...getDiscriminator(type.unwrap())];
  } else if (type instanceof ZodNullable) {
    return [null, ...getDiscriminator(type.unwrap())];
  } else if (type instanceof ZodBranded) {
    return getDiscriminator(type.unwrap());
  } else if (type instanceof ZodReadonly) {
    return getDiscriminator(type.unwrap());
  } else if (type instanceof ZodCatch) {
    return getDiscriminator(type._def.innerType);
  } else {
    return [];
  }
};

class ZodDiscriminatedUnion extends ZodType {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.object) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.object,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const discriminator = this.discriminator;
    const discriminatorValue = ctx.data[discriminator];
    const option = this.optionsMap.get(discriminatorValue);
    if (!option) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_union_discriminator,
        options: Array.from(this.optionsMap.keys()),
        path: [discriminator]
      });
      return INVALID;
    }
    if (ctx.common.async) {
      return option._parseAsync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      });
    } else {
      return option._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      });
    }
  }
  get discriminator() {
    return this._def.discriminator;
  }
  get options() {
    return this._def.options;
  }
  get optionsMap() {
    return this._def.optionsMap;
  }
  static create(discriminator, options, params) {
    const optionsMap = new Map;
    for (const type of options) {
      const discriminatorValues = getDiscriminator(type.shape[discriminator]);
      if (!discriminatorValues.length) {
        throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
      }
      for (const value of discriminatorValues) {
        if (optionsMap.has(value)) {
          throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
        }
        optionsMap.set(value, type);
      }
    }
    return new ZodDiscriminatedUnion({
      typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
      discriminator,
      options,
      optionsMap,
      ...processCreateParams(params)
    });
  }
}
function mergeValues(a, b) {
  const aType = getParsedType(a);
  const bType = getParsedType(b);
  if (a === b) {
    return { valid: true, data: a };
  } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
    const bKeys = util.objectKeys(b);
    const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
    const newObj = { ...a, ...b };
    for (const key of sharedKeys) {
      const sharedValue = mergeValues(a[key], b[key]);
      if (!sharedValue.valid) {
        return { valid: false };
      }
      newObj[key] = sharedValue.data;
    }
    return { valid: true, data: newObj };
  } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
    if (a.length !== b.length) {
      return { valid: false };
    }
    const newArray = [];
    for (let index = 0;index < a.length; index++) {
      const itemA = a[index];
      const itemB = b[index];
      const sharedValue = mergeValues(itemA, itemB);
      if (!sharedValue.valid) {
        return { valid: false };
      }
      newArray.push(sharedValue.data);
    }
    return { valid: true, data: newArray };
  } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
    return { valid: true, data: a };
  } else {
    return { valid: false };
  }
}

class ZodIntersection extends ZodType {
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    const handleParsed = (parsedLeft, parsedRight) => {
      if (isAborted(parsedLeft) || isAborted(parsedRight)) {
        return INVALID;
      }
      const merged = mergeValues(parsedLeft.value, parsedRight.value);
      if (!merged.valid) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.invalid_intersection_types
        });
        return INVALID;
      }
      if (isDirty(parsedLeft) || isDirty(parsedRight)) {
        status.dirty();
      }
      return { status: status.value, value: merged.data };
    };
    if (ctx.common.async) {
      return Promise.all([
        this._def.left._parseAsync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        }),
        this._def.right._parseAsync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        })
      ]).then(([left, right]) => handleParsed(left, right));
    } else {
      return handleParsed(this._def.left._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      }), this._def.right._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      }));
    }
  }
}
ZodIntersection.create = (left, right, params) => {
  return new ZodIntersection({
    left,
    right,
    typeName: ZodFirstPartyTypeKind.ZodIntersection,
    ...processCreateParams(params)
  });
};

class ZodTuple extends ZodType {
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.array) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.array,
        received: ctx.parsedType
      });
      return INVALID;
    }
    if (ctx.data.length < this._def.items.length) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.too_small,
        minimum: this._def.items.length,
        inclusive: true,
        exact: false,
        type: "array"
      });
      return INVALID;
    }
    const rest = this._def.rest;
    if (!rest && ctx.data.length > this._def.items.length) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.too_big,
        maximum: this._def.items.length,
        inclusive: true,
        exact: false,
        type: "array"
      });
      status.dirty();
    }
    const items = [...ctx.data].map((item, itemIndex) => {
      const schema = this._def.items[itemIndex] || this._def.rest;
      if (!schema)
        return null;
      return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
    }).filter((x) => !!x);
    if (ctx.common.async) {
      return Promise.all(items).then((results) => {
        return ParseStatus.mergeArray(status, results);
      });
    } else {
      return ParseStatus.mergeArray(status, items);
    }
  }
  get items() {
    return this._def.items;
  }
  rest(rest) {
    return new ZodTuple({
      ...this._def,
      rest
    });
  }
}
ZodTuple.create = (schemas, params) => {
  if (!Array.isArray(schemas)) {
    throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
  }
  return new ZodTuple({
    items: schemas,
    typeName: ZodFirstPartyTypeKind.ZodTuple,
    rest: null,
    ...processCreateParams(params)
  });
};

class ZodRecord extends ZodType {
  get keySchema() {
    return this._def.keyType;
  }
  get valueSchema() {
    return this._def.valueType;
  }
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.object) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.object,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const pairs = [];
    const keyType = this._def.keyType;
    const valueType = this._def.valueType;
    for (const key in ctx.data) {
      pairs.push({
        key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
        value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
        alwaysSet: key in ctx.data
      });
    }
    if (ctx.common.async) {
      return ParseStatus.mergeObjectAsync(status, pairs);
    } else {
      return ParseStatus.mergeObjectSync(status, pairs);
    }
  }
  get element() {
    return this._def.valueType;
  }
  static create(first, second, third) {
    if (second instanceof ZodType) {
      return new ZodRecord({
        keyType: first,
        valueType: second,
        typeName: ZodFirstPartyTypeKind.ZodRecord,
        ...processCreateParams(third)
      });
    }
    return new ZodRecord({
      keyType: ZodString.create(),
      valueType: first,
      typeName: ZodFirstPartyTypeKind.ZodRecord,
      ...processCreateParams(second)
    });
  }
}

class ZodMap extends ZodType {
  get keySchema() {
    return this._def.keyType;
  }
  get valueSchema() {
    return this._def.valueType;
  }
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.map) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.map,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const keyType = this._def.keyType;
    const valueType = this._def.valueType;
    const pairs = [...ctx.data.entries()].map(([key, value], index) => {
      return {
        key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
        value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
      };
    });
    if (ctx.common.async) {
      const finalMap = new Map;
      return Promise.resolve().then(async () => {
        for (const pair of pairs) {
          const key = await pair.key;
          const value = await pair.value;
          if (key.status === "aborted" || value.status === "aborted") {
            return INVALID;
          }
          if (key.status === "dirty" || value.status === "dirty") {
            status.dirty();
          }
          finalMap.set(key.value, value.value);
        }
        return { status: status.value, value: finalMap };
      });
    } else {
      const finalMap = new Map;
      for (const pair of pairs) {
        const key = pair.key;
        const value = pair.value;
        if (key.status === "aborted" || value.status === "aborted") {
          return INVALID;
        }
        if (key.status === "dirty" || value.status === "dirty") {
          status.dirty();
        }
        finalMap.set(key.value, value.value);
      }
      return { status: status.value, value: finalMap };
    }
  }
}
ZodMap.create = (keyType, valueType, params) => {
  return new ZodMap({
    valueType,
    keyType,
    typeName: ZodFirstPartyTypeKind.ZodMap,
    ...processCreateParams(params)
  });
};

class ZodSet extends ZodType {
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.set) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.set,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const def = this._def;
    if (def.minSize !== null) {
      if (ctx.data.size < def.minSize.value) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.too_small,
          minimum: def.minSize.value,
          type: "set",
          inclusive: true,
          exact: false,
          message: def.minSize.message
        });
        status.dirty();
      }
    }
    if (def.maxSize !== null) {
      if (ctx.data.size > def.maxSize.value) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.too_big,
          maximum: def.maxSize.value,
          type: "set",
          inclusive: true,
          exact: false,
          message: def.maxSize.message
        });
        status.dirty();
      }
    }
    const valueType = this._def.valueType;
    function finalizeSet(elements2) {
      const parsedSet = new Set;
      for (const element of elements2) {
        if (element.status === "aborted")
          return INVALID;
        if (element.status === "dirty")
          status.dirty();
        parsedSet.add(element.value);
      }
      return { status: status.value, value: parsedSet };
    }
    const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
    if (ctx.common.async) {
      return Promise.all(elements).then((elements2) => finalizeSet(elements2));
    } else {
      return finalizeSet(elements);
    }
  }
  min(minSize, message) {
    return new ZodSet({
      ...this._def,
      minSize: { value: minSize, message: errorUtil.toString(message) }
    });
  }
  max(maxSize, message) {
    return new ZodSet({
      ...this._def,
      maxSize: { value: maxSize, message: errorUtil.toString(message) }
    });
  }
  size(size, message) {
    return this.min(size, message).max(size, message);
  }
  nonempty(message) {
    return this.min(1, message);
  }
}
ZodSet.create = (valueType, params) => {
  return new ZodSet({
    valueType,
    minSize: null,
    maxSize: null,
    typeName: ZodFirstPartyTypeKind.ZodSet,
    ...processCreateParams(params)
  });
};

class ZodFunction extends ZodType {
  constructor() {
    super(...arguments);
    this.validate = this.implement;
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.function) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.function,
        received: ctx.parsedType
      });
      return INVALID;
    }
    function makeArgsIssue(args, error2) {
      return makeIssue({
        data: args,
        path: ctx.path,
        errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
        issueData: {
          code: ZodIssueCode.invalid_arguments,
          argumentsError: error2
        }
      });
    }
    function makeReturnsIssue(returns, error2) {
      return makeIssue({
        data: returns,
        path: ctx.path,
        errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
        issueData: {
          code: ZodIssueCode.invalid_return_type,
          returnTypeError: error2
        }
      });
    }
    const params = { errorMap: ctx.common.contextualErrorMap };
    const fn = ctx.data;
    if (this._def.returns instanceof ZodPromise) {
      const me = this;
      return OK(async function(...args) {
        const error2 = new ZodError([]);
        const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
          error2.addIssue(makeArgsIssue(args, e));
          throw error2;
        });
        const result = await Reflect.apply(fn, this, parsedArgs);
        const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
          error2.addIssue(makeReturnsIssue(result, e));
          throw error2;
        });
        return parsedReturns;
      });
    } else {
      const me = this;
      return OK(function(...args) {
        const parsedArgs = me._def.args.safeParse(args, params);
        if (!parsedArgs.success) {
          throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
        }
        const result = Reflect.apply(fn, this, parsedArgs.data);
        const parsedReturns = me._def.returns.safeParse(result, params);
        if (!parsedReturns.success) {
          throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
        }
        return parsedReturns.data;
      });
    }
  }
  parameters() {
    return this._def.args;
  }
  returnType() {
    return this._def.returns;
  }
  args(...items) {
    return new ZodFunction({
      ...this._def,
      args: ZodTuple.create(items).rest(ZodUnknown.create())
    });
  }
  returns(returnType) {
    return new ZodFunction({
      ...this._def,
      returns: returnType
    });
  }
  implement(func) {
    const validatedFunc = this.parse(func);
    return validatedFunc;
  }
  strictImplement(func) {
    const validatedFunc = this.parse(func);
    return validatedFunc;
  }
  static create(args, returns, params) {
    return new ZodFunction({
      args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
      returns: returns || ZodUnknown.create(),
      typeName: ZodFirstPartyTypeKind.ZodFunction,
      ...processCreateParams(params)
    });
  }
}

class ZodLazy extends ZodType {
  get schema() {
    return this._def.getter();
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const lazySchema = this._def.getter();
    return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
  }
}
ZodLazy.create = (getter, params) => {
  return new ZodLazy({
    getter,
    typeName: ZodFirstPartyTypeKind.ZodLazy,
    ...processCreateParams(params)
  });
};

class ZodLiteral extends ZodType {
  _parse(input) {
    if (input.data !== this._def.value) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        received: ctx.data,
        code: ZodIssueCode.invalid_literal,
        expected: this._def.value
      });
      return INVALID;
    }
    return { status: "valid", value: input.data };
  }
  get value() {
    return this._def.value;
  }
}
ZodLiteral.create = (value, params) => {
  return new ZodLiteral({
    value,
    typeName: ZodFirstPartyTypeKind.ZodLiteral,
    ...processCreateParams(params)
  });
};
function createZodEnum(values, params) {
  return new ZodEnum({
    values,
    typeName: ZodFirstPartyTypeKind.ZodEnum,
    ...processCreateParams(params)
  });
}

class ZodEnum extends ZodType {
  _parse(input) {
    if (typeof input.data !== "string") {
      const ctx = this._getOrReturnCtx(input);
      const expectedValues = this._def.values;
      addIssueToContext(ctx, {
        expected: util.joinValues(expectedValues),
        received: ctx.parsedType,
        code: ZodIssueCode.invalid_type
      });
      return INVALID;
    }
    if (!this._cache) {
      this._cache = new Set(this._def.values);
    }
    if (!this._cache.has(input.data)) {
      const ctx = this._getOrReturnCtx(input);
      const expectedValues = this._def.values;
      addIssueToContext(ctx, {
        received: ctx.data,
        code: ZodIssueCode.invalid_enum_value,
        options: expectedValues
      });
      return INVALID;
    }
    return OK(input.data);
  }
  get options() {
    return this._def.values;
  }
  get enum() {
    const enumValues = {};
    for (const val of this._def.values) {
      enumValues[val] = val;
    }
    return enumValues;
  }
  get Values() {
    const enumValues = {};
    for (const val of this._def.values) {
      enumValues[val] = val;
    }
    return enumValues;
  }
  get Enum() {
    const enumValues = {};
    for (const val of this._def.values) {
      enumValues[val] = val;
    }
    return enumValues;
  }
  extract(values, newDef = this._def) {
    return ZodEnum.create(values, {
      ...this._def,
      ...newDef
    });
  }
  exclude(values, newDef = this._def) {
    return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
      ...this._def,
      ...newDef
    });
  }
}
ZodEnum.create = createZodEnum;

class ZodNativeEnum extends ZodType {
  _parse(input) {
    const nativeEnumValues = util.getValidEnumValues(this._def.values);
    const ctx = this._getOrReturnCtx(input);
    if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
      const expectedValues = util.objectValues(nativeEnumValues);
      addIssueToContext(ctx, {
        expected: util.joinValues(expectedValues),
        received: ctx.parsedType,
        code: ZodIssueCode.invalid_type
      });
      return INVALID;
    }
    if (!this._cache) {
      this._cache = new Set(util.getValidEnumValues(this._def.values));
    }
    if (!this._cache.has(input.data)) {
      const expectedValues = util.objectValues(nativeEnumValues);
      addIssueToContext(ctx, {
        received: ctx.data,
        code: ZodIssueCode.invalid_enum_value,
        options: expectedValues
      });
      return INVALID;
    }
    return OK(input.data);
  }
  get enum() {
    return this._def.values;
  }
}
ZodNativeEnum.create = (values, params) => {
  return new ZodNativeEnum({
    values,
    typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
    ...processCreateParams(params)
  });
};

class ZodPromise extends ZodType {
  unwrap() {
    return this._def.type;
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.promise,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
    return OK(promisified.then((data) => {
      return this._def.type.parseAsync(data, {
        path: ctx.path,
        errorMap: ctx.common.contextualErrorMap
      });
    }));
  }
}
ZodPromise.create = (schema, params) => {
  return new ZodPromise({
    type: schema,
    typeName: ZodFirstPartyTypeKind.ZodPromise,
    ...processCreateParams(params)
  });
};

class ZodEffects extends ZodType {
  innerType() {
    return this._def.schema;
  }
  sourceType() {
    return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
  }
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    const effect = this._def.effect || null;
    const checkCtx = {
      addIssue: (arg) => {
        addIssueToContext(ctx, arg);
        if (arg.fatal) {
          status.abort();
        } else {
          status.dirty();
        }
      },
      get path() {
        return ctx.path;
      }
    };
    checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
    if (effect.type === "preprocess") {
      const processed = effect.transform(ctx.data, checkCtx);
      if (ctx.common.async) {
        return Promise.resolve(processed).then(async (processed2) => {
          if (status.value === "aborted")
            return INVALID;
          const result = await this._def.schema._parseAsync({
            data: processed2,
            path: ctx.path,
            parent: ctx
          });
          if (result.status === "aborted")
            return INVALID;
          if (result.status === "dirty")
            return DIRTY(result.value);
          if (status.value === "dirty")
            return DIRTY(result.value);
          return result;
        });
      } else {
        if (status.value === "aborted")
          return INVALID;
        const result = this._def.schema._parseSync({
          data: processed,
          path: ctx.path,
          parent: ctx
        });
        if (result.status === "aborted")
          return INVALID;
        if (result.status === "dirty")
          return DIRTY(result.value);
        if (status.value === "dirty")
          return DIRTY(result.value);
        return result;
      }
    }
    if (effect.type === "refinement") {
      const executeRefinement = (acc) => {
        const result = effect.refinement(acc, checkCtx);
        if (ctx.common.async) {
          return Promise.resolve(result);
        }
        if (result instanceof Promise) {
          throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
        }
        return acc;
      };
      if (ctx.common.async === false) {
        const inner = this._def.schema._parseSync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        });
        if (inner.status === "aborted")
          return INVALID;
        if (inner.status === "dirty")
          status.dirty();
        executeRefinement(inner.value);
        return { status: status.value, value: inner.value };
      } else {
        return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
          if (inner.status === "aborted")
            return INVALID;
          if (inner.status === "dirty")
            status.dirty();
          return executeRefinement(inner.value).then(() => {
            return { status: status.value, value: inner.value };
          });
        });
      }
    }
    if (effect.type === "transform") {
      if (ctx.common.async === false) {
        const base = this._def.schema._parseSync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        });
        if (!isValid(base))
          return INVALID;
        const result = effect.transform(base.value, checkCtx);
        if (result instanceof Promise) {
          throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
        }
        return { status: status.value, value: result };
      } else {
        return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
          if (!isValid(base))
            return INVALID;
          return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
            status: status.value,
            value: result
          }));
        });
      }
    }
    util.assertNever(effect);
  }
}
ZodEffects.create = (schema, effect, params) => {
  return new ZodEffects({
    schema,
    typeName: ZodFirstPartyTypeKind.ZodEffects,
    effect,
    ...processCreateParams(params)
  });
};
ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
  return new ZodEffects({
    schema,
    effect: { type: "preprocess", transform: preprocess },
    typeName: ZodFirstPartyTypeKind.ZodEffects,
    ...processCreateParams(params)
  });
};
class ZodOptional extends ZodType {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType === ZodParsedType.undefined) {
      return OK(undefined);
    }
    return this._def.innerType._parse(input);
  }
  unwrap() {
    return this._def.innerType;
  }
}
ZodOptional.create = (type, params) => {
  return new ZodOptional({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodOptional,
    ...processCreateParams(params)
  });
};

class ZodNullable extends ZodType {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType === ZodParsedType.null) {
      return OK(null);
    }
    return this._def.innerType._parse(input);
  }
  unwrap() {
    return this._def.innerType;
  }
}
ZodNullable.create = (type, params) => {
  return new ZodNullable({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodNullable,
    ...processCreateParams(params)
  });
};

class ZodDefault extends ZodType {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    let data = ctx.data;
    if (ctx.parsedType === ZodParsedType.undefined) {
      data = this._def.defaultValue();
    }
    return this._def.innerType._parse({
      data,
      path: ctx.path,
      parent: ctx
    });
  }
  removeDefault() {
    return this._def.innerType;
  }
}
ZodDefault.create = (type, params) => {
  return new ZodDefault({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodDefault,
    defaultValue: typeof params.default === "function" ? params.default : () => params.default,
    ...processCreateParams(params)
  });
};

class ZodCatch extends ZodType {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const newCtx = {
      ...ctx,
      common: {
        ...ctx.common,
        issues: []
      }
    };
    const result = this._def.innerType._parse({
      data: newCtx.data,
      path: newCtx.path,
      parent: {
        ...newCtx
      }
    });
    if (isAsync(result)) {
      return result.then((result2) => {
        return {
          status: "valid",
          value: result2.status === "valid" ? result2.value : this._def.catchValue({
            get error() {
              return new ZodError(newCtx.common.issues);
            },
            input: newCtx.data
          })
        };
      });
    } else {
      return {
        status: "valid",
        value: result.status === "valid" ? result.value : this._def.catchValue({
          get error() {
            return new ZodError(newCtx.common.issues);
          },
          input: newCtx.data
        })
      };
    }
  }
  removeCatch() {
    return this._def.innerType;
  }
}
ZodCatch.create = (type, params) => {
  return new ZodCatch({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodCatch,
    catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
    ...processCreateParams(params)
  });
};

class ZodNaN extends ZodType {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.nan) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.nan,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return { status: "valid", value: input.data };
  }
}
ZodNaN.create = (params) => {
  return new ZodNaN({
    typeName: ZodFirstPartyTypeKind.ZodNaN,
    ...processCreateParams(params)
  });
};
var BRAND = Symbol("zod_brand");

class ZodBranded extends ZodType {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const data = ctx.data;
    return this._def.type._parse({
      data,
      path: ctx.path,
      parent: ctx
    });
  }
  unwrap() {
    return this._def.type;
  }
}

class ZodPipeline extends ZodType {
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.common.async) {
      const handleAsync = async () => {
        const inResult = await this._def.in._parseAsync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        });
        if (inResult.status === "aborted")
          return INVALID;
        if (inResult.status === "dirty") {
          status.dirty();
          return DIRTY(inResult.value);
        } else {
          return this._def.out._parseAsync({
            data: inResult.value,
            path: ctx.path,
            parent: ctx
          });
        }
      };
      return handleAsync();
    } else {
      const inResult = this._def.in._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      });
      if (inResult.status === "aborted")
        return INVALID;
      if (inResult.status === "dirty") {
        status.dirty();
        return {
          status: "dirty",
          value: inResult.value
        };
      } else {
        return this._def.out._parseSync({
          data: inResult.value,
          path: ctx.path,
          parent: ctx
        });
      }
    }
  }
  static create(a, b) {
    return new ZodPipeline({
      in: a,
      out: b,
      typeName: ZodFirstPartyTypeKind.ZodPipeline
    });
  }
}

class ZodReadonly extends ZodType {
  _parse(input) {
    const result = this._def.innerType._parse(input);
    const freeze = (data) => {
      if (isValid(data)) {
        data.value = Object.freeze(data.value);
      }
      return data;
    };
    return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
  }
  unwrap() {
    return this._def.innerType;
  }
}
ZodReadonly.create = (type, params) => {
  return new ZodReadonly({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodReadonly,
    ...processCreateParams(params)
  });
};
function cleanParams(params, data) {
  const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
  const p2 = typeof p === "string" ? { message: p } : p;
  return p2;
}
function custom(check, _params = {}, fatal) {
  if (check)
    return ZodAny.create().superRefine((data, ctx) => {
      const r = check(data);
      if (r instanceof Promise) {
        return r.then((r2) => {
          if (!r2) {
            const params = cleanParams(_params, data);
            const _fatal = params.fatal ?? fatal ?? true;
            ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
          }
        });
      }
      if (!r) {
        const params = cleanParams(_params, data);
        const _fatal = params.fatal ?? fatal ?? true;
        ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
      }
      return;
    });
  return ZodAny.create();
}
var late = {
  object: ZodObject.lazycreate
};
var ZodFirstPartyTypeKind;
(function(ZodFirstPartyTypeKind2) {
  ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
  ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
  ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
  ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
  ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
  ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
  ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
  ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
  ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
  ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
  ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
  ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
  ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
  ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
  ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
  ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
  ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
  ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
  ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
  ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
  ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
  ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
  ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
  ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
  ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
  ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
  ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
  ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
  ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
  ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
  ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
  ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
  ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
  ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
  ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
  ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
var instanceOfType = (cls, params = {
  message: `Input not instance of ${cls.name}`
}) => custom((data) => data instanceof cls, params);
var stringType = ZodString.create;
var numberType = ZodNumber.create;
var nanType = ZodNaN.create;
var bigIntType = ZodBigInt.create;
var booleanType = ZodBoolean.create;
var dateType = ZodDate.create;
var symbolType = ZodSymbol.create;
var undefinedType = ZodUndefined.create;
var nullType = ZodNull.create;
var anyType = ZodAny.create;
var unknownType = ZodUnknown.create;
var neverType = ZodNever.create;
var voidType = ZodVoid.create;
var arrayType = ZodArray.create;
var objectType = ZodObject.create;
var strictObjectType = ZodObject.strictCreate;
var unionType = ZodUnion.create;
var discriminatedUnionType = ZodDiscriminatedUnion.create;
var intersectionType = ZodIntersection.create;
var tupleType = ZodTuple.create;
var recordType = ZodRecord.create;
var mapType = ZodMap.create;
var setType = ZodSet.create;
var functionType = ZodFunction.create;
var lazyType = ZodLazy.create;
var literalType = ZodLiteral.create;
var enumType = ZodEnum.create;
var nativeEnumType = ZodNativeEnum.create;
var promiseType = ZodPromise.create;
var effectsType = ZodEffects.create;
var optionalType = ZodOptional.create;
var nullableType = ZodNullable.create;
var preprocessType = ZodEffects.createWithPreprocess;
var pipelineType = ZodPipeline.create;
var ostring = () => stringType().optional();
var onumber = () => numberType().optional();
var oboolean = () => booleanType().optional();
var coerce = {
  string: (arg) => ZodString.create({ ...arg, coerce: true }),
  number: (arg) => ZodNumber.create({ ...arg, coerce: true }),
  boolean: (arg) => ZodBoolean.create({
    ...arg,
    coerce: true
  }),
  bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }),
  date: (arg) => ZodDate.create({ ...arg, coerce: true })
};
var NEVER = INVALID;
// src/integrations/harnesses/ids.ts
var HARNESS_ID_TABLE = [
  { id: "opencode", agentDispatch: true, enforcesModelWorkTools: true },
  { id: "claude", agentDispatch: true, enforcesModelWorkTools: true },
  { id: "opencode-sdk", agentDispatch: true, enforcesModelWorkTools: true },
  { id: "codex", agentDispatch: true, enforcesModelWorkTools: false },
  { id: "copilot", agentDispatch: true, enforcesModelWorkTools: false },
  { id: "pi", agentDispatch: true, enforcesModelWorkTools: false },
  { id: "gemini", agentDispatch: true, enforcesModelWorkTools: false },
  { id: "aider", agentDispatch: true, enforcesModelWorkTools: false },
  { id: "amazonq", agentDispatch: true, enforcesModelWorkTools: false },
  { id: "openhands", agentDispatch: true, enforcesModelWorkTools: false }
];
var VALID_HARNESS_IDS = Object.freeze(HARNESS_ID_TABLE.map((h) => h.id));
var HARNESS_AGENT_DISPATCH_IDS = new Set(HARNESS_ID_TABLE.filter((h) => h.agentDispatch).map((h) => h.id));
var HARNESS_MODEL_WORK_IDS = new Set(HARNESS_ID_TABLE.filter((h) => h.enforcesModelWorkTools).map((h) => h.id));

// src/core/extra-params.ts
var EXTRA_PARAMS_PROTECTED_TOP_LEVEL_KEYS = [
  "model",
  "messages",
  "temperature",
  "maxtokens",
  "responseformat",
  "stream",
  "streamoptions",
  "enablethinking",
  "reasoningeffort",
  "chattemplatekwargs"
];
var EXTRA_PARAMS_CREDENTIAL_KEYS = [
  "authorization",
  "headers",
  "apikey",
  "token",
  "password",
  "secret",
  "cookie",
  "setcookie"
];
var PROTECTED_TOP_LEVEL_KEYS = new Set(EXTRA_PARAMS_PROTECTED_TOP_LEVEL_KEYS);
var CREDENTIAL_KEYS = new Set(EXTRA_PARAMS_CREDENTIAL_KEYS);
var LEGACY_EXTRA_PARAMS_FIELD = {
  model: "model",
  temperature: "temperature",
  maxtokens: "maxTokens",
  enablethinking: "enableThinking",
  reasoningeffort: "reasoningEffort"
};
var LIFTABLE_EXTRA_PARAMS_KEYS = new Set(["temperature", "maxtokens", "enablethinking", "reasoningeffort"]);
var EXTRA_PARAMS_NO_FIELD_REMEDY = {
  messages: "AKM builds the request messages internally — remove it from extraParams",
  responseformat: "AKM controls the response format internally — remove it from extraParams",
  stream: "AKM controls streaming internally — remove it from extraParams",
  streamoptions: "AKM controls streaming internally — remove it from extraParams",
  chattemplatekwargs: "set engines.<name>.enableThinking instead of chat_template_kwargs.enable_thinking"
};
function protectedKeyRemedy(normalized) {
  const field = LEGACY_EXTRA_PARAMS_FIELD[normalized];
  if (field) {
    const note = normalized === "reasoningeffort" ? " (moved to a first-class field in 0.9.2)" : "";
    return `set engines.<name>.${field} instead${note}`;
  }
  return EXTRA_PARAMS_NO_FIELD_REMEDY[normalized];
}
function normalizeExtraParamKey(key) {
  return key.toLowerCase().replace(/[^a-z0-9]/g, "");
}
function validateExtraParams(value) {
  if (!value || typeof value !== "object" || Array.isArray(value)) {
    return [{ path: [], message: "must be an object" }];
  }
  const issues = [];
  const seen = new WeakSet;
  const visit2 = (entry, path12) => {
    if (Array.isArray(entry)) {
      if (seen.has(entry))
        return;
      seen.add(entry);
      entry.forEach((child, index) => {
        visit2(child, [...path12, index]);
      });
      return;
    }
    if (!entry || typeof entry !== "object")
      return;
    if (seen.has(entry))
      return;
    seen.add(entry);
    for (const [key, child] of Object.entries(entry)) {
      const normalized = normalizeExtraParamKey(key);
      if (path12.length === 0 && PROTECTED_TOP_LEVEL_KEYS.has(normalized)) {
        const remedy = protectedKeyRemedy(normalized);
        issues.push({
          path: [key],
          message: remedy ? `${key} is protected by AKM — ${remedy}.` : `${key} is protected by AKM`
        });
      }
      if (CREDENTIAL_KEYS.has(normalized)) {
        issues.push({ path: [...path12, key], message: `${key} cannot carry credentials` });
      }
      visit2(child, [...path12, key]);
    }
  };
  visit2(value, []);
  return issues;
}
function formatExtraParamsIssue(label, issue) {
  const suffix = issue.path.map((part) => typeof part === "number" ? `[${part}]` : `.${part}`).join("");
  return `${label}${suffix} ${issue.message}`;
}
function liftLegacyEngineExtraParams(raw) {
  const lifted = [];
  const conflicts = [];
  const rawEngines = raw.engines;
  if (!isRecord(rawEngines)) {
    return { config: raw, lifted, conflicts };
  }
  const engines = {};
  let anyEngineChanged = false;
  for (const [name, engineValue] of Object.entries(rawEngines)) {
    if (!isRecord(engineValue) || !isRecord(engineValue.extraParams)) {
      engines[name] = engineValue;
      continue;
    }
    const engine = { ...engineValue };
    const extraParams = { ...engineValue.extraParams };
    let engineChanged = false;
    for (const [rawKey, value] of Object.entries(engineValue.extraParams)) {
      const normalized = normalizeExtraParamKey(rawKey);
      if (!LIFTABLE_EXTRA_PARAMS_KEYS.has(normalized))
        continue;
      const field = LEGACY_EXTRA_PARAMS_FIELD[normalized];
      if (!field)
        continue;
      const existing = engine[field];
      if (existing !== undefined && existing !== value) {
        conflicts.push({ engine: name, key: rawKey, field, extraParamsValue: value, fieldValue: existing });
        continue;
      }
      delete extraParams[rawKey];
      engineChanged = true;
      if (existing === value) {
        lifted.push(`engines.${name}.extraParams.${rawKey} is redundant — engines.${name}.${field} is already set to the same value; dropped the extraParams entry`);
        continue;
      }
      engine[field] = value;
      lifted.push(`engines.${name}.extraParams.${rawKey} -> engines.${name}.${field}`);
    }
    if (!engineChanged) {
      engines[name] = engineValue;
      continue;
    }
    anyEngineChanged = true;
    if (Object.keys(extraParams).length > 0) {
      engine.extraParams = extraParams;
    } else {
      delete engine.extraParams;
    }
    engines[name] = engine;
  }
  if (!anyEngineChanged) {
    return { config: raw, lifted, conflicts };
  }
  return { config: { ...raw, engines }, lifted, conflicts };
}

// src/core/config/schema/primitives.ts
var CURRENT_CONFIG_VERSION = "0.9.0";
var positiveInt = exports_external.number().int().positive();
var nonNegativeNumber = exports_external.number().finite().min(0);
var nonEmptyString = exports_external.string().min(1).refine((v) => v.trim().length > 0, { message: "expected a non-empty string" });
var httpUrl = exports_external.string().refine((v) => v.startsWith("http://") || v.startsWith("https://"), {
  message: "endpoint must start with http:// or https://"
});
var ENGINE_NAME_PATTERN = new RegExp(ENGINE_NAME_PATTERN_SOURCE);
var ENV_REFERENCE_PATTERN = /^\$[A-Za-z_][A-Za-z0-9_]*$|^\$\{[A-Za-z_][A-Za-z0-9_]*\}$/;
var SECRET_STORE_REFERENCE_PATTERN = /^secret:\/\/(.+)$/;
var engineName = exports_external.string().max(63).regex(ENGINE_NAME_PATTERN, "names must be lowercase kebab-case and must not begin with reserved akm-");
function isApiKeyReference(value) {
  return ENV_REFERENCE_PATTERN.test(value) || SECRET_STORE_REFERENCE_PATTERN.test(value);
}
function symbolicOrWarnApiKey(label) {
  return exports_external.string().superRefine((value) => {
    if (isApiKeyReference(value))
      return;
    warnOnce(`config:literal-api-key:${label}`, `A ${label} in config.json is a literal API key, not a $VAR/\${VAR}/secret:// reference; using it as configured. Prefer \`akm config set ...apiKey '$VAR'\` (with the corresponding env var set) or \`secret://<name>\` (with \`akm secret set <name> ...\`) — see docs/reference/data-and-telemetry.md.`);
  });
}
var chatCompletionsEndpoint = exports_external.string().superRefine((value, ctx) => {
  let url;
  try {
    url = new URL(value);
  } catch {
    ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "endpoint must be a complete URL" });
    return;
  }
  if (url.protocol !== "http:" && url.protocol !== "https:") {
    ctx.addIssue({ code: exports_external.ZodIssueCode.custom, message: "endpoint must use http:// or https://" });
    return;
  }
  if (url.username || url.password) {
    warnOnce(`chatCompletionsEndpoint:userinfo:${value}`, `Config endpoint "${value}" embeds a username/password; consider moving the credential to the engine's apiKey field instead.`);
  }
  if (!url.pathname.endsWith("/chat/completions")) {
    warnOnce(`chatCompletionsEndpoint:path:${value}`, `Config endpoint "${value}" does not end in /chat/completions; using it as configured.`);
  }
});
var ExtraParamsSchema = exports_external.record(exports_external.unknown()).superRefine((value, ctx) => {
  for (const issue of validateExtraParams(value)) {
    ctx.addIssue({ code: exports_external.ZodIssueCode.custom, path: issue.path, message: issue.message });
  }
});
var LlmInvocationOverridesSchema = exports_external.object({
  temperature: exports_external.number().finite().optional(),
  maxTokens: positiveInt.optional(),
  supportsJsonSchema: exports_external.boolean().optional(),
  extraParams: ExtraParamsSchema.optional(),
  contextLength: positiveInt.optional(),
  enableThinking: exports_external.boolean().optional(),
  reasoningEffort: nonEmptyString.optional()
}).passthrough();

// src/core/config/schema/embedding.ts
var EmbeddingOllamaOptionsSchema = exports_external.object({
  num_ctx: positiveInt.optional()
}).passthrough();
var EmbeddingConnectionConfigSchema = exports_external.object({
  provider: exports_external.string().optional(),
  endpoint: exports_external.string().optional(),
  model: exports_external.string().optional(),
  apiKey: symbolicOrWarnApiKey("embedding.apiKey").optional(),
  dimension: positiveInt.optional(),
  localModel: exports_external.string().min(1).optional(),
  maxInputTokens: positiveInt.optional(),
  maxTokens: positiveInt.optional(),
  batchSize: positiveInt.optional(),
  contextLength: positiveInt.optional(),
  ollamaOptions: EmbeddingOllamaOptionsSchema.optional(),
  timeoutMs: positiveInt.optional(),
  queryTimeoutMs: positiveInt.optional(),
  queryTemplate: exports_external.string().optional(),
  documentTemplate: exports_external.string().optional(),
  concurrency: positiveInt.max(16).optional()
}).passthrough();

// src/execution/limits.ts
var EXECUTION_MAX_TIMEOUT_MS = 2 ** 31 - 1;

// src/workflows/resource-limits.ts
var WORKFLOW_MAX_SOURCE_BYTES = 1024 * 1024;
var WORKFLOW_MAX_INSTRUCTION_BYTES = 256 * 1024;
var WORKFLOW_MAX_SCHEMA_BYTES = 256 * 1024;
var WORKFLOW_MAX_EXTRA_PARAMS_BYTES = 64 * 1024;
var WORKFLOW_MAX_CONCURRENCY = 64;
var WORKFLOW_MAX_TIMEOUT_MS = EXECUTION_MAX_TIMEOUT_MS;
var WORKFLOW_ENGINE_NAME_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
var WORKFLOW_MAX_ENGINE_NAME_LENGTH = 63;
var WORKFLOW_ENV_VAR_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
var WORKFLOW_MAX_EXEC_OUTPUT_BYTES = 8 * 1024 * 1024;
var EXEC_CONTEXT_LIMITS_POSIX = {
  perVarBytes: 96 * 1024,
  totalBytes: 128 * 1024,
  source: "Linux caps one argv/environ string at MAX_ARG_STRLEN (32 pages = 131 072 bytes) and macOS caps argv+environ at ARG_MAX (256 KiB)"
};
function utf8Bytes(value) {
  return Buffer.byteLength(value, "utf8");
}
function jsonBytes(value) {
  return utf8Bytes(JSON.stringify(value));
}

// src/core/config/schema/engines.ts
var timeoutMsField = exports_external.union([positiveInt.max(WORKFLOW_MAX_TIMEOUT_MS), exports_external.null()]).optional();
var LlmConnectionConfigSchema = exports_external.object({
  provider: exports_external.string().optional(),
  endpoint: exports_external.string(),
  model: exports_external.string(),
  apiKey: exports_external.string().optional(),
  temperature: exports_external.number().finite().optional(),
  maxTokens: positiveInt.optional(),
  timeoutMs: timeoutMsField,
  concurrency: positiveInt.optional(),
  supportsJsonSchema: exports_external.boolean().optional(),
  extraParams: ExtraParamsSchema.optional(),
  contextLength: positiveInt.optional(),
  enableThinking: exports_external.boolean().optional(),
  reasoningEffort: nonEmptyString.optional()
}).passthrough();
var LlmProfileConfigSchema = LlmConnectionConfigSchema.passthrough();
var AgentPlatformSchema = exports_external.enum(VALID_HARNESS_IDS);
var LlmEngineSchema = exports_external.object({
  kind: exports_external.literal("llm"),
  provider: exports_external.string().optional(),
  endpoint: chatCompletionsEndpoint,
  model: nonEmptyString,
  apiKey: symbolicOrWarnApiKey("engines.<name>.apiKey").optional(),
  apiKeyFile: nonEmptyString.optional(),
  temperature: exports_external.number().finite().optional(),
  maxTokens: positiveInt.optional(),
  timeoutMs: timeoutMsField,
  concurrency: positiveInt.optional(),
  supportsJsonSchema: exports_external.boolean().optional(),
  extraParams: ExtraParamsSchema.optional(),
  contextLength: positiveInt.optional(),
  enableThinking: exports_external.boolean().optional(),
  reasoningEffort: nonEmptyString.optional()
}).passthrough().superRefine((value, ctx) => {
  for (const key of ["platform", "bin", "args", "workspace", "modelAliases", "llmEngine"]) {
    if (key in value)
      ctx.addIssue({ code: exports_external.ZodIssueCode.custom, path: [key], message: `${key} is not valid on an LLM engine` });
  }
  if (value.apiKey !== undefined && value.apiKeyFile !== undefined) {
    ctx.addIssue({
      code: exports_external.ZodIssueCode.custom,
      path: ["apiKeyFile"],
      message: "apiKey and apiKeyFile cannot both be set"
    });
  }
});
var AgentEngineSchema = exports_external.object({
  kind: exports_external.literal("agent"),
  platform: AgentPlatformSchema.refine((platform) => HARNESS_AGENT_DISPATCH_IDS.has(platform), {
    message: "platform does not support agent dispatch"
  }),
  bin: nonEmptyString.optional(),
  args: exports_external.array(exports_external.string()).optional(),
  workspace: nonEmptyString.optional(),
  model: nonEmptyString.optional(),
  timeoutMs: timeoutMsField,
  llmEngine: engineName.optional()
}).passthrough().superRefine((value, ctx) => {
  for (const key of [
    "provider",
    "endpoint",
    "apiKey",
    "apiKeyFile",
    "temperature",
    "maxTokens",
    "concurrency",
    "extraParams",
    "contextLength",
    "enableThinking",
    "reasoningEffort",
    "modelAliases"
  ]) {
    if (key in value)
      ctx.addIssue({ code: exports_external.ZodIssueCode.custom, path: [key], message: `${key} is not valid on an agent engine` });
  }
  if (value.platform !== "opencode-sdk" && value.llmEngine !== undefined) {
    ctx.addIssue({
      code: exports_external.ZodIssueCode.custom,
      path: ["llmEngine"],
      message: "llmEngine is only valid on opencode-sdk"
    });
  }
  if (value.platform === "opencode-sdk" && value.args !== undefined) {
    ctx.addIssue({ code: exports_external.ZodIssueCode.custom, path: ["args"], message: "args is not valid on opencode-sdk" });
  }
});
var EngineConfigSchema = exports_external.union([LlmEngineSchema, AgentEngineSchema]);
var EnginesSchema = exports_external.record(engineName, EngineConfigSchema);

// src/core/config/schema/execution.ts
var toolName = exports_external.string().trim().min(1, "expected a non-empty tool name");
var ExecutionPolicyConfigSchema = exports_external.object({
  allowedTools: exports_external.array(toolName).default([]).superRefine((tools, ctx) => {
    const seen = new Set;
    for (const [index, tool] of tools.entries()) {
      if (seen.has(tool)) {
        ctx.addIssue({ code: exports_external.ZodIssueCode.custom, path: [index], message: "duplicates an earlier tool name" });
      }
      seen.add(tool);
    }
  })
}).passthrough();

// src/core/config/schema/experimental.ts
var ExperimentalConfigSchema = exports_external.object({
  improveAutonomy: exports_external.boolean().optional()
}).passthrough();

// src/core/config/schema/feedback.ts
var FeedbackConfigSchema = exports_external.object({
  requireReason: exports_external.boolean().optional(),
  allowedFailureModes: exports_external.array(nonEmptyString).optional()
}).passthrough();

// src/core/config/schema/improve-processes.ts
var IMPROVE_PROCESS_BASE_FIELDS = {
  engine: engineName.optional(),
  model: nonEmptyString.optional(),
  llm: LlmInvocationOverridesSchema.optional(),
  enabled: exports_external.boolean().optional(),
  timeoutMs: exports_external.union([positiveInt, exports_external.null()]).optional()
};
var allowedTypesField = exports_external.array(exports_external.string().min(1)).optional();
var excludeRefPrefixesField = exports_external.array(exports_external.string().min(1)).optional();
var processLimitField = positiveInt.optional();
var qualityGateField = exports_external.object({
  enabled: exports_external.boolean().optional(),
  engine: engineName.optional(),
  model: nonEmptyString.optional(),
  timeoutMs: exports_external.union([positiveInt, exports_external.null()]).optional(),
  llm: LlmInvocationOverridesSchema.passthrough().optional()
}).passthrough().optional();
var clsField = exports_external.object({
  enabled: exports_external.boolean().optional(),
  adjacentCount: exports_external.number().int().min(1).optional()
}).passthrough().optional();
var fidelityCheckField = exports_external.object({ enabled: exports_external.boolean().optional() }).passthrough().optional();
var lowValueFilterField = exports_external.object({ enabled: exports_external.boolean().optional() }).passthrough().optional();
var defectFilterField = exports_external.object({
  placeholders: exports_external.array(nonEmptyString).optional(),
  metaCommentary: exports_external.array(nonEmptyString).optional(),
  frontmatterKeys: exports_external.array(nonEmptyString).optional()
}).passthrough().optional();
var extractTriageGateField = exports_external.object({
  enabled: exports_external.boolean().optional(),
  minScore: exports_external.number().min(0).optional()
}).passthrough().optional();
var triageJudgmentLlmOverridesField = LlmInvocationOverridesSchema.passthrough();
var triageJudgmentObjectField = exports_external.object({
  enabled: exports_external.boolean().optional(),
  engine: engineName.optional(),
  model: nonEmptyString.optional(),
  timeoutMs: exports_external.union([positiveInt, exports_external.null()]).optional(),
  llm: triageJudgmentLlmOverridesField.optional()
}).passthrough();
var triageJudgmentField = exports_external.union([exports_external.boolean(), triageJudgmentObjectField]).transform((value) => typeof value === "boolean" ? { enabled: value } : { ...value, enabled: value.enabled ?? true }).optional();
var antiCollapseField = exports_external.object({
  enabled: exports_external.boolean().optional(),
  randomClusterFraction: exports_external.number().min(0).max(1).optional()
}).passthrough().optional();
var REFLECT_PROCESS_FIELDS = {
  allowedTypes: allowedTypesField,
  excludeRefPrefixes: excludeRefPrefixesField,
  limit: processLimitField,
  qualityGate: qualityGateField,
  lowValueFilter: lowValueFilterField,
  defectFilter: defectFilterField
};
var DISTILL_PROCESS_FIELDS = {
  allowedTypes: allowedTypesField,
  limit: processLimitField,
  qualityGate: qualityGateField,
  requirePlannedRefs: exports_external.boolean().optional(),
  cls: clsField,
  fidelityCheck: fidelityCheckField
};
var CONSOLIDATE_PROCESS_FIELDS = {
  allowedTypes: allowedTypesField,
  limit: processLimitField,
  minPoolSize: exports_external.number().int().min(0).optional(),
  maxChunkSize: exports_external.number().int().min(1).max(50).optional(),
  p90ChunkSecondsDefault: exports_external.number().finite().positive().optional(),
  antiCollapse: antiCollapseField
};
var MEMORY_INFERENCE_PROCESS_FIELDS = {
  minPendingCount: exports_external.number().int().min(0).optional(),
  cls: clsField
};
var EXTRACT_PROCESS_FIELDS = {
  defaultSince: exports_external.string().min(1).optional(),
  maxTotalChars: positiveInt.optional(),
  minContentChars: exports_external.number().int().min(0).optional(),
  triage: extractTriageGateField,
  minNewSessions: exports_external.number().int().min(0).optional(),
  maxSessionsPerRun: exports_external.number().int().min(0).optional(),
  indexSessions: exports_external.boolean().optional(),
  minSessionDuration: exports_external.number().min(0).optional()
};
var TRIAGE_PROCESS_FIELDS = {
  applyMode: exports_external.enum(["queue", "promote"]).optional(),
  maxAcceptsPerRun: positiveInt.optional(),
  judgment: triageJudgmentField
};
var PROACTIVE_MAINTENANCE_PROCESS_FIELDS = {
  dueDays: exports_external.number().int().min(0).optional(),
  maxPerRun: positiveInt.optional(),
  limit: processLimitField
};
function rejectExcludeRefPrefixesOutsideReflect(value, ctx) {
  if ("excludeRefPrefixes" in value) {
    ctx.addIssue({
      code: exports_external.ZodIssueCode.custom,
      path: ["excludeRefPrefixes"],
      message: "excludeRefPrefixes is only valid on the reflect process"
    });
  }
}
var ImproveProcessConfigSchema = exports_external.object({
  ...IMPROVE_PROCESS_BASE_FIELDS,
  ...REFLECT_PROCESS_FIELDS,
  ...DISTILL_PROCESS_FIELDS,
  ...CONSOLIDATE_PROCESS_FIELDS,
  ...MEMORY_INFERENCE_PROCESS_FIELDS,
  ...EXTRACT_PROCESS_FIELDS,
  ...TRIAGE_PROCESS_FIELDS,
  ...PROACTIVE_MAINTENANCE_PROCESS_FIELDS
}).passthrough();
var ReflectProcessConfigSchema = exports_external.object({ ...IMPROVE_PROCESS_BASE_FIELDS, ...REFLECT_PROCESS_FIELDS }).passthrough();
var DistillProcessConfigSchema = exports_external.object({ ...IMPROVE_PROCESS_BASE_FIELDS, ...DISTILL_PROCESS_FIELDS }).passthrough().superRefine(rejectExcludeRefPrefixesOutsideReflect);
var ConsolidateProcessConfigSchema = exports_external.object({ ...IMPROVE_PROCESS_BASE_FIELDS, ...CONSOLIDATE_PROCESS_FIELDS }).passthrough().superRefine(rejectExcludeRefPrefixesOutsideReflect);
var MemoryInferenceProcessConfigSchema = exports_external.object({ ...IMPROVE_PROCESS_BASE_FIELDS, ...MEMORY_INFERENCE_PROCESS_FIELDS }).passthrough();
var ExtractProcessConfigSchema = exports_external.object({ ...IMPROVE_PROCESS_BASE_FIELDS, ...EXTRACT_PROCESS_FIELDS }).passthrough();
var ValidationProcessConfigSchema = exports_external.object({ ...IMPROVE_PROCESS_BASE_FIELDS }).passthrough();
var TriageProcessConfigSchema = exports_external.object({ ...IMPROVE_PROCESS_BASE_FIELDS, ...TRIAGE_PROCESS_FIELDS }).passthrough();
var ProactiveMaintenanceProcessConfigSchema = exports_external.object({ ...IMPROVE_PROCESS_BASE_FIELDS, ...PROACTIVE_MAINTENANCE_PROCESS_FIELDS }).passthrough();
var RETIRED_PROCESS_NAMES = new Set(["graphExtraction"]);
var ImproveProfileProcessesSchema = exports_external.object({
  reflect: ReflectProcessConfigSchema.optional(),
  distill: DistillProcessConfigSchema.optional(),
  consolidate: ConsolidateProcessConfigSchema.optional(),
  memoryInference: MemoryInferenceProcessConfigSchema.optional(),
  extract: ExtractProcessConfigSchema.optional(),
  validation: ValidationProcessConfigSchema.optional(),
  triage: TriageProcessConfigSchema.optional(),
  proactiveMaintenance: ProactiveMaintenanceProcessConfigSchema.optional()
}).passthrough().superRefine((val, ctx) => {
  if ("feedbackDistillation" in val) {
    ctx.addIssue({
      code: exports_external.ZodIssueCode.custom,
      message: "feedbackDistillation was removed in 0.8.0 — use processes.distill.enabled instead. " + "It now controls both the orchestration gate and the LLM-call gate."
    });
  }
  for (const [name, process2] of Object.entries(val)) {
    if (!IMPROVE_PROCESS_NAMES.includes(name) && !RETIRED_PROCESS_NAMES.has(name) && process2 !== null && typeof process2 === "object" && process2.enabled === true) {
      ctx.addIssue({
        code: exports_external.ZodIssueCode.custom,
        path: [name],
        message: `Unknown enabled improve process "${name}"`
      });
    }
  }
});
var ImproveProfileConfigSchema = exports_external.object({
  engine: engineName.optional(),
  model: nonEmptyString.optional(),
  timeoutMs: exports_external.union([positiveInt, exports_external.null()]).optional(),
  llm: LlmInvocationOverridesSchema.optional(),
  description: exports_external.string().min(1).optional(),
  processes: ImproveProfileProcessesSchema.optional(),
  limit: positiveInt.optional(),
  sync: exports_external.object({
    enabled: exports_external.boolean().optional(),
    push: exports_external.boolean().optional(),
    message: exports_external.string().min(1).optional()
  }).passthrough().optional()
}).passthrough();

// src/core/config/schema/improve.ts
var ImproveSalienceSchema = exports_external.object({
  outcomeWeightEnabled: exports_external.boolean().optional(),
  salienceThreshold: exports_external.number().min(0).max(1).optional()
}).passthrough();
var ImproveStateGcSchema = exports_external.object({
  collect: exports_external.boolean().optional()
}).passthrough();
var ImproveConfigSchema = exports_external.object({
  strategies: exports_external.record(engineName, ImproveProfileConfigSchema).optional(),
  eventRetentionDays: nonNegativeNumber.optional(),
  salience: ImproveSalienceSchema.optional(),
  stateGc: ImproveStateGcSchema.optional()
}).passthrough();

// src/core/config/schema/index-config.ts
var INDEX_PASS_RETIRED_KEYS = new Set([
  "endpoint",
  "provider",
  "apiKey",
  "baseUrl",
  "temperature",
  "maxTokens",
  "capabilities"
]);
var IndexPassConfigSchema = exports_external.preprocess((raw, ctx) => {
  if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
    return raw;
  }
  const obj = raw;
  let cleaned;
  for (const key of Object.keys(obj)) {
    const dotted = [...ctx.path ?? [], key].join(".");
    if (INDEX_PASS_RETIRED_KEYS.has(key)) {
      warnOnce(`index-pass:retired:${dotted}`, `\`${dotted}\` is a retired engine setting and is ignored; select a named engine and use typed invocation fields instead.`);
      cleaned ??= { ...obj };
      delete cleaned[key];
    }
  }
  return cleaned ?? raw;
}, exports_external.object({
  engine: engineName.optional(),
  model: nonEmptyString.optional(),
  timeoutMs: exports_external.union([positiveInt, exports_external.null()]).optional(),
  enabled: exports_external.boolean().optional(),
  llm: LlmInvocationOverridesSchema.optional()
}).passthrough());
var IndexDefaultsSchema = exports_external.object({
  engine: engineName.optional(),
  model: nonEmptyString.optional(),
  timeoutMs: exports_external.union([positiveInt, exports_external.null()]).optional(),
  llm: LlmInvocationOverridesSchema.optional()
}).passthrough();
var IndexConfigRuntimeSchema = exports_external.preprocess((raw, ctx) => {
  if (raw === undefined || raw === null)
    return raw;
  if (Array.isArray(raw)) {
    ctx.addIssue({
      code: exports_external.ZodIssueCode.custom,
      message: 'Invalid `index` config: expected an object keyed by pass name (e.g. `{ "memory": { "enabled": false } }`).'
    });
    return raw;
  }
  if (typeof raw !== "object")
    return raw;
  let cleaned;
  for (const [passName, value] of Object.entries(raw)) {
    if (passName === "stalenessDetection") {
      warnOnce("index:stalenessDetection", "`index.stalenessDetection` is a retired pass and is ignored.");
      cleaned ??= { ...raw };
      delete cleaned.stalenessDetection;
      continue;
    }
    if (typeof value !== "object" || value === null || Array.isArray(value)) {
      ctx.addIssue({
        code: exports_external.ZodIssueCode.custom,
        message: `Invalid \`index.${passName}\` config: expected an object like \`{ "enabled": false }\`.`
      });
      return raw;
    }
  }
  return cleaned ?? raw;
}, exports_external.object({
  defaults: IndexDefaultsSchema.optional()
}).catchall(IndexPassConfigSchema));
var IndexConfigSchema = IndexConfigRuntimeSchema;

// src/core/config/schema/output.ts
var OutputConfigSchema = exports_external.object({
  format: exports_external.enum(["json", "yaml", "text", "jsonl", "md", "html"]).optional(),
  detail: exports_external.enum(["brief", "normal", "full"]).optional()
}).passthrough();

// src/core/config/schema/scheduler.ts
var LegacySchedulerActivationSchema = exports_external.object({ ref: nonEmptyString }).passthrough().transform((activation) => activation.ref);
var SchedulerConfigSchema = exports_external.object({
  enabled: exports_external.array(exports_external.union([nonEmptyString, LegacySchedulerActivationSchema])).optional()
}).passthrough();

// src/core/config/schema/search.ts
var CurateRerankConfigSchema = exports_external.object({
  enabled: exports_external.boolean().optional(),
  endpoint: httpUrl.optional(),
  model: nonEmptyString.optional(),
  apiKey: symbolicOrWarnApiKey("search.curateRerank.apiKey").optional(),
  timeoutMs: positiveInt.optional(),
  topN: positiveInt.max(50).optional()
}).passthrough();
var SearchConfigSchema = exports_external.object({
  defaultExcludeTypes: exports_external.array(nonEmptyString).optional(),
  curateRerank: CurateRerankConfigSchema.optional()
}).passthrough();

// src/core/config/schema/setup.ts
var SetupConfigSchema = exports_external.object({}).passthrough();

// src/core/adapter/adapter-ids.ts
var ADAPTER_ID_TABLE = [
  "website-snapshot",
  "agent-skills",
  "claude",
  "opencode",
  "dotenv",
  "akm-workflow",
  "akm-task",
  "llm-wiki",
  "akm",
  "okf",
  "generic-files"
];
var VALID_ADAPTER_IDS = ADAPTER_ID_TABLE;

// src/core/config/schema/sources-bundles.ts
var VALID_ADAPTER_IDS_SET = new Set(VALID_ADAPTER_IDS);
var SourceConfigEntryOptionsSchema = exports_external.record(exports_external.unknown());
var SourceConfigEntrySchema = exports_external.object({
  type: nonEmptyString,
  path: exports_external.string().min(1).optional(),
  url: exports_external.string().min(1).optional(),
  name: exports_external.string().min(1).optional(),
  enabled: exports_external.boolean().optional(),
  writable: exports_external.boolean().optional(),
  credential: exports_external.string().min(1).optional(),
  primary: exports_external.boolean().optional(),
  options: SourceConfigEntryOptionsSchema.optional()
}).passthrough().superRefine((entry, ctx) => {
  if (entry.options && "pushOnCommit" in entry.options) {
    ctx.addIssue({
      code: exports_external.ZodIssueCode.custom,
      path: ["options", "pushOnCommit"],
      message: "options.pushOnCommit is not supported"
    });
  }
  if (!["filesystem", "git", "website", "npm"].includes(entry.type)) {
    ctx.addIssue({
      code: exports_external.ZodIssueCode.custom,
      path: ["type"],
      message: `unsupported source type "${entry.type}"; expected filesystem, git, website, or npm`
    });
  }
  if (entry.writable === true && (entry.type === "website" || entry.type === "npm")) {
    ctx.addIssue({
      code: exports_external.ZodIssueCode.custom,
      message: `writable: true is only supported on filesystem and git sources (got "${entry.type}"` + (entry.name ? ` on source "${entry.name}"` : "") + ")."
    });
  }
  if (entry.credential !== undefined && entry.type !== "git") {
    ctx.addIssue({
      code: exports_external.ZodIssueCode.custom,
      path: ["credential"],
      message: "credential is only supported on git sources"
    });
  }
  if (entry.credential !== undefined && !isApiKeyReference(entry.credential)) {
    ctx.addIssue({
      code: exports_external.ZodIssueCode.custom,
      path: ["credential"],
      message: "git credential must be a $VAR or secret://<name> reference"
    });
  }
});
var RegistryConfigEntrySchema = exports_external.object({
  url: httpUrl,
  name: exports_external.string().min(1).optional(),
  enabled: exports_external.boolean().optional(),
  provider: exports_external.string().min(1).optional(),
  options: exports_external.record(exports_external.unknown()).optional()
}).passthrough();
var BundleWebsiteDescriptorSchema = exports_external.object({
  url: httpUrl,
  refresh: exports_external.string().min(1).optional(),
  maxPages: positiveInt.optional(),
  maxDepth: positiveInt.optional(),
  respectRobots: exports_external.boolean().optional(),
  crawlTimeoutMs: exports_external.number().int().min(0).optional()
}).passthrough();
var BundleComponentConfigSchema = exports_external.object({
  root: exports_external.string().min(1).optional(),
  adapter: nonEmptyString.optional(),
  writable: exports_external.boolean().optional()
}).passthrough();
var BundleConfigEntrySchema = exports_external.object({
  path: exports_external.string().min(1).optional(),
  git: exports_external.string().min(1).optional(),
  website: BundleWebsiteDescriptorSchema.optional(),
  npm: exports_external.string().min(1).optional(),
  credential: exports_external.string().min(1).optional(),
  writable: exports_external.boolean().optional(),
  enabled: exports_external.boolean().optional(),
  registryId: exports_external.string().min(1).optional(),
  components: exports_external.record(exports_external.string().min(1), BundleComponentConfigSchema).optional()
}).passthrough().superRefine((entry, ctx) => {
  const options = entry.options;
  if (options && typeof options === "object" && "pushOnCommit" in options) {
    ctx.addIssue({
      code: exports_external.ZodIssueCode.custom,
      path: ["options", "pushOnCommit"],
      message: "options.pushOnCommit is not supported"
    });
  }
  const descriptors = ["path", "git", "website", "npm"].filter((k) => entry[k] !== undefined);
  if (descriptors.length === 0) {
    ctx.addIssue({
      code: exports_external.ZodIssueCode.custom,
      message: "a bundle entry must carry exactly one source descriptor (path, git, website, or npm)"
    });
  } else if (descriptors.length > 1) {
    ctx.addIssue({
      code: exports_external.ZodIssueCode.custom,
      message: `a bundle entry must carry exactly one source descriptor; got ${descriptors.join(", ")}`
    });
  }
  if (entry.writable === true && (entry.website !== undefined || entry.npm !== undefined)) {
    ctx.addIssue({
      code: exports_external.ZodIssueCode.custom,
      path: ["writable"],
      message: "writable: true is only supported on path and git bundle sources"
    });
  }
  if (entry.credential !== undefined && entry.git === undefined) {
    ctx.addIssue({
      code: exports_external.ZodIssueCode.custom,
      path: ["credential"],
      message: "credential is only supported on git bundle sources"
    });
  }
  if (entry.credential !== undefined && !isApiKeyReference(entry.credential)) {
    ctx.addIssue({
      code: exports_external.ZodIssueCode.custom,
      path: ["credential"],
      message: "git credential must be a $VAR or secret://<name> reference"
    });
  }
  const componentEntries = entry.components ? Object.entries(entry.components) : [];
  if (entry.components !== undefined && componentEntries.length !== 1) {
    ctx.addIssue({
      code: exports_external.ZodIssueCode.custom,
      path: ["components"],
      message: "a bundle components map must contain exactly one component"
    });
  }
  const componentEntry = componentEntries[0];
  if (componentEntry?.[1].writable === true && (entry.website !== undefined || entry.npm !== undefined)) {
    ctx.addIssue({
      code: exports_external.ZodIssueCode.custom,
      path: ["components", componentEntry[0], "writable"],
      message: "writable: true is only supported on path and git bundle sources"
    });
  }
  if (componentEntry !== undefined) {
    const [componentName, componentValue] = componentEntry;
    const adapterValue = componentValue.adapter;
    if (adapterValue !== undefined && !VALID_ADAPTER_IDS_SET.has(adapterValue)) {
      ctx.addIssue({
        code: exports_external.ZodIssueCode.custom,
        path: ["components", componentName, "adapter"],
        message: `unrecognized adapter "${adapterValue}"; expected one of: ${VALID_ADAPTER_IDS.join(", ")}`
      });
    }
  }
});
var BundlesConfigSchema = exports_external.record(exports_external.string().min(1).refine(isBundleSlug, {
  message: "bundle key must be a legal slug (no '/', ':', '.', '#', or whitespace)"
}), BundleConfigEntrySchema);

// src/core/config/schema/workflow.ts
var WorkflowConfigSchema = exports_external.object({
  maxConcurrency: positiveInt.optional(),
  defaultMapConcurrency: positiveInt.optional(),
  judgeEngine: engineName.optional()
}).passthrough();

// src/core/config/config-schema.ts
var DefaultsSchema = exports_external.object({
  engine: engineName.optional(),
  llmEngine: engineName.optional(),
  improveStrategy: engineName.optional()
}).passthrough();
var AkmConfigShape = {
  configVersion: exports_external.literal(CURRENT_CONFIG_VERSION),
  extends: nonEmptyString.optional(),
  engines: EnginesSchema.optional(),
  defaults: DefaultsSchema.optional(),
  semanticSearchMode: exports_external.enum(["off", "auto"]).default("off"),
  embedding: EmbeddingConnectionConfigSchema.optional(),
  execution: ExecutionPolicyConfigSchema.optional(),
  index: IndexConfigSchema.optional(),
  registries: exports_external.array(RegistryConfigEntrySchema).optional(),
  bundles: BundlesConfigSchema.optional(),
  defaultBundle: nonEmptyString.optional(),
  output: OutputConfigSchema.optional(),
  defaultWriteTarget: nonEmptyString.optional(),
  search: SearchConfigSchema.optional(),
  feedback: FeedbackConfigSchema.optional(),
  archiveRetentionDays: nonNegativeNumber.optional(),
  improve: ImproveConfigSchema.optional(),
  workflow: WorkflowConfigSchema.optional(),
  scheduler: SchedulerConfigSchema.optional(),
  setup: SetupConfigSchema.optional(),
  experimental: ExperimentalConfigSchema.optional()
};
var AkmConfigBaseSchema = exports_external.object(AkmConfigShape).passthrough();
var RETIRED_SOURCE_SHAPE_KEY_MESSAGES = {
  stashDir: "stashDir is not supported; configure `bundles`, or use `akm config path --all` / `akm info` to inspect current paths."
};
var AkmConfigSchema = AkmConfigBaseSchema.superRefine((config, ctx) => {
  const raw = config;
  for (const key of ["stashDir", "sources", "installed"]) {
    if (key in raw && raw[key] !== undefined) {
      ctx.addIssue({
        code: exports_external.ZodIssueCode.custom,
        path: [key],
        message: RETIRED_SOURCE_SHAPE_KEY_MESSAGES[key] ?? `${key} is not supported; configure the current bundles shape`
      });
    }
  }
  if (config.defaultBundle !== undefined) {
    if (config.bundles === undefined) {
      ctx.addIssue({
        code: exports_external.ZodIssueCode.custom,
        path: ["defaultBundle"],
        message: "defaultBundle requires a bundles map"
      });
    } else if (!(config.defaultBundle in config.bundles)) {
      ctx.addIssue({
        code: exports_external.ZodIssueCode.custom,
        path: ["defaultBundle"],
        message: `defaultBundle "${config.defaultBundle}" does not name a configured bundle`
      });
    } else if (config.bundles[config.defaultBundle]?.enabled === false) {
      ctx.addIssue({
        code: exports_external.ZodIssueCode.custom,
        path: ["defaultBundle"],
        message: `defaultBundle "${config.defaultBundle}" is disabled`
      });
    }
  }
  if (config.defaultWriteTarget !== undefined) {
    const target = config.bundles?.[config.defaultWriteTarget];
    if (!target) {
      ctx.addIssue({
        code: exports_external.ZodIssueCode.custom,
        path: ["defaultWriteTarget"],
        message: `defaultWriteTarget "${config.defaultWriteTarget}" does not name a configured bundle`
      });
    } else if (target.enabled === false) {
      ctx.addIssue({
        code: exports_external.ZodIssueCode.custom,
        path: ["defaultWriteTarget"],
        message: `defaultWriteTarget "${config.defaultWriteTarget}" is disabled`
      });
    }
  }
  for (const key of ["llm", "agent", "improve"]) {
    if (config.defaults && key in config.defaults) {
      ctx.addIssue({
        code: exports_external.ZodIssueCode.custom,
        path: ["defaults", key],
        message: `defaults.${key} is retired in 0.9`
      });
    }
  }
  for (const [name, engine] of Object.entries(config.engines ?? {})) {
    if (engine.kind === "agent" && engine.llmEngine) {
      const fallback = config.engines?.[engine.llmEngine];
      if (!fallback || fallback.kind !== "llm") {
        ctx.addIssue({
          code: exports_external.ZodIssueCode.custom,
          path: ["engines", name, "llmEngine"],
          message: "llmEngine must name an LLM engine"
        });
      }
    }
  }
  const defaultEngine = config.defaults?.engine;
  if (defaultEngine && !config.engines?.[defaultEngine]) {
    ctx.addIssue({
      code: exports_external.ZodIssueCode.custom,
      path: ["defaults", "engine"],
      message: "engine does not name a configured engine"
    });
  }
  const confining = [...HARNESS_MODEL_WORK_IDS];
  const confiningPlatforms = `${confining.slice(0, -1).join(", ")} or ${confining.at(-1)}`;
  const modelWorkEngine = (name, path12) => {
    if (!name)
      return;
    const engine = config.engines?.[name];
    if (!engine) {
      ctx.addIssue({ code: exports_external.ZodIssueCode.custom, path: path12, message: "engine does not name a configured engine" });
    } else if (engine.kind !== "llm" && !HARNESS_MODEL_WORK_IDS.has(engine.platform)) {
      ctx.addIssue({
        code: exports_external.ZodIssueCode.custom,
        path: path12,
        message: `engine "${name}" (platform ${engine.platform}) cannot confine the model-work tool policy, which unattended model work requires. Use an LLM engine, or an agent engine on ${confiningPlatforms}.`
      });
    }
  };
  modelWorkEngine(config.defaults?.llmEngine, ["defaults", "llmEngine"]);
  for (const [passName, pass] of Object.entries(config.index ?? {})) {
    const engine = pass?.engine;
    if (typeof engine === "string")
      modelWorkEngine(engine, ["index", passName, "engine"]);
  }
  const workflowJudge = config.workflow?.judgeEngine;
  if (workflowJudge && !config.engines?.[workflowJudge]) {
    ctx.addIssue({
      code: exports_external.ZodIssueCode.custom,
      path: ["workflow", "judgeEngine"],
      message: "judgeEngine does not name a configured engine"
    });
  }
  const defaultStrategy = config.defaults?.improveStrategy;
  if (defaultStrategy && defaultStrategy !== "graph-refresh" && !BUILTIN_IMPROVE_STRATEGY_NAMES.includes(defaultStrategy) && !config.improve?.strategies?.[defaultStrategy]) {
    ctx.addIssue({
      code: exports_external.ZodIssueCode.custom,
      path: ["defaults", "improveStrategy"],
      message: "improveStrategy does not name a built-in or configured strategy"
    });
  }
  for (const [strategyName, strategy] of Object.entries(config.improve?.strategies ?? {})) {
    const strategyPath = ["improve", "strategies", strategyName];
    modelWorkEngine(strategy.engine, [...strategyPath, "engine"]);
    for (const [processName, process2] of Object.entries(strategy.processes ?? {})) {
      const processConfig = process2;
      const processPath = [...strategyPath, "processes", processName];
      if (processConfig.engine && !IMPROVE_ENGINE_PROCESSES.includes(processName)) {
        ctx.addIssue({
          code: exports_external.ZodIssueCode.custom,
          path: [...processPath, "engine"],
          message: `${processName} does not dispatch an engine`
        });
      } else {
        modelWorkEngine(processConfig.engine, [...processPath, "engine"]);
      }
      if (processConfig.judgment?.enabled === true) {
        modelWorkEngine(processConfig.judgment.engine, [...processPath, "judgment", "engine"]);
      }
      modelWorkEngine(processConfig.qualityGate?.engine, [...processPath, "qualityGate", "engine"]);
    }
  }
  if (config.defaultWriteTarget !== undefined) {
    const knownNames = Object.keys(config.bundles ?? {});
    if (knownNames.length === 0) {
      ctx.addIssue({
        code: exports_external.ZodIssueCode.custom,
        path: ["defaultWriteTarget"],
        message: `defaultWriteTarget "${config.defaultWriteTarget}" cannot be resolved: no bundles configured. ` + "Add at least one entry to `bundles` first."
      });
    } else if (!knownNames.includes(config.defaultWriteTarget)) {
      ctx.addIssue({
        code: exports_external.ZodIssueCode.custom,
        path: ["defaultWriteTarget"],
        message: `defaultWriteTarget "${config.defaultWriteTarget}" does not match any configured bundle: ${knownNames.map((n) => `"${n}"`).join(", ")}.`
      });
    }
  }
});

// src/core/config/deep-merge.ts
var UNSAFE_KEYS = new Set(["__proto__", "constructor", "prototype"]);
function isPlainObject(value) {
  if (value === null || typeof value !== "object" || Array.isArray(value))
    return false;
  const prototype = Object.getPrototypeOf(value);
  return prototype === Object.prototype || prototype === null;
}
function copyConfigValue(value) {
  if (Array.isArray(value))
    return value.map(copyConfigValue);
  if (!isPlainObject(value))
    return value;
  const copy = {};
  for (const key of Object.keys(value)) {
    if (UNSAFE_KEYS.has(key))
      throw new TypeError(`Unsafe configuration key: ${key}`);
    copy[key] = copyConfigValue(value[key]);
  }
  return copy;
}
function deepMergeConfig(base, override) {
  const result = copyConfigValue(base);
  for (const key of Object.keys(override)) {
    if (UNSAFE_KEYS.has(key))
      throw new TypeError(`Unsafe configuration key: ${key}`);
    const next = override[key];
    if (next === undefined)
      continue;
    const current = result[key];
    result[key] = isPlainObject(current) && isPlainObject(next) ? deepMergeConfig(current, next) : copyConfigValue(next);
  }
  return result;
}

// src/core/config/config.ts
import fs10 from "node:fs";
import os2 from "node:os";
import path14 from "node:path";
import { isDeepStrictEqual } from "node:util";

// src/core/config/config-io.ts
import fs8 from "node:fs";
import path12 from "node:path";

// src/core/file-lock.ts
import { randomUUID } from "node:crypto";
import fs7 from "node:fs";
function readLockSnapshot(lockPath) {
  let fd;
  try {
    fd = fs7.openSync(lockPath, "r");
  } catch (err) {
    if (err.code === "ENOENT")
      return;
    throw err;
  }
  try {
    const rawContent = readTextFileDescriptorWithLimit(fd, MAX_LOCK_METADATA_BYTES, "Lock metadata", lockPath);
    const stat = fs7.fstatSync(fd);
    return {
      rawContent,
      identity: { dev: stat.dev, ino: stat.ino, size: stat.size, mtimeMs: stat.mtimeMs }
    };
  } finally {
    fs7.closeSync(fd);
  }
}
function sameIdentity(left, right) {
  return left.dev === right.dev && left.ino === right.ino && left.size === right.size && left.mtimeMs === right.mtimeMs;
}
function releaseLockRaw(lockPath) {
  try {
    fs7.unlinkSync(lockPath);
  } catch {}
}
function tryAcquireLockSync(lockPath, payload) {
  try {
    fs7.writeFileSync(lockPath, payload, { flag: "wx" });
  } catch (err) {
    if (err.code === "EEXIST")
      return;
    throw err;
  }
  let snapshot;
  try {
    snapshot = readLockSnapshot(lockPath);
  } catch (error2) {
    releaseLockRaw(lockPath);
    throw error2;
  }
  if (!snapshot) {
    releaseLockRaw(lockPath);
    throw new Error(`Could not read newly acquired lock at ${lockPath}.`);
  }
  return { lockPath, ...snapshot };
}
function launcherPidFromEnv() {
  const raw = process.env.AKM_LAUNCHER_PID;
  if (!raw)
    return;
  const pid = Number.parseInt(raw, 10);
  return Number.isInteger(pid) && pid > 0 ? pid : undefined;
}
function createLockPayload(metadata = {}) {
  const launcherPid = launcherPidFromEnv();
  return JSON.stringify({
    ...metadata,
    pid: process.pid,
    ...launcherPid !== undefined ? { launcherPid } : {},
    lockId: randomUUID()
  });
}
function probeLock(lockPath, opts) {
  let snapshot;
  try {
    snapshot = readLockSnapshot(lockPath);
  } catch (error2) {
    const code = error2?.code;
    if (code === "EACCES" || code === "EPERM")
      return { state: "inaccessible", code };
    return { state: "stale", reason: "unreadable" };
  }
  if (!snapshot)
    return { state: "absent" };
  const { rawContent, identity: identity3 } = snapshot;
  const ageMs = Date.now() - identity3.mtimeMs;
  const { holderPid, launcherPid } = extractLockIdentity(rawContent);
  if (holderPid === undefined) {
    return { state: "stale", reason: "invalid_pid", ageMs, rawContent, identity: identity3 };
  }
  if (!isProcessAlive(holderPid)) {
    return { state: "stale", reason: "pid_dead", holderPid, launcherPid, ageMs, rawContent, identity: identity3 };
  }
  if (opts?.staleAfterMs !== undefined && ageMs > opts.staleAfterMs) {
    return { state: "stale", reason: "age_exceeded", holderPid, launcherPid, ageMs, rawContent, identity: identity3 };
  }
  return { state: "held", holderPid, launcherPid, ageMs, rawContent, identity: identity3 };
}
function reclaimStaleLock(lockPath, probe, options) {
  if (probe.rawContent === undefined || probe.identity === undefined)
    return false;
  const expectedContent = probe.rawContent;
  const expectedIdentity = probe.identity;
  let current;
  try {
    current = readLockSnapshot(lockPath);
  } catch {
    return false;
  }
  if (!current || current.rawContent !== expectedContent || !sameIdentity(current.identity, expectedIdentity)) {
    return false;
  }
  const quarantinePath = `${lockPath}.stale-${process.pid}-${randomUUID()}`;
  try {
    fs7.renameSync(lockPath, quarantinePath);
  } catch (err) {
    if (err.code === "ENOENT")
      return false;
    throw err;
  }
  let quarantined;
  try {
    quarantined = readLockSnapshot(quarantinePath);
  } catch {
    quarantined = undefined;
  }
  if (!quarantined || quarantined.rawContent !== expectedContent || !sameIdentity(quarantined.identity, expectedIdentity)) {
    try {
      fs7.linkSync(quarantinePath, lockPath);
    } catch (err) {
      if (err.code !== "EEXIST")
        throw err;
    }
    releaseLockRaw(quarantinePath);
    return false;
  }
  options?.afterQuarantineVerified?.();
  try {
    fs7.unlinkSync(quarantinePath);
    return true;
  } catch (err) {
    if (err.code === "ENOENT")
      return false;
    throw err;
  }
}
function releaseLock(ownership) {
  const { lockPath } = ownership;
  let current;
  try {
    current = readLockSnapshot(lockPath);
  } catch {
    return;
  }
  if (current && current.rawContent === ownership.rawContent && sameIdentity(current.identity, ownership.identity)) {
    releaseLockRaw(lockPath);
  }
}
function extractLockIdentity(content) {
  const trimmed = content.trim();
  if (!trimmed)
    return {};
  if (trimmed.startsWith("{")) {
    try {
      const parsed = JSON.parse(trimmed);
      const pid2 = typeof parsed.pid === "number" ? parsed.pid : Number.NaN;
      const rawLauncherPid = typeof parsed.launcherPid === "number" ? parsed.launcherPid : Number.NaN;
      return {
        holderPid: Number.isInteger(pid2) && pid2 > 0 ? pid2 : undefined,
        launcherPid: Number.isInteger(rawLauncherPid) && rawLauncherPid > 0 ? rawLauncherPid : undefined
      };
    } catch {
      return {};
    }
  }
  const pid = Number.parseInt(trimmed, 10);
  return { holderPid: Number.isInteger(pid) && pid > 0 ? pid : undefined };
}

// src/core/config/config-io.ts
function readConfigText(configPath) {
  try {
    return readTextFile(configPath, "Config file");
  } catch (err) {
    if (err.code === "ENOENT")
      return;
    throw err;
  }
}
function parseConfigText(text, sourcePath) {
  const stripped = stripJsonComments(text);
  const where = sourcePath ? ` at ${sourcePath}` : "";
  let parsed;
  try {
    parsed = JSON.parse(stripped);
  } catch (err) {
    const detail = err instanceof Error ? err.message : String(err);
    throw new ConfigError(`Failed to parse config JSON${where}: ${detail}`, "INVALID_CONFIG_FILE", "Edit the file to fix the JSON syntax error. Comments (// and /* */) are allowed; trailing commas are not.");
  }
  if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
    throw new ConfigError(`Config file${where} must contain a JSON object at the root, got ${describeJsonRoot(parsed)}.`, "INVALID_CONFIG_FILE");
  }
  return parsed;
}
function describeJsonRoot(value) {
  if (value === null)
    return "null";
  if (Array.isArray(value))
    return "an array";
  if (typeof value === "string")
    return "a string";
  if (typeof value === "number")
    return "a number";
  if (typeof value === "boolean")
    return "a boolean";
  return typeof value;
}
function writeConfigAtomic(configPath, config) {
  writeFileAtomic(configPath, `${JSON.stringify(config, null, 2)}
`);
}
var MAX_CONFIG_BACKUPS = 5;
function backupExistingConfig(configPath, now = new Date) {
  if (!fs8.existsSync(configPath))
    return;
  const backupDir = path12.join(getCacheDir(), "config-backups");
  fs8.mkdirSync(backupDir, { recursive: true, mode: 448 });
  fs8.chmodSync(backupDir, 448);
  const timestamp = now.toISOString().replace(/[.:]/g, "-");
  let sequence = 0;
  let timestamped;
  while (true) {
    timestamped = path12.join(backupDir, `config-${timestamp}${sequence === 0 ? "" : `-${sequence}`}.json`);
    try {
      fs8.copyFileSync(configPath, timestamped, fs8.constants.COPYFILE_EXCL);
      break;
    } catch (error2) {
      if (error2.code !== "EEXIST")
        throw error2;
      sequence++;
    }
  }
  const latest = path12.join(backupDir, "config.latest.json");
  fs8.copyFileSync(configPath, latest);
  fs8.chmodSync(timestamped, 384);
  fs8.chmodSync(latest, 384);
  pruneOldBackups(backupDir);
  return { timestamped, latest };
}
function pruneOldBackups(backupDir) {
  pruneToNewest(backupDir, MAX_CONFIG_BACKUPS, (entry) => entry.isFile() && isTimestampedConfigBackup(entry.name));
}
function isTimestampedConfigBackup(name) {
  return name.startsWith("config-") && name.endsWith(".json") && name !== "config.latest.json";
}
function pruneToNewest(dir, keep, select) {
  let entries;
  try {
    entries = fs8.readdirSync(dir, { withFileTypes: true });
  } catch {
    return;
  }
  const candidates = entries.filter(select).map((entry) => {
    const full = path12.join(dir, entry.name);
    let mtime = 0;
    try {
      mtime = fs8.statSync(full).mtimeMs;
    } catch {}
    return { path: full, mtime };
  }).sort((a, b) => b.mtime - a.mtime);
  for (const stale of candidates.slice(keep)) {
    try {
      fs8.rmSync(stale.path, { recursive: true, force: true });
    } catch {}
  }
}
function getConfigLockPath() {
  return path12.join(getConfigDir(), "config.json.lck");
}
var CONFIG_LOCK_MAX_RETRIES = 40;
var CONFIG_LOCK_RETRY_DELAY_MS = 50;
function sleepSyncMs(ms) {
  sleepSync(ms);
}
function acquireConfigLock() {
  const lockPath = getConfigLockPath();
  try {
    fs8.mkdirSync(path12.dirname(lockPath), { recursive: true });
  } catch {}
  for (let attempt = 0;attempt < CONFIG_LOCK_MAX_RETRIES; attempt++) {
    try {
      const ownership = tryAcquireLockSync(lockPath, createLockPayload());
      if (ownership) {
        return () => releaseLock(ownership);
      }
    } catch (error2) {
      throw new ConfigError(`Unable to acquire config lock at ${lockPath}: ${error2 instanceof Error ? error2.message : String(error2)}`, "INVALID_CONFIG_FILE");
    }
    const probe = probeLock(lockPath);
    if (probe.state === "stale" && reclaimStaleLock(lockPath, probe)) {
      continue;
    }
    if (attempt < CONFIG_LOCK_MAX_RETRIES - 1) {
      sleepSyncMs(CONFIG_LOCK_RETRY_DELAY_MS);
    }
  }
  throw new ConfigError(`Timed out waiting for config lock at ${lockPath}. Another AKM process may be updating config.`, "INVALID_CONFIG_FILE");
}
function withConfigLock(fn) {
  const release = acquireConfigLock();
  try {
    return fn();
  } finally {
    release();
  }
}

// src/core/config/config-sources.ts
import { createHash } from "node:crypto";
import fs9 from "node:fs";
import path13 from "node:path";
function bundleComponentConfig(bundle) {
  if (!bundle?.components)
    return;
  const components = Object.values(bundle.components);
  if (components.length !== 1) {
    throw new ConfigError("A bundle components map must contain exactly one component.", "INVALID_CONFIG_FILE");
  }
  return components[0];
}
function bundleContentRoot(entryPath, componentRoot) {
  return path13.resolve(entryPath, componentRoot ?? ".");
}
function bundlePhysicalContentRoot(entryPath, componentRoot) {
  const resolved = bundleContentRoot(entryPath, componentRoot);
  try {
    return fs9.realpathSync.native(resolved);
  } catch (cause) {
    if (cause.code === "ENOENT")
      return resolved;
    throw new ConfigError(`Unable to resolve physical bundle root ${JSON.stringify(resolved)}: ${cause instanceof Error ? cause.message : String(cause)}`, "INVALID_CONFIG_FILE");
  }
}
function isBundleEnabled(config, bundleId) {
  const bundle = config.bundles?.[bundleId];
  return bundle !== undefined && bundle.enabled !== false;
}
function bundleSourceId(config, bundleId) {
  const bundle = config.bundles?.[bundleId];
  if (!bundle) {
    throw new ConfigError(`Bundle ${JSON.stringify(bundleId)} is not configured.`, "INVALID_CONFIG_FILE");
  }
  const component = bundleComponentConfig(bundle);
  let source;
  if (bundle.path !== undefined) {
    source = { kind: "filesystem", locator: bundlePhysicalContentRoot(bundle.path, component?.root) };
  } else if (bundle.git !== undefined) {
    source = { kind: "git", locator: normalizeInstalledGitRef("git", bundle.git) };
  } else if (bundle.website !== undefined) {
    source = { kind: "website", url: bundle.website.url };
  } else if (bundle.npm !== undefined) {
    source = { kind: "npm", locator: bundle.npm };
  } else {
    throw new ConfigError(`Bundle ${JSON.stringify(bundleId)} has no source descriptor.`, "INVALID_CONFIG_FILE");
  }
  return hashBundleSourceIdentity({
    version: 1,
    source,
    registryId: bundle.registryId ?? null,
    componentRoot: component?.root ?? "."
  });
}
function filesystemBundleSourceId(contentRoot) {
  return hashBundleSourceIdentity({
    version: 1,
    source: { kind: "filesystem", locator: bundlePhysicalContentRoot(contentRoot) },
    registryId: null,
    componentRoot: "."
  });
}
function hashBundleSourceIdentity(identity3) {
  return `sha256:${createHash("sha256").update("akm.bundle-source\x00v1\x00").update(JSON.stringify(identity3)).digest("hex")}`;
}
function bundleContentRoots(config) {
  const bundles = config.bundles ?? {};
  const out = [];
  for (const [id, entry] of Object.entries(bundles)) {
    if (typeof entry.path !== "string" || entry.path.length === 0)
      continue;
    out.push({ id, contentRoot: bundlePhysicalContentRoot(entry.path, bundleComponentConfig(entry)?.root) });
  }
  return out;
}
function bundlesToSourceEntries(config) {
  const bundles = config.bundles;
  if (!bundles)
    return;
  const keys = Object.keys(bundles);
  const defaultKey = config.defaultBundle && config.defaultBundle in bundles ? config.defaultBundle : undefined;
  const ordered = defaultKey ? [defaultKey, ...keys.filter((k) => k !== defaultKey)] : keys;
  const entries = [];
  for (const key of ordered) {
    const entry = bundleEntryToSourceEntry(key, bundles[key], key === defaultKey);
    if (entry)
      entries.push(entry);
  }
  return entries;
}
function bundleEntryToSourceEntry(key, bundle, isPrimary = false) {
  const base = {
    name: key,
    ...bundle.writable !== undefined ? { writable: bundle.writable } : {},
    ...bundle.credential !== undefined ? { credential: bundle.credential } : {},
    ...bundle.enabled !== undefined ? { enabled: bundle.enabled } : {},
    ...isPrimary ? { primary: true } : {}
  };
  if (typeof bundle.path === "string" && bundle.path.length > 0) {
    return { type: "filesystem", path: bundle.path, ...base };
  }
  if (typeof bundle.git === "string" && bundle.git.length > 0) {
    return { type: "git", url: normalizeInstalledGitRef("", bundle.git), ...base };
  }
  if (bundle.website && typeof bundle.website.url === "string") {
    const { url, ...rest } = bundle.website;
    return {
      type: "website",
      url,
      ...Object.keys(rest).length > 0 ? { options: rest } : {},
      ...base
    };
  }
  if (typeof bundle.npm === "string" && bundle.npm.length > 0) {
    return { type: "npm", path: bundle.npm, ...base };
  }
  return;
}
function normalizeInstalledGitRef(source, ref) {
  if (ref.startsWith("git+"))
    return ref.slice(4);
  const isGithubShorthand = ref.startsWith("github:") || source === "github" && /^[^/:#]+\/[^/#]+(?:#.+)?$/.test(ref);
  if (!isGithubShorthand)
    return ref;
  const body = ref.startsWith("github:") ? ref.slice("github:".length) : ref;
  const fragmentAt = body.indexOf("#");
  const repository = fragmentAt >= 0 ? body.slice(0, fragmentAt) : body;
  const requestedRef = fragmentAt >= 0 ? body.slice(fragmentAt + 1) : "";
  const cloneUrl = `https://github.com/${repository.replace(/\.git$/i, "")}`;
  return requestedRef ? `${cloneUrl}/tree/${requestedRef}` : cloneUrl;
}

// src/core/config/config-walker.ts
function unwrap(schema) {
  let current = schema;
  while (true) {
    if (current instanceof exports_external.ZodOptional) {
      current = current._def.innerType;
    } else if (current instanceof exports_external.ZodDefault) {
      current = current._def.innerType;
    } else if (current instanceof exports_external.ZodNullable) {
      current = current._def.innerType;
    } else if (current instanceof exports_external.ZodCatch) {
      current = current._def.innerType;
    } else if (current instanceof exports_external.ZodEffects) {
      current = current._def.schema;
    } else if (current instanceof exports_external.ZodReadonly) {
      current = current._def.innerType;
    } else {
      return current;
    }
  }
}
function resolveSchemaAt(path14, config, raw) {
  let schema = AkmConfigBaseSchema;
  let existing = config;
  for (const [index, segment] of path14.entries()) {
    schema = unwrap(schema);
    if (schema instanceof exports_external.ZodObject) {
      const next = schema.shape[segment];
      if (!next) {
        const catchall = schema._def.catchall;
        if (catchall && !(catchall instanceof exports_external.ZodNever)) {
          schema = catchall;
        } else {
          return;
        }
      } else {
        schema = next;
      }
    } else if (schema instanceof exports_external.ZodRecord) {
      schema = schema._def.valueType;
    } else if (schema instanceof exports_external.ZodUnion) {
      const option = selectUnionObjectOption(schema._def.options, segment, existing, index === path14.length - 1 ? raw : undefined);
      if (!option)
        return;
      schema = option.shape[segment];
    } else {
      return;
    }
    existing = isRecord(existing) ? existing[segment] : undefined;
  }
  return schema;
}
function selectUnionObjectOption(candidates, segment, existing, raw) {
  const options = candidates.map((candidate) => unwrap(candidate)).filter((candidate) => candidate instanceof exports_external.ZodObject);
  if (raw !== undefined) {
    const requested = options.find((option) => {
      const leaf = option.shape[segment];
      if (!leaf || !(unwrap(leaf) instanceof exports_external.ZodLiteral))
        return false;
      return leaf.safeParse(coerceForSchema(leaf, raw, segment)).success;
    });
    if (requested)
      return requested;
  }
  if (isRecord(existing)) {
    const selected = options.find((option) => Object.entries(option.shape).some(([key, field]) => (key in existing) && unwrap(field) instanceof exports_external.ZodLiteral && field.safeParse(existing[key]).success));
    if (selected)
      return segment in selected.shape ? selected : undefined;
  }
  return options.find((option) => (segment in option.shape));
}
function coerceForSchema(schema, raw, key) {
  const target = unwrap(schema);
  if (target instanceof exports_external.ZodString) {
    return raw;
  }
  if (target instanceof exports_external.ZodNumber) {
    const n = Number(raw);
    if (!Number.isFinite(n)) {
      throw new UsageError(`Invalid value for ${key}: expected a number, got "${raw}".`);
    }
    return n;
  }
  if (target instanceof exports_external.ZodBoolean) {
    if (raw === "true")
      return true;
    if (raw === "false")
      return false;
    throw new UsageError(`Invalid value for ${key}: expected true or false, got "${raw}".`);
  }
  if (target instanceof exports_external.ZodEnum) {
    return raw;
  }
  if (target instanceof exports_external.ZodLiteral) {
    return typeof target._def.value === "string" ? raw : target._def.value;
  }
  if (target instanceof exports_external.ZodArray || target instanceof exports_external.ZodObject || target instanceof exports_external.ZodRecord) {
    if (raw === "" || raw === "null")
      return;
    try {
      return JSON.parse(raw);
    } catch (err) {
      const detail = err instanceof Error ? err.message : String(err);
      throw new UsageError(`Invalid JSON for ${key}: ${detail}`, "INVALID_JSON_CONFIG_VALUE");
    }
  }
  if (target instanceof exports_external.ZodUnion) {
    const options = target._def.options;
    let lastErr;
    for (const opt of options) {
      try {
        const coerced = coerceForSchema(opt, raw, key);
        const parsed = opt.safeParse(coerced);
        if (parsed.success)
          return parsed.data;
        lastErr = parsed.error;
      } catch (err) {
        lastErr = err;
      }
    }
    if (lastErr instanceof Error)
      throw new UsageError(`Invalid value for ${key}: ${lastErr.message}`);
    throw new UsageError(`Invalid value for ${key}: did not match any expected type.`);
  }
  if (target instanceof exports_external.ZodNull) {
    if (raw === "" || raw === "null")
      return null;
    throw new UsageError(`Invalid value for ${key}: expected null.`);
  }
  if (raw === "" || raw === "null")
    return;
  try {
    return JSON.parse(raw);
  } catch {
    return raw;
  }
}
// src/core/config/config.ts
var DEFAULT_CONFIG = {
  configVersion: "0.9.0",
  semanticSearchMode: "off",
  registries: [
    { url: "https://raw.githubusercontent.com/itlackey/akm-registry/main/index.json", name: "akm-registry" },
    { url: "https://skills.sh", name: "skills.sh", provider: "skills-sh", enabled: false }
  ],
  output: {
    format: "json",
    detail: "brief"
  }
};
var cachedConfig;
function resetConfigCache() {
  cachedConfig = undefined;
}
function loadUserConfig() {
  const configPath = getConfigPath();
  let stat;
  try {
    stat = fs10.statSync(configPath);
  } catch (err) {
    if (err.code !== "ENOENT") {
      throw new ConfigError(`Unable to read config at ${configPath}: ${err instanceof Error ? err.message : String(err)}`, "INVALID_CONFIG_FILE");
    }
    cachedConfig = undefined;
    return { ...DEFAULT_CONFIG };
  }
  if (cachedConfig && cachedConfig.path === configPath && cachedConfig.mtime === stat.mtimeMs && cachedConfig.size === stat.size) {
    return cachedConfig.config;
  }
  let text;
  try {
    text = readConfigText(configPath);
  } catch (err) {
    throw new ConfigError(`Unable to read config at ${configPath}: ${err instanceof Error ? err.message : String(err)}`, "INVALID_CONFIG_FILE");
  }
  if (text === undefined) {
    cachedConfig = undefined;
    return { ...DEFAULT_CONFIG };
  }
  const finalConfig = parseAndValidateConfigText(text, configPath);
  let finalStat = stat;
  try {
    finalStat = fs10.statSync(configPath);
  } catch {}
  cachedConfig = {
    config: finalConfig,
    path: configPath,
    mtime: finalStat.mtimeMs,
    size: finalStat.size
  };
  return finalConfig;
}
function runConfigFilePipeline(text, sourcePath) {
  const versioned = readConfigVersion(parseConfigText(text, sourcePath), sourcePath);
  const parsedRaw = migrateLegacySourceShape(versioned, sourcePath);
  return liftExtraParamsOrThrow(parsedRaw, sourcePath);
}
function readConfigVersion(raw, sourcePath) {
  const version = raw.configVersion;
  if (version === CURRENT_CONFIG_VERSION)
    return raw;
  if (version !== undefined) {
    warnOnce(`config:config-version${sourcePath ? `:${sourcePath}` : ""}`, `${sourcePath ?? "config.json"} declares configVersion ${JSON.stringify(version)}; this release reads it as ${CURRENT_CONFIG_VERSION}.`);
  }
  return { ...raw, configVersion: CURRENT_CONFIG_VERSION };
}
function liftExtraParamsOrThrow(parsedRaw, sourcePath) {
  const where = sourcePath ? ` at ${sourcePath}` : "";
  const { config: liftedConfig, lifted, conflicts } = liftLegacyEngineExtraParams(parsedRaw);
  if (conflicts.length > 0) {
    const lines = conflicts.map((c) => `  - engines.${c.engine}.extraParams.${c.key} (${JSON.stringify(c.extraParamsValue)}) conflicts with engines.${c.engine}.${c.field} (${JSON.stringify(c.fieldValue)})`).join(`
`);
    throw new ConfigError(`Invalid config${where}: extraParams and the first-class field disagree:
${lines}

Each extraParams key above has a first-class equivalent and akm will not guess which value you meant — remove the extraParams entry once the field carries the value you want.`, "INVALID_CONFIG_FILE");
  }
  if (lifted.length > 0) {
    warnOnce(`config:extra-params-lift${sourcePath ? `:${sourcePath}` : ""}`, `Config${where} uses deprecated extraParams keys with first-class equivalents — auto-lifted in memory:
  - ${lifted.join(`
  - `)}

Run \`akm migrate apply\` to rewrite the config file and silence this warning.`);
  }
  return liftedConfig;
}
function buildEffectiveConfig(liftedLocalRaw, sourcePath) {
  const withExtends = resolveExtendsChain(liftedLocalRaw, sourcePath);
  const where = sourcePath ? ` at ${sourcePath}` : "";
  warnUnknownConfigKeys(liftedLocalRaw, sourcePath);
  const parsed = AkmConfigSchema.safeParse(withExtends);
  if (!parsed.success) {
    const lines = parsed.error.issues.map((i) => `  - ${i.path.join(".") || "(root)"}: ${i.message}`).join(`
`);
    throw new ConfigError(`Invalid config${where}:
${lines}`, "INVALID_CONFIG_FILE");
  }
  const merged = deepMergeConfig(DEFAULT_CONFIG, parsed.data);
  const finalResult = AkmConfigSchema.safeParse(merged);
  if (!finalResult.success) {
    const lines = finalResult.error.issues.map((i) => `  - ${i.path.join(".") || "(root)"}: ${i.message}`).join(`
`);
    throw new ConfigError(`Invalid merged config${sourcePath ? ` at ${sourcePath}` : ""}:
${lines}`, "INVALID_CONFIG_FILE");
  }
  assertUniquePhysicalBundleRoots(finalResult.data, sourcePath);
  return finalResult.data;
}
var RETIRED_CATCHALL_KEY_PATHS = new Set(["index.graph", "index.metadataEnhance"]);
function unknownConfigKeyPaths(root, node = root, prefix = []) {
  const found = [];
  for (const key of Object.keys(node).sort()) {
    const keyPath = [...prefix, key];
    if (RETIRED_CATCHALL_KEY_PATHS.has(keyPath.join(".")) || resolveSchemaAt(keyPath, root) === undefined) {
      found.push(keyPath);
      continue;
    }
    const value = node[key];
    if (isPlainConfigObject(value))
      found.push(...unknownConfigKeyPaths(root, value, keyPath));
  }
  return found;
}
function warnUnknownConfigKeys(raw, sourcePath) {
  for (const keyPath of unknownConfigKeyPaths(raw)) {
    const dotted = keyPath.join(".");
    warnOnce(`config:unknown-key:${sourcePath ?? "inline"}:${dotted}`, `Unknown config key ${JSON.stringify(dotted)}${sourcePath ? ` at ${sourcePath}` : ""} has no defined akm behavior and is ignored. Check the spelling; a key retired by this release or added by a newer one is dropped by \`akm migrate apply\`.`);
  }
}
function deleteConfigPath(node, keyPath) {
  let cursor = node;
  for (const segment of keyPath.slice(0, -1)) {
    if (!isPlainConfigObject(cursor))
      return;
    cursor = cursor[segment];
  }
  if (isPlainConfigObject(cursor))
    delete cursor[keyPath[keyPath.length - 1]];
}
function isPlainConfigObject(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}
function assertUniquePhysicalBundleRoots(config, sourcePath) {
  const owners = new Map;
  for (const { id, contentRoot } of bundleContentRoots(config)) {
    const prior = owners.get(contentRoot);
    if (prior !== undefined) {
      throw new ConfigError(`Invalid config${sourcePath ? ` at ${sourcePath}` : ""}: bundles ${JSON.stringify(prior)} and ${JSON.stringify(id)} resolve to the same physical content root ${contentRoot}.`, "INVALID_CONFIG_FILE", "Configure one bundle id per physical source root; symbolic-link aliases are not separate bundles.");
    }
    owners.set(contentRoot, id);
  }
}
function parseAndValidateConfigText(text, sourcePath) {
  const liftedConfig = runConfigFilePipeline(text, sourcePath);
  return buildEffectiveConfig(liftedConfig, sourcePath);
}
function collectExtendsLayers(localRaw, configPath) {
  const layers = [{ ref: undefined, raw: localRaw }];
  const visited = new Set(configPath ? [path14.resolve(configPath)] : []);
  let current = localRaw;
  let currentPath = configPath;
  let containmentRoot;
  while (true) {
    const ref = current.extends;
    if (ref === undefined)
      return layers;
    if (typeof ref !== "string" || !ref.trim()) {
      throw new ConfigError(`Invalid "extends"${currentPath ? ` at ${currentPath}` : ""}: expected a non-empty string (a file path or bundle//path ref), got ${JSON.stringify(ref)}.`, "INVALID_CONFIG_FILE");
    }
    const resolved = resolveConfigRefSource(ref, current, currentPath, containmentRoot);
    const { text, resolvedPath } = resolved;
    if (visited.has(resolvedPath)) {
      throw new ConfigError(`Config "extends" cycle detected: "${ref}"${currentPath ? ` (from ${currentPath})` : ""} resolves back to an already-visited config at ${resolvedPath}.`, "INVALID_CONFIG_FILE");
    }
    visited.add(resolvedPath);
    const baseRaw = runConfigFilePipeline(text, resolvedPath);
    warnUnknownConfigKeys(baseRaw, resolvedPath);
    layers.push({ ref, raw: baseRaw });
    current = baseRaw;
    currentPath = resolvedPath;
    containmentRoot = resolved.containmentRoot;
  }
}
function resolveExtendsChain(localRaw, configPath) {
  const layers = collectExtendsLayers(localRaw, configPath);
  let merged = {};
  for (let i = layers.length - 1;i >= 0; i--) {
    const layer = layers[i];
    merged = deepMergeConfig(merged, i > 0 ? sanitizeInheritedConfig(layer.raw, layer.ref ?? String(i)) : layer.raw);
  }
  return merged;
}
var HOST_LOCAL_CONFIG_KEYS = new Set([
  "bundles",
  "defaultBundle",
  "defaultWriteTarget",
  "embedding",
  "execution",
  "experimental",
  "registries",
  "scheduler",
  "setup"
]);
function sanitizeInheritedConfig(raw, label) {
  const inherited = { ...raw };
  for (const key of HOST_LOCAL_CONFIG_KEYS) {
    if (!Object.hasOwn(inherited, key))
      continue;
    delete inherited[key];
    warnOnce(`config:inherited-host-local:${label}:${key}`, `Ignoring inherited config key ${JSON.stringify(key)} from ${label}; it is host-local and must be declared in the top-level config file.`);
  }
  if (isPlainObject(inherited.engines)) {
    const engines = {};
    let strippedAuthority = false;
    for (const [name, engine] of Object.entries(inherited.engines)) {
      if (!isPlainObject(engine)) {
        engines[name] = engine;
        continue;
      }
      const portable = { ...engine };
      for (const key of ["apiKey", "apiKeyFile", "bin", "args", "workspace"]) {
        if (!Object.hasOwn(portable, key))
          continue;
        delete portable[key];
        strippedAuthority = true;
      }
      engines[name] = portable;
    }
    inherited.engines = engines;
    if (strippedAuthority) {
      warnOnce(`config:inherited-host-local:${label}:engines-authority`, `Ignoring inherited engine credentials, executable arguments, or workspace from ${label}; those fields are host-local.`);
    }
  }
  if (isPlainObject(inherited.search) && Object.hasOwn(inherited.search, "curateRerank")) {
    const { curateRerank: _curateRerank, ...portableSearch } = inherited.search;
    inherited.search = portableSearch;
    warnOnce(`config:inherited-host-local:${label}:search.curateRerank`, `Ignoring inherited config key "search.curateRerank" from ${label}; network endpoints and credentials are host-local.`);
  }
  if (isPlainObject(inherited.improve) && isPlainObject(inherited.improve.strategies)) {
    const strategies = {};
    let strippedSync = false;
    for (const [name, profile] of Object.entries(inherited.improve.strategies)) {
      if (isPlainObject(profile) && Object.hasOwn(profile, "sync")) {
        const { sync: _sync, ...portableProfile } = profile;
        strategies[name] = portableProfile;
        strippedSync = true;
      } else {
        strategies[name] = profile;
      }
    }
    inherited.improve = { ...inherited.improve, strategies };
    if (strippedSync) {
      warnOnce(`config:inherited-host-local:${label}:improve.sync`, `Ignoring inherited improve strategy sync policy from ${label}; publication policy is host-local.`);
    }
  }
  return inherited;
}
function expandExtendsHomePath(p) {
  return p.startsWith("~") ? path14.join(os2.homedir(), p.slice(1)) : p;
}
function looksLikeBundleAssetRef(ref) {
  const boundary = ref.indexOf("//");
  return boundary > 0 && isBundleSlug(ref.slice(0, boundary));
}
function resolveConfigRefSource(ref, context, fromConfigPath, containmentRoot) {
  return looksLikeBundleAssetRef(ref) ? resolveConfigBundleRefSource(ref, context, containmentRoot) : resolveConfigFileRefSource(ref, fromConfigPath, containmentRoot);
}
function resolveConfigFileRefSource(ref, fromConfigPath, containmentRoot) {
  const expanded = expandExtendsHomePath(ref);
  let resolvedPath;
  if (path14.isAbsolute(expanded)) {
    resolvedPath = expanded;
  } else if (fromConfigPath) {
    resolvedPath = path14.resolve(path14.dirname(fromConfigPath), expanded);
  } else {
    throw new ConfigError(`extends "${ref}" is a relative path, but the current config has no known file location to resolve it against.`, "INVALID_CONFIG_FILE");
  }
  if (containmentRoot !== undefined)
    assertConfigExtendsPhysicalContainment(containmentRoot, resolvedPath, ref);
  const text = readConfigText(resolvedPath);
  if (text === undefined) {
    throw new ConfigError(`extends "${ref}" resolves to ${resolvedPath}, which does not exist. Create the file first, or point "extends" at an existing config.`, "INVALID_CONFIG_FILE");
  }
  return { text, resolvedPath, ...containmentRoot ? { containmentRoot } : {} };
}
function resolveConfigBundleRefSource(ref, context, outerContainmentRoot) {
  const boundary = ref.indexOf("//");
  const bundleId = ref.slice(0, boundary);
  const relativePath = ref.slice(boundary + 2);
  if (!relativePath) {
    throw new ConfigError(`extends "${ref}" is missing a path after "${bundleId}//".`, "INVALID_CONFIG_FILE");
  }
  if (path14.isAbsolute(relativePath)) {
    throw new ConfigError(`extends "${ref}" must be a path relative to bundle "${bundleId}"'s content root, not absolute.`, "INVALID_CONFIG_FILE");
  }
  const bundles = isRecord(context.bundles) ? context.bundles : undefined;
  const bundleEntry = bundles?.[bundleId];
  const bundlePath = isRecord(bundleEntry) && typeof bundleEntry.path === "string" && bundleEntry.path.length > 0 ? bundleEntry.path : undefined;
  if (!bundlePath || !isRecord(bundleEntry)) {
    throw new ConfigError(`extends "${ref}" names bundle "${bundleId}", which is not a configured filesystem bundle (bundles.${bundleId}.path). Only a filesystem bundle can host an "extends" source.`, "INVALID_CONFIG_FILE");
  }
  let componentRoot;
  try {
    componentRoot = bundleComponentConfig(bundleEntry)?.root;
  } catch (err) {
    throw new ConfigError(`extends "${ref}" names bundle "${bundleId}": ${err instanceof Error ? err.message : String(err)}`, "INVALID_CONFIG_FILE");
  }
  const bundleRoot = bundleContentRoot(bundlePath, componentRoot);
  const resolvedPath = path14.resolve(bundleRoot, relativePath);
  const relativeToRoot = path14.relative(bundleRoot, resolvedPath);
  if (relativeToRoot === ".." || relativeToRoot.startsWith(`..${path14.sep}`) || path14.isAbsolute(relativeToRoot)) {
    throw new ConfigError(`extends "${ref}" escapes bundle "${bundleId}"'s content root.`, "INVALID_CONFIG_FILE");
  }
  const containmentRoot = fs10.realpathSync.native(bundleRoot);
  assertConfigExtendsPhysicalContainment(containmentRoot, resolvedPath, ref);
  if (outerContainmentRoot !== undefined) {
    assertConfigExtendsPhysicalContainment(outerContainmentRoot, resolvedPath, ref);
  }
  const text = readConfigText(resolvedPath);
  if (text === undefined) {
    throw new ConfigError(`extends "${ref}" resolves to ${resolvedPath}, which does not exist locally. Sync the bundle first, or point "extends" at an existing file.`, "INVALID_CONFIG_FILE");
  }
  return { text, resolvedPath, containmentRoot: outerContainmentRoot ?? containmentRoot };
}
function assertConfigExtendsPhysicalContainment(root, candidate, ref) {
  let physicalRoot;
  let physicalCandidate;
  try {
    physicalRoot = fs10.realpathSync.native(root);
    physicalCandidate = fs10.realpathSync.native(candidate);
  } catch (cause) {
    throw new ConfigError(`Unable to verify physical containment for extends ${JSON.stringify(ref)}: ${cause instanceof Error ? cause.message : String(cause)}`, "INVALID_CONFIG_FILE");
  }
  const relative = path14.relative(physicalRoot, physicalCandidate);
  if (relative === ".." || relative.startsWith(`..${path14.sep}`) || path14.isAbsolute(relative)) {
    throw new ConfigError(`extends ${JSON.stringify(ref)} resolves through a symbolic link outside its bundle content root.`, "INVALID_CONFIG_FILE");
  }
}
function loadConfig() {
  return loadUserConfig();
}
function validateCompleteConfig(config) {
  const parseResult = AkmConfigSchema.safeParse(config);
  if (parseResult.success)
    return parseResult.data;
  const lines = parseResult.error.issues.map((i) => `  - ${i.path.join(".") || "(root)"}: ${i.message}`).join(`
`);
  throw new ConfigError(`Refusing to save invalid config:
${lines}`, "INVALID_CONFIG_FILE", "Fix the listed fields, or undo the offending `akm config set`. " + "If this looks like an akm bug, re-run with --debug to attach the traceback.");
}
function pruneUnchangedInheritedFields(before, after, localRaw) {
  if (!isPlainObject(after) || !isPlainObject(before))
    return after;
  const localRecord = isPlainObject(localRaw) ? localRaw : undefined;
  const result = {};
  for (const key of Object.keys(after)) {
    const afterValue = after[key];
    const beforeValue = before[key];
    const localHasKey = localRecord ? Object.hasOwn(localRecord, key) : false;
    if (isPlainObject(afterValue) && isPlainObject(beforeValue)) {
      const pruned = pruneUnchangedInheritedFields(beforeValue, afterValue, localHasKey ? localRecord?.[key] : undefined);
      const prunedHasContent = isPlainObject(pruned) ? Object.keys(pruned).length > 0 : pruned !== undefined;
      if (prunedHasContent || localHasKey)
        result[key] = pruned;
      continue;
    }
    if (localHasKey || !isDeepStrictEqual(afterValue, beforeValue)) {
      result[key] = afterValue;
    }
  }
  return result;
}
function configWriteBody(localRaw, current, next, persistTopLevelKeys = []) {
  if (localRaw === undefined)
    return next;
  const pruned = pruneUnchangedInheritedFields(current, next, localRaw);
  for (const key of persistTopLevelKeys) {
    if (Object.hasOwn(next, key))
      pruned[key] = next[key];
  }
  pruned.configVersion = CURRENT_CONFIG_VERSION;
  const ordered = {};
  for (const key of Object.keys(localRaw)) {
    if (Object.hasOwn(pruned, key))
      ordered[key] = pruned[key];
  }
  for (const [key, value] of Object.entries(pruned)) {
    if (!Object.hasOwn(ordered, key))
      ordered[key] = value;
  }
  return ordered;
}
function normalizeConfigFile(configPath, options) {
  return withConfigLock(() => {
    const text = readConfigText(configPath);
    if (text === undefined)
      return { keys: [], changed: false, applied: false };
    const raw = parseConfigText(text, configPath);
    const localRaw = runConfigFilePipeline(text, configPath);
    const current = buildEffectiveConfig(localRaw, configPath);
    const next = validateCompleteConfig({ ...current, configVersion: CURRENT_CONFIG_VERSION });
    const body = withSchedulerOnDisk(configWriteBody(localRaw, current, next), next);
    for (const keyPath of unknownConfigKeyPaths(body))
      deleteConfigPath(body, keyPath);
    const strategies = body.improve?.strategies;
    if (strategies && Object.hasOwn(strategies, "graph-refresh"))
      delete strategies["graph-refresh"];
    const keys = [...new Set([...Object.keys(raw), ...Object.keys(body)])].filter((key) => JSON.stringify(raw[key]) !== JSON.stringify(body[key])).sort();
    if (keys.length === 0 || !options.apply)
      return { keys, changed: keys.length > 0, applied: false };
    const backup = backupExistingConfig(configPath);
    writeConfigAtomic(configPath, body);
    cachedConfig = undefined;
    return { keys, changed: true, applied: true, ...backup ? { backupPath: backup.timestamped } : {} };
  });
}
var UNBOUND_SCHEDULER_SOURCE_ID = `sha256:${"0".repeat(64)}`;
function schedulerSourceIdFor(config, bundleId) {
  if (isBundleEnabled(config, bundleId))
    return bundleSourceId(config, bundleId);
  if (config.bundles?.[bundleId] !== undefined || !process.env.AKM_BUNDLE_DIR?.trim())
    return;
  try {
    const root = resolveStashDir();
    const implicitId = deriveBundleId(undefined, root, new Set(Object.keys(config.bundles ?? {})));
    return implicitId === bundleId ? filesystemBundleSourceId(root) : undefined;
  } catch {
    return;
  }
}
function schedulerEnabledOnDisk(config) {
  const enabled = config.scheduler?.enabled;
  if (enabled === undefined)
    return;
  return enabled.map((ref) => {
    let bundle;
    let conceptId = "";
    try {
      const parsed = parseBundleRef(ref);
      bundle = parsed.bundle;
      conceptId = parsed.conceptId;
    } catch {
      return ref;
    }
    return {
      kind: conceptId.startsWith("workflows/") ? "workflow" : "task",
      ref,
      sourceId: (bundle !== undefined ? schedulerSourceIdFor(config, bundle) : undefined) ?? UNBOUND_SCHEDULER_SOURCE_ID
    };
  });
}
function withSchedulerOnDisk(body, config) {
  const onDisk = schedulerEnabledOnDisk(config);
  if (onDisk === undefined || !isPlainConfigObject(body.scheduler))
    return body;
  return { ...body, scheduler: { ...body.scheduler, enabled: onDisk } };
}
function resolveSecret(value, resolveFromStore) {
  if (value === undefined)
    return;
  if (typeof value !== "string")
    return value;
  const storeRef = SECRET_STORE_REFERENCE_PATTERN.exec(value)?.[1];
  if (storeRef !== undefined) {
    const resolved = resolveFromStore?.(storeRef) ?? null;
    if (resolved === null) {
      throw new ConfigError(`Secret store reference "${value}" did not resolve to a stored value.`, "SECRET_REFERENCE_UNRESOLVED");
    }
    return resolved;
  }
  if (!value.includes("$"))
    return value;
  return value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)/g, (_match, braced, bare) => {
    const name = braced ?? bare;
    const resolved = process.env[name];
    if (!resolved) {
      warnOnce(`config:empty-env-var:${name}`, `Environment variable ${name} referenced by a $VAR apiKey is unset or empty; the request will be sent without a valid credential.`);
    }
    return resolved ?? "";
  });
}

// src/core/redaction.ts
var ENV_PASSTHROUGH_REDACTION_POLICY = {
  HOME: "path",
  PATH: "path",
  USER: "identifier",
  LANG: "identifier",
  LC_ALL: "identifier",
  TERM: "identifier",
  TMPDIR: "path",
  SYSTEMROOT: "path",
  COMSPEC: "path",
  PATHEXT: "path",
  WINDIR: "path",
  TEMP: "path",
  TMP: "path",
  AKM_EVENT_SOURCE: "identifier",
  OPENCODE_CONFIG: "path",
  CLAUDE_CONFIG: "path",
  CODEX_CONFIG: "path",
  XDG_CONFIG_HOME: "path",
  XDG_DATA_HOME: "path",
  XDG_CACHE_HOME: "path",
  XDG_STATE_HOME: "path",
  AWS_PROFILE: "identifier",
  AWS_REGION: "identifier",
  LLM_MODEL: "identifier",
  LLM_BASE_URL: "url"
};
var ENV_PASSTHROUGH_REDACTION_ALLOWLIST = new Set(Object.keys(ENV_PASSTHROUGH_REDACTION_POLICY));
var SIGNED_QUERY_KEYS = new Set([
  "accesskey",
  "accesskeyid",
  "accesstoken",
  "actortoken",
  "apikey",
  "assertion",
  "authorization",
  "authorizationcode",
  "authreqid",
  "clientassertion",
  "clientsecret",
  "code",
  "codeverifier",
  "credential",
  "devicecode",
  "googleaccessid",
  "idtoken",
  "idtokenhint",
  "initialaccesstoken",
  "key",
  "loginhinttoken",
  "logouthint",
  "logouttoken",
  "nonce",
  "oauthcode",
  "oauthtoken",
  "oauthverifier",
  "password",
  "refreshtoken",
  "registrationaccesstoken",
  "requesturi",
  "response",
  "secret",
  "sessiontoken",
  "sharedaccesssignature",
  "sig",
  "signature",
  "softwarestatement",
  "state",
  "subjecttoken",
  "token",
  "usercode",
  "verifier",
  "xamzcredential",
  "xamzsecuritytoken",
  "xamzsignature",
  "xgoogcredential",
  "xgoogsignature"
]);
var CREDENTIAL_KEY_WORDS = new Set(["password", "passwd", "secret", "token", "auth", "credential", "credentials"]);
var NAMED_CREDENTIAL_VALUE_SOURCE = String.raw`\b([A-Za-z][A-Za-z0-9_-]*)(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;"']+)`;

// src/indexer/index-writer-lock.ts
import { AsyncLocalStorage as AsyncLocalStorage3 } from "node:async_hooks";
var DEFAULT_ASSET_MUTATION_MAX_WAIT_MS = 10 * 60 * 1000;
var leaseContext = new AsyncLocalStorage3;

// src/integrations/lockfile.ts
import fs11 from "node:fs";
function readLockfile() {
  const lockfilePath = getLockfilePath();
  try {
    const raw = JSON.parse(fs11.readFileSync(lockfilePath, "utf8"));
    if (!Array.isArray(raw))
      return [];
    return raw.filter(isValidLockfileEntry);
  } catch (err) {
    rethrowIfTestIsolationError(err);
    return [];
  }
}
function lockContentRootFor(bundleId, type) {
  if (!bundleId || type !== "git" && type !== "npm")
    return;
  for (const lock of readLockfile()) {
    if (lock.id === bundleId && typeof lock.localRoot === "string" && lock.localRoot.length > 0) {
      return lock.localRoot;
    }
  }
  return;
}
function isValidLockfileEntry(value) {
  if (typeof value !== "object" || value === null || Array.isArray(value))
    return false;
  const obj = value;
  return typeof obj.id === "string" && obj.id !== "" && typeof obj.source === "string" && ["npm", "github", "git", "local"].includes(obj.source) && typeof obj.ref === "string" && obj.ref !== "";
}

// src/sources/providers/git-install.ts
import { spawnSync as spawnSync4 } from "node:child_process";
import { randomBytes } from "node:crypto";
import fs28 from "node:fs";
import path35 from "node:path";

// src/registry/resolve.ts
import { spawnSync as spawnSync3 } from "node:child_process";
import fs12 from "node:fs";
import os3 from "node:os";
import path15 from "node:path";
import { fileURLToPath as fileURLToPath2, pathToFileURL } from "node:url";

// src/integrations/github.ts
import * as childProcess from "node:child_process";
var GITHUB_API_BASE = "https://api.github.com";
var GITHUB_TOKEN_DOMAINS = new Set(["api.github.com", "github.com", "uploads.github.com"]);
function readGithubTokenFromEnv() {
  if (process.env.GITHUB_TOKEN !== undefined) {
    return process.env.GITHUB_TOKEN.trim();
  }
  if (process.env.GH_TOKEN !== undefined) {
    return process.env.GH_TOKEN.trim();
  }
  return;
}
function readGithubTokenFromGhCli() {
  const result = childProcess.spawnSync("gh", ["auth", "token", "--hostname", "github.com"], {
    encoding: "utf8",
    timeout: 5000,
    stdio: ["ignore", "pipe", "ignore"]
  });
  if (result.status !== 0)
    return;
  const token = result.stdout.trim();
  return token || undefined;
}
function resolveGithubToken() {
  const token = readGithubTokenFromEnv();
  return token !== undefined ? token || undefined : readGithubTokenFromGhCli();
}
function githubHeaders(url) {
  const token = resolveGithubToken();
  const headers = {
    Accept: "application/vnd.github+json",
    "User-Agent": "akm-registry"
  };
  if (token) {
    let includeToken = true;
    if (url) {
      try {
        const hostname = new URL(url).hostname;
        includeToken = GITHUB_TOKEN_DOMAINS.has(hostname);
      } catch {
        includeToken = false;
      }
    }
    if (includeToken)
      headers.Authorization = `Bearer ${token}`;
  }
  return headers;
}
function asRecord(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
}
function asString(value) {
  return typeof value === "string" && value ? value : undefined;
}

// src/registry/network.ts
var DEFAULT_TIMEOUT_MS = 30000;
var DEFAULT_RETRIES = 2;
var DEFAULT_JSON_BYTE_CAP = 10 * 1024 * 1024;
var MAX_RETRY_DELAY_MS = 30000;
async function fetchRegistry(rawUrl, options = {}) {
  const url = parseRegistryUrl(rawUrl);
  const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
  const retries = options.retries ?? DEFAULT_RETRIES;
  for (let attempt = 0;; attempt += 1) {
    const timeout = AbortSignal.timeout(timeoutMs);
    const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
    let response;
    try {
      response = await fetch(rawUrl, { headers: options.headers, signal, redirect: "follow" });
    } catch (error2) {
      if (options.signal?.aborted)
        throw error2;
      if (attempt < retries) {
        await abortableDelay(backoffDelay(attempt, undefined, MAX_RETRY_DELAY_MS), options.signal);
        continue;
      }
      const reason = timeout.aborted ? `timed out after ${timeoutMs}ms` : `failed: ${toErrorMessage(error2)}`;
      throw new TransientError(`Registry request to ${url.host} ${reason} (${rawUrl})`, "REGISTRY_UNREACHABLE");
    }
    if (attempt < retries && shouldRetry(response.status)) {
      await cancelBody(response);
      await abortableDelay(computeRetryDelay(response, attempt, { maxDelayMs: MAX_RETRY_DELAY_MS }), options.signal);
      continue;
    }
    if (response.ok)
      return response;
    await cancelBody(response);
    throw statusError(response.status, rawUrl);
  }
}
async function fetchRegistryJson(rawUrl, options = {}) {
  const response = await fetchRegistry(rawUrl, options);
  try {
    return await jsonWithByteCap(response, options.maxBytes ?? DEFAULT_JSON_BYTE_CAP, {
      bodyTimeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
      signal: options.signal
    });
  } catch (error2) {
    if (options.signal?.aborted)
      throw error2;
    if (error2 instanceof ResponseTooLargeError || error2 instanceof SyntaxError) {
      throw new NotFoundError(`Registry response from ${rawUrl} is not usable: ${toErrorMessage(error2)}`, "REGISTRY_RESPONSE_INVALID");
    }
    throw new TransientError(`Registry response from ${rawUrl} could not be read: ${toErrorMessage(error2)}`, "REGISTRY_UNREACHABLE");
  }
}
function parseRegistryUrl(rawUrl) {
  let url;
  try {
    url = new URL(rawUrl);
  } catch {
    throw new ConfigError(`Registry URL is not a valid URL: ${formatRegistryUrl(rawUrl)}`, "REGISTRY_URL_INVALID");
  }
  if (url.protocol !== "http:" && url.protocol !== "https:") {
    throw new ConfigError(`Registry URL must use http(s), not ${url.protocol || "an empty scheme"}: ${formatRegistryUrl(rawUrl)}`, "REGISTRY_URL_INVALID");
  }
  if (url.username || url.password) {
    throw new ConfigError(`Registry URL must not embed credentials: ${url.origin}`, "REGISTRY_URL_INVALID");
  }
  return url;
}
function statusError(status, rawUrl) {
  const message = `Registry request failed (HTTP ${status}) for ${rawUrl}`;
  if (shouldRetry(status))
    return new TransientError(message, "REGISTRY_UNREACHABLE");
  if (status === 404 || status === 410)
    return new NotFoundError(message, "REGISTRY_NOT_FOUND");
  const hint = status === 401 || status === 403 ? "The registry refused the request. For GitHub, set GITHUB_TOKEN or sign in with `gh auth login`; akm's registry providers send no other credentials." : undefined;
  return new NotFoundError(message, "REGISTRY_RESPONSE_INVALID", hint);
}
async function cancelBody(response) {
  await response.body?.cancel().catch(() => {
    return;
  });
}

// src/registry/semver.ts
var import_semver = __toESM(require_semver2(), 1);
function isExactSemver(version) {
  return import_semver.default.valid(version) !== null;
}
function isSemverRange(input) {
  return import_semver.default.validRange(input) !== null;
}
function maxSatisfying(versions, range) {
  return import_semver.default.maxSatisfying(versions, range) ?? undefined;
}

// src/registry/resolve.ts
function gitCredentialEnvironment(credential) {
  if (!credential)
    return { ...process.env };
  if (/[\r\n\0]/.test(credential)) {
    throw new UsageError("Git credential contains an invalid control character.");
  }
  const configuredCount = process.env.GIT_CONFIG_COUNT;
  const nextIndex = configuredCount === undefined ? 0 : Number(configuredCount);
  if (!Number.isSafeInteger(nextIndex) || nextIndex < 0) {
    throw new UsageError("GIT_CONFIG_COUNT must be a non-negative integer before a Git credential can be added.");
  }
  return {
    ...process.env,
    GIT_CONFIG_COUNT: String(nextIndex + 1),
    [`GIT_CONFIG_KEY_${nextIndex}`]: "http.extraHeader",
    [`GIT_CONFIG_VALUE_${nextIndex}`]: `Authorization: Bearer ${credential}`
  };
}
function validateGitUrl(url) {
  if (/^git@[^:]+:.+$/.test(url))
    return;
  let parsed;
  try {
    parsed = new URL(url);
  } catch {
    throw new UsageError(`Invalid git URL: ${url}`);
  }
  const allowed = ["https:", "http:", "ssh:", "git:"];
  if (!allowed.includes(parsed.protocol)) {
    throw new UsageError(`Unsafe git URL scheme "${parsed.protocol}" in "${url}". Allowed: https, http, ssh, git, git@host:path`);
  }
}
function validateGitRef(ref) {
  if (!/^[a-zA-Z0-9._\-/]+$/.test(ref)) {
    throw new UsageError(`Unsafe git ref "${ref}": only alphanumerics, '.', '_', '-', '/' are allowed`);
  }
}
function parseRegistryRef(rawRef) {
  const ref = rawRef.trim();
  if (!ref)
    throw new UsageError("Registry ref is required.", "MISSING_REQUIRED_ARGUMENT");
  const registryIdHint = detectRegistrySearchId(ref);
  if (registryIdHint) {
    throw new UsageError(registryIdHint);
  }
  if (ref.startsWith("npm:")) {
    return parseNpmRef(ref.slice(4), ref);
  }
  if (ref.startsWith("github:")) {
    return parseGithubShorthand(ref.slice(7), ref);
  }
  if (ref.startsWith("git+")) {
    return parseGitUrl(stripGitTransport(ref), ref);
  }
  if (ref.startsWith("file:")) {
    return tryParseLocalRef(fileUriToPath(ref), true);
  }
  if (ref.startsWith("http://") || ref.startsWith("https://")) {
    return parseRemoteUrl(ref);
  }
  const localRef = tryParseLocalRef(ref, isPathLikeRef(ref));
  if (localRef) {
    return localRef;
  }
  if (ref.startsWith("@") || !looksLikeGithubOwnerRepo(ref)) {
    return parseNpmRef(ref, ref);
  }
  return parseGithubShorthand(ref, ref);
}
var KNOWN_PREFIXES = ["npm:", "github:", "git+", "file:", "http://", "https://"];
function detectRegistrySearchId(ref) {
  const colonIdx = ref.indexOf(":");
  if (colonIdx < 1)
    return;
  for (const prefix2 of KNOWN_PREFIXES) {
    if (ref.startsWith(prefix2))
      return;
  }
  const prefix = ref.slice(0, colonIdx);
  if (!/^[a-z][a-z0-9-]*$/.test(prefix))
    return;
  const rest = ref.slice(colonIdx + 1);
  const segments = rest.split("/").filter(Boolean);
  const suggestedRef = segments.length >= 2 ? `github:${segments[0]}/${segments[1]}` : undefined;
  const lines = [
    `"${ref}" looks like a registry search result ID, not an installable ref.`,
    `The "${prefix}:" prefix is a registry identifier and cannot be passed to \`akm bundle add\`.`,
    ""
  ];
  if (suggestedRef) {
    lines.push(`Try installing the source repository directly:`, `  akm bundle add ${suggestedRef}`, "");
  }
  lines.push("Or search for the installable ref:", `  akm search "${segments.length > 2 ? segments[segments.length - 1] : rest}" --from registry`, "Then install using the installRef value from the result:", "  akm bundle add github:owner/repo", "  akm bundle add npm:package-name");
  return lines.join(`
`);
}
async function resolveRegistryArtifact(parsed, options) {
  switch (parsed.source) {
    case "npm":
      return resolveNpmArtifact(parsed);
    case "local":
      return resolveLocalArtifact(parsed);
    case "git":
      return resolveGitArtifact(parsed, options?.gitCredential);
    case "github":
      return resolveGithubArtifact(parsed, options?.gitCredential);
  }
}
function parseNpmRef(input, originalRef) {
  const trimmed = input.trim();
  if (!trimmed)
    throw new UsageError("Invalid npm ref.");
  const parsed = splitNpmNameAndVersion(trimmed);
  validateNpmPackageName(parsed.packageName);
  return {
    source: "npm",
    ref: originalRef,
    id: `npm:${parsed.packageName}`,
    packageName: parsed.packageName,
    requestedVersionOrTag: parsed.requestedVersionOrTag
  };
}
function parseGithubShorthand(input, originalRef) {
  const [repoPart, requestedRef] = splitRefSuffix(input.trim());
  const segments = repoPart.split("/").filter(Boolean);
  if (segments.length !== 2) {
    throw new UsageError("Invalid GitHub ref. Expected owner/repo or owner/repo#ref.");
  }
  const owner = segments[0];
  const repo = segments[1].replace(/\.git$/i, "");
  if (!owner || !repo) {
    throw new UsageError("Invalid GitHub ref. Expected owner/repo.");
  }
  return {
    source: "github",
    ref: originalRef,
    id: `github:${owner}/${repo}`,
    owner,
    repo,
    requestedRef
  };
}
function parseRemoteUrl(rawUrl) {
  let url;
  try {
    url = new URL(rawUrl);
  } catch {
    throw new UsageError("Invalid registry URL.");
  }
  if (url.hostname === "github.com") {
    return parseGithubUrl(url, rawUrl);
  }
  return parseGitUrl(rawUrl, rawUrl);
}
function parseGithubUrl(url, rawUrl) {
  const segments = url.pathname.split("/").filter(Boolean);
  if (segments.length < 2) {
    throw new UsageError("Invalid GitHub URL. Expected https://github.com/owner/repo.");
  }
  const owner = segments[0];
  const repo = segments[1].replace(/\.git$/i, "");
  const requestedRef = url.hash ? decodeURIComponent(url.hash.slice(1)) : undefined;
  return {
    source: "github",
    ref: rawUrl,
    id: `github:${owner}/${repo}`,
    owner,
    repo,
    requestedRef
  };
}
function parseGitUrl(input, originalRef) {
  const [urlPart, requestedRef] = splitRefSuffix(input.trim());
  if (!urlPart)
    throw new UsageError("Invalid git ref. A URL is required.");
  const normalized = urlPart.replace(/\.git$/i, "");
  return {
    source: "git",
    ref: originalRef,
    id: `git:${normalized}`,
    url: urlPart,
    requestedRef
  };
}
function tryParseLocalRef(rawRef, explicitPath) {
  const resolvedPath = path15.resolve(rawRef);
  let stat;
  try {
    stat = fs12.statSync(resolvedPath);
  } catch {
    if (explicitPath) {
      throw new NotFoundError(`Local path not found: ${resolvedPath}`, "FILE_NOT_FOUND", "Check the path exists and is readable.");
    }
    return;
  }
  if (!stat.isDirectory()) {
    if (explicitPath) {
      throw new UsageError("Local add path must be a directory, but the provided path is not one.");
    }
    return;
  }
  const repoRoot = findGitRepoRoot(resolvedPath);
  return {
    source: "local",
    ref: rawRef,
    id: `local:${toReadableLocalId(resolvedPath)}`,
    repoRoot,
    sourcePath: resolvedPath
  };
}
function isPathLikeRef(ref) {
  if (ref.startsWith("@"))
    return false;
  if (ref === "." || ref === "..")
    return true;
  if (path15.isAbsolute(ref))
    return true;
  if (ref.startsWith("./") || ref.startsWith("../") || ref.startsWith(".\\") || ref.startsWith("..\\")) {
    return true;
  }
  if (looksLikeGithubOwnerRepo(ref))
    return false;
  return ref.includes("/") || ref.includes("\\");
}
var DEFAULT_NPM_REGISTRY_HOST = "registry.npmjs.org";
var UNTRUSTED_TARBALL_HINT = "Set AKM_NPM_REGISTRY to your private npm mirror's base URL if you install from a non-default registry.";
function validateNpmTarballUrl(tarballUrl, packageRef, registryOrigin) {
  let url;
  try {
    url = new URL(tarballUrl);
  } catch {
    throw new NotFoundError(`npm package ${packageRef} returned an invalid tarball URL: ${tarballUrl}`, "REGISTRY_RESPONSE_INVALID", UNTRUSTED_TARBALL_HINT);
  }
  if (url.protocol !== "https:" && url.protocol !== "http:") {
    throw new NotFoundError(`npm package ${packageRef} returned a tarball with disallowed scheme "${url.protocol}".`, "REGISTRY_RESPONSE_INVALID", UNTRUSTED_TARBALL_HINT);
  }
  const expectedOrigin = registryOrigin ?? new URL(npmMetadataRegistry()).origin;
  if (url.origin !== expectedOrigin) {
    throw new NotFoundError(`npm package ${packageRef} returned a tarball URL on untrusted origin "${url.origin}" (expected: ${expectedOrigin}).`, "REGISTRY_RESPONSE_INVALID", UNTRUSTED_TARBALL_HINT);
  }
}
function npmMetadataRegistry() {
  const override = process.env.AKM_NPM_REGISTRY?.trim();
  if (override) {
    let url;
    try {
      url = new URL(override);
    } catch {
      throw new ConfigError(`AKM_NPM_REGISTRY is set to an invalid URL: ${override}`, "REGISTRY_URL_INVALID");
    }
    return `${url.origin}${url.pathname === "/" ? "" : url.pathname}`.replace(/\/+$/, "");
  }
  return `https://${DEFAULT_NPM_REGISTRY_HOST}`;
}
async function resolveNpmArtifact(parsed) {
  const encodedName = encodeURIComponent(parsed.packageName);
  const registryBase = npmMetadataRegistry();
  const metadata = await fetchJson(`${registryBase}/${encodedName}`, undefined);
  const versions = asRecord(metadata.versions);
  const distTags = asRecord(metadata["dist-tags"]);
  const requested = parsed.requestedVersionOrTag;
  let resolvedVersion;
  if (!requested) {
    resolvedVersion = asString(distTags.latest);
  } else if (requested in versions) {
    resolvedVersion = requested;
  } else {
    resolvedVersion = asString(distTags[requested]);
    if (!resolvedVersion && isSemverRange(requested)) {
      const versionKeys = Object.keys(versions).filter(isExactSemver);
      resolvedVersion = maxSatisfying(versionKeys, requested);
    }
  }
  if (!resolvedVersion || !(resolvedVersion in versions)) {
    throw new NotFoundError(`Unable to resolve npm ref "${parsed.ref}".`, "REGISTRY_NOT_FOUND");
  }
  const versionMeta = asRecord(versions[resolvedVersion]);
  const dist = asRecord(versionMeta.dist);
  const tarballUrl = asString(dist.tarball);
  if (!tarballUrl) {
    throw new NotFoundError(`npm package ${parsed.packageName}@${resolvedVersion} does not expose a tarball URL.`, "REGISTRY_RESPONSE_INVALID");
  }
  validateNpmTarballUrl(tarballUrl, `${parsed.packageName}@${resolvedVersion}`, new URL(registryBase).origin);
  const resolvedRevision = asString(dist.shasum) ?? asString(dist.integrity);
  return {
    id: parsed.id,
    source: parsed.source,
    ref: parsed.ref,
    artifactUrl: tarballUrl,
    resolvedVersion,
    resolvedRevision
  };
}
async function resolveGithubArtifact(parsed, credential) {
  const gitUrl = `https://github.com/${encodeURIComponent(parsed.owner)}/${encodeURIComponent(parsed.repo)}.git`;
  const repoBase = `${GITHUB_API_BASE}/repos/${encodeURIComponent(parsed.owner)}/${encodeURIComponent(parsed.repo)}`;
  const gitResolvedRevision = resolveGitRevisionFromRemote(gitUrl, parsed.requestedRef, credential);
  if (gitResolvedRevision) {
    return {
      id: parsed.id,
      source: parsed.source,
      ref: parsed.ref,
      artifactUrl: gitUrl,
      resolvedVersion: parsed.requestedRef,
      resolvedRevision: gitResolvedRevision
    };
  }
  const headers = { ...githubHeaders(), ...credential ? { Authorization: `Bearer ${credential}` } : {} };
  if (parsed.requestedRef) {
    const commit2 = await tryFetchJson(`${repoBase}/commits/${encodeURIComponent(parsed.requestedRef)}`, headers);
    const resolvedRevision = asString(commit2?.sha) ?? parsed.requestedRef;
    return {
      id: parsed.id,
      source: parsed.source,
      ref: parsed.ref,
      artifactUrl: `${repoBase}/tarball/${encodeURIComponent(parsed.requestedRef)}`,
      resolvedRevision,
      resolvedVersion: parsed.requestedRef
    };
  }
  const latestRelease = await tryFetchJson(`${repoBase}/releases/latest`, headers);
  if (latestRelease) {
    const tarballUrl = asString(latestRelease.tarball_url);
    if (tarballUrl) {
      return {
        id: parsed.id,
        source: parsed.source,
        ref: parsed.ref,
        artifactUrl: tarballUrl,
        resolvedVersion: asString(latestRelease.tag_name),
        resolvedRevision: asString(latestRelease.target_commitish)
      };
    }
  }
  const repoMeta = await fetchJson(repoBase, headers);
  const defaultBranch = asString(repoMeta.default_branch);
  if (!defaultBranch) {
    throw new NotFoundError(`Unable to resolve default branch for ${parsed.owner}/${parsed.repo}.`, "REGISTRY_RESPONSE_INVALID");
  }
  const commit = await tryFetchJson(`${repoBase}/commits/${encodeURIComponent(defaultBranch)}`, headers);
  return {
    id: parsed.id,
    source: parsed.source,
    ref: parsed.ref,
    artifactUrl: `${repoBase}/tarball/${encodeURIComponent(defaultBranch)}`,
    resolvedVersion: defaultBranch,
    resolvedRevision: asString(commit?.sha) ?? defaultBranch
  };
}
function resolveGitRevisionFromRemote(url, requestedRef, credential) {
  validateGitUrl(url);
  const ref = requestedRef ?? "HEAD";
  if (requestedRef)
    validateGitRef(requestedRef);
  const result = spawnSync3("git", ["ls-remote", url, ref], {
    encoding: "utf8",
    timeout: 30000,
    env: gitCredentialEnvironment(credential)
  });
  if (result.status !== 0)
    return;
  const firstLine = result.stdout.trim().split(/\r?\n/)[0];
  return firstLine?.split(/\s/)[0] || undefined;
}
async function resolveGitArtifact(parsed, credential) {
  const resolvedRevision = resolveGitRevisionFromRemote(parsed.url, parsed.requestedRef, credential);
  if (!resolvedRevision) {
    throw new NotFoundError(`Unable to resolve ${parsed.requestedRef ?? "HEAD"} for ${parsed.url} via 'git ls-remote'; refusing to install without a verifiable revision.`, "REGISTRY_NOT_FOUND");
  }
  return {
    id: parsed.id,
    source: parsed.source,
    ref: parsed.ref,
    artifactUrl: parsed.url,
    resolvedVersion: parsed.requestedRef,
    resolvedRevision
  };
}
async function resolveLocalArtifact(parsed) {
  return {
    id: parsed.id,
    source: parsed.source,
    ref: parsed.ref,
    artifactUrl: pathToFileURL(parsed.sourcePath).toString(),
    resolvedRevision: parsed.repoRoot ? readGitValue(parsed.repoRoot, "rev-parse", "HEAD") : undefined,
    resolvedVersion: parsed.repoRoot ? readGitValue(parsed.repoRoot, "rev-parse", "--abbrev-ref", "HEAD") : undefined
  };
}
function splitNpmNameAndVersion(input) {
  if (input.startsWith("@")) {
    const secondAt = input.indexOf("@", 1);
    if (secondAt > 0) {
      return {
        packageName: input.slice(0, secondAt),
        requestedVersionOrTag: input.slice(secondAt + 1) || undefined
      };
    }
    return { packageName: input };
  }
  const at = input.lastIndexOf("@");
  if (at > 0) {
    return {
      packageName: input.slice(0, at),
      requestedVersionOrTag: input.slice(at + 1) || undefined
    };
  }
  return { packageName: input };
}
function validateNpmPackageName(name) {
  if (!name)
    throw new UsageError("Invalid npm package name: name is required.");
  if (name.length > 214)
    throw new UsageError(`Invalid npm package name: "${name}" exceeds 214 characters.`);
  if (name !== name.toLowerCase() && !name.startsWith("@")) {
    throw new UsageError(`Invalid npm package name: "${name}" must be lowercase.`);
  }
  if (name.startsWith(".") || name.startsWith("_")) {
    throw new UsageError(`Invalid npm package name: "${name}" cannot start with . or _.`);
  }
  if (/[~'!()*]/.test(name) || name.includes(" ") || encodeURIComponent(name).replace(/%40/g, "@").replace(/%2[Ff]/g, "/") !== name) {
    throw new UsageError(`Invalid npm package name: "${name}" contains invalid characters.`);
  }
}
function looksLikeGithubOwnerRepo(ref) {
  const [repoPart] = splitRefSuffix(ref);
  const parts = repoPart.split("/").filter(Boolean);
  return parts.length === 2;
}
function splitRefSuffix(value) {
  const hash = value.indexOf("#");
  if (hash < 0)
    return [value, undefined];
  return [value.slice(0, hash), value.slice(hash + 1) || undefined];
}
function stripGitTransport(ref) {
  return ref.slice(4);
}
function fileUriToPath(ref) {
  const after = ref.slice(5);
  if (after.startsWith("//")) {
    try {
      return fileURLToPath2(ref);
    } catch {}
  }
  return after;
}
function toReadableLocalId(absolutePath) {
  const home = os3.homedir();
  if (absolutePath === home)
    return "~";
  if (absolutePath.startsWith(home + path15.sep)) {
    return `~/${absolutePath.slice(home.length + 1)}`;
  }
  return absolutePath;
}
function findGitRepoRoot(startDir) {
  let current = path15.resolve(startDir);
  while (true) {
    if (fs12.existsSync(path15.join(current, ".git"))) {
      return current;
    }
    const parent = path15.dirname(current);
    if (parent === current)
      return;
    current = parent;
  }
}
function readGitValue(repoRoot, ...args) {
  const result = spawnSync3("git", ["-C", repoRoot, ...args], { encoding: "utf8" });
  if (result.status !== 0)
    return;
  const value = result.stdout.trim();
  return value || undefined;
}
var REGISTRY_JSON_BYTE_CAP = 10 * 1024 * 1024;
async function fetchJson(url, headers) {
  return fetchRegistryJson(url, { headers, timeoutMs: 30000, maxBytes: REGISTRY_JSON_BYTE_CAP });
}
async function tryFetchJson(url, headers) {
  try {
    return await fetchJson(url, headers);
  } catch (error2) {
    if (error2 instanceof NotFoundError)
      return null;
    throw error2;
  }
}

// src/sources/providers/provider-utils.ts
import { createHash as createHash4, randomUUID as randomUUID2 } from "node:crypto";
import fs27 from "node:fs";
import path34 from "node:path";

// src/core/adapter/adapters/agent-skills-adapter.ts
import fs13 from "node:fs";
import path16 from "node:path";

// src/core/write-provenance.ts
var activeJournals = new Set;

// src/core/asset/frontmatter.ts
function parseFrontmatter(raw) {
  const parsedBlock = parseFrontmatterBlock(raw);
  if (!parsedBlock) {
    return { data: {}, content: raw, frontmatter: null, bodyStartLine: 1 };
  }
  let data = {};
  if (parsedBlock.frontmatter.trim()) {
    try {
      const parsed = $parse(parsedBlock.frontmatter);
      if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {
        data = normalizeYamlValues(parsed);
      }
    } catch {
      data = parseFrontmatterLenient(parsedBlock.frontmatter);
    }
  }
  return {
    data,
    content: parsedBlock.content,
    frontmatter: parsedBlock.frontmatter,
    bodyStartLine: parsedBlock.bodyStartLine
  };
}
function normalizeYamlValues(value) {
  if (value instanceof Date) {
    const y = value.getUTCFullYear();
    const m = String(value.getUTCMonth() + 1).padStart(2, "0");
    const d = String(value.getUTCDate()).padStart(2, "0");
    return `${y}-${m}-${d}`;
  }
  if (Array.isArray(value))
    return value.map(normalizeYamlValues);
  if (value !== null && typeof value === "object") {
    return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, normalizeYamlValues(v)]));
  }
  return value;
}
function parseFrontmatterLenient(frontmatter) {
  const data = {};
  for (const line of frontmatter.split(/\r?\n/)) {
    const m = line.match(/^([\w][\w-]*):\s*(.*)$/);
    if (!m)
      continue;
    const key = m[1];
    const rawValue = (m[2] ?? "").trim();
    try {
      const singleEntry = $parse(`k: ${rawValue}`);
      if (singleEntry !== null && typeof singleEntry === "object" && !Array.isArray(singleEntry)) {
        const v = singleEntry.k;
        data[key] = v === null || v === undefined ? "" : v;
      } else {
        data[key] = rawValue;
      }
    } catch {
      data[key] = rawValue;
    }
  }
  return data;
}
function parseFrontmatterBlock(raw) {
  const match = raw.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r\n|\r|\n|$)([\s\S]*)$/);
  if (match) {
    const frontmatter = match[1].replace(/\r/g, "");
    const content = match[2];
    return {
      frontmatter,
      content,
      bodyStartLine: countLines(raw.slice(0, match[0].length - content.length)) + 1
    };
  }
  const emptyMatch = raw.match(/^---\r?\n---(?:\r\n|\r|\n)([\s\S]*)$/);
  if (emptyMatch) {
    return { frontmatter: "", content: emptyMatch[1], bodyStartLine: 3 };
  }
  return null;
}
function countLines(text) {
  if (text.length === 0)
    return 0;
  return text.split(/\r?\n/).length - 1;
}

// src/core/adapter/adapters/shared.ts
import { createHash as createHash2 } from "node:crypto";

// src/core/asset/frontmatter-lint.ts
function checkUnquotedDescriptionColon(frontmatterText) {
  if (!frontmatterText)
    return null;
  const document = $parseDocument(frontmatterText);
  const description = document.get("description", true);
  if (document.errors.length === 0 && $isScalar(description) && description.type === "PLAIN" && typeof description.value === "string" && description.value.includes(":")) {
    return `description value contains unquoted colon: ${description.value}`;
  }
  if (document.errors.length > 0) {
    const line = frontmatterText.split(/\r?\n/).find((candidate) => candidate.startsWith("description:"));
    const value = line?.slice("description:".length).trim();
    if (value?.includes(":"))
      return `description value contains unquoted colon: ${value}`;
  }
  return null;
}

// src/core/adapter/adapters/shared.ts
function hashContent(content) {
  return createHash2("sha256").update(content, "utf8").digest("hex");
}
function nonEmptyString2(value) {
  if (typeof value !== "string")
    return;
  const trimmed = value.trim();
  return trimmed.length > 0 ? trimmed : undefined;
}
function readTags(value) {
  if (!Array.isArray(value))
    return;
  const tags = value.filter((tag) => typeof tag === "string" && tag.trim().length > 0);
  return tags.length > 0 ? tags : undefined;
}
var RESERVED_FILES = new Set(["index.md", "log.md"]);
function checkMissingUpdated(data, frontmatterText) {
  return frontmatterText !== null && !("updated" in data);
}
function findStalePathCandidates(body) {
  const pathRe = /(?:\/home\/|\/tmp\/|\/var\/|\/root\/|\/opt\/)[^\s"'`)\]>,\n]+/g;
  const out = [];
  let match;
  while ((match = pathRe.exec(body)) !== null)
    out.push(match[0]);
  return out;
}
function stripFencedBlocksSimple(body) {
  const lines = body.split(/\r?\n/);
  let inFence = false;
  const out = lines.map((line) => {
    if (/^\s*```/.test(line)) {
      const wasInFence = inFence;
      inFence = !inFence;
      return wasInFence || inFence ? "" : line;
    }
    return inFence ? "" : line;
  });
  return out.join(`
`);
}
var BUNDLE_BODY_REF_RE_SRC = "(?:^|[\\s`\"'(,[])([^\\s:.#/`\"'()[\\],<>]+\\/\\/[^\\s\"'`)\\]>,\\n]+)";
function isNonRefConceptId(conceptId) {
  const id = conceptId.split("#", 1)[0];
  if (!id || id.length <= 1 || id === "**")
    return true;
  if (id.includes("<"))
    return true;
  return false;
}
function extractProseRefTokens(text) {
  const re = new RegExp(BUNDLE_BODY_REF_RE_SRC, "gm");
  const scanBody = stripFencedBlocksSimple(text);
  const refs = [];
  let match;
  while ((match = re.exec(scanBody)) !== null) {
    const token = match[1];
    if (token.includes("$(") || token.includes("${") || token.includes("::"))
      continue;
    if (isNonRefConceptId(token.slice(token.indexOf("//") + 2)))
      continue;
    refs.push(token);
  }
  return refs;
}
function refTokenFromListValue(value) {
  const trimmed = value.trim();
  if (!trimmed || trimmed.includes("$(") || trimmed.includes("${") || trimmed.includes("::"))
    return null;
  const boundary = trimmed.indexOf("//");
  const conceptId = boundary >= 0 ? trimmed.slice(boundary + 2) : trimmed;
  if (conceptId.includes(":") || isNonRefConceptId(conceptId))
    return null;
  return trimmed;
}
var XREF_FRONTMATTER_KEYS = ["xrefs", "supersededBy", "contradictedBy"];
function readRefStringOrArray(value) {
  if (typeof value === "string") {
    const trimmed = value.trim();
    return trimmed ? [trimmed] : null;
  }
  if (!Array.isArray(value))
    return null;
  const out = value.filter((v) => typeof v === "string" && v.trim().length > 0).map((v) => v.trim());
  return out.length > 0 ? out : null;
}
async function runBaseValidateChecks(relPath, parsed, componentRoot, ctx) {
  const diagnostics = [];
  const { data, content: body, frontmatter } = parsed;
  const unquotedColonDetail = checkUnquotedDescriptionColon(frontmatter);
  if (unquotedColonDetail) {
    diagnostics.push({ file: relPath, issue: "unquoted-colon", detail: unquotedColonDetail, fixed: false });
  }
  if (checkMissingUpdated(data, frontmatter)) {
    diagnostics.push({
      file: relPath,
      issue: "missing-updated",
      detail: "no updated field in frontmatter",
      fixed: false
    });
  }
  const staleCandidates = [
    ...findStalePathCandidates(body),
    ...frontmatter ? findStalePathCandidates(frontmatter) : []
  ];
  for (const candidate of staleCandidates) {
    const found = await ctx.readFile(candidate);
    if (found !== null)
      continue;
    const portableHint = candidate.startsWith(componentRoot) ? ` (portable form: $AKM_BUNDLE_DIR${candidate.slice(componentRoot.length)})` : "";
    diagnostics.push({
      file: relPath,
      issue: "stale-path",
      detail: `nonexistent path: ${candidate}${portableHint}`,
      fixed: false
    });
  }
  for (const ref of extractProseRefTokens(body)) {
    const { exists } = await ctx.resolveRef(ref);
    if (!exists)
      diagnostics.push({ file: relPath, issue: "missing-ref", detail: `missing ref: ${ref}`, fixed: false });
  }
  if (frontmatter !== null) {
    for (const key of XREF_FRONTMATTER_KEYS) {
      const values = readRefStringOrArray(data[key]);
      if (values === null)
        continue;
      for (const value of values) {
        const ref = refTokenFromListValue(value);
        if (ref === null)
          continue;
        const { exists } = await ctx.resolveRef(ref);
        if (!exists) {
          diagnostics.push({
            file: relPath,
            issue: "missing-ref",
            detail: `missing ref: ${ref} (frontmatter ${key})`,
            fixed: false
          });
        }
      }
    }
  }
  return diagnostics;
}

// src/core/adapter/adapters/agent-skills-adapter.ts
var COMPONENT_ID = "main";
var SKILL_MANIFEST = "SKILL.md";
var NAME_MAX = 64;
var DESCRIPTION_MAX = 1024;
var RESERVED_NAME_WORDS = ["anthropic", "claude"];
var NAME_RE = /^[a-z0-9]+(-[a-z0-9]+)*$/;
function skillPackage(relPath) {
  const posix = toPosix(relPath);
  const segs = posix.split("/").filter((s) => s.length > 0);
  if (segs.length < 2 || segs[segs.length - 1] !== SKILL_MANIFEST)
    return null;
  const conceptId = segs.slice(0, segs.length - 1).join("/");
  const dirName = segs[segs.length - 2];
  return { conceptId, dirName };
}
function recognize(c, file) {
  const pkg = skillPackage(file.relPath);
  if (pkg === null)
    return null;
  const raw = file.content();
  const parsed = parseFrontmatter(raw);
  const data = parsed.data;
  const body = parsed.content;
  const name = nonEmptyString2(data.name) ?? pkg.dirName;
  const description = nonEmptyString2(data.description);
  const tags = readTags(data.tags);
  const doc = {
    ref: `${c.id}//${pkg.conceptId}`,
    bundle: c.id,
    component: COMPONENT_ID,
    conceptId: pkg.conceptId,
    path: file.absPath,
    hash: hashContent(raw),
    adapterId: "agent-skills",
    type: "skill",
    name,
    content: body
  };
  if (description !== undefined)
    doc.description = description;
  if (tags !== undefined)
    doc.tags = tags;
  return doc;
}
function skillFieldDiagnostics(relPath, dirName, data) {
  const diagnostics = [];
  const name = typeof data.name === "string" ? data.name.normalize("NFKC") : "";
  const lower = name.toLowerCase();
  const reserved = RESERVED_NAME_WORDS.find((w) => lower.includes(w));
  const nameInvalid = name.length < 1 || name.length > NAME_MAX || !NAME_RE.test(name) || reserved !== undefined || name !== dirName;
  if (nameInvalid) {
    diagnostics.push({
      file: relPath,
      issue: "skill-name-invalid",
      detail: `skill name '${name}' must match ^[a-z0-9]+(-[a-z0-9]+)*$ (NFKC, 1-${NAME_MAX} chars, ` + `no reserved word, == parent dir name '${dirName}') — Agent Skills hard rule (spec §4.5).`,
      fixed: false
    });
  }
  const description = typeof data.description === "string" ? data.description : "";
  if (description.length > DESCRIPTION_MAX) {
    diagnostics.push({
      file: relPath,
      issue: "skill-description-too-long",
      detail: `skill description is ${description.length} characters; the Agent Skills hard limit is 1-${DESCRIPTION_MAX} (spec §4.5).`,
      fixed: false
    });
  }
  return diagnostics;
}
var MAX_PACKAGE_PROBE_DEPTH = 3;
function missingManifestDiagnostic(dir) {
  return { file: dir, issue: "missing-skill-md", detail: `no SKILL.md in ${dir}/`, fixed: false };
}
async function scanPackageCandidate(dir, entries, ctx, depth) {
  if (entries.includes(SKILL_MANIFEST))
    return { containsManifest: true, diagnostics: [] };
  if (depth >= MAX_PACKAGE_PROBE_DEPTH) {
    return { containsManifest: false, diagnostics: [missingManifestDiagnostic(dir)] };
  }
  const children = [];
  for (const entry of entries) {
    if (entry.startsWith("."))
      continue;
    const child = `${dir}/${entry}`;
    const childEntries = await ctx.list(child);
    if (childEntries.length === 0)
      continue;
    children.push(await scanPackageCandidate(child, childEntries, ctx, depth + 1));
  }
  if (children.some((child) => child.containsManifest)) {
    return {
      containsManifest: true,
      diagnostics: children.flatMap((child) => child.diagnostics)
    };
  }
  return { containsManifest: false, diagnostics: [missingManifestDiagnostic(dir)] };
}
async function missingManifestDiagnostics(ctx) {
  const diagnostics = [];
  for (const name of await ctx.list(".")) {
    if (name.startsWith("."))
      continue;
    const entries = await ctx.list(name);
    if (entries.length === 0)
      continue;
    diagnostics.push(...(await scanPackageCandidate(name, entries, ctx, 1)).diagnostics);
  }
  return diagnostics;
}
async function validate(_c, changes, ctx) {
  const diagnostics = [];
  const seenDirs = new Set;
  for (const change of changes) {
    if (change.op === "delete")
      continue;
    const raw = change.after ?? await ctx.readFile(change.path);
    if (typeof raw !== "string")
      continue;
    const pkg = skillPackage(change.path);
    if (pkg === null)
      continue;
    if (seenDirs.has(pkg.conceptId))
      continue;
    seenDirs.add(pkg.conceptId);
    diagnostics.push(...skillFieldDiagnostics(toPosix(change.path), pkg.dirName, parseFrontmatter(raw).data));
  }
  diagnostics.push(...await missingManifestDiagnostics(ctx));
  return diagnostics;
}
var agentSkillsAdapter = {
  id: "agent-skills",
  version: "0.9.0",
  extensions: [".md"],
  recognize,
  validate,
  readCandidates(c, conceptId) {
    return [{ path: path16.join(c.root, conceptId, SKILL_MANIFEST), conceptId }];
  },
  placeNew(c, conceptId) {
    return path16.join(c.root, conceptId, SKILL_MANIFEST);
  },
  looksLikeRoot(root) {
    let entries;
    try {
      entries = fs13.readdirSync(root, { withFileTypes: true });
    } catch {
      return false;
    }
    return entries.some((entry) => {
      if (!entry.isDirectory())
        return false;
      try {
        return fs13.existsSync(path16.join(root, entry.name, SKILL_MANIFEST));
      } catch {
        return false;
      }
    });
  }
};

// src/core/adapter/adapters/akm-adapter.ts
import fs17 from "node:fs";
import path22 from "node:path";

// src/indexer/passes/metadata.ts
import fs14 from "node:fs";
import path17 from "node:path";
var SCOPE_KEYS = ["user", "agent", "run", "channel"];
var KNOWN_QUALITY_VALUES = new Set(["generated", "curated", "enriched", "proposed"]);
var warnedUnknownQualityValues = new Set;
function normalizeQuality(raw) {
  if (KNOWN_QUALITY_VALUES.has(raw))
    return raw;
  if (!warnedUnknownQualityValues.has(raw)) {
    warnedUnknownQualityValues.add(raw);
    warn(`Warning: unknown quality value "${raw}" — entry remains searchable, but consider using "generated", "curated", or "proposed" (v1 spec §4.2).`);
  }
  return raw;
}
function normalizeScopeObject(raw) {
  const out = {};
  for (const key of SCOPE_KEYS) {
    const value = raw[key];
    if (typeof value === "string") {
      const trimmed = value.trim();
      if (trimmed)
        out[key] = trimmed;
    } else if (typeof value === "number" && Number.isFinite(value)) {
      out[key] = String(value);
    }
  }
  return Object.keys(out).length > 0 ? out : undefined;
}
function applyScopeFrontmatter(entry, fmData) {
  const collected = {};
  for (const key of SCOPE_KEYS) {
    const fmKey = `scope_${key}`;
    if (Object.hasOwn(fmData, fmKey)) {
      collected[key] = fmData[fmKey];
    }
  }
  if (Object.keys(collected).length === 0)
    return;
  const scope = normalizeScopeObject(collected);
  if (scope)
    entry.scope = scope;
}
function normalizeIntent(value) {
  if (typeof value !== "object" || value === null || Array.isArray(value))
    return;
  const raw = value;
  const intent = {};
  const when = asNonEmptyString(raw.when);
  const input = asNonEmptyString(raw.input);
  const output = asNonEmptyString(raw.output);
  if (when)
    intent.when = when;
  if (input)
    intent.input = input;
  if (output)
    intent.output = output;
  return Object.keys(intent).length > 0 ? intent : undefined;
}
function normalizeMemoryBackref(value) {
  if (!value)
    return;
  try {
    const parsed = parseBundleRef(value);
    return parsed.fragment === undefined && parsed.conceptId.startsWith("memories/") ? parsed.conceptId : undefined;
  } catch {
    return;
  }
}
function derivedFromConceptId(source, derivedFrom) {
  const fromSource = normalizeMemoryBackref(source);
  if (fromSource)
    return fromSource;
  const rawDerivedFrom = derivedFrom?.trim();
  if (!rawDerivedFrom)
    return;
  const qualified = normalizeMemoryBackref(rawDerivedFrom);
  if (qualified)
    return qualified;
  if (rawDerivedFrom.includes(":") || rawDerivedFrom.includes("//"))
    return;
  try {
    return parseBundleRef(`memories/${rawDerivedFrom}`).conceptId;
  } catch {
    return;
  }
}
function applyCuratedFrontmatter(entry, fmData) {
  const description = asNonEmptyString(fmData.description);
  if (description) {
    entry.description = description;
    entry.source = "frontmatter";
    entry.confidence = 0.9;
  }
  const tags = normalizeNonEmptyStringList(fmData.tags);
  if (tags)
    entry.tags = normalizeTerms(tags);
  const aliases = normalizeNonEmptyStringList(fmData.aliases);
  if (aliases)
    entry.aliases = normalizeTerms(aliases);
  const searchHints = normalizeNonEmptyStringList(fmData.searchHints);
  if (searchHints)
    entry.searchHints = searchHints;
  const usage = normalizeNonEmptyStringList(fmData.usage);
  if (usage)
    entry.usage = usage;
  const examples = normalizeNonEmptyStringList(fmData.examples);
  if (examples)
    entry.examples = examples;
  const run = asNonEmptyString(fmData.run);
  if (run)
    entry.run = run;
  const setup = asNonEmptyString(fmData.setup);
  if (setup)
    entry.setup = setup;
  const cwd = asNonEmptyString(fmData.cwd);
  if (cwd)
    entry.cwd = cwd;
  const quality = asNonEmptyString(fmData.quality);
  if (quality)
    entry.quality = normalizeQuality(quality);
  const category = asNonEmptyString(fmData.category);
  if (category)
    entry.category = category;
  const beliefState = asNonEmptyString(fmData.beliefState);
  if (beliefState)
    entry.beliefState = beliefState;
  const supersededBy = normalizeNonEmptyStringList(fmData.supersededBy);
  if (supersededBy)
    entry.supersededBy = supersededBy;
  const contradictedBy = normalizeNonEmptyStringList(fmData.contradictedBy);
  if (contradictedBy)
    entry.contradictedBy = contradictedBy;
  const currentBeliefRefs = normalizeNonEmptyStringList(fmData.currentBeliefRefs);
  if (currentBeliefRefs)
    entry.currentBeliefRefs = currentBeliefRefs;
  if (fmData.captureMode === "hot" || fmData.captureMode === "background") {
    entry.captureMode = fmData.captureMode;
  }
  const whenToUse = asNonEmptyString(fmData.when_to_use);
  if (whenToUse)
    entry.whenToUse = whenToUse;
  if (Array.isArray(fmData.lessonStrength)) {
    entry.lessonStrength = fmData.lessonStrength.length;
  } else if (typeof fmData.lessonStrength === "number" && Number.isFinite(fmData.lessonStrength)) {
    entry.lessonStrength = Math.max(0, Math.floor(fmData.lessonStrength));
  }
  const evidenceSources = normalizeNonEmptyStringList(fmData.evidenceSources);
  if (evidenceSources)
    entry.evidenceSources = evidenceSources;
  if (entry.type === "memory") {
    const isDerivedByName = entry.name.toLowerCase().endsWith(".derived");
    const isDerivedByFm = fmData.inferred === true;
    if (isDerivedByName || isDerivedByFm) {
      const parent = derivedFromConceptId(asNonEmptyString(fmData.source), asNonEmptyString(fmData.derivedFrom));
      if (parent)
        entry.derivedFrom = parent;
    }
  }
  const intent = normalizeIntent(fmData.intent);
  if (intent)
    entry.intent = intent;
  if (typeof fmData.scope === "object" && fmData.scope !== null && !Array.isArray(fmData.scope)) {
    const normalizedScope = normalizeScopeObject(fmData.scope);
    if (normalizedScope)
      entry.scope = normalizedScope;
  }
  applyScopeFrontmatter(entry, fmData);
}
function normalizeNonEmptyStringList(value) {
  if (typeof value === "string") {
    const trimmed = value.trim();
    return trimmed ? [trimmed] : undefined;
  }
  if (!Array.isArray(value))
    return;
  const filtered = value.filter((item) => typeof item === "string").map((item) => item.trim()).filter((item) => item.length > 0);
  return filtered.length > 0 ? filtered : undefined;
}
function extractCommandParameters(template) {
  const params = [];
  if (/\$ARGUMENTS\b/.test(template)) {
    params.push({ name: "ARGUMENTS" });
  }
  for (const match of template.matchAll(/\$([1-9])(?!\d)/g)) {
    const name = `$${match[1]}`;
    if (!params.some((p) => p.name === name)) {
      params.push({ name });
    }
  }
  for (const match of template.matchAll(/\{\{([a-zA-Z_][a-zA-Z0-9_]*)\}\}/g)) {
    const name = match[1];
    if (!params.some((p) => p.name === name)) {
      params.push({ name });
    }
  }
  return params.length > 0 ? params : undefined;
}
function applyWikiFrontmatter(entry, fmData) {
  if (isWikiRole(fmData.wikiRole))
    entry.wikiRole = fmData.wikiRole;
  const pageKind = fmData.pageKind;
  if (typeof pageKind === "string" && pageKind.trim().length > 0) {
    entry.pageKind = pageKind.trim();
  }
  const xrefs = Array.isArray(fmData.xrefs) ? normalizeNonEmptyStringList(fmData.xrefs) : undefined;
  if (xrefs)
    entry.xrefs = xrefs;
  const sources = Array.isArray(fmData.sources) ? normalizeNonEmptyStringList(fmData.sources) : undefined;
  if (sources)
    entry.sources = sources;
}
function isWikiRole(value) {
  return value === "schema" || value === "index" || value === "log" || value === "raw" || value === "page";
}
function parseVerifiedFamily(value) {
  const entries = Array.isArray(value) ? value : [value];
  return entries.filter((v) => v !== null && typeof v === "object" && !Array.isArray(v)).map((v) => {
    const by = asNonEmptyString(v.by);
    if (!by)
      return;
    const at = asNonEmptyString(v.at);
    return at ? { by, at } : { by };
  }).filter((v) => v !== undefined);
}
function applyProvenanceFrontmatter(entry, fmData) {
  const provenance = fmData.provenance;
  const nested = provenance !== null && typeof provenance === "object" && !Array.isArray(provenance) ? provenance : {};
  const result = {};
  const generatedMapping = fmData.generated !== null && typeof fmData.generated === "object" && !Array.isArray(fmData.generated) ? fmData.generated : undefined;
  const generatedBy = asNonEmptyString(generatedMapping?.by) ?? asNonEmptyString(nested.generatedBy);
  if (generatedBy)
    result.generatedBy = generatedBy;
  const generatedAt = asNonEmptyString(generatedMapping?.at) ?? asNonEmptyString(nested.generatedAt);
  if (generatedAt)
    result.generatedAt = generatedAt;
  const verified = fmData.verified !== undefined ? parseVerifiedFamily(fmData.verified) : parseVerifiedFamily(nested.verified);
  if (verified.length > 0)
    result.verified = verified;
  if (Array.isArray(nested.sources)) {
    const sources = nested.sources.filter((s) => s !== null && typeof s === "object" && !Array.isArray(s)).map((s) => {
      const resource = asNonEmptyString(s.resource);
      return resource ? { resource } : undefined;
    }).filter((s) => s !== undefined);
    if (sources.length > 0)
      result.sources = sources;
  }
  if (Object.keys(result).length > 0)
    entry.provenance = result;
}
function extractScriptParameters(filePath, content) {
  if (content === undefined) {
    try {
      content = fs14.readFileSync(filePath, "utf8");
    } catch {
      return;
    }
  }
  const lines = content.split(/\r?\n/).slice(0, 50);
  const params = [];
  const paramRegex = /^[\s/*#;-]*@param\s+(?:\{([^}]+)\}\s+)?(\w+)(?:\s+-\s+(.+))?/;
  for (const line of lines) {
    const match = line.match(paramRegex);
    if (match) {
      const param = { name: match[2] };
      if (match[1])
        param.type = match[1].trim();
      if (match[3])
        param.description = match[3].trim();
      params.push(param);
    }
  }
  return params.length > 0 ? params : undefined;
}
function extractFrontmatterParameters(fmData) {
  const paramsRaw = fmData.params;
  if (typeof paramsRaw !== "object" || paramsRaw === null || Array.isArray(paramsRaw))
    return;
  const paramsObj = paramsRaw;
  const params = [];
  for (const [key, value] of Object.entries(paramsObj)) {
    const param = { name: key };
    if (typeof value === "string" && value.trim()) {
      param.description = value.trim();
    }
    params.push(param);
  }
  return params.length > 0 ? params : undefined;
}
function mergeParameters(existing, additional) {
  if (!additional || additional.length === 0)
    return existing;
  if (!existing || existing.length === 0)
    return additional;
  const names = new Set(existing.map((p) => p.name));
  const merged = [...existing];
  for (const param of additional) {
    if (!names.has(param.name)) {
      merged.push(param);
      names.add(param.name);
    }
  }
  return merged;
}
function splitCommentList(raw) {
  return raw.split(/[;,]/).map((item) => item.trim()).filter((item) => item.length > 0);
}
function parseCommentScope(raw) {
  const pairs = raw.split(/[;,]/).map((item) => item.trim()).filter((item) => item.length > 0);
  if (pairs.length === 0)
    return;
  const scopeRaw = {};
  for (const pair of pairs) {
    const [keyPart, ...valueParts] = pair.split("=");
    const key = keyPart?.trim();
    const value = valueParts.join("=").trim();
    if (!key || !value)
      continue;
    if (SCOPE_KEYS.includes(key)) {
      scopeRaw[key] = value;
    }
  }
  return normalizeScopeObject(scopeRaw);
}
function parseIntentCommentLine(cleaned, metadata) {
  const intentMatch = cleaned.match(/^@intent(?:\.(when|input|output))?\s+(.+)$/);
  if (!intentMatch)
    return false;
  metadata.intent ??= {};
  const value = intentMatch[2].trim();
  const key = intentMatch[1];
  if (key === "when")
    metadata.intent.when = value;
  else if (key === "input")
    metadata.intent.input = value;
  else if (key === "output")
    metadata.intent.output = value;
  else
    metadata.intent.when ??= value;
  return true;
}
var COMMENT_TAGS = [
  [/^@description\s+(.+)$/, (m, v) => m.description = v.trim()],
  [/^@tags?\s+(.+)$/, (m, v) => m.tags = splitCommentList(v)],
  [/^@aliases?\s+(.+)$/, (m, v) => m.aliases = splitCommentList(v)],
  [/^@searchHints?\s+(.+)$/, (m, v) => m.searchHints = splitCommentList(v)],
  [/^@usage\s+(.+)$/, (m, v) => m.usage = [...m.usage ?? [], v.trim()]],
  [/^@examples?\s+(.+)$/, (m, v) => m.examples = [...m.examples ?? [], v.trim()]],
  [/^@run\s+(.+)$/, (m, v) => m.run = v.trim()],
  [/^@setup\s+(.+)$/, (m, v) => m.setup = v.trim()],
  [/^@cwd\s+(.+)$/, (m, v) => m.cwd = v.trim()],
  [
    /^@scope\s+(.+)$/,
    (m, v) => {
      const scope = parseCommentScope(v);
      if (scope)
        m.scope = scope;
    }
  ]
];
function extractCommentMetadata(filePath, content) {
  if (content === undefined) {
    try {
      content = fs14.readFileSync(filePath, "utf8");
    } catch {
      return;
    }
  }
  const lines = content.split(/\r?\n/).slice(0, 50);
  const metadata = {};
  for (const line of lines) {
    const trimmed = line.trim();
    if (!/^(?:\/\/|#|\/?\*|;|--)/.test(trimmed) && !trimmed.startsWith("'"))
      continue;
    const cleaned = trimmed.replace(/^(?:\/\/|##?|\/?\*\*?\/?|;|--|'?)\s*/, "").replace(/\*\/\s*$/, "").trim();
    if (!cleaned)
      continue;
    if (parseIntentCommentLine(cleaned, metadata))
      continue;
    for (const [pattern, apply] of COMMENT_TAGS) {
      const match = cleaned.match(pattern);
      if (match) {
        apply(metadata, match[1]);
        break;
      }
    }
  }
  return Object.keys(metadata).length > 0 ? metadata : undefined;
}
function applyCommentMetadata(entry, metadata) {
  if (!metadata)
    return;
  let usedCommentMetadata = false;
  const use = (key, value) => {
    entry[key] = value;
    usedCommentMetadata = true;
  };
  if (metadata.description && !entry.description)
    use("description", metadata.description);
  if (metadata.tags?.length && (!entry.tags || entry.tags.length === 0))
    use("tags", normalizeTerms(metadata.tags));
  if (metadata.aliases?.length)
    use("aliases", normalizeTerms(metadata.aliases));
  if (metadata.searchHints?.length)
    use("searchHints", metadata.searchHints);
  if (metadata.usage?.length)
    use("usage", metadata.usage);
  if (metadata.examples?.length)
    use("examples", metadata.examples);
  if (metadata.intent && Object.keys(metadata.intent).length > 0)
    use("intent", metadata.intent);
  if (metadata.run)
    use("run", metadata.run);
  if (metadata.setup)
    use("setup", metadata.setup);
  if (metadata.cwd)
    use("cwd", metadata.cwd);
  if (metadata.scope)
    use("scope", metadata.scope);
  if (usedCommentMetadata && entry.source !== "frontmatter" && entry.source !== "manual") {
    entry.source = "comments";
    entry.confidence = Math.max(entry.confidence ?? 0, 0.7);
  }
}
function mergeAliases(existing, generated) {
  const merged = normalizeTerms([...existing ?? [], ...generated]);
  return merged.length > 0 ? merged : undefined;
}
var MARKDOWN_CONTENT_MAX_CHARS = 1e6;
function findInnerFrontmatterBlock(lines) {
  let i = 0;
  while (i < lines.length && i < 3 && lines[i].trim() === "")
    i += 1;
  if (lines[i] !== "---")
    return null;
  for (let j = i + 1;j < lines.length; j += 1) {
    if (lines[j] === "---")
      return { open: i, close: j };
  }
  return null;
}
function hasSessionMemoryMarker(fmData, body) {
  if (typeof fmData.akm_memory_kind === "string")
    return true;
  const lines = body.split(/\r?\n/);
  const block = findInnerFrontmatterBlock(lines);
  if (!block)
    return false;
  for (let i = block.open + 1;i < block.close; i += 1) {
    if (/^akm_memory_kind:\s*\S/.test(lines[i]))
      return true;
  }
  return false;
}
function isFrontmatterShaped(lines, block) {
  for (let i = block.open + 1;i < block.close; i += 1) {
    const line = lines[i];
    if (line.trim() === "")
      continue;
    if (/^\s/.test(line))
      continue;
    if (/^[A-Za-z0-9_.-]+:(\s|$)/.test(line))
      continue;
    return false;
  }
  return true;
}
function truncateUnicodeSafe(text, maxChars) {
  if (text.length <= maxChars)
    return text;
  let cut = text.slice(0, maxChars);
  const lastCode = cut.charCodeAt(cut.length - 1);
  if (lastCode >= 55296 && lastCode <= 56319)
    cut = cut.slice(0, -1);
  const boundary = cut.lastIndexOf(" ");
  if (boundary >= Math.floor(maxChars * 0.9))
    cut = cut.slice(0, boundary);
  return cut.trimEnd();
}
function parseMarkdownFenceOpening(line) {
  const match = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line);
  const run = match?.[1];
  if (!run)
    return;
  const marker = run[0];
  if (marker === "`" && match?.[2]?.includes("`"))
    return;
  return { marker, length: run.length };
}
function isMarkdownFenceClosing(line, fence) {
  let cursor = 0;
  while (cursor < line.length && cursor < 3 && line[cursor] === " ")
    cursor += 1;
  const runStart = cursor;
  while (cursor < line.length && line[cursor] === fence.marker)
    cursor += 1;
  if (cursor - runStart < fence.length)
    return false;
  return /^[\t ]*$/.test(line.slice(cursor));
}
function stripMarkdownHtmlComments(line, state) {
  let cursor = 0;
  let visible = "";
  while (cursor < line.length) {
    if (state.inComment) {
      const close = line.indexOf("-->", cursor);
      if (close < 0)
        return visible;
      state.inComment = false;
      cursor = close + 3;
      continue;
    }
    const open = line.indexOf("<!--", cursor);
    if (open < 0)
      return `${visible}${line.slice(cursor)}`;
    visible += line.slice(cursor, open);
    state.inComment = true;
    cursor = open + 4;
  }
  return visible;
}
function findBalancedMarkdownClose(text, openAt, open, close) {
  let depth = 1;
  for (let cursor = openAt + 1;cursor < text.length; cursor += 1) {
    const char = text[cursor];
    if (char === "\\") {
      cursor += 1;
      continue;
    }
    if (char === open)
      depth += 1;
    if (char !== close)
      continue;
    depth -= 1;
    if (depth === 0)
      return cursor;
  }
  return;
}
function findMarkdownDestinationClose(text, openAt) {
  let depth = 1;
  let phase = "before-destination";
  let quote;
  let parenthesizedTitle = false;
  let titleSeparator = false;
  for (let cursor = openAt + 1;cursor < text.length; cursor += 1) {
    const char = text[cursor];
    if (char === "\\") {
      cursor += 1;
      continue;
    }
    if (phase === "before-destination") {
      if (/\s/u.test(char ?? ""))
        continue;
      if (char === "<") {
        phase = "angle-destination";
        continue;
      }
      if (char === ")")
        return cursor;
      phase = "bare-destination";
    }
    if (phase === "angle-destination") {
      if (char === ">")
        phase = "after-destination";
      continue;
    }
    if (phase === "title") {
      if (quote) {
        if (char === quote) {
          quote = undefined;
          phase = "after-destination";
          titleSeparator = false;
        }
        continue;
      }
      if (parenthesizedTitle) {
        if (char === "(")
          depth += 1;
        if (char !== ")")
          continue;
        depth -= 1;
        if (depth === 1) {
          parenthesizedTitle = false;
          phase = "after-destination";
          titleSeparator = false;
        }
      }
      continue;
    }
    if (phase === "after-destination") {
      if (/\s/u.test(char ?? "")) {
        titleSeparator = true;
        continue;
      }
      if (char === ")")
        return cursor;
      if (titleSeparator && (char === '"' || char === "'")) {
        quote = char;
        phase = "title";
        continue;
      }
      if (titleSeparator && char === "(") {
        depth += 1;
        parenthesizedTitle = true;
        phase = "title";
        continue;
      }
      phase = "bare-destination";
    }
    if (phase !== "bare-destination")
      continue;
    if (char === "(") {
      depth += 1;
      continue;
    }
    if (char === ")") {
      depth -= 1;
      if (depth === 0)
        return cursor;
      continue;
    }
    if (/\s/u.test(char ?? "") && depth === 1) {
      phase = "after-destination";
      titleSeparator = true;
    }
  }
  return;
}
var MAX_MARKDOWN_LINK_NESTING = 32;
function stripMarkdownLinkDestinations(text, nesting = 0) {
  let visible = "";
  let cursor = 0;
  while (cursor < text.length) {
    const isImage = text[cursor] === "!" && text[cursor + 1] === "[";
    const labelOpen = isImage ? cursor + 1 : cursor;
    if (text[labelOpen] !== "[") {
      visible += text[cursor];
      cursor += 1;
      continue;
    }
    const labelClose = findBalancedMarkdownClose(text, labelOpen, "[", "]");
    const destinationOpen = labelClose === undefined ? undefined : labelClose + 1;
    if (destinationOpen === undefined || text[destinationOpen] !== "(") {
      visible += text[cursor];
      cursor += 1;
      continue;
    }
    const destinationClose = findMarkdownDestinationClose(text, destinationOpen);
    if (destinationClose === undefined) {
      visible += text[cursor];
      cursor += 1;
      continue;
    }
    if (nesting < MAX_MARKDOWN_LINK_NESTING) {
      visible += stripMarkdownLinkDestinations(text.slice(labelOpen + 1, labelClose), nesting + 1);
    }
    cursor = destinationClose + 1;
  }
  return visible;
}
function projectMarkdownContent(body, truncationInfo) {
  const lines = body.split(/\r?\n/);
  const innerBlock = findInnerFrontmatterBlock(lines);
  const start = innerBlock && isFrontmatterShaped(lines, innerBlock) ? innerBlock.close + 1 : 0;
  const projected = [];
  forEachVisibleMarkdownLine(lines, start, (_index, visible) => {
    let trimmed = visible.trim();
    if (!trimmed || /^(-{3,}|\*{3,}|_{3,}|=+)$/.test(trimmed))
      return;
    if (/^\s*\[[^\]]+\]:\s*\S+/.test(trimmed))
      return;
    if (/^<[^>]+>$/.test(trimmed))
      return;
    trimmed = stripMarkdownLinkDestinations(trimmed);
    trimmed = trimmed.replace(/`{1,2}([^`]+)`{1,2}/g, "$1");
    trimmed = trimmed.replace(/^#{1,6}\s+/, "");
    trimmed = trimmed.replace(/^(?:>|[-+*]|\d+[.)])\s+/, "");
    trimmed = trimmed.replace(/<[^>]+>/g, " ");
    trimmed = trimmed.replace(/[|]+/g, " ");
    trimmed = trimmed.replace(/\s+/g, " ").trim();
    if (trimmed)
      projected.push(trimmed);
  });
  const text = projected.join(" ").replace(/\s+/g, " ").trim();
  if (!text)
    return;
  if (truncationInfo)
    truncationInfo.truncated = text.length > MARKDOWN_CONTENT_MAX_CHARS;
  return truncateUnicodeSafe(text, MARKDOWN_CONTENT_MAX_CHARS);
}
function forEachVisibleMarkdownLine(lines, start, visit2) {
  let fence;
  const htmlComment = { inComment: false };
  for (let index = start;index < lines.length; index += 1) {
    const rawLine = lines[index];
    if (fence) {
      if (isMarkdownFenceClosing(rawLine, fence))
        fence = undefined;
      continue;
    }
    const leadingFence = htmlComment.inComment ? undefined : parseMarkdownFenceOpening(rawLine);
    if (leadingFence) {
      fence = leadingFence;
      continue;
    }
    const visible = stripMarkdownHtmlComments(rawLine, htmlComment);
    const openingFence = parseMarkdownFenceOpening(visible.trim());
    if (openingFence) {
      fence = openingFence;
      continue;
    }
    visit2(index, visible);
  }
}
var markdownFragmentContentByEntry = new WeakMap;
var markdownFragmentProjectionEntries = new WeakSet;
function setMarkdownFragmentContent(entry, content) {
  markdownFragmentProjectionEntries.add(entry);
  if (content)
    markdownFragmentContentByEntry.set(entry, content);
}
function getMarkdownFragmentContent(entry) {
  return markdownFragmentContentByEntry.get(entry);
}
function hasMarkdownFragmentContent(entry) {
  return markdownFragmentProjectionEntries.has(entry);
}
function projectMarkdownFragmentContent(raw) {
  const lines = raw.split(/\r?\n/);
  const parsed = parseFrontmatter(raw);
  const projected = lines.map(() => "");
  forEachVisibleMarkdownLine(lines, parsed.frontmatter ? parsed.bodyStartLine - 1 : 0, (index, visible) => {
    if (/^\s*\[[^\]]+\]:\s*\S+/.test(visible) || /^\s*<[^>]+>\s*$/.test(visible))
      return;
    projected[index] = stripMarkdownLinkDestinations(visible).replace(/<[^>]+>/g, " ").replace(/[ \t]+$/g, "");
  });
  const text = projected.join(`
`);
  return text.trim() ? text : undefined;
}
function applyPreContributorFields(entry, file, ctx, pkgMeta) {
  const ext = path17.extname(file).toLowerCase();
  if (pkgMeta) {
    if (pkgMeta.description && !entry.description) {
      entry.description = pkgMeta.description;
      entry.source = "package";
      entry.confidence = 0.8;
    }
    if (pkgMeta.keywords && pkgMeta.keywords.length > 0)
      entry.tags = normalizeTerms(pkgMeta.keywords);
  }
  if (ext === ".md" && entry.type !== "secret") {
    const content = ctx.content();
    const parsed = parseFrontmatter(content);
    applyCuratedFrontmatter(entry, parsed.data);
    const fmParams = extractFrontmatterParameters(parsed.data);
    if (fmParams)
      entry.parameters = fmParams;
    applyWikiFrontmatter(entry, parsed.data);
    applyProvenanceFrontmatter(entry, parsed.data);
    const safeForFragments = entry.type !== "env" && entry.type !== "session" && !hasSessionMemoryMarker(parsed.data, parsed.content);
    setMarkdownFragmentContent(entry, safeForFragments ? projectMarkdownFragmentContent(content) : undefined);
    if (safeForFragments) {
      const truncationInfo = { truncated: false };
      const contentProjection = projectMarkdownContent(parsed.content, truncationInfo);
      if (contentProjection) {
        entry.content = contentProjection;
        if (truncationInfo.truncated) {
          entry.contentTruncated = true;
          warn(`${file}: indexed content truncated to ${MARKDOWN_CONTENT_MAX_CHARS} chars`);
        }
      }
    }
    if (entry.type === "command") {
      const cmdParams = extractCommandParameters(parsed.content);
      if (cmdParams) {
        entry.parameters = mergeParameters(entry.parameters, cmdParams);
      }
    }
  }
  if (ext !== ".md" && entry.type !== "env" && entry.type !== "secret") {
    const content = ctx.content();
    const scriptParams = extractScriptParameters(file, content);
    if (scriptParams)
      entry.parameters = scriptParams;
    applyCommentMetadata(entry, extractCommentMetadata(file, content));
  }
}
function applyPostContributorFields(entry, file, canonicalName, dirPath) {
  const ext = path17.extname(file).toLowerCase();
  const baseName = path17.basename(file, ext);
  if (!entry.description) {
    entry.description = fileNameToDescription(baseName);
    entry.source = "filename";
    entry.confidence = Math.min(entry.confidence ?? 0.55, 0.55);
  }
  if (!entry.tags || entry.tags.length === 0) {
    entry.tags = extractTagsFromPath(file, dirPath);
  }
  entry.tags = [...entry.tags ?? [], ...extractDirTagsFromName(canonicalName)];
  entry.tags = normalizeTerms(entry.tags ?? []);
  entry.aliases = mergeAliases(entry.aliases, buildAliases(canonicalName, entry.tags));
  entry.filename = path17.basename(file);
}
function normalizeTerms(values) {
  const normalized = new Set;
  for (const value of values) {
    const cleaned = value.toLowerCase().replace(/[-_]+/g, " ").replace(/\s+/g, " ").trim();
    if (!cleaned)
      continue;
    normalized.add(cleaned);
  }
  return Array.from(normalized);
}
function buildAliases(name, tags) {
  const aliases = new Set;
  const spaced = name.replace(/[-_]+/g, " ").trim().toLowerCase();
  if (spaced && spaced !== name.toLowerCase())
    aliases.add(spaced);
  if (tags.length > 1)
    aliases.add(tags.join(" "));
  return Array.from(aliases);
}
function extractPackageMetadata(dirPath) {
  const pkgPath = path17.join(dirPath, "package.json");
  if (!fs14.existsSync(pkgPath))
    return null;
  try {
    const pkg = JSON.parse(fs14.readFileSync(pkgPath, "utf8"));
    const result = {};
    if (typeof pkg.name === "string")
      result.name = pkg.name;
    if (typeof pkg.description === "string")
      result.description = pkg.description;
    if (Array.isArray(pkg.keywords)) {
      result.keywords = pkg.keywords.filter((k) => typeof k === "string");
    }
    return Object.keys(result).length > 0 ? result : null;
  } catch {
    return null;
  }
}
function fileNameToDescription(fileName) {
  return fileName.replace(/[-_]+/g, " ").replace(/([a-z])([A-Z])/g, "$1 $2").toLowerCase().trim();
}
function extractTagsFromPath(filePath, rootDir) {
  const rel = path17.relative(rootDir, filePath);
  const parts = rel.split(path17.sep);
  const tags = new Set;
  for (const part of parts) {
    const name = part.replace(path17.extname(part), "");
    for (const token of name.split(/[-_./\\]+/)) {
      const clean = token.toLowerCase().trim();
      if (clean && clean.length > 1)
        tags.add(clean);
    }
  }
  return Array.from(tags);
}
function extractDirTagsFromName(name) {
  const tags = new Set;
  for (const segment of name.split("/").slice(0, -1)) {
    for (const token of segment.split(/[-_.]+/)) {
      const clean = token.toLowerCase().trim();
      if (clean && clean.length > 1)
        tags.add(clean);
    }
  }
  return Array.from(tags);
}

// src/core/adapter/execution-source.ts
import { createHash as createHash3 } from "node:crypto";

// src/execution/source.ts
var EXECUTION_SOURCE_SCHEMA_VERSION = 1;
var MODEL_WORK_POLICY_ID = "model-work";
function requireRecord(value, path18) {
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
    throw new TypeError(`${path18} must be an object`);
  }
  return value;
}
function createAdapterExtensions(first, second, ...rest) {
  const entries = typeof first === "string" ? [[first, second]] : [first, ...second === undefined ? [] : [second], ...rest];
  const out = {};
  for (const [owner, values] of entries)
    out[owner] = cloneExecutionJsonObject(values, `extensions.${owner}`);
  return Object.freeze(out);
}
function cloneAdapterExtensions(value, path18) {
  const out = {};
  for (const [owner, fields] of Object.entries(requireRecord(value, path18))) {
    out[owner] = cloneExecutionJsonObject(fields, `${path18}.${owner}`);
  }
  return Object.freeze(out);
}
var IDENTITY_KEYS = ["ref", "bundle", "adapter", "file", "hash"];
function identityFrom(value, path18) {
  const record = requireRecord(value, path18);
  const out = {};
  for (const key of IDENTITY_KEYS) {
    const field = record[key];
    if (typeof field !== "string" || field.length === 0)
      throw new TypeError(`${path18}.${key} must be a non-empty string`);
    out[key] = field;
  }
  return Object.freeze(out);
}
function createExecutionSourceIdentity(input) {
  return identityFrom(input, "execution source identity");
}
function cloneUnresolvedExecutionDefaults(input, path18 = "execution source defaults") {
  const record = requireRecord(input, path18);
  const present = (key) => Object.hasOwn(record, key) && record[key] !== undefined;
  const out = {};
  for (const key of ["agent", "engine", "model", "workspace"]) {
    if (!present(key))
      continue;
    const value = record[key];
    if (value !== null && typeof value !== "string")
      throw new TypeError(`${path18}.${key} must be a string or null`);
    out[key] = value;
  }
  if (present("timeout")) {
    const timeout = record.timeout;
    if (timeout !== null && typeof timeout !== "string" && typeof timeout !== "number") {
      throw new TypeError(`${path18}.timeout must be a string, number, or null`);
    }
    out.timeout = timeout;
  }
  for (const key of ["inference", "outputSchema", "runtime"]) {
    if (!present(key))
      continue;
    out[key] = record[key] === null ? null : cloneExecutionJsonObject(record[key], `${path18}.${key}`);
  }
  if (present("environment")) {
    const environment = record.environment === null ? null : cloneExecutionJsonObject(record.environment, `${path18}.environment`);
    if (environment !== null && Object.values(environment).some((value) => typeof value !== "string")) {
      throw new TypeError(`${path18}.environment values must be strings`);
    }
    out.environment = environment;
  }
  if (present("tools"))
    out.tools = cloneToolSelection(record.tools, `${path18}.tools`);
  return Object.freeze(out);
}
function cloneToolSelection(value, path18 = "tools") {
  if (value === null || typeof value === "string")
    return value;
  const cloned = cloneExecutionJson(value, path18);
  if (Array.isArray(cloned)) {
    if (cloned.some((tool) => typeof tool !== "string"))
      throw new TypeError(`${path18} array values must be strings`);
    return cloned;
  }
  return cloneExecutionJsonObject(cloned, path18);
}
function createAdapterRenderedExecutionSource(input) {
  const { kind, content } = input;
  if (kind !== "command" && kind !== "persona")
    throw new TypeError("execution source kind is invalid");
  if (typeof content !== "string")
    throw new TypeError("execution source content must be a string");
  return Object.freeze({
    schemaVersion: EXECUTION_SOURCE_SCHEMA_VERSION,
    kind,
    content,
    defaults: cloneUnresolvedExecutionDefaults(input.defaults ?? {}),
    identity: createExecutionSourceIdentity(input.identity),
    ...input.extensions ? { extensions: cloneAdapterExtensions(input.extensions, "execution source extensions") } : {}
  });
}

// src/core/adapter/execution-source.ts
function nextLine(text, start) {
  const lf = text.indexOf(`
`, start);
  if (lf < 0)
    return { line: text.slice(start), next: text.length };
  const end = lf > start && text[lf - 1] === "\r" ? lf - 1 : lf;
  return { line: text.slice(start, end), next: lf + 1 };
}
function parseExecutionMarkdown(raw, filePath) {
  if (typeof raw !== "string")
    throw new TypeError("execution source raw content must be a string");
  const where = filePath ? ` (${filePath})` : "";
  const withoutBom = raw.startsWith("\uFEFF") ? raw.slice(1) : raw;
  const opening = nextLine(withoutBom, 0);
  if (opening.line !== "---")
    return { content: withoutBom, data: Object.freeze({}) };
  if (opening.next === withoutBom.length) {
    throw new UsageError(`execution source${where} has unterminated frontmatter`);
  }
  let cursor = opening.next;
  let frontmatterEnd = -1;
  let bodyStart = -1;
  while (cursor <= withoutBom.length) {
    const lineStart = cursor;
    const current = nextLine(withoutBom, cursor);
    if (current.line === "---") {
      frontmatterEnd = lineStart;
      bodyStart = current.next;
      break;
    }
    if (current.next === cursor || current.next === withoutBom.length)
      break;
    cursor = current.next;
  }
  if (frontmatterEnd < 0 || bodyStart < 0) {
    throw new UsageError(`execution source${where} has unterminated frontmatter`);
  }
  const yaml = withoutBom.slice(opening.next, frontmatterEnd);
  const document = $parseDocument(yaml, { uniqueKeys: true });
  if (document.errors.length > 0) {
    throw new UsageError(`execution source${where} has invalid YAML frontmatter: ${document.errors[0]?.message ?? "parse error"}`);
  }
  if (document.warnings.length > 0) {
    warnOnce(`execution-source:yaml-warning:${filePath ?? "<inline>"}`, `execution source${where} YAML frontmatter uses an unsupported tag or construct: ${document.warnings[0]?.message}. Using it as parsed.`);
  }
  if (!$isMap(document.contents)) {
    throw new UsageError(`execution source${where} YAML frontmatter must be a mapping`);
  }
  let unsupported;
  $visit(document, {
    Alias: () => {
      unsupported ??= "aliases";
    },
    Node: (_key, node) => {
      if (node.tag)
        unsupported ??= "custom or explicit tags";
      if (node.anchor !== undefined)
        unsupported ??= "anchors";
    },
    Pair: (_key, pair) => {
      if (!$isScalar(pair.key) || typeof pair.key.value !== "string")
        unsupported ??= "non-string mapping keys";
    }
  });
  if (unsupported) {
    warnOnce(`execution-source:unsupported:${filePath ?? "<inline>"}`, `execution source${where} YAML frontmatter uses ${unsupported}, which akm does not fully support; using the bounded conversion's result as-is.`);
  }
  let root;
  try {
    root = document.toJS({ maxAliasCount: 0 });
  } catch (cause) {
    const detail = cause instanceof Error ? cause.message : String(cause);
    throw new UsageError(`execution source${where} YAML frontmatter could not be converted safely: ${detail}`);
  }
  const data = cloneExecutionJsonObject(root, "execution source YAML frontmatter");
  return { content: withoutBom.slice(bodyStart), data: Object.freeze(data) };
}
function own(data, key) {
  return Object.hasOwn(data, key);
}
function requireMetadataMapping(value, path18) {
  try {
    return snapshotStrictRecord(value, path18);
  } catch (cause) {
    throw new TypeError(`${path18} must be a mapping with enumerable data fields`, { cause });
  }
}
function nullableString(value, path18) {
  if (value !== null && typeof value !== "string")
    throw new TypeError(`${path18} must be a string or null`);
  return value;
}
function nullableObject(value, path18) {
  return value === null ? null : cloneExecutionJsonObject(value, path18);
}
function nullableTimeout(value, path18) {
  const timeout = cloneExecutionJson(value, path18);
  if (timeout !== null && typeof timeout !== "string" && typeof timeout !== "number") {
    throw new TypeError(`${path18} must be a string, number, or null`);
  }
  return timeout;
}
function executionDefaultsFromFrontmatter(data, options) {
  const frontmatter = snapshotStrictRecord(data, "frontmatter");
  const kind = options.kind;
  if (kind !== "command" && kind !== "persona") {
    throw new TypeError("execution frontmatter projection options.kind is invalid");
  }
  const allowTopLevelEngine = Object.hasOwn(options, "allowTopLevelEngine") ? options.allowTopLevelEngine : false;
  if (typeof allowTopLevelEngine !== "boolean") {
    throw new TypeError("execution frontmatter projection options.allowTopLevelEngine must be a boolean");
  }
  const configuredToolsKeys = Object.hasOwn(options, "toolsKeys") ? cloneExecutionJson(options.toolsKeys, "execution frontmatter projection options.toolsKeys") : ["tools"];
  if (!Array.isArray(configuredToolsKeys) || configuredToolsKeys.some((key) => typeof key !== "string" || !key)) {
    throw new TypeError("execution frontmatter projection options.toolsKeys must be an array of non-empty strings");
  }
  const namespace = own(frontmatter, "akm") ? requireMetadataMapping(frontmatter.akm, "frontmatter.akm") : snapshotStrictRecord({}, "frontmatter.akm");
  for (const key of ["workspace", "environment", "runtime"]) {
    const location = own(frontmatter, key) ? `frontmatter.${key}` : own(namespace, key) ? `frontmatter.akm.${key}` : undefined;
    if (location) {
      throw new TypeError(`${location} is host-controlled and cannot be declared by an executable asset; configure the selected engine or workflow execution environment instead`);
    }
  }
  const out = Object.create(null);
  if (kind === "command" && own(frontmatter, "agent")) {
    out.agent = nullableString(frontmatter.agent, "frontmatter.agent");
  }
  const namespacedEngine = own(namespace, "engine") ? nullableString(namespace.engine, "frontmatter.akm.engine") : undefined;
  const topLevelEngine = allowTopLevelEngine && own(frontmatter, "engine") ? nullableString(frontmatter.engine, "frontmatter.engine") : undefined;
  if (topLevelEngine !== undefined)
    out.engine = topLevelEngine;
  else if (namespacedEngine !== undefined)
    out.engine = namespacedEngine;
  if (own(frontmatter, "model")) {
    out.model = nullableString(frontmatter.model, "frontmatter.model");
  }
  let toolsSelected = false;
  for (const key of configuredToolsKeys) {
    if (!own(frontmatter, key))
      continue;
    const selection = cloneToolSelection(frontmatter[key], `frontmatter.${key}`);
    if (!toolsSelected) {
      out.tools = selection;
      toolsSelected = true;
    }
  }
  let inferenceEntries;
  if (own(namespace, "inference")) {
    if (namespace.inference === null)
      inferenceEntries = null;
    else {
      inferenceEntries = new Map;
      for (const [key, value] of Object.entries(cloneExecutionJsonObject(namespace.inference, "frontmatter.akm.inference"))) {
        inferenceEntries.set(key, value);
      }
    }
  }
  for (const key of ["temperature", "effort"]) {
    if (!own(frontmatter, key))
      continue;
    if (inferenceEntries === null) {
      throw new TypeError(`frontmatter.${key} conflicts with explicit null frontmatter.akm.inference`);
    }
    inferenceEntries ??= new Map;
    const value = frontmatter[key];
    if (key === "temperature") {
      if (value !== null && typeof value !== "number") {
        throw new TypeError("frontmatter.temperature must be a number or null");
      }
    } else if (value !== null && typeof value !== "string") {
      throw new TypeError("frontmatter.effort must be a string or null");
    }
    inferenceEntries.set(key, cloneExecutionJson(value, `frontmatter.${key}`));
  }
  if (inferenceEntries === null)
    out.inference = null;
  else if (inferenceEntries !== undefined)
    out.inference = Object.fromEntries(inferenceEntries);
  const namespacedSchema = own(namespace, "schema") ? nullableObject(namespace.schema, "frontmatter.akm.schema") : undefined;
  const topLevelSchema = own(frontmatter, "schema") ? nullableObject(frontmatter.schema, "frontmatter.schema") : undefined;
  if (topLevelSchema !== undefined)
    out.outputSchema = topLevelSchema;
  else if (namespacedSchema !== undefined)
    out.outputSchema = namespacedSchema;
  const namespacedTimeouts = new Map;
  for (const key of ["timeoutMs", "timeout"]) {
    if (own(namespace, key)) {
      namespacedTimeouts.set(key, nullableTimeout(namespace[key], `frontmatter.akm.${key}`));
    }
  }
  const topLevelTimeouts = new Map;
  if (allowTopLevelEngine) {
    for (const key of ["timeoutMs", "timeout"]) {
      if (own(frontmatter, key)) {
        topLevelTimeouts.set(key, nullableTimeout(frontmatter[key], `frontmatter.${key}`));
      }
    }
  }
  const timeoutKey = namespacedTimeouts.has("timeoutMs") ? "timeoutMs" : namespacedTimeouts.has("timeout") ? "timeout" : undefined;
  const topLevelTimeoutKey = allowTopLevelEngine ? topLevelTimeouts.has("timeoutMs") ? "timeoutMs" : topLevelTimeouts.has("timeout") ? "timeout" : undefined : undefined;
  const selectedTimeoutKey = topLevelTimeoutKey ?? timeoutKey;
  if (selectedTimeoutKey) {
    out.timeout = topLevelTimeoutKey ? topLevelTimeouts.get(selectedTimeoutKey) : namespacedTimeouts.get(selectedTimeoutKey);
  }
  return out;
}
function renderMarkdownExecutionSource(input) {
  const raw = input.raw;
  if (typeof raw !== "string")
    throw new TypeError("adapter execution source.raw must be a string");
  const kind = input.kind;
  if (kind !== "command" && kind !== "persona")
    throw new TypeError("adapter execution source.kind is invalid");
  const identity3 = input.identity;
  const parsed = parseExecutionMarkdown(raw, identity3.file);
  const hasDefaults = Object.hasOwn(input, "defaults");
  const defaultsProjection = input.defaults;
  const defaults = typeof defaultsProjection === "function" ? defaultsProjection(parsed.data) : defaultsProjection;
  if (hasDefaults && defaults === undefined) {
    throw new TypeError("adapter execution source defaults must be omitted or resolve to an object");
  }
  const extensionsProjection = input.extensions;
  const extensionsAreProjected = typeof extensionsProjection === "function";
  const extensions = extensionsAreProjected ? extensionsProjection(parsed.data) : extensionsProjection;
  if (Object.hasOwn(input, "extensions") && !extensionsAreProjected && extensions === undefined) {
    throw new TypeError("adapter execution source extensions must be omitted or be an adapter-owned extension object");
  }
  return createAdapterRenderedExecutionSource({
    kind,
    content: parsed.content,
    identity: {
      ref: identity3.ref,
      bundle: identity3.bundle,
      adapter: identity3.adapter,
      file: identity3.file,
      hash: createHash3("sha256").update(raw, "utf8").digest("hex")
    },
    ...hasDefaults ? { defaults } : {},
    ...extensions === undefined ? {} : { extensions }
  });
}

// src/core/type-presentation.ts
function shellQuote(value) {
  return `'${value.replace(/'/g, `'\\''`)}'`;
}
function buildWorkflowAction(ref) {
  return `Start or resume execution with \`akm workflow run ${shellQuote(ref)}\`.`;
}
var TYPE_PRESENTATION = {
  skill: {
    label: "Skill",
    renderer: "skill-md",
    action: (ref) => `akm show ${ref} -> follow the instructions`,
    fragmentRef: false
  },
  command: {
    label: "Command",
    renderer: "command-md",
    action: (ref) => `akm show ${ref} -> fill placeholders and dispatch`,
    fragmentRef: false
  },
  agent: {
    label: "Agent",
    renderer: "agent-md",
    action: (ref) => `akm show ${ref} -> dispatch with full prompt`,
    fragmentRef: false
  },
  knowledge: {
    label: "Knowledge",
    renderer: "knowledge-md",
    action: (ref) => `akm show ${ref} -> read reference material`
  },
  workflow: {
    label: "Workflow",
    renderer: "workflow-md",
    action: (ref) => buildWorkflowAction(ref),
    fragmentRef: false
  },
  script: {
    label: "Script",
    renderer: "script-source",
    action: (ref) => `akm show ${ref} -> execute the run command`,
    fragmentRef: false
  },
  memory: { label: "Memory", renderer: "memory-md", action: (ref) => `akm show ${ref} -> recall context` },
  env: {
    label: "Env",
    renderer: "env-file",
    action: (ref) => `akm show ${ref} -> inspect key names; akm env run ${ref} -- <command> -> run with the whole .env injected (prefer --clean to minimize inherited parent env; child stdout is not redacted). akm env export ${ref} --out <file> writes a sourceable script (values to a file, not stdout).`
  },
  secret: {
    label: "Secret",
    renderer: "secret-file",
    action: (ref) => `akm show ${ref} -> name only (value never shown); akm secret run ${ref} <VAR> -- <command> -> run with value injected into $VAR`
  },
  lesson: {
    label: "Lesson",
    renderer: "lesson-md",
    action: (ref) => `akm show ${ref} -> read the lesson and apply when_to_use`
  },
  task: {
    label: "Task",
    renderer: "task-yaml",
    action: (ref) => `akm show ${ref} -> inspect; akm task run <id> -> run now; akm task enable|disable ${ref} -> change local scheduling`,
    fragmentRef: false
  },
  session: {
    label: "Session",
    renderer: "session-md",
    action: (ref) => `akm show ${ref} -> read the session summary; follow the \`access\` frontmatter to open the raw log at \`log_path\``
  },
  fact: {
    label: "Fact",
    renderer: "fact-md",
    action: (ref) => `akm show ${ref} -> read the stash fact and apply it as durable context`
  },
  instruction: {
    label: "Instruction",
    renderer: "knowledge-md",
    action: (ref) => `akm show ${ref} -> read the project instructions`,
    fragmentRef: false
  }
};
var DEFAULT_PRESENTATION = { label: "Asset" };
function presentationFor(type) {
  if (type !== undefined && isKnownType(type))
    return TYPE_PRESENTATION[type];
  return DEFAULT_PRESENTATION;
}

// src/indexer/walk/matchers.ts
var DIR_TYPE_MAP = [
  {
    dir: "scripts",
    type: "script",
    test: (ext) => SCRIPT_EXTENSIONS.has(ext)
  },
  {
    dir: "commands",
    type: "command",
    test: (ext) => ext === ".md"
  },
  {
    dir: "agents",
    type: "agent",
    test: (ext) => ext === ".md"
  },
  {
    dir: "knowledge",
    type: "knowledge",
    test: (ext) => ext === ".md"
  },
  {
    dir: "instructions",
    type: "instruction",
    test: (ext) => ext === ".md"
  },
  {
    dir: "workflows",
    type: "workflow",
    test: (ext) => ext === ".md" || ext === ".yml"
  },
  {
    dir: "memories",
    type: "memory",
    test: (ext) => ext === ".md"
  },
  {
    dir: "lessons",
    type: "lesson",
    test: (ext) => ext === ".md"
  },
  {
    dir: "env",
    type: "env",
    test: (_, fileName) => fileName === ".env" || fileName.endsWith(".env")
  },
  {
    dir: "secrets",
    type: "secret",
    test: (_, fileName) => !fileName.endsWith(".lock") && !fileName.endsWith(".sensitive")
  },
  {
    dir: "tasks",
    type: "task",
    test: (ext) => ext === ".yml"
  },
  {
    dir: "sessions",
    type: "session",
    test: (ext) => ext === ".md"
  },
  {
    dir: "facts",
    type: "fact",
    test: (ext) => ext === ".md"
  }
];
var ARGUMENTS_PLACEHOLDER_RE = /\$ARGUMENTS/;
var NUMERIC_PLACEHOLDER_RE = /\$[123](?!\d|[.,]\d)/;
var SMART_MD_FACTS = {
  workflow: { type: "workflow", specificity: 19 },
  toolsAgent: { type: "agent", specificity: 20 },
  command: { type: "command", specificity: 18 },
  modelAgent: { type: "agent", specificity: 8 },
  knowledge: { type: "knowledge", specificity: 5 }
};
var TYPED_DIR_DOC_FILES = new Set(["readme.md"]);
function isTypedDirDocFile(fileName) {
  return TYPED_DIR_DOC_FILES.has(fileName.toLowerCase());
}
function isNestedSkillResource(ctx) {
  return ctx.ancestorDirs[0] === "skills" && ctx.ancestorDirs.length > 1 && ctx.fileName !== "SKILL.md";
}
function matchDirectoryHint(dirName, ctx, specificity) {
  if (dirName === "skills" && ctx.fileName === "SKILL.md") {
    return { type: "skill", specificity };
  }
  for (const rule of DIR_TYPE_MAP) {
    if (rule.dir === dirName && rule.test(ctx.ext, ctx.fileName)) {
      if (isTypedDirDocFile(ctx.fileName))
        return null;
      return { type: rule.type, specificity };
    }
  }
  return null;
}
function hasDeclaredDirType(ctx) {
  if (isNestedSkillResource(ctx))
    return false;
  return ctx.ancestorDirs.some((dir) => matchDirectoryHint(dir, ctx, 0) !== null);
}
function classifyByExtension(ctx) {
  if (ctx.fileName === "SKILL.md") {
    return { type: "skill", specificity: 25 };
  }
  if (SCRIPT_EXTENSIONS.has(ctx.ext)) {
    return { type: "script", specificity: 3 };
  }
  return null;
}
function classifyByDirectory(ctx) {
  if (isNestedSkillResource(ctx))
    return null;
  for (const dir of ctx.ancestorDirs) {
    const result = matchDirectoryHint(dir, ctx, 10);
    if (result)
      return result;
  }
  return null;
}
function classifyByParentDirHint(ctx) {
  const { parentDir, ext, fileName } = ctx;
  if (isNestedSkillResource(ctx))
    return null;
  if (parentDir === "skills" && (fileName === "SKILL.md" || ext === ".md")) {
    return { type: "skill", specificity: 15 };
  }
  return matchDirectoryHint(parentDir, ctx, 15);
}
function classifyBySmartMd(ctx) {
  if (ctx.ext !== ".md")
    return null;
  if (ctx.ancestorDirs.includes("secrets"))
    return null;
  if (isTypedDirDocFile(ctx.fileName)) {
    return SMART_MD_FACTS.knowledge;
  }
  const body = ctx.content();
  const fm = ctx.frontmatter();
  if (fm && fm.type === "workflow") {
    return SMART_MD_FACTS.workflow;
  }
  if (fm) {
    if ("tools" in fm) {
      return SMART_MD_FACTS.toolsAgent;
    }
    if ("agent" in fm) {
      return SMART_MD_FACTS.command;
    }
  }
  if (ARGUMENTS_PLACEHOLDER_RE.test(body)) {
    return SMART_MD_FACTS.command;
  }
  if (NUMERIC_PLACEHOLDER_RE.test(body) && !hasDeclaredDirType(ctx)) {
    return SMART_MD_FACTS.command;
  }
  if (fm && "model" in fm) {
    return SMART_MD_FACTS.modelAgent;
  }
  return SMART_MD_FACTS.knowledge;
}
function toMatchResult(ctx, classify) {
  const fact = classify(ctx);
  return fact ? matchResultForFact(fact) : null;
}
function matchResultForFact(fact) {
  const renderer = presentationFor(fact.type).renderer;
  if (!renderer)
    return null;
  return {
    type: fact.type,
    specificity: fact.specificity,
    renderer,
    ...fact.meta ? { meta: fact.meta } : {}
  };
}
function extensionMatcher(ctx) {
  return toMatchResult(ctx, classifyByExtension);
}
function directoryMatcher(ctx) {
  return toMatchResult(ctx, classifyByDirectory);
}
function parentDirHintMatcher(ctx) {
  return toMatchResult(ctx, classifyByParentDirHint);
}
function smartMdMatcher(ctx) {
  return toMatchResult(ctx, classifyBySmartMd);
}

// src/core/adapter/recognize-match.ts
var AKM_MATCHERS = [
  extensionMatcher,
  directoryMatcher,
  parentDirHintMatcher,
  smartMdMatcher
];
function winningMatch(hits) {
  if (hits.length === 0)
    return null;
  hits.sort((a, b) => {
    const specDiff = b.result.specificity - a.result.specificity;
    if (specDiff !== 0)
      return specDiff;
    return b.index - a.index;
  });
  return hits[0].result;
}
function recognizeMatch(file) {
  const hits = [];
  for (let i = 0;i < AKM_MATCHERS.length; i++) {
    const result = AKM_MATCHERS[i](file);
    if (result !== null)
      hits.push({ result, index: i });
  }
  return winningMatch(hits);
}

// src/core/adapter/adapters/akm-lint.ts
import path21 from "node:path";

// src/commands/env/env.ts
var import_dotenv = __toESM(require_main(), 1);

// src/commands/lint/env-key-rules.ts
var DANGEROUS_ENV_KEYS = new Set([
  "LD_PRELOAD",
  "LD_LIBRARY_PATH",
  "LD_AUDIT",
  "LD_DEBUG",
  "LD_BIND_NOW",
  "LD_PROFILE",
  "LD_ASSUME_KERNEL",
  "LD_TRACE_LOADED_OBJECTS",
  "DYLD_INSERT_LIBRARIES",
  "DYLD_LIBRARY_PATH",
  "DYLD_FRAMEWORK_PATH",
  "PATH",
  "BASH_ENV",
  "ENV",
  "PROMPT_COMMAND",
  "PS1",
  "PS2",
  "IFS",
  "ZDOTDIR",
  "NODE_OPTIONS",
  "NODE_PATH",
  "NODE_TLS_REJECT_UNAUTHORIZED",
  "PYTHONSTARTUP",
  "PYTHONPATH",
  "PYTHONINSPECT",
  "PYTHONHOME",
  "PYTHONNOUSERSITE",
  "RUBYLIB",
  "RUBYOPT",
  "PERL5LIB",
  "PERL5OPT",
  "JAVA_TOOL_OPTIONS",
  "JDK_JAVA_OPTIONS",
  "_JAVA_OPTIONS",
  "GIT_SSH_COMMAND",
  "GIT_EXTERNAL_DIFF",
  "GIT_PAGER",
  "GIT_EDITOR",
  "EDITOR",
  "VISUAL",
  "PAGER"
]);
var DANGEROUS_ENV_KEY_PATTERNS = [
  {
    pattern: /^BASH_FUNC_/,
    reason: "Shellshock-class bash function injection (CVE-2014-6271)"
  },
  {
    pattern: /^GIT_CONFIG_/,
    reason: "Git config injection through environment override variables"
  }
];
function isDangerousEnvKey(key) {
  if (DANGEROUS_ENV_KEYS.has(key))
    return true;
  for (const { pattern } of DANGEROUS_ENV_KEY_PATTERNS) {
    if (pattern.test(key))
      return true;
  }
  return false;
}

// src/tasks/source/bounded-document.ts
import fs15 from "node:fs";
import path18 from "node:path";
import { types as utilTypes } from "node:util";
var TASK_V3_MAX_JSON_DEPTH = 64;
var TASK_V3_MAX_JSON_NODES = 1e4;
var TASK_V3_MAX_COLLECTION_ITEMS = 1024;
var TASK_V3_MAX_OBJECT_KEYS = 256;
var TASK_V3_MAX_STRING_BYTES = 256 * 1024;
var TASK_V3_MAX_SCHEDULES = 64;
var TASK_V3_MAX_REDACT_NAMES = 32;
function own2(value, key) {
  return Object.hasOwn(value, key);
}
function utf8Bytes2(value) {
  return new TextEncoder().encode(value).byteLength;
}
function sourceError(ctx, fieldPath, detail) {
  const dotted = fieldPath.length === 0 ? "$" : fieldPath.reduce((display, segment) => typeof segment === "number" ? `${display}[${segment}]` : display.length > 0 ? `${display}.${segment}` : segment, "");
  const line = ctx.lineAt?.(fieldPath);
  const location = `${ctx.filePath}${line === undefined ? "" : `:${line}`}`;
  throw new UsageError(`Invalid ${ctx.sourceLabel} at ${location}: ${dotted} ${detail}`, "TASK_SOURCE_INVALID");
}
function cloneBoundedJson(value, ctx, fieldPath, state, depth = 0, ancestors = new Set) {
  state.nodes += 1;
  if (state.nodes > TASK_V3_MAX_JSON_NODES)
    sourceError(ctx, fieldPath, `exceeds the ${TASK_V3_MAX_JSON_NODES}-node limit.`);
  if (depth > TASK_V3_MAX_JSON_DEPTH)
    sourceError(ctx, fieldPath, `exceeds the nesting depth of ${TASK_V3_MAX_JSON_DEPTH}.`);
  if (value === null || typeof value === "boolean")
    return value;
  if (typeof value === "number") {
    if (!Number.isFinite(value))
      sourceError(ctx, fieldPath, "must be a finite JSON number.");
    return value;
  }
  if (typeof value === "string") {
    if (!wellFormedUnicode(value))
      sourceError(ctx, fieldPath, "must contain well-formed Unicode.");
    if (utf8Bytes2(value) > TASK_V3_MAX_STRING_BYTES) {
      sourceError(ctx, fieldPath, `exceeds the ${TASK_V3_MAX_STRING_BYTES}-byte string limit.`);
    }
    return value;
  }
  if (value === undefined)
    sourceError(ctx, fieldPath, "must be omitted instead of set to undefined.");
  if (typeof value !== "object")
    sourceError(ctx, fieldPath, "must be JSON-safe.");
  if (utilTypes.isProxy(value))
    sourceError(ctx, fieldPath, "must not be a Proxy object.");
  if (ancestors.has(value))
    sourceError(ctx, fieldPath, "must not contain a cycle.");
  const nextAncestors = new Set(ancestors).add(value);
  if (Array.isArray(value)) {
    if (Object.getPrototypeOf(value) !== Array.prototype)
      sourceError(ctx, fieldPath, "array must use the standard prototype.");
    const rawLength = Reflect.getOwnPropertyDescriptor(value, "length")?.value;
    if (typeof rawLength !== "number" || !Number.isInteger(rawLength) || rawLength < 0 || rawLength > TASK_V3_MAX_COLLECTION_ITEMS) {
      sourceError(ctx, fieldPath, `array exceeds the ${TASK_V3_MAX_COLLECTION_ITEMS}-item limit.`);
    }
    const length = rawLength;
    const keys = Reflect.ownKeys(value);
    if (keys.length !== length + 1)
      sourceError(ctx, fieldPath, "array must be dense and contain no extra fields.");
    const result2 = [];
    for (let index = 0;index < length; index += 1) {
      const descriptor = Reflect.getOwnPropertyDescriptor(value, String(index));
      if (!descriptor || !("value" in descriptor) || !descriptor.enumerable) {
        sourceError(ctx, [...fieldPath, index], "array item must be an enumerable data property in a dense array.");
      }
      result2.push(cloneBoundedJson(descriptor.value, ctx, [...fieldPath, index], state, depth + 1, nextAncestors));
    }
    return Object.freeze(result2);
  }
  let snapshot;
  try {
    snapshot = snapshotStrictRecord(value, fieldPath.map(String).join(".") || "task source");
  } catch (cause) {
    sourceError(ctx, fieldPath, cause instanceof Error ? cause.message : String(cause));
  }
  const entries = Object.entries(snapshot);
  if (entries.length > TASK_V3_MAX_OBJECT_KEYS) {
    sourceError(ctx, fieldPath, `mapping exceeds the ${TASK_V3_MAX_OBJECT_KEYS}-key limit.`);
  }
  const result = Object.create(null);
  for (const [key, child] of entries) {
    if (!wellFormedUnicode(key))
      sourceError(ctx, fieldPath, "contains a mapping key with malformed Unicode.");
    if (utf8Bytes2(key) > TASK_V3_MAX_STRING_BYTES) {
      sourceError(ctx, fieldPath, `contains a mapping key exceeding the ${TASK_V3_MAX_STRING_BYTES}-byte string limit.`);
    }
    Object.defineProperty(result, key, {
      value: cloneBoundedJson(child, ctx, [...fieldPath, key], state, depth + 1, nextAncestors),
      enumerable: true,
      configurable: false,
      writable: false
    });
  }
  return Object.freeze(result);
}
function asRecord2(value, ctx, fieldPath) {
  if (value === null || Array.isArray(value) || typeof value !== "object")
    sourceError(ctx, fieldPath, "must be a mapping.");
  return value;
}
function checkKeys(value, allowed, ctx, fieldPath) {
  const allow = new Set(allowed);
  const firstUnknown = Object.keys(value).find((key) => !allow.has(key));
  if (firstUnknown !== undefined)
    sourceError(ctx, [...fieldPath, firstUnknown], "is an unsupported field.");
}
function presentJsonValue(value, ctx, fieldPath) {
  if (value === undefined)
    sourceError(ctx, fieldPath, "must be omitted instead of set to undefined.");
  return value;
}
function stringField(value, ctx, fieldPath, options = {}) {
  if (value === null && options.nullable)
    return null;
  if (typeof value !== "string")
    sourceError(ctx, fieldPath, options.nullable ? "must be a string or null." : "must be a string.");
  if (options.nonempty && value.trim().length === 0)
    sourceError(ctx, fieldPath, "must be a non-empty string.");
  return value;
}
function noGithubExpression(value, ctx, fieldPath) {
  if (value.includes("${{"))
    sourceError(ctx, fieldPath, "contains an unsupported GitHub expression.");
}
function parseEnvironment(value, ctx) {
  const environment = asRecord2(value, ctx, ["env"]);
  for (const [key, child] of Object.entries(environment)) {
    if (!WORKFLOW_ENV_VAR_NAME_PATTERN.test(key))
      sourceError(ctx, ["env", key], "has an invalid environment variable name.");
    if (typeof child !== "string" && typeof child !== "number" && typeof child !== "boolean") {
      sourceError(ctx, ["env", key], "must be a string, finite number, or boolean.");
    }
  }
  return environment;
}
function parseStringArray(value, ctx, fieldPath, options = {}) {
  if (!Array.isArray(value))
    sourceError(ctx, fieldPath, "must be an array of strings.");
  if (options.max !== undefined && value.length > options.max)
    sourceError(ctx, fieldPath, `accepts at most ${options.max} items.`);
  const strings = [];
  for (const [index, entry] of value.entries()) {
    if (typeof entry !== "string" || entry.length === 0)
      sourceError(ctx, [...fieldPath, index], "must be a non-empty string.");
    if (options.pattern && !options.pattern.test(entry))
      sourceError(ctx, [...fieldPath, index], "has an invalid value.");
    strings.push(entry);
  }
  return Object.freeze(strings);
}
function parseTimeout(value, ctx) {
  if (value === null)
    return null;
  if (typeof value === "string" && value.trim() !== value) {
    sourceError(ctx, ["akm", "timeout"], "must not contain surrounding whitespace.");
  }
  const milliseconds = typeof value === "string" ? parseDuration(value, DURATION_UNITS) : value;
  if (milliseconds === null || typeof milliseconds !== "number" || !Number.isSafeInteger(milliseconds) || milliseconds < 0 || milliseconds > EXECUTION_MAX_TIMEOUT_MS) {
    sourceError(ctx, ["akm", "timeout"], `must be null, 0 through ${EXECUTION_MAX_TIMEOUT_MS} milliseconds, or a common duration such as 20m.`);
  }
  return value;
}
function parseTools(value, ctx) {
  if (value === null || typeof value === "string")
    return value;
  if (Array.isArray(value)) {
    if (value.some((entry) => typeof entry !== "string"))
      sourceError(ctx, ["akm", "tools"], "array values must be strings.");
    return value;
  }
  if (typeof value === "object")
    return value;
  sourceError(ctx, ["akm", "tools"], "must be a string, string array, mapping, or null.");
}
function validateWorkingDirectory(value, ctx) {
  if (value.trim().length === 0 || value.includes("\x00") || path18.posix.isAbsolute(value.replaceAll("\\", "/")) || /^[A-Za-z]:[\\/]/.test(value) || value.startsWith("\\\\")) {
    sourceError(ctx, ["working-directory"], "must be a non-empty relative path contained by the workspace root.");
  }
  const segments = value.replaceAll("\\", "/").split("/");
  if (segments.some((segment) => segment === ".." || segment.length === 0)) {
    sourceError(ctx, ["working-directory"], "must not contain empty or escaping path segments.");
  }
  if (!ctx.workspaceRoot) {
    sourceError(ctx, ["working-directory"], "requires a workspace root so physical containment can be verified.");
  }
  let realRoot;
  let realCandidate;
  try {
    realRoot = fs15.realpathSync(ctx.workspaceRoot);
    const candidate = path18.resolve(realRoot, value);
    const stat = fs15.statSync(candidate);
    if (!stat.isDirectory())
      sourceError(ctx, ["working-directory"], "must resolve to a directory.");
    realCandidate = fs15.realpathSync(candidate);
  } catch (cause) {
    if (cause instanceof UsageError)
      throw cause;
    sourceError(ctx, ["working-directory"], `cannot be physically verified: ${cause instanceof Error ? cause.message : String(cause)}.`);
  }
  const relative = path18.relative(realRoot, realCandidate);
  if (relative.startsWith("..") || path18.isAbsolute(relative)) {
    sourceError(ctx, ["working-directory"], "resolves outside the workspace root and is not physically contained.");
  }
}
function yamlProblem(message) {
  return message.split(`
`)[0]?.trim() || "invalid YAML";
}
function yamlAstError(options, node, detail) {
  const range = node?.range;
  const line = range && options.lineCounter ? options.lineCounter.linePos(range[0] ?? 0).line : undefined;
  throw new UsageError(`Invalid ${options.sourceLabel} at ${options.filePath}${line === undefined ? "" : `:${line}`}: ${detail}`, "TASK_SOURCE_INVALID");
}
function assertBoundedTaskYamlDocument(document, options) {
  const stack = [{ node: document.contents, depth: 0 }];
  let nodes = 0;
  while (stack.length > 0) {
    const current = stack.pop();
    if (!current)
      break;
    const node = current.node;
    if (node === null || node === undefined)
      continue;
    nodes += 1;
    if (nodes > TASK_V3_MAX_JSON_NODES) {
      yamlAstError(options, node, `YAML exceeds the ${TASK_V3_MAX_JSON_NODES}-node limit.`);
    }
    if (current.depth > TASK_V3_MAX_JSON_DEPTH) {
      yamlAstError(options, node, `YAML exceeds the nesting depth of ${TASK_V3_MAX_JSON_DEPTH}.`);
    }
    if ($isAlias(node))
      yamlAstError(options, node, "YAML aliases are unsupported.");
    if (node.anchor !== undefined) {
      yamlAstError(options, node, "YAML anchors are unsupported.");
    }
    if (node.tag) {
      yamlAstError(options, node, "custom or explicit YAML tags are unsupported.");
    }
    if ($isScalar(node))
      continue;
    if ($isSeq(node)) {
      if (node.items.length > TASK_V3_MAX_COLLECTION_ITEMS) {
        yamlAstError(options, node, `YAML sequence exceeds the ${TASK_V3_MAX_COLLECTION_ITEMS}-item limit.`);
      }
      for (let index = node.items.length - 1;index >= 0; index -= 1) {
        stack.push({ node: node.items[index], depth: current.depth + 1 });
      }
      continue;
    }
    if ($isMap(node)) {
      if (node.items.length > TASK_V3_MAX_OBJECT_KEYS) {
        yamlAstError(options, node, `YAML mapping exceeds the ${TASK_V3_MAX_OBJECT_KEYS}-key limit.`);
      }
      for (let index = node.items.length - 1;index >= 0; index -= 1) {
        const pair = node.items[index];
        if (!pair)
          yamlAstError(options, node, "sparse YAML mappings are unsupported.");
        if (!$isScalar(pair.key) || typeof pair.key.value !== "string") {
          yamlAstError(options, pair.key, "non-string YAML mapping keys are unsupported.");
        }
        if (!wellFormedUnicode(pair.key.value)) {
          yamlAstError(options, pair.key, "YAML mapping key must contain well-formed Unicode.");
        }
        if (utf8Bytes2(pair.key.value) > TASK_V3_MAX_STRING_BYTES) {
          yamlAstError(options, pair.key, `YAML mapping key exceeds the ${TASK_V3_MAX_STRING_BYTES}-byte string limit.`);
        }
        if (pair.key.value === "<<")
          yamlAstError(options, pair.key, "YAML merge keys are unsupported.");
        stack.push({ node: pair.value, depth: current.depth + 1 });
        stack.push({ node: pair.key, depth: current.depth + 1 });
      }
      continue;
    }
    yamlAstError(options, node, "unsupported YAML node kind.");
  }
}
function readBoundedTaskSourceYaml(input, options) {
  const sourceLabel = options.sourceLabel;
  if (typeof input.yaml !== "string") {
    throw new UsageError(`Invalid ${sourceLabel} at ${input.filePath}: source must be a string.`, "TASK_SOURCE_INVALID");
  }
  const lineCounter2 = new $LineCounter;
  let document;
  try {
    document = $parseDocument(input.yaml, { lineCounter: lineCounter2, uniqueKeys: true });
  } catch (cause) {
    throw new UsageError(`Invalid ${sourceLabel} at ${input.filePath}: YAML parsing failed: ${cause instanceof Error ? cause.message : String(cause)}`, "TASK_SOURCE_INVALID");
  }
  const [problem] = document.errors;
  if (problem) {
    const offset = Array.isArray(problem.pos) ? problem.pos[0] : 0;
    throw new UsageError(`Invalid ${sourceLabel} at ${input.filePath}:${lineCounter2.linePos(offset).line}: ${yamlProblem(problem.message)}`, "TASK_SOURCE_INVALID");
  }
  const [warning] = document.warnings;
  if (warning) {
    throw new UsageError(`Invalid ${sourceLabel} at ${input.filePath}: unsupported YAML construct: ${yamlProblem(warning.message)}`, "TASK_SOURCE_INVALID");
  }
  assertBoundedTaskYamlDocument(document, { filePath: input.filePath, sourceLabel, lineCounter: lineCounter2 });
  let root;
  try {
    root = document.toJS({ maxAliasCount: 0 });
  } catch (cause) {
    throw new UsageError(`Invalid ${sourceLabel} at ${input.filePath}: YAML expansion failed: ${cause instanceof Error ? cause.message : String(cause)}`, "TASK_SOURCE_INVALID");
  }
  const lineAt = (fieldPath) => {
    for (let depth = fieldPath.length;depth >= 0; depth -= 1) {
      const node = depth === 0 ? document.contents : document.getIn(fieldPath.slice(0, depth), true);
      const range = node?.range;
      if (range)
        return lineCounter2.linePos(range[0]).line;
    }
    return;
  };
  return { root, lineAt };
}

// src/commands/command/builtin-action.ts
function parseBuiltinCommandAction(value) {
  const input = snapshotStrictRecord(value, "built-in command action with");
  assertSnapshotKeys(input, ["ref", "content", "arguments"], "built-in command action with");
  const hasRef = Object.hasOwn(input, "ref");
  const hasContent = Object.hasOwn(input, "content");
  if (hasRef === hasContent) {
    throw new UsageError("Built-in command action with requires exactly one of ref or content.", "INVALID_FLAG_VALUE");
  }
  if (Object.hasOwn(input, "arguments") && typeof input.arguments !== "string") {
    throw new UsageError("Built-in command action with.arguments must be a string.", "INVALID_FLAG_VALUE");
  }
  const exactArguments = Object.hasOwn(input, "arguments") ? { arguments: input.arguments } : {};
  if (hasRef) {
    if (typeof input.ref !== "string" || input.ref.length === 0) {
      throw new UsageError("Built-in command action with.ref must be a non-empty string.", "INVALID_FLAG_VALUE");
    }
    return Object.freeze({ kind: "stored", ref: input.ref, ...exactArguments });
  }
  if (typeof input.content !== "string") {
    throw new UsageError("Built-in command action with.content must be a string.", "INVALID_FLAG_VALUE");
  }
  return Object.freeze({ kind: "inline", content: input.content, ...exactArguments });
}

// src/core/json-schema.ts
var MAX_DEFINITION_DEPTH = 64;
function validateJsonSchemaSubset(value, schema, options) {
  const errors3 = [];
  validateNode(value, schema, "$", { errors: errors3, depth: 0, redactValues: options?.redactValues ?? false });
  return errors3;
}
var JSON_SCHEMA_SUBSET_SUPPORTED_KEYWORDS = "type, enum, properties, required, items, additionalProperties: false, minItems, maxItems, " + "minLength, maxLength, minimum, maximum, allOf, anyOf, oneOf, not";
var KNOWN_TYPE_NAMES = new Set(["string", "number", "integer", "boolean", "object", "array", "null"]);
var UNSUPPORTED_KEYWORDS = new Set([
  "$ref",
  "$defs",
  "definitions",
  "$anchor",
  "$dynamicRef",
  "$dynamicAnchor",
  "if",
  "then",
  "else",
  "const",
  "pattern",
  "format",
  "patternProperties",
  "propertyNames",
  "additionalItems",
  "prefixItems",
  "contains",
  "minContains",
  "maxContains",
  "uniqueItems",
  "multipleOf",
  "exclusiveMinimum",
  "exclusiveMaximum",
  "minProperties",
  "maxProperties",
  "dependencies",
  "dependentRequired",
  "dependentSchemas",
  "unevaluatedItems",
  "unevaluatedProperties",
  "contentEncoding",
  "contentMediaType",
  "contentSchema"
]);
var UNSUPPORTED_KEYWORD_HINTS = new Map([
  ["$ref", `inline the referenced schema (the subset resolves no references, so it cannot follow "$ref")`],
  ["$defs", `inline the definitions at their use sites — "$ref" is not resolved, so "$defs" can never be reached`],
  [
    "definitions",
    `inline the definitions at their use sites — "$ref" is not resolved, so "definitions" can never be reached`
  ],
  ["const", `use a single-value "enum" (e.g. enum: [pass])`],
  [
    "pattern",
    `use "enum" when the allowed strings can be listed, or "minLength"/"maxLength" for a size bound — ` + `a regular-expression constraint is not expressible in the subset; check the shape in the step's gate rubric instead`
  ],
  [
    "format",
    `"format" is annotation-only in JSON Schema 2020-12 and the subset enforces no string-shape keyword — ` + `use "enum" when the allowed values can be listed, otherwise check the shape in the step's gate rubric`
  ],
  ["patternProperties", `declare the properties explicitly under "properties", or drop the constraint`],
  ["if", `use "anyOf"/"oneOf" to express the alternatives directly`],
  ["then", `use "anyOf"/"oneOf" to express the alternatives directly`],
  ["else", `use "anyOf"/"oneOf" to express the alternatives directly`],
  ["uniqueItems", `drop the constraint, or validate uniqueness in the step's gate rubric`]
]);
function checkJsonSchemaDefinition(schema) {
  const issues = [];
  checkDefinitionNode(schema, [], issues, 0);
  return issues;
}
function pointerFor(path19) {
  return path19.length === 0 ? "$" : `$.${path19.map(String).join(".")}`;
}
function pushIssue(issues, path19, keyword, kind, message) {
  issues.push({ path: [...path19], pointer: pointerFor(path19), keyword, kind, message });
}
function isSupportedEnumValue(value) {
  return value === null || typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);
}
function checkDefinitionNode(schema, path19, issues, depth) {
  if (depth > MAX_DEFINITION_DEPTH) {
    pushIssue(issues, path19, "(depth)", "malformed", `schema nesting exceeds the depth limit of ${MAX_DEFINITION_DEPTH}`);
    return;
  }
  for (const keyword of Object.keys(schema)) {
    if (UNSUPPORTED_KEYWORDS.has(keyword)) {
      const hint = UNSUPPORTED_KEYWORD_HINTS.get(keyword);
      pushIssue(issues, [...path19, keyword], keyword, "unsupported", `keyword "${keyword}" is not enforced by the workflow schema subset — the schema would silently not ` + `constrain what it looks like it constrains${hint ? `; ${hint}` : ""}`);
    }
  }
  const declared = schema.type;
  if (declared !== undefined) {
    const names = Array.isArray(declared) ? declared : [declared];
    if (names.length === 0) {
      pushIssue(issues, [...path19, "type"], "type", "malformed", `"type" must name at least one type`);
    }
    for (const [index, name] of names.entries()) {
      const namePath = Array.isArray(declared) ? [...path19, "type", index] : [...path19, "type"];
      if (typeof name !== "string") {
        pushIssue(issues, namePath, "type", "malformed", `"type" must be a string or an array of strings`);
      } else if (!KNOWN_TYPE_NAMES.has(name)) {
        pushIssue(issues, namePath, "type", "malformed", `unknown type ${JSON.stringify(name)} (valid types: ${[...KNOWN_TYPE_NAMES].join(", ")})`);
      }
    }
  }
  if (schema.enum !== undefined) {
    if (!Array.isArray(schema.enum) || schema.enum.length === 0) {
      pushIssue(issues, [...path19, "enum"], "enum", "malformed", `"enum" must be a non-empty array of allowed values`);
    } else {
      schema.enum.forEach((value, index) => {
        if (isSupportedEnumValue(value))
          return;
        pushIssue(issues, [...path19, "enum", index], "enum", "unsupported", `"enum" values must be JSON primitives (string, finite number, boolean, or null) in the workflow ` + `schema subset — object and array enum members cannot be matched by the runtime subset`);
      });
    }
  }
  for (const keyword of ["allOf", "anyOf", "oneOf"]) {
    const branches = schema[keyword];
    if (branches === undefined)
      continue;
    if (!Array.isArray(branches) || branches.length === 0) {
      pushIssue(issues, [...path19, keyword], keyword, "malformed", `"${keyword}" must be a non-empty array of schema objects`);
      continue;
    }
    branches.forEach((branch, index) => {
      if (isRecord(branch)) {
        checkDefinitionNode(branch, [...path19, keyword, index], issues, depth + 1);
      } else {
        pushIssue(issues, [...path19, keyword, index], keyword, "malformed", `"${keyword}[${index}]" must be a schema object`);
      }
    });
  }
  if (schema.not !== undefined) {
    if (isRecord(schema.not)) {
      checkDefinitionNode(schema.not, [...path19, "not"], issues, depth + 1);
    } else {
      pushIssue(issues, [...path19, "not"], "not", "malformed", `"not" must be a schema object`);
    }
  }
  if (schema.required !== undefined) {
    if (!Array.isArray(schema.required) || !schema.required.every((key) => typeof key === "string")) {
      pushIssue(issues, [...path19, "required"], "required", "malformed", `"required" must be an array of property-name strings`);
    }
  }
  if (schema.properties !== undefined) {
    if (!isRecord(schema.properties)) {
      pushIssue(issues, [...path19, "properties"], "properties", "malformed", `"properties" must be an object mapping property names to schemas`);
    } else {
      for (const [key, propSchema] of Object.entries(schema.properties)) {
        if (isRecord(propSchema)) {
          checkDefinitionNode(propSchema, [...path19, "properties", key], issues, depth + 1);
        } else {
          pushIssue(issues, [...path19, "properties", key], "properties", "malformed", `property ${JSON.stringify(key)} must be a schema object`);
        }
      }
    }
  }
  if (schema.items !== undefined) {
    if (isRecord(schema.items)) {
      checkDefinitionNode(schema.items, [...path19, "items"], issues, depth + 1);
    } else if (Array.isArray(schema.items)) {
      pushIssue(issues, [...path19, "items"], "items", "unsupported", `tuple-form "items" (an array of schemas) is not enforced by the workflow schema subset — use a single schema object`);
    } else {
      pushIssue(issues, [...path19, "items"], "items", "malformed", `"items" must be a schema object`);
    }
  }
  if (schema.additionalProperties !== undefined && typeof schema.additionalProperties !== "boolean") {
    if (isRecord(schema.additionalProperties)) {
      pushIssue(issues, [...path19, "additionalProperties"], "additionalProperties", "unsupported", `schema-form "additionalProperties" is not enforced by the workflow schema subset — only "additionalProperties: false" is`);
    } else {
      pushIssue(issues, [...path19, "additionalProperties"], "additionalProperties", "malformed", `"additionalProperties" must be a boolean (only "false" is enforced)`);
    }
  }
  for (const keyword of ["minItems", "maxItems", "minLength", "maxLength"]) {
    const value = schema[keyword];
    if (value !== undefined && (typeof value !== "number" || !Number.isInteger(value) || value < 0)) {
      pushIssue(issues, [...path19, keyword], keyword, "malformed", `"${keyword}" must be a non-negative integer`);
    }
  }
  for (const keyword of ["minimum", "maximum"]) {
    const value = schema[keyword];
    if (value !== undefined && (typeof value !== "number" || !Number.isFinite(value))) {
      pushIssue(issues, [...path19, keyword], keyword, "malformed", `"${keyword}" must be a finite number`);
    }
  }
}
function typeOf(value) {
  if (value === null)
    return "null";
  if (Array.isArray(value))
    return "array";
  switch (typeof value) {
    case "string":
      return "string";
    case "boolean":
      return "boolean";
    case "number":
      return Number.isInteger(value) ? "integer" : "number";
    default:
      return "object";
  }
}
function matchesType(actual, expected) {
  if (expected === actual)
    return true;
  return expected === "number" && actual === "integer";
}
function branchErrors(value, schema, path19, ctx) {
  const errors3 = [];
  validateNode(value, schema, path19, { ...ctx, errors: errors3, depth: ctx.depth + 1 });
  return errors3;
}
function combinatorBranches(schema, keyword) {
  const raw = schema[keyword];
  if (!Array.isArray(raw))
    return [];
  return raw.filter(isRecord);
}
function summarizeBranchFailures(failures) {
  const shown = failures.slice(0, 3).map((f) => `${f.index + 1}: ${f.errors[0] ?? "no match"}`);
  if (failures.length > shown.length)
    shown.push(`…${failures.length - shown.length} more`);
  return shown.join("; ");
}
function validateCombinators(value, schema, path19, ctx) {
  for (const branch of combinatorBranches(schema, "allOf")) {
    ctx.errors.push(...branchErrors(value, branch, path19, ctx));
  }
  for (const keyword of ["anyOf", "oneOf"]) {
    const branches = combinatorBranches(schema, keyword);
    if (branches.length === 0)
      continue;
    const failures = [];
    const matched = [];
    branches.forEach((branch, index) => {
      const errors3 = branchErrors(value, branch, path19, ctx);
      if (errors3.length === 0)
        matched.push(index + 1);
      else
        failures.push({ index, errors: errors3 });
    });
    if (matched.length === 0) {
      ctx.errors.push(`${path19}: value matches none of the ${branches.length} "${keyword}" schemas (${summarizeBranchFailures(failures)})`);
    } else if (keyword === "oneOf" && matched.length > 1) {
      ctx.errors.push(`${path19}: value matches ${matched.length} "oneOf" schemas (branches ${matched.join(", ")}); exactly one must match`);
    }
  }
  const not = schema.not;
  if (isRecord(not) && branchErrors(value, not, path19, ctx).length === 0) {
    ctx.errors.push(`${path19}: value must not match the "not" schema`);
  }
}
function validateNode(value, schema, path19, ctx) {
  const errors3 = ctx.errors;
  if (ctx.depth > MAX_DEFINITION_DEPTH) {
    errors3.push(`${path19}: schema nesting exceeds the depth limit of ${MAX_DEFINITION_DEPTH}`);
    return;
  }
  const actual = typeOf(value);
  const declared = schema.type;
  if (typeof declared === "string" || Array.isArray(declared)) {
    const expected = (Array.isArray(declared) ? declared : [declared]).filter((t) => typeof t === "string");
    if (expected.length > 0 && !expected.some((t) => matchesType(actual, t))) {
      errors3.push(`${path19}: expected type ${expected.join(" | ")}, got ${actual}`);
      return;
    }
  }
  if (Array.isArray(schema.enum) && schema.enum.length > 0) {
    const allowed = schema.enum;
    if (!allowed.some((candidate) => candidate === value)) {
      errors3.push(ctx.redactValues ? `${path19}: value is not one of ${JSON.stringify(allowed)}` : `${path19}: value ${JSON.stringify(value)} is not one of ${JSON.stringify(allowed)}`);
      return;
    }
  }
  validateCombinators(value, schema, path19, ctx);
  if (actual === "string" && typeof value === "string") {
    if (typeof schema.minLength === "number" && value.length < schema.minLength) {
      errors3.push(`${path19}: string shorter than minLength ${schema.minLength}`);
    }
    if (typeof schema.maxLength === "number" && value.length > schema.maxLength) {
      errors3.push(`${path19}: string longer than maxLength ${schema.maxLength}`);
    }
    return;
  }
  if ((actual === "number" || actual === "integer") && typeof value === "number") {
    if (typeof schema.minimum === "number" && value < schema.minimum) {
      errors3.push(ctx.redactValues ? `${path19}: value is below minimum ${schema.minimum}` : `${path19}: ${value} is below minimum ${schema.minimum}`);
    }
    if (typeof schema.maximum === "number" && value > schema.maximum) {
      errors3.push(ctx.redactValues ? `${path19}: value is above maximum ${schema.maximum}` : `${path19}: ${value} is above maximum ${schema.maximum}`);
    }
    return;
  }
  if (actual === "array" && Array.isArray(value)) {
    if (typeof schema.minItems === "number" && value.length < schema.minItems) {
      errors3.push(`${path19}: array has fewer than minItems ${schema.minItems}`);
    }
    if (typeof schema.maxItems === "number" && value.length > schema.maxItems) {
      errors3.push(`${path19}: array has more than maxItems ${schema.maxItems}`);
    }
    const items = schema.items;
    if (items && typeof items === "object" && !Array.isArray(items)) {
      value.forEach((element, index) => {
        validateNode(element, items, `${path19}[${index}]`, {
          ...ctx,
          depth: ctx.depth + 1
        });
      });
    }
    return;
  }
  if (actual === "object" && typeof value === "object" && value !== null) {
    const record = value;
    const properties = schema.properties && typeof schema.properties === "object" && !Array.isArray(schema.properties) ? schema.properties : undefined;
    if (Array.isArray(schema.required)) {
      for (const key of schema.required) {
        if (typeof key === "string" && !Object.hasOwn(record, key)) {
          errors3.push(`${path19}: missing required property "${key}"`);
        }
      }
    }
    if (properties) {
      for (const [key, propSchema] of Object.entries(properties)) {
        if (!Object.hasOwn(record, key))
          continue;
        if (propSchema && typeof propSchema === "object" && !Array.isArray(propSchema)) {
          validateNode(record[key], propSchema, `${path19}.${key}`, {
            ...ctx,
            depth: ctx.depth + 1
          });
        }
      }
    }
    if (schema.additionalProperties === false) {
      for (const key of Object.keys(record)) {
        if (!properties || !Object.hasOwn(properties, key)) {
          errors3.push(`${path19}: unexpected property "${key}" (additionalProperties: false)`);
        }
      }
    }
  }
}

// src/execution/input-contract.ts
var INPUT_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
function applyInputDefaults(contract, values) {
  const result = { ...values };
  for (const [name, declaration] of Object.entries(contract)) {
    if (Object.hasOwn(result, name))
      continue;
    if (Object.hasOwn(declaration, "default"))
      result[name] = declaration.default;
  }
  return result;
}
function validateInputs(contract, values, options) {
  const pathRoot = options?.pathRoot ?? "$";
  const properties = {};
  for (const [name, declaration] of Object.entries(contract))
    properties[name] = declaration.schema;
  const schemaErrors = Object.keys(properties).length === 0 ? [] : validateJsonSchemaSubset(values, { type: "object", properties }, { redactValues: true }).map((error2) => error2.replace(/^\$/, pathRoot));
  const missingRequired = [];
  for (const [name, declaration] of Object.entries(contract)) {
    if (declaration.required && !Object.hasOwn(values, name)) {
      missingRequired.push(`${pathRoot}.${name}: is required`);
    }
  }
  return [...schemaErrors, ...missingRequired];
}

// src/execution/target-ref.ts
var FAMILY_KIND = {
  commands: "command",
  scripts: "script",
  tasks: "task",
  workflows: "workflow"
};
function targetRefInvalid(value) {
  return new UsageError(`Target ref ${JSON.stringify(value)} must be a canonical commands/, scripts/, tasks/, or workflows/ asset ref.`, "TARGET_REF_INVALID");
}
function classifyTargetRef(value) {
  let parsed;
  try {
    parsed = parseBundleRef(value);
  } catch {
    throw targetRefInvalid(value);
  }
  if (parsed.fragment !== undefined)
    throw targetRefInvalid(value);
  if (bundleRefToString(parsed) !== value)
    throw targetRefInvalid(value);
  const slash = parsed.conceptId.indexOf("/");
  if (slash < 0)
    throw targetRefInvalid(value);
  const family = parsed.conceptId.slice(0, slash);
  const name = parsed.conceptId.slice(slash + 1);
  if (name.length === 0)
    throw targetRefInvalid(value);
  const kind = FAMILY_KIND[family];
  if (kind === undefined)
    throw targetRefInvalid(value);
  return Object.freeze({ kind, ref: value });
}

// src/workflows/exec/param-secrets.ts
var SECRET_KEY_HINTS = [
  "secret",
  "token",
  "password",
  "passwd",
  "apikey",
  "api_key",
  "api-key",
  "accesskey",
  "access_key",
  "privatekey",
  "private_key",
  "credential",
  "bearer",
  "auth_token",
  "authtoken",
  "client_secret"
];
var SECRET_VALUE_PREFIX = /^(sk-|rk-|ghp_|gho_|ghu_|ghs_|ghr_|github_pat_|xox[baprs]-|AKIA|ASIA|AIza|ya29\.|-----BEGIN)/;
function keyLooksSecret(key) {
  const lower = key.toLowerCase();
  return SECRET_KEY_HINTS.some((hint) => lower.includes(hint));
}
function valueLooksSecret(value) {
  const s = value.trim();
  if (s.length < 20 || /\s/.test(s))
    return false;
  if (SECRET_VALUE_PREFIX.test(s))
    return true;
  const classes = [/[a-z]/, /[A-Z]/, /[0-9]/, /[^A-Za-z0-9]/].filter((re) => re.test(s)).length;
  if (s.length >= 24 && classes >= 3)
    return true;
  if (s.length >= 32 && /^[A-Za-z0-9+/=_-]+$/.test(s))
    return true;
  return false;
}
var MOVE_TO_ENV = "Workflow params are copied verbatim into every native unit execution context and returned in `akm workflow run` and " + "`akm workflow status` output — move secrets to an env binding (`env:` ref), whose value native execution resolves " + "only at dispatch instead of storing it as a run param.";
function detectSecretShapedParams(params) {
  const warnings = [];
  const seen = new Set;
  walkSecretShaped(params, (path19, why) => {
    if (seen.has(path19))
      return;
    seen.add(path19);
    warnings.push(`Run param "${path19}" ${why}. ${MOVE_TO_ENV} (Heuristic warning; params are declared non-secret.)`);
  });
  return warnings;
}
function walkSecretShaped(params, hit) {
  const walk = (value, path19, key) => {
    if (key !== null && keyLooksSecret(key))
      hit(path19, "has a secret-suggesting name", value);
    if (typeof value === "string") {
      if (valueLooksSecret(value))
        hit(path19, "has a secret-shaped value (long, high-entropy string)", value);
      return;
    }
    if (Array.isArray(value)) {
      for (let i = 0;i < value.length; i++)
        walk(value[i], `${path19}[${i}]`, null);
      return;
    }
    if (value && typeof value === "object") {
      for (const [k, v] of Object.entries(value)) {
        walk(v, path19 ? `${path19}.${k}` : k, k);
      }
    }
  };
  for (const [k, v] of Object.entries(params))
    walk(v, k, k);
}

// src/tasks/source-v3.ts
var TASK_EXTENSION = ".yml";
var TASK_NEAR_MISS_EXTENSION = ".yaml";
function taskExtensionDetail(relPath) {
  const base = relPath.replace(/\.yaml$/i, "");
  return `task file uses the ${TASK_NEAR_MISS_EXTENSION} extension; akm recognizes tasks only as ` + `${TASK_EXTENSION}, so this file is never indexed or scheduled — rename it to ${base}${TASK_EXTENSION}.`;
}
var TASK_V3_HOST_SHELLS = ["bash", "sh", "zsh", "pwsh", "powershell", "cmd"];
function taskSourceErrorDetail(cause) {
  if (!(cause instanceof Error))
    return String(cause);
  const hint = "hint" in cause && typeof cause.hint === "function" ? cause.hint() : undefined;
  return hint ? `${cause.message} ${hint}` : cause.message;
}

// src/tasks/task-run-reserved-flags.ts
var TASK_RUN_VALUE_FLAGS = ["bundle", "format", "detail", "shape", "output"];
var TASK_RUN_BOOLEAN_FLAGS = [
  "scheduled",
  "quiet",
  "verbose",
  "help",
  "no-quiet",
  "no-verbose"
];
var TASK_RUN_SELF_DIAGNOSED_FLAGS = ["target"];
var TASK_RUN_RESERVED_FLAG_NAMES = new Set([
  ...TASK_RUN_VALUE_FLAGS,
  ...TASK_RUN_BOOLEAN_FLAGS,
  ...TASK_RUN_SELF_DIAGNOSED_FLAGS
]);

// src/tasks/source/task-source-v4.ts
var TASK_SOURCE_V4_VERSION = 4;
var TASK_SOURCE_V4_TOP_LEVEL_KEYS = [
  "version",
  "name",
  "description",
  "when_to_use",
  "tags",
  "inputs",
  "output",
  "uses",
  "run",
  "with",
  "env",
  "shell",
  "working-directory",
  "schedule",
  "agent",
  "engine",
  "model",
  "inference",
  "tools",
  "timeout",
  "redact",
  "maxSteps",
  "maxRetries"
];
var TASK_SOURCE_V4_SCHEDULE_KEYS = ["cron", "inputs"];
var SUBSET_KEYWORD_NAMES = JSON_SCHEMA_SUBSET_SUPPORTED_KEYWORDS.split(",").map((entry) => entry.split(":")[0]?.trim() ?? "").filter((entry) => entry.length > 0);
var TASK_INPUT_DECLARATION_KEYS = Object.freeze([...SUBSET_KEYWORD_NAMES, "title", "description", "default"]);
var SHELL_SET = new Set(TASK_V3_HOST_SHELLS);
var SOURCE_LABEL = "task source v4";
function ctxFrom(options) {
  return {
    filePath: options.filePath,
    sourceLabel: SOURCE_LABEL,
    ...options.workspaceRoot ? { workspaceRoot: options.workspaceRoot } : {},
    ...options.lineAt ? { lineAt: options.lineAt } : {}
  };
}
function looksLikeGithubActionLocator(value) {
  const at = value.lastIndexOf("@");
  if (at <= 0)
    return false;
  const locator = value.slice(0, at);
  const revision = value.slice(at + 1);
  if (revision.length === 0 || /\s/.test(revision))
    return false;
  if (locator.length === 0 || /\s/.test(locator) || !locator.includes("/"))
    return false;
  return true;
}
var TASK_SOURCE_V4_USES_REMEDY = "Use a canonical commands/, scripts/, or workflows/ ref, or akm/command, instead.";
function classifyTaskSourceV4Uses(value) {
  if (typeof value !== "string" || value.length === 0 || value.trim() !== value || /\s/.test(value) || value.includes("${{")) {
    throw new UsageError("Task source v4 uses must be one exact, non-empty executable ref without expressions.");
  }
  if (value === "akm/command") {
    return Object.freeze({ kind: "builtin-command", ref: "akm/command" });
  }
  let classified;
  try {
    classified = classifyTargetRef(value);
  } catch (cause) {
    if (looksLikeGithubActionLocator(value)) {
      throw new UsageError("GitHub Action targets were removed in task source v4 — the github-action uses: variant no longer exists. " + `${TASK_SOURCE_V4_USES_REMEDY}`);
    }
    if (cause instanceof UsageError && cause.code === "TARGET_REF_INVALID") {
      throw new UsageError(`${JSON.stringify(value)} is not an executable task source v4 target. ${TASK_SOURCE_V4_USES_REMEDY}`);
    }
    throw cause instanceof Error ? cause : new UsageError(String(cause));
  }
  if (classified.kind === "task") {
    throw new UsageError(`A task ref is not an executable task source v4 target. ${TASK_SOURCE_V4_USES_REMEDY}`);
  }
  return Object.freeze({ kind: classified.kind, ref: classified.ref });
}
function nullableSelectorTopLevel(value, ctx, key) {
  const selector = stringField(value, ctx, [key], { nullable: true });
  if (selector !== null && selector.trim().length === 0)
    sourceError(ctx, [key], "must be null or a non-empty string.");
  return selector;
}
function parseTimeoutTopLevel(value, ctx) {
  if (value === null)
    return null;
  if (typeof value === "string" && value.trim() !== value) {
    sourceError(ctx, ["timeout"], "must not contain surrounding whitespace.");
  }
  const milliseconds = typeof value === "string" ? parseDuration(value, DURATION_UNITS) : value;
  if (milliseconds === null || typeof milliseconds !== "number" || !Number.isSafeInteger(milliseconds) || milliseconds < 0 || milliseconds > EXECUTION_MAX_TIMEOUT_MS) {
    sourceError(ctx, ["timeout"], `must be null, 0 through ${EXECUTION_MAX_TIMEOUT_MS} milliseconds, or a common duration such as 20m.`);
  }
  return value;
}
function parseToolsTopLevel(value, ctx) {
  if (value === null || typeof value === "string")
    return value;
  if (Array.isArray(value)) {
    if (value.some((entry) => typeof entry !== "string"))
      sourceError(ctx, ["tools"], "array values must be strings.");
    return value;
  }
  if (typeof value === "object")
    return value;
  sourceError(ctx, ["tools"], "must be a string, string array, mapping, or null.");
}
function parseTarget(input, ctx) {
  const hasUses = own2(input, "uses");
  if (hasUses) {
    if (own2(input, "shell"))
      sourceError(ctx, ["shell"], "is legal only with run.");
    if (own2(input, "working-directory"))
      sourceError(ctx, ["working-directory"], "is legal only with run.");
    const usesText = stringField(input.uses, ctx, ["uses"], { nonempty: true });
    let uses;
    try {
      uses = classifyTaskSourceV4Uses(usesText);
    } catch (cause) {
      sourceError(ctx, ["uses"], cause instanceof Error ? cause.message : String(cause));
    }
    let withValues;
    if (own2(input, "with")) {
      if (uses.kind !== "builtin-command") {
        sourceError(ctx, ["with"], "is legal only with uses: akm/command; declare typed inputs: instead.");
      }
      withValues = asRecord2(presentJsonValue(input.with, ctx, ["with"]), ctx, ["with"]);
    }
    if (uses.kind === "builtin-command") {
      let command;
      try {
        command = parseBuiltinCommandAction(withValues);
      } catch (cause) {
        sourceError(ctx, ["with"], cause instanceof Error ? cause.message : String(cause));
      }
      return Object.freeze({ kind: "uses", uses, ...withValues ? { with: withValues } : {}, command });
    }
    return Object.freeze({ kind: "uses", uses, ...withValues ? { with: withValues } : {} });
  }
  if (own2(input, "with"))
    sourceError(ctx, ["with"], "is legal only with uses: akm/command; declare typed inputs: instead.");
  const run = stringField(input.run, ctx, ["run"], { nonempty: true });
  let shell;
  if (own2(input, "shell")) {
    const rawShell = stringField(input.shell, ctx, ["shell"], { nonempty: true });
    if (!SHELL_SET.has(rawShell)) {
      sourceError(ctx, ["shell"], `must be one of the closed host-shell table: ${TASK_V3_HOST_SHELLS.join(", ")}.`);
    }
    shell = rawShell;
  }
  let workingDirectory;
  if (own2(input, "working-directory")) {
    workingDirectory = stringField(input["working-directory"], ctx, ["working-directory"], {
      nonempty: true
    });
    validateWorkingDirectory(workingDirectory, ctx);
  }
  return Object.freeze({
    kind: "run",
    run,
    ...shell ? { shell } : {},
    ...workingDirectory ? { workingDirectory } : {}
  });
}
function parseExecutionControls(input, ctx) {
  const out = {};
  for (const key of ["agent", "engine", "model"]) {
    if (own2(input, key))
      out[key] = nullableSelectorTopLevel(input[key], ctx, key);
  }
  if (own2(input, "inference")) {
    const inference = presentJsonValue(input.inference, ctx, ["inference"]);
    out.inference = inference === null ? null : asRecord2(inference, ctx, ["inference"]);
  }
  if (own2(input, "tools"))
    out.tools = parseToolsTopLevel(presentJsonValue(input.tools, ctx, ["tools"]), ctx);
  if (own2(input, "timeout"))
    out.timeout = parseTimeoutTopLevel(input.timeout, ctx);
  if (own2(input, "redact")) {
    const names = parseStringArray(input.redact, ctx, ["redact"], {
      max: TASK_V3_MAX_REDACT_NAMES,
      pattern: WORKFLOW_ENV_VAR_NAME_PATTERN
    });
    if (new Set(names).size !== names.length)
      sourceError(ctx, ["redact"], "must not contain duplicate names.");
    out.redact = names;
  }
  if (own2(input, "maxSteps")) {
    if (!Number.isSafeInteger(input.maxSteps) || input.maxSteps < 1) {
      sourceError(ctx, ["maxSteps"], "must be a positive safe integer.");
    }
    out.maxSteps = input.maxSteps;
  }
  if (own2(input, "maxRetries")) {
    if (!Number.isSafeInteger(input.maxRetries) || input.maxRetries < 0) {
      sourceError(ctx, ["maxRetries"], "must be a non-negative safe integer.");
    }
    out.maxRetries = input.maxRetries;
  }
  return Object.freeze(out);
}
function stripDeclarationAnnotations(declInput) {
  const schema = {};
  let hasDefault = false;
  let defaultValue;
  let required = false;
  for (const [key, value] of Object.entries(declInput)) {
    if (key === "default") {
      hasDefault = true;
      defaultValue = value;
      continue;
    }
    if (key === "required") {
      required = value;
      continue;
    }
    schema[key] = value;
  }
  return { schema, hasDefault, defaultValue, required };
}
function parseInputDeclaration(name, raw, ctx) {
  const declPath = ["inputs", name];
  const declInput = asRecord2(raw, ctx, declPath);
  checkKeys(declInput, TASK_INPUT_DECLARATION_KEYS, ctx, declPath);
  if (own2(declInput, "required") && typeof declInput.required !== "boolean") {
    sourceError(ctx, [...declPath, "required"], "must be a boolean at the declaration root (nested objects' own required: […] keeps ordinary JSON Schema array semantics).");
  }
  const { schema, hasDefault, defaultValue, required } = stripDeclarationAnnotations(declInput);
  if (hasDefault && required) {
    sourceError(ctx, declPath, "must not declare both default and required: true.");
  }
  const definitionIssue = checkJsonSchemaDefinition(schema)[0];
  if (definitionIssue)
    sourceError(ctx, declPath, `is not a supported JSON schema: ${definitionIssue.message}`);
  if (utf8Bytes2(JSON.stringify(schema)) > WORKFLOW_MAX_SCHEMA_BYTES) {
    sourceError(ctx, declPath, `serialized schema exceeds the ${WORKFLOW_MAX_SCHEMA_BYTES}-byte limit.`);
  }
  if (hasDefault) {
    const violations = validateJsonSchemaSubset(defaultValue, schema);
    if (violations.length > 0) {
      sourceError(ctx, [...declPath, "default"], `does not satisfy its own declaration: ${violations.join("; ")}`);
    }
    const secretWarnings = detectSecretShapedParams({ [name]: defaultValue });
    for (const message of secretWarnings)
      warn(message);
  }
  return Object.freeze({
    schema: Object.freeze(schema),
    ...hasDefault ? { default: defaultValue } : {},
    required
  });
}
function parseInputDeclarations(value, ctx) {
  const input = asRecord2(value, ctx, ["inputs"]);
  const names = Object.keys(input);
  const result = {};
  for (const name of names) {
    if (!INPUT_NAME_PATTERN.test(name)) {
      sourceError(ctx, ["inputs", name], "must match the input name pattern (a letter/underscore, then letters, digits, or underscores).");
    }
    if (TASK_RUN_RESERVED_FLAG_NAMES.has(name)) {
      sourceError(ctx, ["inputs", name], TASK_RUN_SELF_DIAGNOSED_FLAGS.includes(name) ? `collides with the retired \`akm task --${name}\` spelling, which every task subcommand still rejects with a rename hint, so no --${name} flag can ever reach this input; declare the input under a different name.` : `collides with akm task run's own --${name} flag; declare the input under a different name.`);
    }
    result[name] = parseInputDeclaration(name, input[name], ctx);
  }
  return Object.freeze(result);
}
function parseOutputSchema(value, ctx) {
  const schema = asRecord2(value, ctx, ["output"]);
  const issue = checkJsonSchemaDefinition(schema)[0];
  if (issue)
    sourceError(ctx, ["output"], `is not a supported JSON schema: ${issue.message}`);
  return schema;
}
function targetConsumesOutputSchema(target) {
  return target.kind === "uses" && (target.uses.kind === "command" || target.uses.kind === "builtin-command");
}
function checkScheduleEntryRunnable(inputs, contract, ctx, entryPath) {
  const errors3 = validateInputs(contract, applyInputDefaults(contract, { ...inputs }), { pathRoot: "inputs" });
  if (errors3.length === 0)
    return;
  sourceError(ctx, entryPath, `does not satisfy the task's declared inputs once defaults are applied: ${errors3.join("; ")}. ` + "A scheduled run supplies no input flags — give this schedule entry an inputs: value for each input " + "named above, or declare a default: on the input instead (a required: true input may not carry one).");
}
function parseScheduleEntry(entryRaw, index, contract, ctx) {
  const entryPath = ["schedule", index];
  const entry = asRecord2(entryRaw, ctx, entryPath);
  checkKeys(entry, TASK_SOURCE_V4_SCHEDULE_KEYS, ctx, entryPath);
  if (!own2(entry, "cron"))
    sourceError(ctx, [...entryPath, "cron"], "is required.");
  const cron = stringField(entry.cron, ctx, [...entryPath, "cron"], { nonempty: true });
  noGithubExpression(cron, ctx, [...entryPath, "cron"]);
  let inputsLiteral = Object.freeze({});
  if (own2(entry, "inputs")) {
    const inputsValue = asRecord2(presentJsonValue(entry.inputs, ctx, [...entryPath, "inputs"]), ctx, [
      ...entryPath,
      "inputs"
    ]);
    checkKeys(inputsValue, Object.keys(contract), ctx, [...entryPath, "inputs"]);
    const errors3 = validateInputs(contract, inputsValue, { pathRoot: "inputs" });
    if (errors3.length > 0)
      sourceError(ctx, entryPath, errors3.join("; "));
    inputsLiteral = Object.freeze({ ...inputsValue });
  }
  checkScheduleEntryRunnable(inputsLiteral, contract, ctx, entryPath);
  return Object.freeze({ cron, inputs: inputsLiteral, source: `schedule[${index}].cron`, ordinal: index });
}
function parseSchedule(input, contract, ctx) {
  if (!own2(input, "schedule"))
    return Object.freeze([]);
  const raw = presentJsonValue(input.schedule, ctx, ["schedule"]);
  if (typeof raw === "string") {
    const cron = stringField(raw, ctx, ["schedule"], { nonempty: true });
    noGithubExpression(cron, ctx, ["schedule"]);
    checkScheduleEntryRunnable(Object.freeze({}), contract, ctx, ["schedule"]);
    return Object.freeze([Object.freeze({ cron, inputs: Object.freeze({}), source: "schedule", ordinal: 0 })]);
  }
  if (!Array.isArray(raw) || raw.length === 0) {
    sourceError(ctx, ["schedule"], "must be a non-empty string or a non-empty list of {cron, inputs?} records.");
  }
  if (raw.length > TASK_V3_MAX_SCHEDULES) {
    sourceError(ctx, ["schedule"], `accepts at most ${TASK_V3_MAX_SCHEDULES} entries.`);
  }
  const bindings = raw.map((entryRaw, index) => parseScheduleEntry(entryRaw, index, contract, ctx));
  return Object.freeze(bindings);
}
function checkTopLevelKeys(input, ctx) {
  if (own2(input, "akm")) {
    sourceError(ctx, ["akm"], "is removed in task source v4; its members are top-level keys now (schedule, timeout, engine, model, redact, " + "maxSteps, maxRetries, description, when_to_use, tags, agent, inference, tools, and output for outputSchema) " + "— see docs/reference/tasks.md.");
  }
  if (own2(input, "on")) {
    sourceError(ctx, ["on"], "is removed in task source v4; declare a top-level schedule: instead.");
  }
  checkKeys(input, TASK_SOURCE_V4_TOP_LEVEL_KEYS, ctx, []);
}
function parseTaskSourceV4Document(value, options) {
  const ctx = ctxFrom(options);
  const cloned = cloneBoundedJson(value, ctx, [], { nodes: 0 });
  const input = asRecord2(cloned, ctx, []);
  if (!own2(input, "version"))
    sourceError(ctx, ["version"], "is required and must be 4.");
  if (input.version !== TASK_SOURCE_V4_VERSION)
    sourceError(ctx, ["version"], "must be exactly 4.");
  checkTopLevelKeys(input, ctx);
  const hasUses = own2(input, "uses");
  const hasRun = own2(input, "run");
  if (hasUses === hasRun)
    sourceError(ctx, [], "requires exactly one executable selector: uses or run.");
  const name = own2(input, "name") ? stringField(input.name, ctx, ["name"]) : undefined;
  const description = own2(input, "description") ? stringField(input.description, ctx, ["description"]) : undefined;
  const whenToUse = own2(input, "when_to_use") ? stringField(input.when_to_use, ctx, ["when_to_use"]) : undefined;
  const tags = own2(input, "tags") ? parseStringArray(input.tags, ctx, ["tags"]) : undefined;
  const env = own2(input, "env") ? parseEnvironment(presentJsonValue(input.env, ctx, ["env"]), ctx) : undefined;
  const target = parseTarget(input, ctx);
  const inputs = own2(input, "inputs") ? parseInputDeclarations(presentJsonValue(input.inputs, ctx, ["inputs"]), ctx) : undefined;
  let output;
  if (own2(input, "output")) {
    if (!targetConsumesOutputSchema(target)) {
      sourceError(ctx, ["output"], "is legal only with a command target (uses: commands/<ref> or uses: akm/command); " + "run:, uses: scripts/, and uses: workflows/ targets do not enforce an output schema.");
    }
    output = parseOutputSchema(presentJsonValue(input.output, ctx, ["output"]), ctx);
  }
  const schedule = parseSchedule(input, inputs ?? Object.freeze({}), ctx);
  const execution = parseExecutionControls(input, ctx);
  return Object.freeze({
    version: TASK_SOURCE_V4_VERSION,
    ...name !== undefined ? { name } : {},
    ...description !== undefined ? { description } : {},
    ...whenToUse !== undefined ? { when_to_use: whenToUse } : {},
    ...tags !== undefined ? { tags } : {},
    ...inputs !== undefined ? { inputs } : {},
    ...output !== undefined ? { output } : {},
    target,
    ...env !== undefined ? { env } : {},
    execution,
    schedule,
    manualOnly: schedule.length === 0,
    source: Object.freeze({ path: options.filePath })
  });
}
function parseTaskSourceV4(input) {
  const { root, lineAt } = readBoundedTaskSourceYaml(input, { sourceLabel: SOURCE_LABEL });
  return parseTaskSourceV4Document(root, {
    filePath: input.filePath,
    ...input.workspaceRoot ? { workspaceRoot: input.workspaceRoot } : {},
    lineAt
  });
}

// src/tasks/source/parse-task-source.ts
function peekTaskSourceVersion(root) {
  if (root === null || typeof root !== "object" || Array.isArray(root))
    return;
  const value = root.version;
  return typeof value === "number" ? value : undefined;
}
var TASK_MIGRATE_HINT = "Run `akm migrate apply --dry-run` to preview the task-v3 to task-source-v4 conversion, then run `akm migrate apply`.";
function legacyVersionError(filePath, version) {
  return new UsageError(`TASK_SCHEMA_VERSION_UNSUPPORTED: Task at ${filePath} uses task schema version ${version}; this release reads only version 4. Run \`akm migrate apply\` to convert it.`, "TASK_SCHEMA_VERSION_UNSUPPORTED", TASK_MIGRATE_HINT);
}
function unsupportedVersionError(filePath, version) {
  return new UsageError(`TASK_SCHEMA_VERSION_UNSUPPORTED: Task at ${filePath} uses task schema version ${version}, which this release does not accept.`, "TASK_SCHEMA_VERSION_UNSUPPORTED", TASK_MIGRATE_HINT);
}
function v4ScheduleHasRetiredEnabledKey(root) {
  if (root === null || typeof root !== "object" || Array.isArray(root))
    return false;
  const schedule = root.schedule;
  if (!Array.isArray(schedule))
    return false;
  return schedule.some((entry) => entry !== null && typeof entry === "object" && !Array.isArray(entry) && Object.hasOwn(entry, "enabled"));
}
function parseTaskSource(input) {
  const { root, lineAt } = readBoundedTaskSourceYaml(input, { sourceLabel: "task source" });
  const version = peekTaskSourceVersion(root);
  if (version !== undefined && version !== TASK_SOURCE_V4_VERSION) {
    if (version === 2 || version === 3)
      throw legacyVersionError(input.filePath, version);
    throw unsupportedVersionError(input.filePath, version);
  }
  if (version === TASK_SOURCE_V4_VERSION && v4ScheduleHasRetiredEnabledKey(root)) {
    throw new UsageError(`Invalid task source v4 at ${input.filePath}: schedule[].enabled was removed (scheduler activation is host-local config). Run \`akm migrate apply\` to rewrite it.`, "TASK_SOURCE_INVALID", TASK_MIGRATE_HINT);
  }
  const documentOptions = {
    filePath: input.filePath,
    ...input.workspaceRoot ? { workspaceRoot: input.workspaceRoot } : {},
    lineAt
  };
  return Object.freeze({ version: 4, v4: parseTaskSourceV4Document(root, documentOptions) });
}

// src/workflows/compile.ts
import path20 from "node:path";

// src/commands/command/portable-template.ts
var PORTABLE_ARGUMENTS_PLACEHOLDER = "$ARGUMENTS";

// src/workflows/plan.ts
var WORKFLOW_PLAN_VERSION = 6;

// src/workflows/source-semantics.ts
import fs16 from "node:fs";
import path19 from "node:path";

// src/tasks/schedule.ts
var ALIAS_TO_CRON = {
  "@hourly": "0 * * * *",
  "@daily": "0 0 * * *",
  "@midnight": "0 0 * * *",
  "@weekly": "0 0 * * 0",
  "@monthly": "0 0 1 * *",
  "@yearly": "0 0 1 1 *",
  "@annually": "0 0 1 1 *"
};
var REBOOT_ALIAS = "@reboot";
var REBOOT_FIELDS = {
  minute: { kind: "star" },
  hour: { kind: "star" },
  dom: { kind: "star" },
  month: { kind: "star" },
  dow: { kind: "star" }
};
var DOW_NAMES = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
var MONTH_NAMES = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
function substituteNamedTokens(raw, fieldName) {
  const names = fieldName === "month" ? MONTH_NAMES : DOW_NAMES;
  const offset = fieldName === "month" ? 1 : 0;
  const indexOf = (token) => {
    const idx = names.indexOf(token.toLowerCase());
    return idx === -1 ? undefined : idx + offset;
  };
  return raw.split(",").map((part) => {
    const rangeMatch = part.match(/^([A-Za-z]{3})-([A-Za-z]{3})$/);
    if (rangeMatch) {
      const start = indexOf(rangeMatch[1]);
      const end = indexOf(rangeMatch[2]);
      if (start !== undefined && end !== undefined)
        return `${start}-${end}`;
      return part;
    }
    const single = /^[A-Za-z]{3}$/.test(part) ? indexOf(part) : undefined;
    return single !== undefined ? String(single) : part;
  }).join(",");
}
var FIELD_LIMITS = {
  minute: { min: 0, max: 59 },
  hour: { min: 0, max: 23 },
  dom: { min: 1, max: 31 },
  month: { min: 1, max: 12 },
  dow: { min: 0, max: 6 }
};
var SUPPORTED_HINT = "Supported subset: `*`, single integers (`5`), ranges (`A-B`), steps (`*/N`, `A-B/N`), and comma lists " + "(`7,37`). Day-of-week and month fields also accept three-letter names and name ranges (`MON`, `MON-FRI`, " + "`JAN`). Aliases: `@hourly`, `@daily`, `@weekly`, `@monthly`, `@yearly`/`@annually`, `@reboot` (cron only).";
function parseSchedule2(input, backend) {
  const trimmed = input.trim();
  if (trimmed.toLowerCase() === REBOOT_ALIAS) {
    if (backend !== "cron") {
      throw new UsageError(`Schedule "${input}" (@reboot, run once at startup) has no ${backend === "launchd" ? "macOS launchd" : "Windows Task Scheduler"} equivalent this release expresses. Use a cron-backed install, or rewrite the task with a recurring schedule.`, "INVALID_FLAG_VALUE");
    }
    return { raw: input, cron: REBOOT_ALIAS, fields: REBOOT_FIELDS };
  }
  const cron = expandAlias(input);
  const fields = parseCronFields(cron, input);
  const spec = { raw: input, cron, fields };
  if (backend === "launchd")
    translateToLaunchd(spec);
  if (backend === "schtasks")
    translateToSchtasks(spec);
  return spec;
}
function expandAlias(raw) {
  const trimmed = raw.trim();
  if (!trimmed) {
    throw new UsageError("Schedule is empty.", "MISSING_REQUIRED_ARGUMENT");
  }
  const lower = trimmed.toLowerCase();
  if (lower in ALIAS_TO_CRON)
    return ALIAS_TO_CRON[lower];
  return trimmed;
}
function parseCronFields(cron, original) {
  const parts = cron.split(/\s+/);
  if (parts.length !== 5) {
    throw new UsageError(`Invalid schedule "${original}": expected 5 fields, got ${parts.length}. ${SUPPORTED_HINT}`, "INVALID_FLAG_VALUE");
  }
  const [m, h, dom, mon, dow] = parts;
  return {
    minute: parseField(m, "minute", FIELD_LIMITS.minute, original),
    hour: parseField(h, "hour", FIELD_LIMITS.hour, original),
    dom: parseField(dom, "day-of-month", FIELD_LIMITS.dom, original),
    month: parseField(mon, "month", FIELD_LIMITS.month, original),
    dow: parseField(dow, "day-of-week", FIELD_LIMITS.dow, original)
  };
}
function parseField(rawInput, name, limit, original) {
  const raw = name === "month" || name === "day-of-week" ? substituteNamedTokens(rawInput, name) : rawInput;
  if (raw === "*")
    return { kind: "star" };
  const stepMatch = raw.match(/^\*\/(\d+)$/);
  if (stepMatch) {
    const step = Number(stepMatch[1]);
    const range = limit.max - limit.min + 1;
    if (!Number.isInteger(step) || step <= 0 || step > range) {
      throw new UsageError(`Invalid ${name} step "${raw}" in schedule "${original}". ${SUPPORTED_HINT}`, "INVALID_FLAG_VALUE");
    }
    return { kind: "step", step };
  }
  const rangeStepMatch = raw.match(/^(\d+)-(\d+)\/(\d+)$/);
  if (rangeStepMatch) {
    const start = Number(rangeStepMatch[1]);
    const end = Number(rangeStepMatch[2]);
    const step = Number(rangeStepMatch[3]);
    if (start < limit.min || end > limit.max || start > end || step <= 0) {
      throw new UsageError(`Invalid ${name} range-step "${raw}" in schedule "${original}" (allowed ${limit.min}-${limit.max}).`, "INVALID_FLAG_VALUE");
    }
    return { kind: "rangeStep", start, end, step };
  }
  const rangeMatch = raw.match(/^(\d+)-(\d+)$/);
  if (rangeMatch) {
    const start = Number(rangeMatch[1]);
    const end = Number(rangeMatch[2]);
    if (start < limit.min || end > limit.max || start > end) {
      throw new UsageError(`Invalid ${name} range "${raw}" in schedule "${original}" (allowed ${limit.min}-${limit.max}).`, "INVALID_FLAG_VALUE");
    }
    return { kind: "rangeStep", start, end, step: 1 };
  }
  if (/^\d+$/.test(raw)) {
    const value = Number(raw);
    if (value < limit.min || value > limit.max) {
      throw new UsageError(`Invalid ${name} value "${raw}" in schedule "${original}" (allowed ${limit.min}-${limit.max}).`, "INVALID_FLAG_VALUE");
    }
    return { kind: "value", value };
  }
  if (/^\d+(,\d+)+$/.test(raw)) {
    const values = [...new Set(raw.split(",").map((s) => Number(s)))].sort((a, b) => a - b);
    for (const v of values) {
      if (!Number.isInteger(v) || v < limit.min || v > limit.max) {
        throw new UsageError(`Invalid ${name} list value "${v}" in schedule "${original}" (allowed ${limit.min}-${limit.max}).`, "INVALID_FLAG_VALUE");
      }
    }
    return { kind: "list", values };
  }
  throw new UsageError(`Unsupported ${name} expression "${raw}" in schedule "${original}". ${SUPPORTED_HINT}`, "INVALID_FLAG_VALUE");
}
function translateToLaunchd(spec) {
  const f = spec.fields;
  rejectDomDowCombination(spec, "macOS launchd");
  if ((f.minute.kind === "step" || f.minute.kind === "rangeStep") && f.hour.kind === "star" && f.dom.kind === "star" && f.month.kind === "star" && f.dow.kind === "star") {
    return { calendars: expandFieldValues(f.minute, FIELD_LIMITS.minute).map((Minute) => ({ Minute })) };
  }
  if (f.minute.kind === "value" && (f.hour.kind === "step" || f.hour.kind === "rangeStep") && f.dom.kind === "star" && f.month.kind === "star" && f.dow.kind === "star") {
    return {
      calendars: expandFieldValues(f.hour, FIELD_LIMITS.hour).map((Hour) => ({
        Minute: f.minute.kind === "value" ? f.minute.value : 0,
        Hour
      }))
    };
  }
  const dowValues = expandListLikeField(f.dow, FIELD_LIMITS.dow);
  const monthValues = expandListLikeField(f.month, FIELD_LIMITS.month);
  const remainingFieldsAreSimple = (f.minute.kind === "value" || f.minute.kind === "star") && (f.hour.kind === "value" || f.hour.kind === "star") && (f.dom.kind === "value" || f.dom.kind === "star");
  if ((dowValues || monthValues) && remainingFieldsAreSimple) {
    const base = {};
    if (f.minute.kind === "value")
      base.Minute = f.minute.value;
    if (f.hour.kind === "value")
      base.Hour = f.hour.value;
    if (f.dom.kind === "value")
      base.Day = f.dom.value;
    const months = monthValues ?? (f.month.kind === "value" ? [f.month.value] : [undefined]);
    const weekdays = dowValues ?? (f.dow.kind === "value" ? [f.dow.value] : [undefined]);
    const calendars = [];
    for (const month of months) {
      for (const weekday of weekdays) {
        calendars.push({
          ...base,
          ...month !== undefined ? { Month: month } : {},
          ...weekday !== undefined ? { Weekday: weekday } : {}
        });
      }
    }
    return { calendars };
  }
  const calendar = {};
  rejectStepInsideCalendar(f.minute, "minute", spec);
  rejectStepInsideCalendar(f.hour, "hour", spec);
  rejectStepInsideCalendar(f.dom, "day-of-month", spec);
  rejectStepInsideCalendar(f.month, "month", spec);
  rejectStepInsideCalendar(f.dow, "day-of-week", spec);
  if (f.minute.kind === "value")
    calendar.Minute = f.minute.value;
  if (f.hour.kind === "value")
    calendar.Hour = f.hour.value;
  if (f.dom.kind === "value")
    calendar.Day = f.dom.value;
  if (f.month.kind === "value")
    calendar.Month = f.month.value;
  if (f.dow.kind === "value")
    calendar.Weekday = f.dow.value;
  if (Object.keys(calendar).length === 0) {
    return {
      calendars: expandFieldValues({ kind: "step", step: 1 }, FIELD_LIMITS.minute).map((Minute) => ({ Minute }))
    };
  }
  return { calendar };
}
function expandFieldValues(field, limit) {
  const start = field.kind === "rangeStep" ? field.start : limit.min;
  const end = field.kind === "rangeStep" ? field.end : limit.max;
  const values = [];
  for (let value = start;value <= end; value += field.step)
    values.push(value);
  return values;
}
function expandListLikeField(field, limit) {
  if (field.kind === "list")
    return field.values;
  if (field.kind === "rangeStep")
    return expandFieldValues(field, limit);
  return null;
}
function rejectStepInsideCalendar(field, name, spec) {
  if (field.kind === "step") {
    throw new UsageError(`Schedule "${spec.raw}" uses step (${name} = */N) in a position macOS launchd cannot express. ${SUPPORTED_HINT}`, "INVALID_FLAG_VALUE", "Either restrict the step to the minute or hour field only, or rewrite the schedule with concrete values.");
  }
  if (field.kind === "rangeStep") {
    const shape = field.step === 1 ? "A-B" : "A-B/N";
    throw new UsageError(`Schedule "${spec.raw}" uses a range (${name} = ${shape}) in a position macOS launchd cannot express. ${SUPPORTED_HINT}`, "INVALID_FLAG_VALUE", "Restrict the range to the minute, hour, day-of-week, or month field, or rewrite the schedule with a concrete value.");
  }
  if (field.kind === "list") {
    throw new UsageError(`Schedule "${spec.raw}" uses comma list (${name} = a,b,...) which macOS launchd cannot express as a single trigger. ${SUPPORTED_HINT}`, "INVALID_FLAG_VALUE", "Either install one task per list element, or rewrite the schedule with a step (`*/N`) or single value.");
  }
}
var MAX_SCHTASKS_TRIGGERS = 48;
function translateToSchtasks(spec) {
  const f = spec.fields;
  rejectDomDowCombination(spec, "Windows Task Scheduler");
  if (f.minute.kind === "step" && f.hour.kind === "star" && f.dom.kind === "star" && f.month.kind === "star" && f.dow.kind === "star") {
    if (60 % f.minute.step !== 0) {
      return minuteValuesTrigger(expandFieldValues(f.minute, FIELD_LIMITS.minute), spec);
    }
    return { kind: "minute", everyMinutes: f.minute.step };
  }
  if (f.minute.kind === "rangeStep" && f.hour.kind === "star" && f.dom.kind === "star" && f.month.kind === "star" && f.dow.kind === "star") {
    if (f.minute.start === FIELD_LIMITS.minute.min && f.minute.end === FIELD_LIMITS.minute.max) {
      if (60 % f.minute.step === 0)
        return { kind: "minute", everyMinutes: f.minute.step };
    }
    return minuteValuesTrigger(expandFieldValues(f.minute, FIELD_LIMITS.minute), spec);
  }
  if (f.minute.kind === "value" && f.hour.kind === "step" && f.dom.kind === "star" && f.month.kind === "star" && f.dow.kind === "star") {
    if (24 % f.hour.step === 0 && f.hour.step < 24) {
      return { kind: "hour", everyHours: f.hour.step, atMinute: f.minute.value };
    }
    return {
      kind: "hourValues",
      hours: expandFieldValues(f.hour, FIELD_LIMITS.hour),
      atMinute: f.minute.value
    };
  }
  if (f.minute.kind === "value" && f.hour.kind === "rangeStep" && f.dom.kind === "star" && f.month.kind === "star" && f.dow.kind === "star") {
    if (f.hour.start === FIELD_LIMITS.hour.min && f.hour.end === FIELD_LIMITS.hour.max) {
      if (24 % f.hour.step === 0 && f.hour.step < 24) {
        return { kind: "hour", everyHours: f.hour.step, atMinute: f.minute.value };
      }
    }
    return {
      kind: "hourValues",
      hours: expandFieldValues(f.hour, FIELD_LIMITS.hour),
      atMinute: f.minute.value
    };
  }
  if (f.minute.kind === "value" && f.hour.kind === "star" && f.dom.kind === "star" && f.month.kind === "star" && f.dow.kind === "star") {
    return { kind: "hour", everyHours: 1, atMinute: f.minute.value };
  }
  if (f.minute.kind === "value" && f.hour.kind === "value" && f.dom.kind === "star" && f.month.kind === "star" && f.dow.kind === "star") {
    return { kind: "daily", atHour: f.hour.value, atMinute: f.minute.value };
  }
  if (f.minute.kind === "value" && f.hour.kind === "value" && f.dom.kind === "star" && f.month.kind === "star" && (f.dow.kind === "value" || f.dow.kind === "list" || f.dow.kind === "rangeStep")) {
    const daysOfWeek = f.dow.kind === "value" ? [f.dow.value] : expandListLikeField(f.dow, FIELD_LIMITS.dow);
    return {
      kind: "weekly",
      atHour: f.hour.value,
      atMinute: f.minute.value,
      daysOfWeek
    };
  }
  if (f.minute.kind === "value" && f.hour.kind === "value" && (f.dom.kind === "value" || f.dom.kind === "list") && (f.month.kind === "star" || f.month.kind === "value" || f.month.kind === "list") && f.dow.kind === "star") {
    const daysOfMonth = f.dom.kind === "value" ? [f.dom.value] : f.dom.values;
    const months = f.month.kind === "star" ? Array.from({ length: 12 }, (_, i) => i + 1) : f.month.kind === "value" ? [f.month.value] : f.month.values;
    return { kind: "monthly", atHour: f.hour.value, atMinute: f.minute.value, daysOfMonth, months };
  }
  throw new UsageError(`Schedule "${spec.raw}" cannot be expressed as a Windows Task Scheduler trigger. ${SUPPORTED_HINT}`, "INVALID_FLAG_VALUE", "Use one of: minute steps/range-steps, fixed-minute hour steps/range-steps, hourly, daily, weekly on one or more weekdays, or monthly on one or more days-of-month.");
}
function minuteValuesTrigger(minutes, spec) {
  if (minutes.length > MAX_SCHTASKS_TRIGGERS) {
    throw new UsageError(`Schedule "${spec.raw}" requires ${minutes.length} native triggers; Windows Task Scheduler allows at most ${MAX_SCHTASKS_TRIGGERS}.`, "INVALID_FLAG_VALUE", "Use a full-field step whose interval divides 60, or reduce the minute range.");
  }
  return { kind: "minuteValues", minutes };
}
function rejectDomDowCombination(spec, backend) {
  if (spec.fields.dom.kind !== "star" && spec.fields.dow.kind !== "star") {
    throw new UsageError(`Schedule "${spec.raw}": day-of-month and day-of-week use OR semantics in cron, which ${backend} cannot express portably.`, "INVALID_FLAG_VALUE", "Use either day-of-month or day-of-week, but not both.");
  }
}

// src/workflows/source-semantics.ts
class WorkflowSourceSemanticError extends Error {
  code;
  constructor(code, message) {
    super(message);
    this.code = code;
    this.name = "WorkflowSourceSemanticError";
  }
}
function workflowShellCommand(shell, content) {
  if (shell === "cmd")
    return ["cmd", "/d", "/s", "/c", content];
  if (shell === "pwsh" || shell === "powershell")
    return [shell, "-Command", content];
  return [shell, "-c", content];
}
function canonicalizeWorkflowCron(value) {
  const canonical = value.trim().split(/\s+/).join(" ");
  if (canonical.startsWith("@") || canonical.split(" ").length !== 5) {
    throw new WorkflowSourceSemanticError("invalid-cron", "GitHub schedule cron must use exactly five fields.");
  }
  try {
    parseSchedule2(canonical, "cron");
  } catch (cause) {
    throw new WorkflowSourceSemanticError("invalid-cron", cause instanceof Error ? cause.message : "Invalid cron schedule.");
  }
  return canonical;
}
function canonicalizeWorkflowRun(value) {
  if (value.includes("${{")) {
    throw new WorkflowSourceSemanticError("unsupported-github-expression", "GitHub expressions and contexts are not supported.");
  }
  if (value.includes("\x00")) {
    throw new WorkflowSourceSemanticError("invalid-exec-argv", "Local run may not contain NUL bytes.");
  }
  return value;
}
function canonicalizeWorkflowWorkingDirectory(value, workspaceRoot) {
  if (hasControlCharacter(value)) {
    throw new WorkflowSourceSemanticError("working-directory-control-character", "working-directory may not contain NUL or control characters.");
  }
  if (value === "" || value.trim() === "") {
    throw new WorkflowSourceSemanticError("working-directory-escape", "working-directory must be a non-empty relative contained path.");
  }
  const portable = value.replaceAll("\\", "/");
  const segments = portable.split("/");
  if (path19.posix.isAbsolute(portable) || path19.win32.isAbsolute(value) || portable.startsWith("~") || segments.some((segment) => segment === "" || segment === "..")) {
    throw new WorkflowSourceSemanticError("working-directory-escape", "working-directory must be relative and contained.");
  }
  const withoutDots = segments.filter((segment) => segment !== ".");
  const canonical = withoutDots.length === 0 ? "." : withoutDots.join("/");
  if (workspaceRoot !== undefined)
    verifyPhysicalContainment(workspaceRoot, canonical);
  return canonical;
}
function hasControlCharacter(value) {
  for (const character of value) {
    const codePoint = character.codePointAt(0) ?? 0;
    if (codePoint <= 31 || codePoint === 127)
      return true;
  }
  return false;
}
function classifyWorkflowStepUses(value) {
  if (value.includes("${{")) {
    throw new WorkflowSourceSemanticError("unsupported-github-expression", "GitHub expressions are unsupported in uses.");
  }
  if (value.length === 0 || value.trim() !== value || /\s/.test(value)) {
    throw new WorkflowSourceSemanticError("unsupported-uses-target", "uses must be one exact, non-empty executable ref");
  }
  if (value === "akm/command")
    return { kind: "builtin-command", ref: "akm/command" };
  try {
    return classifyTargetRef(value);
  } catch (cause) {
    throw usesFailure(value, cause);
  }
}
function validateWorkflowBuiltinCommand(value, mode) {
  let action;
  try {
    action = parseBuiltinCommandAction(value);
  } catch (cause) {
    throw new WorkflowSourceSemanticError("builtin-command-inputs", cause instanceof Error ? cause.message : "Invalid akm/command inputs.");
  }
  const expectedMode = action.kind === "stored" ? "stored-ref" : "portable-template";
  const effectiveMode = mode ?? expectedMode;
  if (action.kind === "stored") {
    if (effectiveMode !== "stored-ref") {
      throw new WorkflowSourceSemanticError("builtin-command-inputs", "Stored akm/command refs require commandMode stored-ref.");
    }
    return action;
  }
  if (effectiveMode === "stored-ref") {
    throw new WorkflowSourceSemanticError("builtin-command-inputs", "Inline akm/command content cannot use commandMode stored-ref.");
  }
  if (effectiveMode === "literal" && action.arguments !== undefined) {
    throw new WorkflowSourceSemanticError("builtin-command-inputs", "Literal akm/command content cannot declare arguments because no substitution occurs.");
  }
  return action;
}
function usesFailure(value, cause) {
  const message = cause instanceof Error ? cause.message : String(cause);
  const code = value.startsWith("docker://") ? "docker-action-unsupported" : value.startsWith("./") || value.startsWith("../") || value.startsWith("/") ? "local-action-path-unsupported" : /^(?:[A-Za-z0-9][A-Za-z0-9._-]*\/\/)?agents\//.test(value) ? "non-executable-asset-ref" : "unsupported-uses-target";
  return new WorkflowSourceSemanticError(code, message);
}
function verifyPhysicalContainment(workspaceRoot, relative) {
  let root;
  try {
    root = fs16.realpathSync(workspaceRoot);
  } catch {
    throw new WorkflowSourceSemanticError("working-directory-unverifiable", "Workspace root cannot be physically verified.");
  }
  const candidate = path19.resolve(root, ...relative.split("/"));
  if (!contained(root, candidate)) {
    throw new WorkflowSourceSemanticError("working-directory-escape", "working-directory escapes the workspace.");
  }
  let current = root;
  for (const segment of relative === "." ? [] : relative.split("/")) {
    current = path19.join(current, segment);
    try {
      const entry = fs16.lstatSync(current);
      if (entry.isSymbolicLink()) {
        let physical2;
        try {
          physical2 = fs16.realpathSync(current);
        } catch {
          throw new WorkflowSourceSemanticError("working-directory-unverifiable", "working-directory contains a dangling or unresolvable symlink.");
        }
        if (!contained(root, physical2)) {
          throw new WorkflowSourceSemanticError("working-directory-escape", "working-directory resolves through a symlink outside the workspace.");
        }
        let target;
        try {
          target = fs16.statSync(current);
        } catch {
          throw new WorkflowSourceSemanticError("working-directory-unverifiable", "working-directory symlink target cannot be physically verified.");
        }
        if (!target.isDirectory()) {
          throw new WorkflowSourceSemanticError("working-directory-unverifiable", "working-directory must resolve through directories.");
        }
        continue;
      }
      if (!entry.isDirectory()) {
        throw new WorkflowSourceSemanticError("working-directory-unverifiable", "working-directory must resolve through directories.");
      }
      const physical = fs16.realpathSync(current);
      if (!contained(root, physical)) {
        throw new WorkflowSourceSemanticError("working-directory-escape", "working-directory resolves through a symlink outside the workspace.");
      }
    } catch (cause) {
      if (cause instanceof WorkflowSourceSemanticError)
        throw cause;
      const code = cause?.code;
      if (code === "ENOENT") {
        return;
      }
      throw new WorkflowSourceSemanticError("working-directory-unverifiable", "working-directory cannot be physically verified.");
    }
  }
}
function contained(root, candidate) {
  const relative = path19.relative(root, candidate);
  return relative === "" || !relative.startsWith(`..${path19.sep}`) && relative !== ".." && !path19.isAbsolute(relative);
}

// src/workflows/github-yaml.ts
class WorkflowSourceFailure extends Error {
  error;
  constructor(code, message, source) {
    super(message);
    this.name = "WorkflowSourceFailure";
    this.error = { code, message, path: source.path, line: source.start };
  }
}
var ROOT_KEYS = ["name", "on", "jobs"];
var TRIGGER_KEYS = ["schedule", "workflow_dispatch"];
var SCHEDULE_KEYS = ["cron"];
var JOB_KEYS = ["name", "needs", "runs-on", "steps"];
var STEP_KEYS = ["id", "name", "uses", "run", "with", "env", "shell", "working-directory"];
var UNSAFE_KEYS2 = new Set(["__proto__", "prototype", "constructor"]);
var HOST_SHELLS = new Set(["bash", "sh", "zsh", "pwsh", "powershell", "cmd"]);
var SOURCE_ID = /^[A-Za-z_][A-Za-z0-9_-]{0,127}$/;
var INPUT_KEY = /^[A-Za-z_][A-Za-z0-9_.-]{0,127}$/;
var ENV_KEY = /^[A-Za-z_][A-Za-z0-9_]*$/;
var MAX_YAML_DEPTH = 32;
var MAX_YAML_NODES = 20000;
var MAX_STEPS_PER_JOB = 256;
function looksLikeGithubWorkflowSource(source) {
  if (utf8Bytes(source) > WORKFLOW_MAX_SOURCE_BYTES)
    return false;
  let doc;
  try {
    doc = $parseDocument(source, { strict: true, uniqueKeys: true, version: "1.2" });
  } catch {
    return false;
  }
  if (!$isMap(doc.contents))
    return false;
  const keys = new Set;
  for (const pair of doc.contents.items) {
    if ($isScalar(pair.key) && typeof pair.key.value === "string")
      keys.add(pair.key.value);
  }
  return keys.has("on") && keys.has("jobs");
}
function parseGithubWorkflowSource(source, options) {
  const documentSource = wholeSourceSpan(source, options.path);
  if (utf8Bytes(source) > WORKFLOW_MAX_SOURCE_BYTES) {
    throw new WorkflowSourceFailure("source-size-limit", "Workflow source exceeds the 1 MiB limit.", documentSource);
  }
  const lineCounter2 = new $LineCounter;
  let doc;
  try {
    doc = $parseDocument(source, {
      lineCounter: lineCounter2,
      strict: true,
      uniqueKeys: true,
      version: "1.2"
    });
  } catch {
    throw new WorkflowSourceFailure("invalid-yaml", "Workflow YAML could not be parsed.", documentSource);
  }
  if (doc.errors.length > 0) {
    const problem = doc.errors[0];
    if (!problem)
      throw new WorkflowSourceFailure("invalid-yaml", "Invalid YAML.", documentSource);
    const offset = Array.isArray(problem.pos) ? problem.pos[0] : 0;
    const errorSource = spanAtOffset(options.path, lineCounter2, offset);
    const code = /Map keys must be unique/i.test(problem.message) ? "duplicate-key" : "invalid-yaml";
    throw new WorkflowSourceFailure(code, cleanYamlMessage(problem.message), errorSource);
  }
  const firstWarning = doc.warnings[0];
  if (firstWarning && /tag/i.test(firstWarning.message)) {
    throw new WorkflowSourceFailure("yaml-custom-tag", cleanYamlMessage(firstWarning.message), documentSource);
  }
  const rootNode = doc.contents;
  if (!$isMap(rootNode)) {
    throw new WorkflowSourceFailure("mapping-root-required", "GitHub workflow YAML root must be a mapping.", documentSource);
  }
  const parsedRoot = rootNode;
  const reader = new StrictYamlReader(options.path, lineCounter2);
  reader.rejectAliases(parsedRoot);
  reader.checkTree(parsedRoot);
  const root = reader.fields(parsedRoot, ROOT_KEYS, "workflow");
  reader.requiredString(root, "name", "workflow");
  const schedules = parseTriggers(reader, reader.required(root, "on", "workflow"));
  const steps = parseJob(reader, reader.required(root, "jobs", "workflow"), options);
  return { irVersion: WORKFLOW_PLAN_VERSION, title: options.title, schedules, steps };
}

class StrictYamlReader {
  filePath;
  lineCounter;
  nodes = 0;
  constructor(filePath, lineCounter2) {
    this.filePath = filePath;
    this.lineCounter = lineCounter2;
  }
  span(node) {
    const range = node?.range;
    if (!range)
      return { path: this.filePath, start: 1, end: 1 };
    const start = this.lineCounter.linePos(range[0]).line;
    const end = this.lineCounter.linePos(Math.max(range[0], range[1] - 1)).line;
    return { path: this.filePath, start, end: Math.max(start, end) };
  }
  rejectAliases(root) {
    const pending = [{ node: root, depth: 0 }];
    let nodes = 0;
    while (pending.length > 0) {
      const current = pending.pop();
      if (!current)
        break;
      nodes++;
      if (nodes > MAX_YAML_NODES)
        this.fail("yaml-node-limit", "YAML exceeds the node limit.", current.node);
      if (current.depth > MAX_YAML_DEPTH) {
        this.fail("yaml-depth-limit", "YAML exceeds the depth limit.", current.node);
      }
      if ($isAlias(current.node))
        this.fail("yaml-alias", "YAML aliases are not supported.", current.node);
      if ($isSeq(current.node)) {
        for (const item of current.node.items) {
          if (item)
            pending.push({ node: item, depth: current.depth + 1 });
        }
      } else if ($isMap(current.node)) {
        for (const pair of current.node.items) {
          if (pair.key)
            pending.push({ node: pair.key, depth: current.depth + 1 });
          if (pair.value)
            pending.push({ node: pair.value, depth: current.depth + 1 });
        }
      }
    }
  }
  checkTree(node, depth = 0) {
    this.nodes++;
    if (this.nodes > MAX_YAML_NODES)
      this.fail("yaml-node-limit", "YAML exceeds the node limit.", node);
    if (depth > MAX_YAML_DEPTH)
      this.fail("yaml-depth-limit", "YAML exceeds the depth limit.", node);
    if ($isAlias(node))
      this.fail("yaml-alias", "YAML aliases are not supported.", node);
    if ("anchor" in node && typeof node.anchor === "string" && node.anchor !== "") {
      this.fail("yaml-anchor", "YAML anchors are not supported.", node);
    }
    if (node.tag !== undefined)
      this.fail("yaml-custom-tag", "Explicit YAML tags are not supported.", node);
    if ($isScalar(node)) {
      if (typeof node.value === "string" && node.value.includes("${{")) {
        this.fail("unsupported-github-expression", "GitHub expressions and contexts are not supported.", node);
      }
      return;
    }
    if ($isSeq(node)) {
      for (const item of node.items)
        if (item)
          this.checkTree(item, depth + 1);
      return;
    }
    if ($isMap(node)) {
      for (const pair of node.items) {
        if (pair.key)
          this.checkTree(pair.key, depth + 1);
        if (pair.value)
          this.checkTree(pair.value, depth + 1);
      }
    }
  }
  fields(node, allowed, context) {
    if (!$isMap(node))
      this.fail("mapping-required", `${context} must be a mapping.`, node);
    const accepted = new Set(allowed);
    const out = new Map;
    for (const pair of node.items) {
      if (!$isScalar(pair.key) || typeof pair.key.value !== "string" || pair.key.value.trim() === "") {
        this.fail("string-key-required", `${context} keys must be non-empty strings.`, pair.key);
      }
      const key = pair.key.value;
      if (UNSAFE_KEYS2.has(key))
        this.fail("unsafe-key", `${context} contains unsafe key ${JSON.stringify(key)}.`, pair.key);
      if (!accepted.has(key))
        this.fail("unknown-key", `${context} contains unknown key ${JSON.stringify(key)}.`, pair.key);
      out.set(key, pair);
    }
    return out;
  }
  arbitraryFields(node, context) {
    if (!$isMap(node))
      this.fail("mapping-required", `${context} must be a mapping.`, node);
    const out = new Map;
    for (const pair of node.items) {
      if (!$isScalar(pair.key) || typeof pair.key.value !== "string" || pair.key.value.trim() === "") {
        this.fail("string-key-required", `${context} keys must be non-empty strings.`, pair.key);
      }
      const key = pair.key.value;
      if (UNSAFE_KEYS2.has(key))
        this.fail("unsafe-key", `${context} contains unsafe key ${JSON.stringify(key)}.`, pair.key);
      out.set(key, pair);
    }
    return out;
  }
  plain(node, context) {
    if (node === null)
      return null;
    if ($isScalar(node))
      return node.value;
    if ($isSeq(node)) {
      return node.items.map((item) => {
        if (!item)
          this.fail("sparse-yaml-sequence", `${context} may not contain empty entries.`, node);
        return this.plain(item, context);
      });
    }
    if ($isMap(node)) {
      const out = {};
      for (const [key, pair] of this.arbitraryFields(node, context)) {
        out[key] = this.plain(pair.value, `${context}.${key}`);
      }
      return out;
    }
    this.fail("invalid-yaml-node", `${context} contains an unsupported YAML node.`, node);
  }
  required(fields, key, context) {
    const pair = fields.get(key);
    if (!pair)
      this.fail("missing-key", `${context} is missing required key ${JSON.stringify(key)}.`, undefined);
    return pair.value;
  }
  requiredString(fields, key, context) {
    return this.string(this.required(fields, key, context), `${context}.${key}`);
  }
  optionalString(fields, key, context) {
    const pair = fields.get(key);
    return pair ? this.string(pair.value, `${context}.${key}`) : undefined;
  }
  string(node, context) {
    if (!$isScalar(node) || typeof node.value !== "string" || node.value.trim() === "") {
      this.fail("string-required", `${context} must be a non-empty string.`, node);
    }
    return node.value;
  }
  scalar(node, context, allowNull) {
    if (node === null || $isScalar(node) && node.value === null) {
      if (allowNull)
        return null;
      this.fail("scalar-required", `${context} may not be null.`, node);
    }
    if (!$isScalar(node))
      this.fail("scalar-required", `${context} must be a scalar.`, node);
    const value = node.value;
    if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") {
      this.fail("scalar-required", `${context} must be a string, number, or boolean.`, node);
    }
    if (typeof value === "number" && !Number.isFinite(value)) {
      this.fail("scalar-required", `${context} must be a finite number.`, node);
    }
    return value;
  }
  sequence(node, context, max, allowEmpty = false) {
    if (!$isSeq(node) || !allowEmpty && node.items.length === 0) {
      this.fail("sequence-required", `${context} must be ${allowEmpty ? "an" : "a non-empty"} list.`, node);
    }
    if (node.items.length > max)
      this.fail("step-count-limit", `${context} exceeds ${max} entries.`, node);
    return node.items.map((item) => {
      if (!item)
        this.fail("sparse-yaml-sequence", `${context} may not contain empty entries.`, node);
      return item;
    });
  }
  fail(code, message, node) {
    throw new WorkflowSourceFailure(code, message, this.span(node));
  }
}
function parseTriggers(reader, node) {
  const fields = reader.arbitraryFields(node, "workflow.on");
  for (const [key, pair] of fields) {
    if (!TRIGGER_KEYS.includes(key)) {
      reader.fail("unsupported-service-event", `GitHub service event ${JSON.stringify(key)} is unsupported for local execution.`, pair.key);
    }
  }
  if (fields.size === 0)
    reader.fail("trigger-required", "workflow.on must declare schedule or workflow_dispatch.", node);
  const schedules = [];
  const schedule = fields.get("schedule");
  if (schedule) {
    const records = reader.sequence(schedule.value, "workflow.on.schedule", 64);
    for (const [ordinal, record] of records.entries()) {
      const scheduleFields = reader.fields(record, SCHEDULE_KEYS, `workflow.on.schedule[${ordinal}]`);
      const cronNode = reader.required(scheduleFields, "cron", `workflow.on.schedule[${ordinal}]`);
      const cron = validateCron(reader, reader.string(cronNode, `workflow.on.schedule[${ordinal}].cron`), cronNode);
      schedules.push({ cron, ordinal, line: reader.span(cronNode).start });
    }
  }
  const manual = fields.get("workflow_dispatch");
  if (manual) {
    const nullValue = manual.value === null || $isScalar(manual.value) && manual.value.value === null;
    if (!nullValue) {
      if (!$isMap(manual.value)) {
        reader.fail("workflow-dispatch-inputs-unsupported", "workflow_dispatch must be null or an empty mapping; inputs are unsupported.", manual.value);
      }
      if (manual.value.items.length > 0) {
        reader.fail("workflow-dispatch-inputs-unsupported", "workflow_dispatch inputs are not supported for local execution.", manual.value.items[0]?.key);
      }
    }
  }
  return schedules;
}
function validateCron(reader, cron, node) {
  try {
    return canonicalizeWorkflowCron(cron);
  } catch (cause) {
    semanticReaderFail(reader, cause, node);
  }
}
function parseJob(reader, node, options) {
  const jobs = reader.arbitraryFields(node, "workflow.jobs");
  const [first, second] = [...jobs];
  if (jobs.size !== 1 || !first) {
    reader.fail("multi-job-unsupported", `AKM workflow YAML requires exactly one job; this document declares ${jobs.size}. AKM's YAML is an AKM workflow format executed by AKM's native engine, not GitHub Actions — split the jobs into separate workflows.`, second ? second[1].key : node);
  }
  const [id, pair] = first;
  const jobNode = pair.value;
  if (!SOURCE_ID.test(id))
    reader.fail("invalid-job-id", `Invalid job id ${JSON.stringify(id)}.`, jobNode);
  const fields = reader.fields(jobNode, JOB_KEYS, `workflow.jobs.${id}`);
  const runner = reader.required(fields, "runs-on", `workflow.jobs.${id}`);
  if (!$isSeq(runner) || runner.items.length !== 1 || !$isScalar(runner.items[0]) || runner.items[0].value !== "self-hosted") {
    reader.fail("unsupported-runner", `Job ${JSON.stringify(id)} must declare exactly runs-on: [self-hosted].`, runner);
  }
  const needs = fields.get("needs");
  if (needs) {
    const values = $isSeq(needs.value) ? reader.sequence(needs.value, `workflow.jobs.${id}.needs`, 256).map((item) => reader.string(item, `workflow.jobs.${id}.needs`)) : [reader.string(needs.value, `workflow.jobs.${id}.needs`)];
    for (const need of values)
      if (!SOURCE_ID.test(need))
        reader.fail("invalid-job-id", `Invalid needs id ${need}.`, needs.value);
    if (values.length > 0) {
      reader.fail("multi-job-unsupported", `Job ${id} declares needs, but an AKM workflow has exactly one job; remove needs.`, pair.key);
    }
  }
  reader.optionalString(fields, "name", `workflow.jobs.${id}`);
  const stepNodes = reader.sequence(reader.required(fields, "steps", `workflow.jobs.${id}`), `workflow.jobs.${id}.steps`, MAX_STEPS_PER_JOB);
  const stepIds = new Set;
  return stepNodes.map((step, index) => parseStep(reader, step, id, index, stepIds, options));
}
function parseStep(reader, node, jobId, index, stepIds, options) {
  const context = `workflow.jobs.${jobId}.steps[${index}]`;
  const fields = reader.fields(node, STEP_KEYS, context);
  const id = reader.requiredString(fields, "id", context);
  if (!SOURCE_ID.test(id))
    reader.fail("invalid-step-id", `Invalid step id ${JSON.stringify(id)}.`, fields.get("id")?.value);
  if (stepIds.has(id))
    reader.fail("duplicate-step-id", `Job ${jobId} has duplicate step id ${id}.`, fields.get("id")?.value);
  stepIds.add(id);
  const usesPair = fields.get("uses");
  const runPair = fields.get("run");
  if (usesPair === undefined === (runPair === undefined)) {
    reader.fail("step-target-xor", `${context} must declare exactly one of uses or run.`, node);
  }
  reader.optionalString(fields, "name", context);
  const env = parseScalarMap(reader, fields.get("env"), `${context}.env`, ENV_KEY, false);
  const target = usesPair ? parseUsesStep(reader, usesPair, fields) : parseRunStep(reader, runPair, fields, options);
  const spec = { ...target, ...env ? { env } : {}, source: reader.span(node) };
  return {
    stepId: id,
    title: id,
    sequenceIndex: index,
    spec,
    gate: { kind: "gate", id: `${id}.gate`, stepId: id, criteria: [], maxLoops: 1, frozenJudge: null }
  };
}
function parseUsesStep(reader, usesPair, fields) {
  if (fields.has("shell") || fields.has("working-directory")) {
    reader.fail("uses-field-conflict", "shell and working-directory are legal only with run.", usesPair.value);
  }
  const uses = reader.string(usesPair.value, "step.uses");
  let target;
  try {
    target = classifyWorkflowStepUses(uses);
  } catch (cause) {
    semanticReaderFail(reader, cause, usesPair.value);
  }
  const withValues = target.kind === "task" || target.kind === "workflow" ? parsePlainMap(reader, fields.get("with"), "step.with", INPUT_KEY) : parseScalarMap(reader, fields.get("with"), "step.with", INPUT_KEY, true);
  const commandMode = target.kind === "builtin-command" ? validateBuiltinCommand(reader, withValues, fields.get("with")?.value ?? usesPair.value) : undefined;
  return {
    uses,
    ...commandMode ? { commandMode } : {},
    ...withValues ? { with: withValues } : {}
  };
}
function validateBuiltinCommand(reader, values, node) {
  try {
    const action = validateWorkflowBuiltinCommand(values);
    if (action.kind === "stored")
      return "stored-ref";
    return action.arguments !== undefined || action.content.includes("$ARGUMENTS") ? "portable-template" : "literal";
  } catch (cause) {
    semanticReaderFail(reader, cause, node);
  }
}
function parseRunStep(reader, runPair, fields, options) {
  if (fields.has("with"))
    reader.fail("run-field-conflict", "with is legal only with uses.", fields.get("with")?.value);
  let run;
  try {
    run = canonicalizeWorkflowRun(reader.string(runPair.value, "step.run"));
  } catch (cause) {
    semanticReaderFail(reader, cause, runPair.value);
  }
  const shell = fields.has("shell") ? reader.requiredString(fields, "shell", "step") : undefined;
  if (shell !== undefined && !HOST_SHELLS.has(shell))
    reader.fail("unsupported-shell", `Unsupported shell ${shell}.`, fields.get("shell")?.value);
  let workingDirectory = fields.has("working-directory") ? reader.requiredString(fields, "working-directory", "step") : undefined;
  if (workingDirectory !== undefined) {
    try {
      workingDirectory = canonicalizeWorkflowWorkingDirectory(workingDirectory, options.workspaceRoot);
    } catch (cause) {
      semanticReaderFail(reader, cause, fields.get("working-directory")?.value);
    }
  }
  return {
    exec: { command: workflowShellCommand(shell ?? "sh", run), ...workingDirectory ? { cwd: workingDirectory } : {} },
    instructions: `Run ${run}.`
  };
}
function parseScalarMap(reader, pair, context, keyPattern, allowNull) {
  if (!pair)
    return;
  const fields = reader.arbitraryFields(pair.value, context);
  const out = {};
  for (const [key, valuePair] of fields) {
    if (!keyPattern.test(key))
      reader.fail("invalid-mapping-key", `${context} has invalid key ${JSON.stringify(key)}.`, valuePair.key);
    out[key] = reader.scalar(valuePair.value, `${context}.${key}`, allowNull);
  }
  return out;
}
function parsePlainMap(reader, pair, context, keyPattern) {
  if (!pair)
    return;
  const fields = reader.arbitraryFields(pair.value, context);
  const out = {};
  for (const [key, valuePair] of fields) {
    if (!keyPattern.test(key))
      reader.fail("invalid-mapping-key", `${context} has invalid key ${JSON.stringify(key)}.`, valuePair.key);
    out[key] = reader.plain(valuePair.value, `${context}.${key}`);
  }
  return out;
}
function wholeSourceSpan(source, filePath) {
  return { path: filePath, start: 1, end: Math.max(1, source.split(/\r?\n/).length) };
}
function spanAtOffset(filePath, counter, offset) {
  const line = counter.linePos(Math.max(0, offset)).line;
  return { path: filePath, start: line, end: line };
}
function cleanYamlMessage(message) {
  return message.replace(/\s+at line \d+, column \d+:[\s\S]*$/i, "").trim();
}
function semanticReaderFail(reader, cause, node) {
  if (cause instanceof WorkflowSourceSemanticError)
    reader.fail(cause.code, cause.message, node);
  reader.fail("invalid-workflow-source", cause instanceof Error ? cause.message : String(cause), node);
}

// src/core/asset/markdown.ts
function parseMarkdownToc(content) {
  const lines = content.split(/\r?\n/);
  const headings = [];
  const parsed = parseFrontmatter(content);
  const start = parsed.frontmatter ? parsed.bodyStartLine - 1 : 0;
  let inFence = false;
  for (let i = start;i < lines.length; i++) {
    if (/^\s*(`{3,}|~{3,})/.test(lines[i])) {
      inFence = !inFence;
      continue;
    }
    if (inFence)
      continue;
    const match = lines[i].match(/^(#{1,6})\s+(.+)$/);
    if (match) {
      headings.push({
        level: match[1].length,
        text: match[2].replace(/\s+#+\s*$/, "").trim(),
        line: i + 1
      });
    }
  }
  return { headings, totalLines: lines.length };
}

// src/workflows/program/expressions.ts
var GRAMMAR_HINT = "allowed forms: params.<name>, steps.<id>.output(.<ident>|[<int>])*";
function parseReference(source) {
  const text = source.trim();
  if (text === "")
    return { ok: false, message: `Empty reference; ${GRAMMAR_HINT}.` };
  const root = readIdent(text, 0);
  if (!root) {
    return { ok: false, message: `Invalid reference "${text}" — must start with an identifier; ${GRAMMAR_HINT}.` };
  }
  switch (root.name) {
    case "params": {
      if (text[root.end] !== ".") {
        return { ok: false, message: `"params" requires a name: params.<name> (got "${text}").` };
      }
      const name = readIdent(text, root.end + 1);
      if (!name) {
        return { ok: false, message: `Invalid param name after "params." in "${text}".` };
      }
      if (name.end !== text.length) {
        return {
          ok: false,
          message: `"params.${name.name}" takes exactly one name — found trailing "${text.slice(name.end)}".`
        };
      }
      return { ok: true, expr: { kind: "param", name: name.name } };
    }
    case "steps": {
      if (text[root.end] !== ".") {
        return { ok: false, message: `"steps" requires a step id: steps.<id>.output (got "${text}").` };
      }
      const stepId = readIdent(text, root.end + 1);
      if (!stepId) {
        return { ok: false, message: `Invalid step id after "steps." in "${text}".` };
      }
      if (text[stepId.end] !== ".") {
        return { ok: false, message: `"steps.${stepId.name}" must be followed by ".output" (got "${text}").` };
      }
      const output = readIdent(text, stepId.end + 1);
      if (!output || output.name !== "output") {
        return { ok: false, message: `Expected ".output" after "steps.${stepId.name}" in "${text}".` };
      }
      const path20 = parsePath(text, output.end);
      if (!path20.ok)
        return { ok: false, message: path20.message };
      return { ok: true, expr: { kind: "stepOutput", stepId: stepId.name, path: path20.path } };
    }
    default:
      return { ok: false, message: `Unknown root "${root.name}" in "${text}"; ${GRAMMAR_HINT}.` };
  }
}
function readIdent(text, start) {
  if (start >= text.length || !/[A-Za-z_]/.test(text[start]))
    return null;
  let end = start + 1;
  while (end < text.length && /[A-Za-z0-9_-]/.test(text[end]))
    end++;
  return { name: text.slice(start, end), end };
}
function parsePath(text, start) {
  const path20 = [];
  let i = start;
  while (i < text.length) {
    const char = text[i];
    if (char === ".") {
      const ident = readIdent(text, i + 1);
      if (!ident) {
        return { ok: false, message: `Invalid path segment after "." at position ${i} in "${text}".` };
      }
      path20.push(ident.name);
      i = ident.end;
    } else if (char === "[") {
      let j = i + 1;
      while (j < text.length && /[0-9]/.test(text[j]))
        j++;
      if (j === i + 1 || text[j] !== "]") {
        return {
          ok: false,
          message: `Invalid indexer at position ${i} in "${text}" — expected [<non-negative integer>].`
        };
      }
      path20.push(Number.parseInt(text.slice(i + 1, j), 10));
      i = j + 1;
    } else {
      return { ok: false, message: `Unexpected character "${char}" at position ${i} in "${text}".` };
    }
  }
  return { ok: true, path: path20 };
}
function formatReference(expr) {
  switch (expr.kind) {
    case "param":
      return `params.${expr.name}`;
    case "stepOutput": {
      let text = `steps.${expr.stepId}.output`;
      for (const segment of expr.path) {
        text += typeof segment === "number" ? `[${segment}]` : `.${segment}`;
      }
      return text;
    }
  }
}

// src/workflows/parser.ts
var PROGRAM_REDUCERS = ["collect", "vote"];
var PROGRAM_ON_ERROR = ["fail", "continue"];
var PROGRAM_ISOLATION_KINDS = ["none", "worktree"];
var RETRY_REASON_SET = {
  timeout: true,
  spawn_failed: true,
  non_zero_exit: true,
  parse_error: true,
  cooldown: true,
  llm_rate_limit: true,
  llm_content_filter: true,
  llm_invalid_json: true,
  content_policy_reject: true,
  unsupported_type: true,
  no_change: true,
  quality_rejected: true,
  aborted: true
};
var PROGRAM_RETRY_REASONS = Object.keys(RETRY_REASON_SET);
var PROGRAM_STEP_ID_PATTERN = /^[A-Za-z_][A-Za-z0-9_-]*$/;
var PROGRAM_PARAM_NAME_PATTERN = INPUT_NAME_PATTERN;
var ENVELOPE_KEYS = [
  "type",
  "description",
  "tags",
  "when_to_use",
  "xrefs",
  "updated",
  "timestamp",
  "generated",
  "verified",
  "provenance",
  "status",
  "stale_after"
];
var WORKFLOW_KEYS = ["params", "outputs", "defaults", "budget", "steps"];
var TOP_LEVEL_KEYS = [...ENVELOPE_KEYS, ...WORKFLOW_KEYS];
var DEFAULTS_KEYS = ["engine", "model", "timeout", "on_error", "llm"];
var BUDGET_KEYS = ["max_tokens", "max_units"];
var STEP_KEYS2 = ["id", "unit", "map", "route", "inputs", "output", "gate"];
var UNIT_KEYS = ["exec", "engine", "model", "llm", "timeout", "retry", "on_error", "output", "env", "isolation"];
var EXEC_KEYS = ["command", "cwd", "pass_env"];
var UNIT_ENGINE_KEYS = ["engine", "model", "llm"];
var MAP_KEYS = ["over", "concurrency", "reducer", "unit"];
var ROUTE_KEYS = ["input", "when", "default"];
var RETRY_KEYS = ["max", "on"];
var GATE_KEYS = ["max_loops"];
var ROUTE_BRANCH_KEYS = ["match", "step"];
var OUTPUT_ENTRY_KEYS = ["from", "schema"];
var ACTOR_STAMP_KEYS = ["by", "at"];
var TIMEOUT_VALUE = /^(\d+)(ms|s|m)?$/;
var TIMEOUT_HINT = `Use "<n>ms", "<n>s", "<n>m" (e.g. "10m"), or "none"`;
var LIFECYCLE_STATUSES = new Set(["draft", "stable", "deprecated"]);
function parseWorkflow(markdown, source) {
  if (utf8Bytes(markdown) > WORKFLOW_MAX_SOURCE_BYTES) {
    return {
      ok: false,
      errors: [{ line: 1, message: "Workflow source exceeds the 1 MiB resource limit." }]
    };
  }
  const errors3 = [];
  const path20 = source.path;
  const lines = markdown.split(/\r?\n/);
  const totalLines = lines.length;
  const fmBlock = parseFrontmatterBlock(markdown);
  if (!fmBlock) {
    return {
      ok: false,
      errors: [
        {
          line: 1,
          message: `Workflow markdown must start with a YAML frontmatter block ("---" ... "---") declaring at least ` + `a non-empty "steps" list.`
        }
      ]
    };
  }
  const lineOffset = 1;
  const frontmatterEndLine = Math.max(1, fmBlock.bodyStartLine - 1);
  const lineCounter2 = new $LineCounter;
  let doc;
  try {
    doc = $parseDocument(fmBlock.frontmatter, { lineCounter: lineCounter2 });
  } catch (cause) {
    return {
      ok: false,
      errors: [{ line: 2, message: `Workflow frontmatter is not valid YAML: ${describeError(cause)}` }]
    };
  }
  for (const problem of doc.errors) {
    const offset = Array.isArray(problem.pos) ? problem.pos[0] : 0;
    errors3.push({
      line: Math.max(1, lineCounter2.linePos(offset).line + lineOffset),
      message: yamlErrorMessage(problem.message)
    });
  }
  if (errors3.length > 0)
    return { ok: false, errors: errors3 };
  let root;
  try {
    root = doc.toJS();
  } catch (cause) {
    return { ok: false, errors: [{ line: 2, message: `YAML expansion failed: ${describeError(cause)}` }] };
  }
  const lineAt = (p) => {
    for (let depth = p.length;depth >= 0; depth--) {
      const node = depth === 0 ? doc.contents : doc.getIn(p.slice(0, depth), true);
      const range = node?.range;
      if (range)
        return Math.max(1, lineCounter2.linePos(range[0]).line + lineOffset);
    }
    return 2;
  };
  const ctx = {
    filePath: path20,
    errors: errors3,
    ...source.validateExecCwd ? { validateExecCwd: source.validateExecCwd } : {},
    lineAt,
    lineAtOffset: (offset) => Math.max(1, lineCounter2.linePos(offset).line + lineOffset),
    nodeAt: (p) => p.length === 0 ? doc.contents : doc.getIn(p, true),
    refAt: (p) => {
      for (let depth = p.length;depth >= 0; depth--) {
        const node = depth === 0 ? doc.contents : doc.getIn(p.slice(0, depth), true);
        const range = node?.range;
        if (range) {
          const start = Math.max(1, lineCounter2.linePos(range[0]).line + lineOffset);
          const end = Math.max(start, lineCounter2.linePos(Math.max(range[0], range[1] - 1)).line + lineOffset);
          return { path: path20, start, end };
        }
      }
      return { path: path20, start: frontmatterEndLine, end: frontmatterEndLine };
    },
    err: (p, message) => errors3.push({ line: lineAt(p), message }),
    errAtLine: (line, message) => errors3.push({ line, message })
  };
  if (root === null || root === undefined)
    root = {};
  if (!isRecord(root)) {
    return {
      ok: false,
      errors: [{ line: 2, message: `Workflow frontmatter must be a YAML mapping (key: value pairs).` }]
    };
  }
  checkUnknownKeys(ctx, root, [], TOP_LEVEL_KEYS, "workflow frontmatter");
  checkEnvelopeFields(ctx, root, frontmatterEndLine);
  const description = typeof root.description === "string" ? root.description : undefined;
  readTags2(ctx, root.tags, frontmatterEndLine);
  const params = parseParams(ctx, root.params);
  const outputs = parseOutputs(ctx, root.outputs);
  const defaults = parseDefaults(ctx, root.defaults);
  const budget = parseBudget(ctx, root.budget);
  const parsedSteps = parseSteps(ctx, root.steps);
  const toc = parseMarkdownToc(markdown);
  const declaredIds = new Set(parsedSteps.map((s) => s.id));
  const { sections, preamble } = bindStepSections(toc.headings, lines, fmBlock.bodyStartLine, totalLines, path20, declaredIds, errors3);
  const steps = parsedSteps.map((step, index) => {
    const section = sections.get(step.id);
    if (!section) {
      if (step.route === undefined) {
        errors3.push({
          line: step.source.start,
          message: `Step "${step.id}" is a unit/map step and must have a "## ${step.id}" body section with its instructions.`
        });
      }
    } else if (step.route === undefined && !section.instructions) {
      errors3.push({
        line: section.headingLine,
        message: `Step "${step.id}" section ("## ${step.id}") is empty. Add the step's instructions below the heading.`
      });
    }
    for (const [block, what] of [
      [section?.instructions, "instructions exceed"],
      [section?.gateRubric, "gate rubric exceeds"]
    ]) {
      if (block && utf8Bytes(block.text) > WORKFLOW_MAX_INSTRUCTION_BYTES) {
        errors3.push({ line: block.source.start, message: `Step "${step.id}" ${what} the 256 KiB resource limit.` });
      }
    }
    const rubric = section?.gateRubric?.text;
    return {
      stepId: step.id,
      title: step.id,
      sequenceIndex: index,
      spec: stepSpec(step, section),
      ...step.route ? {
        route: {
          input: step.route.input,
          when: Object.fromEntries(step.route.branches.map((branch) => [branch.match, branch.stepId])),
          ...step.route.defaultStepId !== undefined ? { defaultStepId: step.route.defaultStepId } : {}
        }
      } : {},
      ...step.output !== undefined ? { outputSchema: step.output } : {},
      gate: {
        kind: "gate",
        id: `${step.id}.gate`,
        stepId: step.id,
        criteria: rubric?.trim() ? [rubric] : [],
        maxLoops: step.gate?.maxLoops ?? 1,
        frozenJudge: null
      }
    };
  });
  checkCanonicalXrefs(root.xrefs, frontmatterEndLine, errors3);
  if (errors3.length > 0)
    return { ok: false, errors: sortErrors(errors3) };
  const paramNames = params ? Object.keys(params) : [];
  const plan = {
    irVersion: WORKFLOW_PLAN_VERSION,
    title: source.title ?? path20.replace(/^.*[\\/]/, "").replace(/\.[^.]*$/, ""),
    ...params && paramNames.length > 0 ? { params: paramNames, paramSchemas: params } : {},
    ...outputs ? { outputs: sortedByName(outputs) } : {},
    ...budget ? { budget } : {},
    ...defaults ? { defaults } : {},
    ...description ? { description } : {},
    ...preamble ? { preamble } : {},
    steps
  };
  return { ok: true, plan };
}
function stepSpec(step, section) {
  const prose = section?.instructions?.text;
  if (step.route)
    return { ...prose?.trim() ? { instructions: prose } : {}, source: step.source };
  const dispatchUnit = step.map?.unit ?? step.unit;
  const { exec, source: _unitSource, ...unit } = dispatchUnit ?? { source: step.source };
  return {
    ...exec ? { exec: { ...exec }, ...prose?.trim() ? { instructions: prose } : {} } : { uses: "akm/command", commandMode: "literal", with: { content: prose ?? "" } },
    ...Object.keys(unit).length > 0 ? { unit } : {},
    ...step.map ? {
      map: {
        over: step.map.over,
        ...step.map.concurrency !== undefined ? { concurrency: step.map.concurrency } : {},
        ...step.map.reducer !== undefined ? { reducer: step.map.reducer } : {}
      }
    } : {},
    ...step.inputs ? { inputs: [...step.inputs] } : {},
    source: step.source
  };
}
function sortedByName(entries) {
  return Object.fromEntries(Object.keys(entries).sort(compareCodePoints).map((name) => [name, entries[name]]));
}
function checkCanonicalXrefs(value, line, errors3) {
  if (!Array.isArray(value))
    return;
  for (const ref of value) {
    try {
      if (typeof ref !== "string")
        throw new Error("non-canonical ref");
      const parsed = parseBundleRef(ref);
      if (parsed.conceptId.includes(":") || ref !== bundleRefToString(parsed))
        throw new Error("non-canonical ref");
    } catch {
      errors3.push({
        line,
        message: `Workflow frontmatter "xrefs" contains an invalid or non-canonical ref: ${String(ref)}.`
      });
    }
  }
}
function bindStepSections(headings, lines, bodyStartLine, totalLines, path20, declaredIds, errors3) {
  const sections = new Map;
  const h2s = headings.filter((h) => h.level === 2);
  const firstH2Line = h2s[0]?.line;
  const preambleRaw = firstH2Line ? sliceLines(lines, bodyStartLine, firstH2Line - 1).trim() : sliceLines(lines, bodyStartLine, totalLines).trim();
  for (let i = 0;i < headings.length; i++) {
    const h = headings[i];
    if (h.level !== 2)
      continue;
    if (!declaredIds.has(h.text)) {
      errors3.push({
        line: h.line,
        message: `Unexpected level-2 heading "## ${h.text}" on line ${h.line} — no step "${h.text}" is declared in frontmatter "steps:". Level-2 headings must exactly match a declared step id. To document something that is not a step, use a level-3 heading.`
      });
      continue;
    }
    if (sections.has(h.text)) {
      errors3.push({
        line: h.line,
        message: `Step "${h.text}" has more than one "## ${h.text}" section (first on line ${sections.get(h.text).headingLine}). Keep only one.`
      });
      continue;
    }
    const sectionEnd = findNextHeadingAtOrAboveLevel(headings, i, 2, totalLines);
    const gate = findGateSubsection(headings, i, sectionEnd, path20, h.text, errors3);
    const instructionsEnd = gate ? gate.headingLine - 1 : sectionEnd;
    const instructionsText = sliceProseLines(lines, h.line + 1, instructionsEnd);
    const section = { headingLine: h.line };
    if (instructionsText) {
      section.instructions = { text: instructionsText, source: { path: path20, start: h.line + 1, end: instructionsEnd } };
    }
    if (gate) {
      const gateText = sliceProseLines(lines, gate.bodyStart, gate.bodyEnd);
      if (gateText) {
        section.gateRubric = { text: gateText, source: { path: path20, start: gate.bodyStart, end: gate.bodyEnd } };
      }
    }
    sections.set(h.text, section);
  }
  return { sections, preamble: preambleRaw || undefined };
}
function findGateSubsection(headings, stepHeadingIndex, sectionEnd, path20, stepId, errors3) {
  let found;
  for (let j = stepHeadingIndex + 1;j < headings.length; j++) {
    const h = headings[j];
    if (h.line > sectionEnd)
      break;
    if (h.level <= 2)
      break;
    if (h.level !== 3 || h.text !== "gate")
      continue;
    if (found) {
      errors3.push({
        line: h.line,
        message: `Step "${stepId}" has more than one "### gate" sub-heading (first on line ${found.headingLine}). Keep only one.`
      });
      continue;
    }
    found = { headingLine: h.line, bodyStart: h.line + 1, bodyEnd: sectionEnd };
  }
  return found;
}
function findNextHeadingAtOrAboveLevel(headings, fromIndex, level, totalLines) {
  for (let i = fromIndex + 1;i < headings.length; i++) {
    if (headings[i].level <= level)
      return headings[i].line - 1;
  }
  return totalLines;
}
function sliceLines(lines, startLineInclusive, endLineInclusive) {
  if (endLineInclusive < startLineInclusive)
    return "";
  const s = Math.max(1, startLineInclusive);
  const e = Math.min(endLineInclusive, lines.length);
  return lines.slice(s - 1, e).join(`
`);
}
function sliceProseLines(lines, startLineInclusive, endLineInclusive) {
  let start = Math.max(1, startLineInclusive);
  let end = Math.min(endLineInclusive, lines.length);
  while (start <= end && /^\s*$/.test(lines[start - 1]))
    start++;
  while (end >= start && /^\s*$/.test(lines[end - 1]))
    end--;
  return sliceLines(lines, start, end);
}
function checkEnvelopeFields(ctx, root, fmEndLine) {
  if (root.type !== undefined && root.type !== "workflow") {
    ctx.err(["type"], `Workflow frontmatter "type" must be "workflow" (got ${JSON.stringify(root.type)}).`);
  }
  if (root.when_to_use !== undefined && typeof root.when_to_use !== "string") {
    ctx.err(["when_to_use"], `Workflow frontmatter "when_to_use" must be a string.`);
  }
  if (root.description !== undefined && typeof root.description !== "string") {
    ctx.err(["description"], `Workflow frontmatter "description" must be a string.`);
  }
  checkXrefs(ctx, root.xrefs, fmEndLine);
  if (root.updated !== undefined && typeof root.updated !== "string") {
    ctx.err(["updated"], `Workflow frontmatter "updated" must be a string.`);
  }
  if (root.timestamp !== undefined && typeof root.timestamp !== "string") {
    ctx.err(["timestamp"], `Workflow frontmatter "timestamp" must be a string.`);
  }
  checkActorStamp(ctx, root.generated, ["generated"], `"generated"`);
  if (root.verified !== undefined) {
    if (Array.isArray(root.verified)) {
      root.verified.forEach((entry, i) => {
        checkActorStamp(ctx, entry, ["verified", i], `"verified"`);
      });
    } else {
      checkActorStamp(ctx, root.verified, ["verified"], `"verified"`);
    }
  }
  if (root.provenance !== undefined && !isRecord(root.provenance)) {
    ctx.err(["provenance"], `Workflow frontmatter "provenance" must be a mapping.`);
  }
  if (root.status !== undefined && (typeof root.status !== "string" || !LIFECYCLE_STATUSES.has(root.status))) {
    ctx.err(["status"], `Workflow frontmatter "status" must be one of: draft, stable, deprecated.`);
  }
  if (root.stale_after !== undefined && typeof root.stale_after !== "string") {
    ctx.err(["stale_after"], `Workflow frontmatter "stale_after" must be a string.`);
  }
}
function checkActorStamp(ctx, value, path20, label) {
  if (value === undefined)
    return;
  if (!isRecord(value)) {
    ctx.err(path20, `Workflow frontmatter ${label} must be a mapping with a non-empty "by".`);
    return;
  }
  checkUnknownKeys(ctx, value, path20, ACTOR_STAMP_KEYS, `${label} actor stamp`);
  if (typeof value.by !== "string" || value.by.length === 0) {
    ctx.err([...path20, "by"], `Workflow frontmatter ${label} must be a mapping with a non-empty "by".`);
  }
  if (value.at !== undefined && typeof value.at !== "string") {
    ctx.err([...path20, "at"], `Workflow frontmatter ${label} actor stamp "at" must be a string.`);
  }
}
function readTags2(ctx, value, fmEndLine) {
  if (value === undefined)
    return;
  if (!Array.isArray(value) || !value.every((tag) => typeof tag === "string" && tag.trim().length > 0)) {
    ctx.errAtLine(fmEndLine, `Workflow frontmatter "tags" must be an array of non-empty strings.`);
    return;
  }
  return value.map((tag) => tag.trim());
}
function checkXrefs(ctx, value, fmEndLine) {
  if (value === undefined)
    return;
  if (!Array.isArray(value) || !value.every((ref) => typeof ref === "string")) {
    ctx.errAtLine(fmEndLine, `Workflow frontmatter "xrefs" must be an array of canonical asset refs.`);
  }
}
function parseParams(ctx, raw) {
  if (raw === undefined)
    return;
  if (!isRecord(raw)) {
    ctx.err(["params"], `"params" must be a mapping of param name to a JSON Schema object (e.g. changed_files: { type: array }).`);
    return;
  }
  const params = {};
  for (const [paramName, value] of Object.entries(raw)) {
    if (!PROGRAM_PARAM_NAME_PATTERN.test(paramName)) {
      ctx.err(["params", paramName], `Param name "${paramName}" is invalid. Use letters, digits, and underscores, starting with a letter or underscore, so "params.${paramName}" can address it.`);
      continue;
    }
    if (!isRecord(value)) {
      ctx.err(["params", paramName], `Param "${paramName}" must be a JSON Schema object (e.g. { type: string }).`);
      continue;
    }
    if (jsonBytes(value) > WORKFLOW_MAX_SCHEMA_BYTES) {
      ctx.err(["params", paramName], `Param "${paramName}" schema exceeds the 256 KiB resource limit.`);
    }
    checkSchemaDefinition(ctx, value, ["params", paramName], `Param "${paramName}" schema`);
    params[paramName] = value;
  }
  return Object.keys(params).length > 0 ? params : undefined;
}
function parseOutputs(ctx, raw) {
  if (raw === undefined)
    return;
  if (!isRecord(raw)) {
    ctx.err(["outputs"], `"outputs" must be a mapping of output name to { from, schema? } (e.g. report: { from: steps.summarize.output }).`);
    return;
  }
  const outputs = {};
  for (const [outputName, value] of Object.entries(raw)) {
    const path20 = ["outputs", outputName];
    if (!PROGRAM_PARAM_NAME_PATTERN.test(outputName)) {
      ctx.err(path20, `Output name "${outputName}" is invalid. Use letters, digits, and underscores, starting with a letter or ` + `underscore, so "steps.<child>.output.${outputName}" can address it.`);
      continue;
    }
    if (!isRecord(value)) {
      ctx.err(path20, `Output "${outputName}" must be a mapping with "from" (and optional "schema").`);
      continue;
    }
    checkUnknownKeys(ctx, value, path20, OUTPUT_ENTRY_KEYS, `output "${outputName}"`);
    if (typeof value.from !== "string" || value.from.trim() === "") {
      ctx.err([...path20, "from"], `Output "${outputName}" must declare "from": a steps.<id>.output(.<seg>)* reference.`);
      continue;
    }
    const parsedFrom = parseReference(value.from);
    if (!parsedFrom.ok) {
      ctx.err([...path20, "from"], `Output "${outputName}" "from": ${parsedFrom.message}`);
      continue;
    }
    if (parsedFrom.expr.kind !== "stepOutput") {
      ctx.err([...path20, "from"], `Output "${outputName}" "from" must reference a step output (steps.<id>.output...), not a param — an ` + `output projects a step artifact, never a param (got "${value.from}").`);
      continue;
    }
    const entry = { from: value.from };
    if (value.schema !== undefined) {
      if (!isRecord(value.schema)) {
        ctx.err([...path20, "schema"], `Output "${outputName}" "schema" must be a JSON Schema object.`);
      } else {
        if (jsonBytes(value.schema) > WORKFLOW_MAX_SCHEMA_BYTES) {
          ctx.err([...path20, "schema"], `Output "${outputName}" schema exceeds the 256 KiB resource limit.`);
        }
        checkSchemaDefinition(ctx, value.schema, [...path20, "schema"], `Output "${outputName}" schema`);
        entry.schema = value.schema;
      }
    }
    outputs[outputName] = entry;
  }
  return Object.keys(outputs).length > 0 ? outputs : undefined;
}
function parseDefaults(ctx, raw) {
  if (raw === undefined)
    return;
  const path20 = ["defaults"];
  if (!isRecord(raw)) {
    ctx.err(path20, `"defaults" must be a mapping with any of: ${DEFAULTS_KEYS.join(", ")}.`);
    return;
  }
  checkUnknownKeys(ctx, raw, path20, DEFAULTS_KEYS, `"defaults"`);
  const defaults = {};
  if (raw.engine !== undefined) {
    const engine = parseEngineName(ctx, raw.engine, [...path20, "engine"], `"defaults.engine"`);
    if (engine !== undefined)
      defaults.engine = engine;
  }
  if (raw.model !== undefined) {
    if (typeof raw.model === "string" && raw.model.trim() !== "")
      defaults.model = raw.model.trim();
    else
      ctx.err([...path20, "model"], `"defaults.model" must be a non-empty string (a model alias or exact id).`);
  }
  const timeoutMs = parseTimeoutField(ctx, raw.timeout, [...path20, "timeout"], `"defaults.timeout"`);
  if (timeoutMs !== undefined)
    defaults.timeoutMs = timeoutMs;
  const onError = parseEnumField(ctx, raw.on_error, [...path20, "on_error"], `"defaults.on_error"`, PROGRAM_ON_ERROR);
  if (onError !== undefined)
    defaults.onError = onError;
  const llm = parseLlmOverrides(ctx, raw.llm, [...path20, "llm"], `"defaults.llm"`);
  if (llm !== undefined)
    defaults.llm = llm;
  return Object.keys(defaults).length > 0 ? defaults : undefined;
}
function parseBudget(ctx, raw) {
  if (raw === undefined)
    return;
  const path20 = ["budget"];
  if (!isRecord(raw)) {
    ctx.err(path20, `"budget" must be a mapping with any of: ${BUDGET_KEYS.join(", ")}.`);
    return;
  }
  checkUnknownKeys(ctx, raw, path20, BUDGET_KEYS, `"budget"`);
  const budget = {};
  if (raw.max_tokens !== undefined) {
    if (typeof raw.max_tokens === "number" && Number.isInteger(raw.max_tokens) && raw.max_tokens >= 1) {
      budget.maxTokens = raw.max_tokens;
    } else {
      ctx.err([...path20, "max_tokens"], `"budget.max_tokens" must be an integer >= 1.`);
    }
  }
  if (raw.max_units !== undefined) {
    if (typeof raw.max_units === "number" && Number.isInteger(raw.max_units) && raw.max_units >= 1) {
      budget.maxUnits = raw.max_units;
    } else {
      ctx.err([...path20, "max_units"], `"budget.max_units" must be an integer >= 1.`);
    }
  }
  return Object.keys(budget).length > 0 ? budget : undefined;
}
function parseSteps(ctx, raw) {
  if (!Array.isArray(raw) || raw.length === 0) {
    ctx.err(["steps"], `"steps" is required and must be a list with at least one step.`);
    return [];
  }
  const idIndex = new Map;
  raw.forEach((rawStep, index) => {
    if (isRecord(rawStep) && typeof rawStep.id === "string" && !idIndex.has(rawStep.id)) {
      idIndex.set(rawStep.id, index);
    }
  });
  const steps = [];
  const seenIds = new Map;
  const routeChecks = [];
  raw.forEach((rawStep, index) => {
    const path20 = ["steps", index];
    if (!isRecord(rawStep)) {
      ctx.err(path20, `Step ${index + 1} must be a mapping with an "id".`);
      return;
    }
    const label = typeof rawStep.id === "string" && rawStep.id !== "" ? `Step "${rawStep.id}"` : `Step ${index + 1}`;
    checkUnknownKeys(ctx, rawStep, path20, STEP_KEYS2, label);
    let id = "";
    if (typeof rawStep.id !== "string" || rawStep.id === "") {
      ctx.err([...path20, "id"], `${label} requires a non-empty string "id".`);
    } else if (!PROGRAM_STEP_ID_PATTERN.test(rawStep.id)) {
      ctx.err([...path20, "id"], `${label} has an invalid id "${rawStep.id}". A step id cannot be referenced from steps.${rawStep.id}.output ` + `unless it matches [A-Za-z_][A-Za-z0-9_-]* (a letter or underscore first, then letters, digits, ` + `underscores, or dashes; no dots, no leading digit).`);
    } else {
      id = rawStep.id;
      const firstIndex = seenIds.get(id);
      if (firstIndex !== undefined) {
        ctx.err([...path20, "id"], `Duplicate step id "${id}" (first used by step ${firstIndex + 1}). Step ids must be unique.`);
      } else {
        seenIds.set(id, index);
      }
    }
    const declaredKinds = ["map", "route"].filter((kind) => rawStep[kind] !== undefined);
    if (declaredKinds.length > 1) {
      ctx.err(path20, `${label} must declare at most one of "map" or "route" (found ${declaredKinds.join(" + ")}).`);
    }
    const isRoute = rawStep.route !== undefined;
    const isMapStep = rawStep.map !== undefined;
    if (isRoute && rawStep.unit !== undefined) {
      ctx.err(path20, `${label} is a route step and cannot also declare "unit" (route steps dispatch no unit).`);
    }
    if (isMapStep && rawStep.unit !== undefined) {
      ctx.err(path20, `${label} is a map step; the per-item dispatch-override bag belongs at "map.unit", not top-level "unit".`);
    }
    if (isRoute && rawStep.inputs !== undefined) {
      ctx.err(path20, `${label} is a route step and cannot declare "inputs" (route steps dispatch no unit).`);
    }
    const unit = rawStep.unit !== undefined && !isRoute && !isMapStep ? parseUnit(ctx, rawStep.unit, [...path20, "unit"], label) : undefined;
    const map = isMapStep ? parseMap(ctx, rawStep.map, [...path20, "map"], label) : undefined;
    const route = isRoute ? parseRoute(ctx, rawStep.route, [...path20, "route"], label, index, routeChecks) : undefined;
    const inputs = !isRoute ? parseInputs(ctx, rawStep.inputs, [...path20, "inputs"], label) : undefined;
    const output = parseSchemaObject(ctx, rawStep.output, [...path20, "output"], `${label} "output"`);
    const gate = rawStep.gate !== undefined ? parseGate(ctx, rawStep.gate, [...path20, "gate"], label) : undefined;
    const step = { id, source: ctx.refAt(path20) };
    if (unit)
      step.unit = unit;
    if (map)
      step.map = map;
    if (route)
      step.route = route;
    if (inputs)
      step.inputs = inputs;
    if (output !== undefined)
      step.output = output;
    if (gate !== undefined)
      step.gate = gate;
    steps.push(step);
  });
  for (const check of routeChecks) {
    const targets = [...check.branches.map((b) => ({ stepId: b.stepId, line: b.line }))];
    if (check.defaultTarget)
      targets.push(check.defaultTarget);
    for (const target of targets) {
      const targetIndex = idIndex.get(target.stepId);
      if (targetIndex === undefined) {
        ctx.errAtLine(target.line, `${check.stepLabel} routes to unknown step "${target.stepId}". Route targets must name a step id in this workflow.`);
      } else if (targetIndex === check.stepIndex) {
        ctx.errAtLine(target.line, `${check.stepLabel} must not route to itself.`);
      } else if (targetIndex < check.stepIndex) {
        ctx.errAtLine(target.line, `${check.stepLabel} routes backward to "${target.stepId}" (step ${targetIndex + 1}). Route targets must come after the routing step.`);
      }
    }
  }
  return steps;
}
function parseUnit(ctx, raw, path20, stepLabel) {
  if (!isRecord(raw)) {
    ctx.err(path20, `${stepLabel} "unit" must be a mapping (a dispatch-override bag).`);
    return;
  }
  checkUnknownKeys(ctx, raw, path20, UNIT_KEYS, `${stepLabel} "unit"`);
  const unit = { source: ctx.refAt(path20) };
  if (raw.exec !== undefined) {
    const exec = parseExec(ctx, raw.exec, [...path20, "exec"], stepLabel);
    if (exec !== undefined)
      unit.exec = exec;
    for (const key of UNIT_ENGINE_KEYS) {
      if (raw[key] === undefined)
        continue;
      ctx.err([...path20, key], `${stepLabel} "unit" declares both "exec" and "${key}". An exec unit runs a shell command and never ` + `reaches an engine, so "${key}" would have no effect — remove one of the two.`);
    }
  }
  if (raw.engine !== undefined) {
    const engine = parseEngineName(ctx, raw.engine, [...path20, "engine"], `${stepLabel} "engine"`);
    if (engine !== undefined)
      unit.engine = engine;
  }
  if (raw.model !== undefined) {
    if (typeof raw.model === "string" && raw.model.trim() !== "")
      unit.model = raw.model.trim();
    else
      ctx.err([...path20, "model"], `${stepLabel} "model" must be a non-empty string (a model alias or exact id).`);
  }
  const llm = parseLlmOverrides(ctx, raw.llm, [...path20, "llm"], `${stepLabel} "llm"`);
  if (llm !== undefined)
    unit.llm = llm;
  const timeoutMs = parseTimeoutField(ctx, raw.timeout, [...path20, "timeout"], `${stepLabel} "timeout"`);
  if (timeoutMs !== undefined)
    unit.timeoutMs = timeoutMs;
  const retry = parseRetry(ctx, raw.retry, [...path20, "retry"], stepLabel);
  if (retry !== undefined)
    unit.retry = retry;
  const onError = parseEnumField(ctx, raw.on_error, [...path20, "on_error"], `${stepLabel} "on_error"`, PROGRAM_ON_ERROR);
  if (onError !== undefined)
    unit.onError = onError;
  const output = parseSchemaObject(ctx, raw.output, [...path20, "output"], `${stepLabel} unit "output"`);
  if (output !== undefined)
    unit.output = output;
  if (raw.env !== undefined) {
    if (Array.isArray(raw.env) && raw.env.every((entry) => typeof entry === "string" && entry.trim() !== "")) {
      const envRefs = raw.env.map((entry) => entry.trim());
      const duplicate = envRefs.find((ref, i) => envRefs.indexOf(ref) !== i);
      if (duplicate !== undefined) {
        ctx.err([...path20, "env"], `${stepLabel} "env" contains a duplicate entry: "${duplicate}".`);
      } else {
        unit.env = envRefs;
      }
    } else {
      ctx.err([...path20, "env"], `${stepLabel} "env" must be a list of non-empty env asset refs.`);
    }
  }
  const isolation = parseEnumField(ctx, raw.isolation, [...path20, "isolation"], `${stepLabel} "isolation"`, PROGRAM_ISOLATION_KINDS);
  if (isolation !== undefined)
    unit.isolation = isolation;
  return unit;
}
function parseExec(ctx, raw, path20, stepLabel) {
  if (!isRecord(raw)) {
    ctx.err(path20, `${stepLabel} "exec" must be a mapping with a "command" argv list.`);
    return;
  }
  checkUnknownKeys(ctx, raw, path20, EXEC_KEYS, `${stepLabel} "exec"`);
  const command = parseExecCommand(ctx, raw.command, [...path20, "command"], stepLabel);
  if (command === undefined)
    return;
  const exec = { command };
  const cwd = parseExecCwd(ctx, raw.cwd, [...path20, "cwd"], stepLabel);
  if (cwd !== undefined)
    exec.cwd = cwd;
  const passEnv = parseExecPassEnv(ctx, raw.pass_env, [...path20, "pass_env"], stepLabel);
  if (passEnv !== undefined)
    exec.passEnv = passEnv;
  return exec;
}
function parseExecPassEnv(ctx, raw, path20, stepLabel) {
  if (raw === undefined)
    return;
  if (!Array.isArray(raw) || raw.length === 0) {
    ctx.err(path20, `${stepLabel} "exec.pass_env" must be a non-empty list of environment variable NAMES to copy through from ` + `akm's own environment, e.g. pass_env: [CARGO_HOME]. Values never appear here — use "env:" bindings for those.`);
    return;
  }
  const names = [];
  for (const [index, entry] of raw.entries()) {
    if (typeof entry !== "string" || !WORKFLOW_ENV_VAR_NAME_PATTERN.test(entry)) {
      ctx.err(path20, `${stepLabel} "exec.pass_env[${index}]" must be an environment variable name matching ` + `${WORKFLOW_ENV_VAR_NAME_PATTERN.source}.`);
      return;
    }
    if (names.includes(entry)) {
      ctx.err(path20, `${stepLabel} "exec.pass_env" lists "${entry}" more than once.`);
      return;
    }
    names.push(entry);
  }
  return names;
}
function parseExecCommand(ctx, raw, path20, stepLabel) {
  if (!Array.isArray(raw) || raw.length === 0) {
    ctx.err(path20, `${stepLabel} "exec" requires "command": a non-empty argv list, e.g. command: ["bun", "run", "test:unit"]. ` + `A single shell string is not accepted — the command is spawned directly, never through a shell.`);
    return;
  }
  const argv = [];
  for (const [index, entry] of raw.entries()) {
    if (typeof entry !== "string" || entry === "") {
      ctx.err(path20, `${stepLabel} "exec.command[${index}]" must be a non-empty string.`);
      return;
    }
    if (entry.includes("\x00")) {
      ctx.err([...path20, index], `${stepLabel} "exec.command[${index}]" may not contain NUL bytes.`);
      return;
    }
    argv.push(entry);
  }
  return argv;
}
function parseExecCwd(ctx, raw, path20, stepLabel) {
  if (raw === undefined)
    return;
  if (typeof raw !== "string" || raw.trim() === "") {
    ctx.err(path20, `${stepLabel} "exec.cwd" must be a non-empty relative path inside the unit's working directory.`);
    return;
  }
  const value = raw.trim();
  if (!isContainedRelativePath(value)) {
    ctx.err(path20, `${stepLabel} "exec.cwd" (${JSON.stringify(value)}) must be a RELATIVE path inside the unit's working ` + `directory — absolute paths, Windows drive letters, "~", and ".." segments are rejected.`);
    return;
  }
  if (ctx.validateExecCwd) {
    const semantic = ctx.validateExecCwd(value);
    if (!semantic.ok) {
      ctx.errors.push({
        code: semantic.code,
        line: ctx.lineAt(path20),
        message: semantic.message
      });
      return;
    }
    return semantic.value;
  }
  return value;
}
function parseMap(ctx, raw, path20, stepLabel) {
  if (!isRecord(raw)) {
    ctx.err(path20, `${stepLabel} "map" must be a mapping with an "over" key.`);
    return;
  }
  checkUnknownKeys(ctx, raw, path20, MAP_KEYS, `${stepLabel} "map"`);
  let over = "";
  if (typeof raw.over === "string" && raw.over.trim() !== "") {
    over = raw.over.trim();
    checkReferenceSyntax(ctx, over, [...path20, "over"], `${stepLabel} "over"`);
  } else {
    ctx.err([...path20, "over"], `${stepLabel} "map" requires "over": a reference naming the item list (e.g. steps.discover.output.files).`);
  }
  let concurrency;
  if (raw.concurrency !== undefined) {
    if (typeof raw.concurrency === "number" && Number.isInteger(raw.concurrency) && raw.concurrency > 0) {
      concurrency = Math.min(raw.concurrency, WORKFLOW_MAX_CONCURRENCY);
    } else {
      ctx.err([...path20, "concurrency"], `${stepLabel} "concurrency" must be a positive integer.`);
    }
  }
  const reducer = parseEnumField(ctx, raw.reducer, [...path20, "reducer"], `${stepLabel} "reducer"`, PROGRAM_REDUCERS);
  const unit = raw.unit !== undefined ? parseUnit(ctx, raw.unit, [...path20, "unit"], stepLabel) : undefined;
  const map = { over };
  if (concurrency !== undefined)
    map.concurrency = concurrency;
  if (reducer !== undefined)
    map.reducer = reducer;
  if (unit !== undefined)
    map.unit = unit;
  return map;
}
function parseRoute(ctx, raw, path20, stepLabel, stepIndex, routeChecks) {
  if (!isRecord(raw)) {
    ctx.err(path20, `${stepLabel} "route" must be a mapping with "input" and "when" keys.`);
    return;
  }
  checkUnknownKeys(ctx, raw, path20, ROUTE_KEYS, `${stepLabel} "route"`);
  let input = "";
  if (typeof raw.input === "string" && raw.input.trim() !== "") {
    input = raw.input.trim();
    checkReferenceSyntax(ctx, input, [...path20, "input"], `${stepLabel} "route.input"`);
  } else {
    ctx.err([...path20, "input"], `${stepLabel} "route" requires "input": a reference naming the value to route on.`);
  }
  const check = { stepIndex, stepLabel, branches: [] };
  const whenPath = [...path20, "when"];
  if (!Array.isArray(raw.when) || raw.when.length === 0) {
    ctx.err(whenPath, `${stepLabel} "route" requires "when": a non-empty list of { match, step } branches (e.g. when: [{ match: pass, step: ship }]).`);
  } else {
    const seenMatches = new Map;
    raw.when.forEach((branch, i) => {
      const branchPath = [...whenPath, i];
      if (!isRecord(branch)) {
        ctx.err(branchPath, `${stepLabel} "when[${i}]" must be a mapping: { match, step }.`);
        return;
      }
      checkUnknownKeys(ctx, branch, branchPath, ROUTE_BRANCH_KEYS, `${stepLabel} "when[${i}]"`);
      const matchLine = ctx.lineAt([...branchPath, "match"]);
      if (branch.match === undefined || typeof branch.match !== "string" && typeof branch.match !== "number" && typeof branch.match !== "boolean") {
        ctx.err([...branchPath, "match"], `${stepLabel} "when[${i}].match" must be a string, number, or boolean.`);
        return;
      }
      const match = String(branch.match);
      if (match === "") {
        ctx.errAtLine(matchLine, `${stepLabel} "when[${i}].match" must not be empty.`);
        return;
      }
      if (typeof branch.step !== "string" || branch.step.trim() === "") {
        ctx.err([...branchPath, "step"], `${stepLabel} "when[${i}].step" must be a step id string.`);
        return;
      }
      const stepId = branch.step.trim();
      const stepLine = ctx.lineAt([...branchPath, "step"]);
      const firstLine = seenMatches.get(match);
      if (firstLine !== undefined) {
        ctx.errAtLine(matchLine, `${stepLabel} has a duplicate "when" match "${match}" (first declared on line ${firstLine}). Matches must be unique.`);
        return;
      }
      seenMatches.set(match, matchLine);
      check.branches.push({ match, stepId, line: stepLine });
    });
  }
  let defaultStepId;
  if (raw.default !== undefined) {
    if (typeof raw.default === "string" && raw.default.trim() !== "") {
      defaultStepId = raw.default.trim();
      check.defaultTarget = { stepId: defaultStepId, line: ctx.lineAt([...path20, "default"]) };
    } else {
      ctx.err([...path20, "default"], `${stepLabel} "route.default" must be a step id string.`);
    }
  }
  routeChecks.push(check);
  const route = { input, branches: check.branches.map(({ match, stepId }) => ({ match, stepId })) };
  if (defaultStepId !== undefined)
    route.defaultStepId = defaultStepId;
  return route;
}
function parseInputs(ctx, raw, path20, stepLabel) {
  if (raw === undefined)
    return;
  if (!Array.isArray(raw) || raw.length === 0) {
    ctx.err(path20, `${stepLabel} "inputs" must be a non-empty list of reference strings.`);
    return;
  }
  const out = [];
  const seen = new Set;
  raw.forEach((entry, i) => {
    if (typeof entry !== "string" || entry.trim() === "") {
      ctx.err([...path20, i], `${stepLabel} "inputs[${i}]" must be a non-empty reference string.`);
      return;
    }
    const value = entry.trim();
    if (seen.has(value)) {
      ctx.err([...path20, i], `${stepLabel} "inputs[${i}]" duplicates an earlier entry: "${value}".`);
      return;
    }
    seen.add(value);
    checkReferenceSyntax(ctx, value, [...path20, i], `${stepLabel} "inputs[${i}]"`);
    out.push(value);
  });
  return out.length > 0 ? out : undefined;
}
function parseGate(ctx, raw, path20, stepLabel) {
  if (!isRecord(raw)) {
    ctx.err(path20, `${stepLabel} "gate" must be a mapping with any of: ${GATE_KEYS.join(", ")}.`);
    return;
  }
  checkUnknownKeys(ctx, raw, path20, GATE_KEYS, `${stepLabel} "gate"`);
  const gate = {};
  if (raw.max_loops !== undefined) {
    if (typeof raw.max_loops === "number" && Number.isInteger(raw.max_loops) && raw.max_loops >= 1) {
      gate.maxLoops = raw.max_loops;
    } else {
      ctx.err([...path20, "max_loops"], `${stepLabel} "gate.max_loops" must be an integer of at least 1.`);
    }
  }
  return gate;
}
function parseEngineName(ctx, raw, path20, label) {
  if (typeof raw !== "string" || raw.trim() === "") {
    ctx.err(path20, `${label} must be a non-empty engine name.`);
    return;
  }
  const name = raw.trim();
  if (!WORKFLOW_ENGINE_NAME_PATTERN.test(name) || name.length > WORKFLOW_MAX_ENGINE_NAME_LENGTH) {
    ctx.err(path20, `${label} has an invalid engine name ${JSON.stringify(name)}. Engine names are lowercase words of letters ` + `and digits separated by single dashes, starting with a letter (e.g. "code-review-llm"), at most ` + `${WORKFLOW_MAX_ENGINE_NAME_LENGTH} characters.`);
    return;
  }
  return name;
}
function parseRetry(ctx, raw, path20, stepLabel) {
  if (raw === undefined)
    return;
  if (!isRecord(raw)) {
    ctx.err(path20, `${stepLabel} "retry" must be a mapping: { max: <n>, on: [<failure_reason>, …] }.`);
    return;
  }
  checkUnknownKeys(ctx, raw, path20, RETRY_KEYS, `${stepLabel} "retry"`);
  let ok = true;
  if (!(typeof raw.max === "number" && Number.isInteger(raw.max) && raw.max >= 0)) {
    ctx.err([...path20, "max"], `${stepLabel} "retry.max" is required and must be a non-negative integer.`);
    ok = false;
  }
  const on = [];
  if (Array.isArray(raw.on) && raw.on.length > 0) {
    raw.on.forEach((reason, i) => {
      if (typeof reason === "string" && PROGRAM_RETRY_REASONS.includes(reason)) {
        on.push(reason);
      } else {
        ctx.err([...path20, "on", i], `${stepLabel} "retry.on" has unknown failure reason ${JSON.stringify(reason)}. Valid reasons: ${PROGRAM_RETRY_REASONS.join(", ")}.`);
        ok = false;
      }
    });
  } else {
    ctx.err([...path20, "on"], `${stepLabel} "retry.on" is required and must be a non-empty list of failure reasons (${PROGRAM_RETRY_REASONS.join(", ")}).`);
    ok = false;
  }
  return ok ? { max: raw.max, on } : undefined;
}
function parseTimeoutField(ctx, raw, path20, label) {
  if (raw === undefined)
    return;
  if (typeof raw === "number") {
    if (Number.isInteger(raw) && raw > 0)
      return checkTimeoutCeiling(ctx, raw, path20, label, String(raw));
    ctx.err(path20, `${label} has a non-positive timeout ${JSON.stringify(raw)}. ${TIMEOUT_HINT}.`);
    return;
  }
  if (typeof raw !== "string") {
    ctx.err(path20, `${label} must be a duration string. ${TIMEOUT_HINT}.`);
    return;
  }
  const value = raw.trim().toLowerCase();
  if (value === "none")
    return null;
  const match = value.match(TIMEOUT_VALUE);
  if (!match) {
    ctx.err(path20, `${label} has an invalid timeout "${raw}". ${TIMEOUT_HINT}.`);
    return;
  }
  const n = Number.parseInt(match[1], 10);
  const unit = match[2] ?? "ms";
  const timeoutMs = unit === "m" ? n * 60000 : unit === "s" ? n * 1000 : n;
  if (timeoutMs <= 0) {
    ctx.err(path20, `${label} has a non-positive timeout "${raw}". Use a positive duration or "none".`);
    return;
  }
  return checkTimeoutCeiling(ctx, timeoutMs, path20, label, raw);
}
function checkTimeoutCeiling(ctx, timeoutMs, path20, label, raw) {
  if (timeoutMs <= WORKFLOW_MAX_TIMEOUT_MS)
    return timeoutMs;
  ctx.err(path20, `${label} has a timeout "${raw}" above the maximum of ${WORKFLOW_MAX_TIMEOUT_MS} ms (about 24.8 days). ` + `Use a shorter duration or "none" for no timeout.`);
  return;
}
function parseEnumField(ctx, raw, path20, label, allowed) {
  if (raw === undefined)
    return;
  if (typeof raw === "string" && allowed.includes(raw))
    return raw;
  ctx.err(path20, `${label} must be one of: ${allowed.join(" | ")} (got ${JSON.stringify(raw)}).`);
  return;
}
function parseLlmOverrides(ctx, raw, path20, label) {
  if (raw === undefined)
    return;
  if (!isRecord(raw)) {
    ctx.err(path20, `${label} must be a mapping of LLM invocation overrides.`);
    return;
  }
  const keys = [
    "temperature",
    "max_tokens",
    "supports_json_schema",
    "extra_params",
    "context_length",
    "enable_thinking",
    "reasoning_effort"
  ];
  checkUnknownKeys(ctx, raw, path20, keys, label);
  const result = {};
  if (raw.temperature !== undefined) {
    if (typeof raw.temperature === "number" && Number.isFinite(raw.temperature))
      result.temperature = raw.temperature;
    else
      ctx.err([...path20, "temperature"], `${label}.temperature must be a finite number.`);
  }
  if (raw.max_tokens !== undefined) {
    if (typeof raw.max_tokens === "number" && Number.isInteger(raw.max_tokens) && raw.max_tokens > 0) {
      result.maxTokens = raw.max_tokens;
    } else
      ctx.err([...path20, "max_tokens"], `${label}.max_tokens must be a positive integer.`);
  }
  if (raw.supports_json_schema !== undefined) {
    if (typeof raw.supports_json_schema === "boolean")
      result.supportsJsonSchema = raw.supports_json_schema;
    else
      ctx.err([...path20, "supports_json_schema"], `${label}.supports_json_schema must be a boolean.`);
  }
  if (raw.extra_params !== undefined) {
    if (!isRecord(raw.extra_params)) {
      ctx.err([...path20, "extra_params"], `${label}.extra_params must be a JSON object.`);
    } else {
      const issues = validateExtraParams(raw.extra_params);
      for (const issue of issues) {
        ctx.err([...path20, "extra_params", ...issue.path], `${formatExtraParamsIssue(`${label}.extra_params`, issue)}.`);
      }
      if (jsonBytes(raw.extra_params) > WORKFLOW_MAX_EXTRA_PARAMS_BYTES) {
        ctx.err([...path20, "extra_params"], `${label}.extra_params exceeds the 64 KiB resource limit.`);
      }
      if (issues.length === 0 && jsonBytes(raw.extra_params) <= WORKFLOW_MAX_EXTRA_PARAMS_BYTES) {
        result.extraParams = raw.extra_params;
      }
    }
  }
  if (raw.context_length !== undefined) {
    if (typeof raw.context_length === "number" && Number.isInteger(raw.context_length) && raw.context_length > 0) {
      result.contextLength = raw.context_length;
    } else
      ctx.err([...path20, "context_length"], `${label}.context_length must be a positive integer.`);
  }
  if (raw.enable_thinking !== undefined) {
    if (typeof raw.enable_thinking === "boolean")
      result.enableThinking = raw.enable_thinking;
    else
      ctx.err([...path20, "enable_thinking"], `${label}.enable_thinking must be a boolean.`);
  }
  if (raw.reasoning_effort !== undefined) {
    if (typeof raw.reasoning_effort === "string" && raw.reasoning_effort.trim().length > 0) {
      result.reasoningEffort = raw.reasoning_effort;
    } else
      ctx.err([...path20, "reasoning_effort"], `${label}.reasoning_effort must be a non-empty string.`);
  }
  return Object.keys(result).length > 0 ? result : undefined;
}
function parseSchemaObject(ctx, raw, path20, label) {
  if (raw === undefined)
    return;
  if (!isRecord(raw)) {
    ctx.err(path20, `${label} must be a JSON Schema object (e.g. { type: object, properties: { … } }).`);
    return;
  }
  if (jsonBytes(raw) > WORKFLOW_MAX_SCHEMA_BYTES) {
    ctx.err(path20, `${label} exceeds the 256 KiB resource limit.`);
  }
  checkSchemaDefinition(ctx, raw, path20, label);
  return raw;
}
function checkSchemaDefinition(ctx, schema, path20, label) {
  for (const issue of checkJsonSchemaDefinition(schema)) {
    const issuePath = [...path20, ...issue.path];
    if (issue.kind === "unsupported") {
      ctx.err(issuePath, `${label} (at ${issue.pointer}): ${issue.message}. Supported JSON Schema keywords: ` + `${JSON_SCHEMA_SUBSET_SUPPORTED_KEYWORDS}.`);
    } else {
      ctx.err(issuePath, `${label} is not a valid JSON Schema (at ${issue.pointer}): ${issue.message}.`);
    }
  }
}
function checkReferenceSyntax(ctx, text, path20, label) {
  const result = parseReference(text);
  if (!result.ok)
    ctx.err(path20, `${label}: ${result.message}`);
}
function checkUnknownKeys(ctx, obj, path20, allowed, label) {
  for (const key of Object.keys(obj)) {
    if (!allowed.includes(key)) {
      ctx.err([...path20, key], `Unknown ${label} key "${key}". Allowed keys: ${allowed.join(", ")}.`);
    }
  }
}
function describeError(cause) {
  return cause instanceof Error ? cause.message : String(cause);
}
function yamlErrorMessage(message) {
  const first = message.split(`
`, 1)[0] ?? message;
  return first.replace(/ at line \d+, column \d+:?\s*$/, "").trim();
}
function sortErrors(errors3) {
  return [...errors3].sort((a, b) => a.line - b.line);
}

// src/workflows/compile.ts
function compileWorkflowSource(source, options) {
  const extension = path20.extname(options.path).toLowerCase();
  const title = options.title ?? path20.basename(options.path, path20.extname(options.path));
  if (extension === ".yml") {
    try {
      return { ok: true, plan: parseGithubWorkflowSource(source, { ...options, title }) };
    } catch (cause) {
      if (cause instanceof WorkflowSourceFailure)
        return { ok: false, errors: [cause.error] };
      const message = cause instanceof Error ? cause.message : String(cause);
      return { ok: false, errors: [{ code: "invalid-workflow-source", message, path: options.path, line: 1 }] };
    }
  }
  if (extension !== ".md") {
    return {
      ok: false,
      errors: [
        {
          code: "unsupported-workflow-extension",
          message: `Workflow source ${options.path} must use .md or .yml.`,
          path: options.path,
          line: 1
        }
      ]
    };
  }
  const parsed = parseWorkflow(source, {
    path: options.path,
    title,
    validateExecCwd: (value) => {
      try {
        return { ok: true, value: canonicalizeWorkflowWorkingDirectory(value, options.workspaceRoot) };
      } catch (cause) {
        if (cause instanceof WorkflowSourceSemanticError)
          return { ok: false, code: cause.code, message: cause.message };
        return { ok: false, code: "working-directory-unverifiable", message: "cwd cannot be physically verified." };
      }
    }
  });
  if (parsed.ok)
    return parsed;
  return {
    ok: false,
    errors: parsed.errors.map((error2) => ({
      code: error2.code ?? "invalid-markdown-workflow",
      message: error2.message,
      path: options.path,
      line: error2.line
    }))
  };
}
function workflowStepInstructions(step) {
  const spec = step.spec;
  if (!spec)
    return "";
  if (spec.instructions !== undefined)
    return spec.instructions;
  if (spec.uses === "akm/command") {
    const action = parseBuiltinCommandAction(spec.with);
    if (action.kind === "stored") {
      return `Invoke stored command ${action.ref}${action.arguments === undefined ? "" : " with arguments"}.`;
    }
    if (spec.commandMode === "literal")
      return action.content;
    return action.content.split(PORTABLE_ARGUMENTS_PLACEHOLDER).join(action.arguments ?? "");
  }
  if (spec.uses !== undefined)
    return `Invoke local target ${spec.uses}.`;
  return "";
}
function checkWorkflowPlan(plan) {
  const errors3 = [];
  const allStepIds = new Set(plan.steps.map((step) => step.stepId));
  const earlierStepIds = new Set;
  const check = (text, line, label, paramsAllowed) => {
    const parsed = parseReference(text);
    if (!parsed.ok) {
      errors3.push({ line, message: `${label}: ${parsed.message}` });
      return;
    }
    if (parsed.expr.kind === "param") {
      if (paramsAllowed)
        return;
      errors3.push({
        line,
        message: `${label}: "${formatReference(parsed.expr)}" names a param, not a step output — params are already ` + `attached to every unit, so declaring one as an input is redundant. "inputs:" only names step outputs ` + `(steps.<id>.output...).`
      });
      return;
    }
    if (earlierStepIds.has(parsed.expr.stepId))
      return;
    const why = allStepIds.has(parsed.expr.stepId) ? `step "${parsed.expr.stepId}" does not come before this step — references must name an earlier step (a producer that has already run)` : `"${parsed.expr.stepId}" is not a step in this workflow`;
    errors3.push({ line, message: `${label}: "${formatReference(parsed.expr)}" cannot be resolved — ${why}.` });
  };
  for (const step of plan.steps) {
    const line = step.spec?.source.start ?? 1;
    if (step.spec?.map)
      check(step.spec.map.over, line, `Step "${step.stepId}" map.over`, true);
    if (step.route)
      check(step.route.input, line, `Step "${step.stepId}" route.input`, true);
    for (const [index, reference] of (step.spec?.inputs ?? []).entries()) {
      check(reference, line, `Step "${step.stepId}" inputs[${index}]`, false);
    }
    earlierStepIds.add(step.stepId);
  }
  for (const [name, declaration] of Object.entries(plan.outputs ?? {})) {
    const parsed = parseReference(declaration.from);
    const label = `Output "${name}" from`;
    if (!parsed.ok)
      errors3.push({ line: 1, message: `${label}: ${parsed.message}` });
    else if (parsed.expr.kind === "param") {
      errors3.push({
        line: 1,
        message: `${label}: "${formatReference(parsed.expr)}" names a param, not a step output — an output projects a ` + `STEP artifact, never a param. "outputs:" only names step outputs (steps.<id>.output...).`
      });
    } else if (!allStepIds.has(parsed.expr.stepId)) {
      errors3.push({
        line: 1,
        message: `${label}: "${formatReference(parsed.expr)}" cannot be resolved — "${parsed.expr.stepId}" is not a step in this workflow.`
      });
    }
  }
  if (errors3.length > 0)
    return { ok: false, errors: errors3 };
  return { ok: true, warnings: workflowWarnings(plan) };
}
function workflowWarnings(plan) {
  const warnings = [];
  const declared = plan.paramSchemas ? new Set(Object.keys(plan.paramSchemas)) : undefined;
  for (const step of plan.steps) {
    const line = step.spec?.source.start ?? 1;
    const maxLoops = step.gate.maxLoops;
    if (maxLoops > 1 && step.spec?.exec && step.gate.criteria.length > 0) {
      warnings.push({
        line,
        message: `Step "${step.stepId}" declares \`gate.max_loops: ${maxLoops}\` on an \`exec\` step — it runs its command ` + `ONCE. A gate loop re-executes the step so it can address the judge's feedback, and a frozen argv cannot ` + `read that feedback; looping would only repeat the command's side effects. The gate still evaluates and ` + `can still fail the step.`
      });
    }
    if (!declared)
      continue;
    const scan = (text, label) => {
      if (!text)
        return;
      const parsed = parseReference(text);
      if (!parsed.ok || parsed.expr.kind !== "param" || declared.has(parsed.expr.name))
        return;
      warnings.push({
        line,
        message: `${label}: "${formatReference(parsed.expr)}" references a param not declared in \`params:\` ` + `(declared: ${[...declared].join(", ") || "none"}) — likely a typo. An undeclared param supplied at start ` + `still resolves at run time.`
      });
    };
    scan(step.spec?.map?.over, `Step "${step.stepId}" map.over`);
    scan(step.route?.input, `Step "${step.stepId}" route.input`);
  }
  return warnings;
}

// src/core/adapter/adapters/akm-lint.ts
var KNOWN_CATEGORIES = new Set(["personal", "team", "project", "convention", "meta"]);
var PLACEHOLDER_STRINGS = ["Describe what this workflow accomplishes", "Example Workflow"];
var SUPPRESSION_COMMENT = "# akm-lint-ok: dangerous-env-key";
function checkMissingNameOrType(data, frontmatter) {
  if (!frontmatter)
    return null;
  const missingFields = [];
  if (!("name" in data) || !data.name)
    missingFields.push("name");
  if (!("type" in data) || !data.type)
    missingFields.push("type");
  if (missingFields.length === 0)
    return null;
  return `missing fields: ${missingFields.join(", ")}`;
}
function checkInvalidTypeValue(data, allowedTypes) {
  if (!("type" in data) || !data.type)
    return null;
  const value = String(data.type);
  if (allowedTypes.includes(value))
    return null;
  return `type field has invalid value '${value}'; expected one of: ${allowedTypes.join(", ")}`;
}
function suggestSlug(filePath) {
  return path21.basename(filePath, ".md").toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
}
function nameOrTypeDiagnostics(relPath, data, frontmatter, allowedTypes) {
  const missingFieldDetail = checkMissingNameOrType(data, frontmatter);
  if (missingFieldDetail) {
    const slug = suggestSlug(relPath);
    return [
      {
        file: relPath,
        issue: "missing-name-or-type",
        detail: `${missingFieldDetail}; suggested slug: ${slug}`,
        fixed: false
      }
    ];
  }
  const invalidTypeDetail = checkInvalidTypeValue(data, allowedTypes);
  if (invalidTypeDetail) {
    return [{ file: relPath, issue: "missing-name-or-type", detail: invalidTypeDetail, fixed: false }];
  }
  return [];
}
function collectSuppressedKeys(raw) {
  const suppressed = new Set;
  const lines = raw.split(/\r?\n/);
  let prevNonEmpty = "";
  for (const line of lines) {
    const trimmed = line.trim();
    if (trimmed === "")
      continue;
    const keyMatch = trimmed.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=/);
    if (keyMatch && prevNonEmpty.toLowerCase() === SUPPRESSION_COMMENT) {
      suppressed.add(keyMatch[1]);
    }
    prevNonEmpty = trimmed;
  }
  return suppressed;
}
function dangerousEnvKeyDiagnostics(type, relPath, raw) {
  if (type !== "env" && type !== "secret")
    return [];
  const baseNameWithExt = path21.basename(relPath);
  if (!baseNameWithExt.endsWith(".env"))
    return [];
  const ref = conceptIdForStashFile(type, ".", relPath);
  const keys = scanEnvKeyNames(raw);
  const suppressed = collectSuppressedKeys(raw);
  const diagnostics = [];
  for (const key of keys) {
    if (!isDangerousEnvKey(key))
      continue;
    if (suppressed.has(key))
      continue;
    diagnostics.push({
      file: relPath,
      issue: "dangerous-env-key",
      detail: `Env key \`${key}\` can be used to hijack process execution when injected via \`akm env run\`. Ref: ${ref}. Review this file before running \`akm env run\` commands against untrusted stashes. (suppress with: ${SUPPRESSION_COMMENT} on previous line)`,
      fixed: false
    });
  }
  return diagnostics;
}
var AKM_SKILL_DIRS = new Set(["skills"]);
async function skillDirectoryDiagnostics(relPath, seen, ctx, skillDirs = AKM_SKILL_DIRS) {
  const segments = relPath.replace(/\\/g, "/").split("/").filter((s) => s.length > 0);
  if (segments.length < 3 || !skillDirs.has(segments[0]))
    return [];
  const skillDir = `${segments[0]}/${segments[1]}`;
  if (seen.has(skillDir))
    return [];
  seen.add(skillDir);
  const skillMd = await ctx.readFile(`${skillDir}/SKILL.md`);
  if (skillMd !== null)
    return [];
  return [{ file: skillDir, issue: "missing-skill-md", detail: `no SKILL.md in ${skillDir}/`, fixed: false }];
}
async function perTypeValidateChecks(args) {
  const { type, relPath, raw, data, frontmatter, body, ext, ctx, workspaceRoot } = args;
  switch (type) {
    case "command":
      return nameOrTypeDiagnostics(relPath, data, frontmatter, ["command"]);
    case "agent":
      return nameOrTypeDiagnostics(relPath, data, frontmatter, ["agent"]);
    case "fact":
      return factDiagnostics(relPath, data);
    case "task":
      return taskDiagnostics(relPath, raw, workspaceRoot);
    case "workflow":
      return ext === ".md" ? workflowDiagnostics(relPath, raw, body) : [];
    case "memory":
      return memoryDiagnostics(relPath, data, body, ctx);
    case "env":
    case "secret":
      return dangerousEnvKeyDiagnostics(type, relPath, raw);
    default:
      return [];
  }
}
function factDiagnostics(relPath, data) {
  const category = typeof data.category === "string" ? data.category.trim() : "";
  if (!category) {
    return [
      {
        file: relPath,
        issue: "missing-category",
        detail: "fact is missing a `category` (personal|team|project|convention|meta)",
        fixed: false
      }
    ];
  }
  if (!KNOWN_CATEGORIES.has(category)) {
    return [
      {
        file: relPath,
        issue: "missing-category",
        detail: `unrecognized category "${category}" (expected one of: ${[...KNOWN_CATEGORIES].join(", ")})`,
        fixed: false
      }
    ];
  }
  return [];
}
function taskDiagnostics(relPath, raw, workspaceRoot) {
  try {
    parseTaskSource({
      filePath: relPath,
      yaml: raw,
      ...workspaceRoot ? { workspaceRoot } : {}
    });
    return [];
  } catch (cause) {
    return [
      {
        file: relPath,
        issue: "invalid-task-yaml",
        detail: taskSourceErrorDetail(cause),
        fixed: false
      }
    ];
  }
}
function matchWorkflowPlaceholder(body) {
  return PLACEHOLDER_STRINGS.find((p) => body.includes(p)) ?? null;
}
function workflowStructureDiagnostics(relPath, raw, parsePath2) {
  return workflowFrontendDiagnostics(relPath, raw, parsePath2).errors;
}
function lineOf(err) {
  return typeof err.line === "number" && Number.isFinite(err.line) && err.line > 0 ? { line: err.line } : {};
}
function workflowYamlSourceDiagnostics(relPath, raw, parsePath2, workspaceRoot) {
  if (isAkmRegistryCachePath(parsePath2))
    return { errors: [], warnings: [] };
  const compiled = compileWorkflowSource(raw, { path: parsePath2, workspaceRoot });
  if (compiled.ok)
    return { errors: [], warnings: [] };
  return {
    errors: compiled.errors.map((error2) => ({
      file: relPath,
      issue: "invalid-workflow-structure",
      detail: error2.message,
      fixed: false,
      ...lineOf(error2)
    })),
    warnings: []
  };
}
function workflowFrontendDiagnostics(relPath, raw, parsePath2) {
  const none = { errors: [], warnings: [] };
  if (isAkmRegistryCachePath(parsePath2))
    return none;
  const errors3 = [];
  const warnings = [];
  try {
    const result = compileWorkflowSource(raw, { path: parsePath2 });
    if (!result.ok) {
      for (const err of result.errors ?? []) {
        errors3.push({
          file: relPath,
          issue: "invalid-workflow-structure",
          detail: err.message ?? String(err),
          fixed: false,
          ...lineOf(err)
        });
      }
      return { errors: errors3, warnings };
    }
    const compiled = checkWorkflowPlan(result.plan);
    if (!compiled.ok) {
      for (const err of compiled.errors) {
        errors3.push({
          file: relPath,
          issue: "invalid-workflow-structure",
          detail: err.message,
          fixed: false,
          ...lineOf(err)
        });
      }
      return { errors: errors3, warnings };
    }
    for (const warning of compiled.warnings) {
      warnings.push({
        file: relPath,
        issue: "workflow-warning",
        detail: warning.message,
        fixed: false,
        ...lineOf(warning)
      });
    }
  } catch (e) {
    errors3.push({
      file: relPath,
      issue: "invalid-workflow-structure",
      detail: `workflow parser error: ${e instanceof Error ? e.message : String(e)}`,
      fixed: false
    });
  }
  return { errors: errors3, warnings };
}
function workflowDiagnostics(relPath, raw, body) {
  const diagnostics = [];
  const placeholderMatch = matchWorkflowPlaceholder(body);
  if (placeholderMatch) {
    diagnostics.push({
      file: relPath,
      issue: "placeholder-stub",
      detail: `placeholder text: "${placeholderMatch}"`,
      fixed: false
    });
  }
  diagnostics.push(...workflowStructureDiagnostics(relPath, raw, relPath));
  return diagnostics;
}
var ORPHANED_STUB_DETAIL = "inferenceProcessed stub with no derived sibling";
function memoryOrphanStubApplies(data, body) {
  return data.inferenceProcessed === true && body.trim().length < 100;
}
async function memoryDiagnostics(relPath, data, body, ctx) {
  if (!memoryOrphanStubApplies(data, body))
    return [];
  const derivedPath = `${relPath.replace(/\.md$/, "")}.derived.md`;
  const sibling = await ctx.readFile(derivedPath);
  if (sibling !== null)
    return [];
  return [{ file: relPath, issue: "orphaned-stub", detail: ORPHANED_STUB_DETAIL, fixed: false }];
}

// src/core/adapter/adapters/akm-metadata.ts
function extractDescriptionFromComments(content) {
  const lines = content.split(/\r?\n/).slice(0, 50);
  const blockStart = lines.findIndex((l) => /^\s*\/\*\*/.test(l));
  if (blockStart >= 0) {
    const desc = [];
    for (let i = blockStart;i < lines.length; i++) {
      const line = lines[i];
      if (i > blockStart && /\*\//.test(line))
        break;
      const cleaned = line.replace(/^\s*\/?\*\*?\s?/, "").replace(/\*\/\s*$/, "").trim();
      if (cleaned)
        desc.push(cleaned);
    }
    if (desc.length > 0)
      return desc.join(" ");
  }
  let start = 0;
  if (lines[0]?.startsWith("#!"))
    start = 1;
  const hashLines = [];
  for (let i = start;i < lines.length; i++) {
    const line = lines[i].trim();
    if (line.startsWith("#") && !line.startsWith("#!")) {
      hashLines.push(line.replace(/^#+\s*/, "").trim());
    } else if (line === "") {} else {
      break;
    }
  }
  if (hashLines.length > 0)
    return hashLines.join(" ");
  return null;
}
function applyFrontmatterDescriptionAndTags(fm, out) {
  const desc = nonEmptyString2(fm.description);
  if (desc && !out.description) {
    out.description = desc;
    out.source = "frontmatter";
    out.confidence = 0.9;
  }
  if (Array.isArray(fm.tags) && fm.tags.length > 0) {
    const fmTags = fm.tags.filter((t) => typeof t === "string" && t.trim().length > 0);
    if (fmTags.length > 0) {
      out.tags = Array.from(new Set([...out.tags ?? [], ...fmTags]));
    }
  }
}
function storedCommandRef(action) {
  return action?.kind === "stored" ? action.ref : undefined;
}
function workflowStepTarget(spec) {
  if (!spec?.uses)
    return;
  if (spec.uses !== "akm/command")
    return spec.uses;
  if (spec.commandMode !== "stored-ref")
    return;
  try {
    return storedCommandRef(parseBuiltinCommandAction(spec.with));
  } catch {
    return;
  }
}
function finalizeHints(out, hints) {
  if (hints.size > 0)
    out.searchHints = Array.from(hints).filter(Boolean);
}
function foldRecognizedMetadata(rendererName, file) {
  const out = {};
  switch (rendererName) {
    case "knowledge-md": {
      try {
        const toc = parseMarkdownToc(file.content());
        if (toc.headings.length > 0)
          out.toc = toc.headings;
      } catch {}
      return out;
    }
    case "lesson-md": {
      try {
        const fm = parseFrontmatter(file.content()).data;
        applyFrontmatterDescriptionAndTags(fm, out);
        const whenToUse = nonEmptyString2(fm.when_to_use);
        if (whenToUse)
          finalizeHints(out, new Set([`when_to_use:${whenToUse}`]));
      } catch {}
      return out;
    }
    case "memory-md": {
      try {
        const fm = parseFrontmatter(file.content()).data;
        applyFrontmatterDescriptionAndTags(fm, out);
        const hints = new Set;
        const source = nonEmptyString2(fm.source);
        if (source)
          hints.add(source);
        const fmObservedAt = nonEmptyString2(fm.observed_at);
        if (fmObservedAt) {
          hints.add(`observed_at:${fmObservedAt}`);
        } else {
          try {
            const isoDate = file.stat().mtime.toISOString().slice(0, 10);
            hints.add(`observed_at:${isoDate}`);
          } catch {}
        }
        const expires = nonEmptyString2(fm.expires);
        if (expires)
          hints.add(`expires:${expires}`);
        if (fm.subjective === true)
          hints.add("subjective");
        finalizeHints(out, hints);
      } catch {}
      return out;
    }
    case "script-source": {
      if (file.ext === ".md")
        return out;
      const commentDesc = extractDescriptionFromComments(file.content());
      if (commentDesc && !out.description) {
        out.description = commentDesc;
        out.source = "comments";
        out.confidence = 0.7;
      }
      return out;
    }
    case "env-file": {
      const keys = scanEnvKeyNames(file.content());
      if (keys.length > 0)
        out.searchHints = keys;
      out.tags = Array.from(new Set([...out.tags ?? [], "env", "secrets"]));
      return out;
    }
    case "secret-file": {
      out.tags = Array.from(new Set([...out.tags ?? [], "secret", "sensitive"]));
      return out;
    }
    case "task-yaml": {
      out.tags = Array.from(new Set([...out.tags ?? [], "task", "scheduled"]));
      try {
        const parsed = parseTaskSource({ yaml: file.content(), filePath: file.absPath, workspaceRoot: file.stashRoot });
        const v4 = parsed.v4;
        const target = v4.target;
        const hints = new Set;
        for (const binding of v4.schedule)
          hints.add(`schedule:${binding.cron}`);
        if (target.kind === "uses") {
          if (target.uses.kind === "workflow")
            hints.add(`workflow:${target.uses.ref}`);
          else if (target.uses.kind === "command")
            hints.add(`prompt:${target.uses.ref}`);
          else if (target.command?.kind === "inline")
            hints.add(`prompt:${target.command.content}`);
          else if (target.command?.kind === "stored")
            hints.add(`prompt:${target.command.ref}`);
          else
            hints.add(`uses:${target.uses.ref}`);
          const used = target.uses.kind !== "builtin-command" ? target.uses.ref : storedCommandRef(target.command);
          if (used)
            out.uses = [used];
        } else {
          hints.add(`run:${target.run}`);
        }
        if (v4.description && !out.description) {
          out.description = v4.description;
          out.source = "task-source";
          out.confidence = 0.9;
        }
        if (v4.tags && v4.tags.length > 0) {
          out.tags = Array.from(new Set([...out.tags ?? [], ...v4.tags]));
        }
        if (v4.when_to_use)
          hints.add(`when_to_use:${v4.when_to_use}`);
        finalizeHints(out, hints);
      } catch {}
      return out;
    }
    case "session-md": {
      try {
        const fm = parseFrontmatter(file.content()).data;
        applyFrontmatterDescriptionAndTags(fm, out);
        out.tags = Array.from(new Set([...out.tags ?? [], "session"]));
        const hints = new Set;
        const harness = nonEmptyString2(fm.harness);
        if (harness)
          hints.add(`harness:${harness}`);
        const project = nonEmptyString2(fm.project);
        if (project)
          hints.add(`project:${project}`);
        const logPath = nonEmptyString2(fm.log_path);
        if (logPath)
          hints.add(`log_path:${logPath}`);
        finalizeHints(out, hints);
      } catch {}
      return out;
    }
    case "fact-md": {
      try {
        const fm = parseFrontmatter(file.content()).data;
        applyFrontmatterDescriptionAndTags(fm, out);
        const tags = new Set([...out.tags ?? [], "fact"]);
        const hints = new Set;
        const category = nonEmptyString2(fm.category);
        if (category) {
          tags.add(category);
          hints.add(`category:${category}`);
        }
        if (fm.pinned === true) {
          tags.add("pinned");
          hints.add("pinned");
        }
        out.tags = Array.from(tags).filter(Boolean);
        finalizeHints(out, hints);
      } catch {}
      return out;
    }
    case "workflow-md": {
      try {
        const result = compileWorkflowSource(file.content(), { path: file.relPath, workspaceRoot: file.stashRoot });
        if (!result.ok)
          return out;
        const plan = result.plan;
        const hints = new Set;
        const uses = new Set;
        if (plan.preamble)
          hints.add(plan.preamble);
        for (const step of plan.steps) {
          hints.add(step.stepId);
          hints.add(workflowStepInstructions(step));
          if (step.gate.criteria[0])
            hints.add(step.gate.criteria[0]);
          const used = workflowStepTarget(step.spec);
          if (used)
            uses.add(used);
        }
        out.searchHints = Array.from(hints).filter(Boolean);
        if (uses.size > 0)
          out.uses = [...uses];
        if (plan.paramSchemas) {
          const parameters = Object.entries(plan.paramSchemas).map(([name, schema]) => {
            const description = schema.description;
            return { name, ...typeof description === "string" && description ? { description } : {} };
          });
          if (parameters.length)
            out.parameters = parameters;
        }
      } catch {}
      return out;
    }
    default:
      return out;
  }
}
function applyFoldedMetadata(entry, folded) {
  if (folded.description && !entry.description) {
    entry.description = folded.description;
    if (folded.source)
      entry.source = folded.source;
    if (folded.confidence !== undefined)
      entry.confidence = folded.confidence;
  }
  if (folded.tags && folded.tags.length > 0) {
    entry.tags = Array.from(new Set([...entry.tags ?? [], ...folded.tags]));
  }
  if (folded.searchHints) {
    entry.searchHints = Array.from(new Set([...entry.searchHints ?? [], ...folded.searchHints])).filter(Boolean);
  }
  if (folded.toc)
    entry.toc = folded.toc;
  if (folded.parameters)
    entry.parameters = folded.parameters;
  if (folded.uses)
    entry.uses = folded.uses;
}

// src/core/adapter/adapters/akm-adapter.ts
function isReservedFileName(name) {
  return RESERVED_FILES.has(name.toLowerCase());
}
var WIKI_INFRA_FILES = new Set(["schema.md", "index.md", "log.md"]);
function akmStashAbstains(root, absPath) {
  const relPath = path22.relative(root, absPath);
  if (!relPath || relPath.startsWith("..") || path22.isAbsolute(relPath))
    return false;
  const segments = relPath.split(/[\\/]+/).filter(Boolean);
  if (segments.length === 0)
    return false;
  if (segments.length === 1 && segments[0]?.toLowerCase() === "readme.md")
    return true;
  if (segments[0] === "env" && (absPath.endsWith(".env") || path22.basename(absPath) === ".env")) {
    if (fs17.existsSync(absPath.replace(/\.env$/, ".sensitive")))
      return true;
  }
  if (segments[0] === "secrets") {
    if (absPath.endsWith(".sensitive") || absPath.endsWith(".lock"))
      return true;
    if (fs17.existsSync(`${absPath}.sensitive`))
      return true;
  }
  const wikisIdx = segments.indexOf("wikis");
  if (wikisIdx < 0 || wikisIdx + 1 >= segments.length)
    return false;
  const wikiRelativeSegments = segments.slice(wikisIdx + 2);
  return wikiRelativeSegments.length === 1 && WIKI_INFRA_FILES.has(wikiRelativeSegments[0]);
}
function stashDirToType(stashDir) {
  for (const type of placementTypes()) {
    if (stashDirFor(type) === stashDir)
      return type;
  }
  return;
}
var DOCUMENT_JSON_CARRIED_FIELDS = [
  "examples",
  "usage",
  "intent",
  "xrefs",
  "pageKind",
  "whenToUse",
  "toc",
  "parameters",
  "source",
  "category",
  "supersededBy",
  "contradictedBy",
  "run",
  "setup",
  "cwd",
  "wikiRole",
  "sources",
  "evidenceSources",
  "uses",
  "provenance"
];
function indexDocumentFromEntry(entry, base, rendererName) {
  const extras = { renderer: rendererName };
  for (const field of DOCUMENT_JSON_CARRIED_FIELDS) {
    const value = entry[field];
    if (value !== undefined)
      extras[field] = value;
  }
  const doc = {
    ...base,
    name: entry.name,
    documentJson: extras
  };
  if (entry.description !== undefined)
    doc.description = entry.description;
  if (entry.tags !== undefined)
    doc.tags = entry.tags;
  if (entry.content !== undefined)
    doc.content = entry.content;
  if (entry.contentTruncated !== undefined)
    doc.contentTruncated = entry.contentTruncated;
  if (entry.aliases !== undefined)
    doc.aliases = entry.aliases;
  if (entry.searchHints !== undefined)
    doc.searchHints = entry.searchHints;
  if (entry.quality !== undefined)
    doc.quality = entry.quality;
  if (entry.confidence !== undefined)
    doc.confidence = entry.confidence;
  if (entry.beliefState !== undefined)
    doc.beliefState = entry.beliefState;
  if (entry.currentBeliefRefs !== undefined)
    doc.currentBeliefRefs = entry.currentBeliefRefs;
  if (entry.scope !== undefined)
    doc.scope = entry.scope;
  if (entry.captureMode !== undefined)
    doc.captureMode = entry.captureMode;
  if (entry.lessonStrength !== undefined)
    doc.lessonStrength = entry.lessonStrength;
  if (entry.derivedFrom !== undefined)
    doc.derivedFrom = entry.derivedFrom;
  if (hasMarkdownFragmentContent(entry))
    setMarkdownFragmentContent(doc, getMarkdownFragmentContent(entry));
  return doc;
}
function conceptIdForRecognizedType(root, filePath, type) {
  const canonicalName = deriveCanonicalAssetNameFromStashRoot(type, root, filePath);
  if (canonicalName === undefined)
    return;
  const stashDir = stashDirFor(type);
  return stashDir !== undefined ? `${stashDir}/${canonicalName}` : canonicalName;
}
function recognize2(c, file) {
  if (isReservedFileName(file.fileName))
    return null;
  if (akmStashAbstains(c.root, file.absPath))
    return null;
  const match = recognizeMatch(file);
  if (match === null)
    return null;
  const conceptId = conceptIdForRecognizedType(c.root, file.absPath, match.type);
  if (conceptId === undefined)
    return null;
  const stashDir = stashDirFor(match.type);
  const canonicalName = stashDir !== undefined ? conceptId.slice(stashDir.length + 1) : conceptId;
  const dirPath = path22.dirname(file.absPath);
  const entry = {
    name: canonicalName,
    type: match.type,
    quality: "generated",
    confidence: 0.55,
    source: "filename"
  };
  applyPreContributorFields(entry, file.absPath, file, extractPackageMetadata(dirPath));
  applyFoldedMetadata(entry, foldRecognizedMetadata(match.renderer, file));
  applyPostContributorFields(entry, file.absPath, canonicalName, dirPath);
  return indexDocumentFromEntry(entry, {
    ref: `${c.id}//${conceptId}`,
    bundle: c.id,
    component: c.id,
    conceptId,
    path: file.absPath,
    hash: hashContent(file.content()),
    adapterId: "akm",
    type: match.type
  }, match.renderer);
}
function renderExecutionSource(c, file) {
  const document = recognize2(c, file);
  if (document?.type !== "command" && document?.type !== "agent")
    return null;
  if (!document.ref)
    return null;
  const raw = file.content();
  return renderMarkdownExecutionSource({
    kind: document.type === "command" ? "command" : "persona",
    raw,
    identity: {
      ref: document.ref,
      bundle: c.id,
      adapter: "akm",
      file: file.relPath
    },
    defaults: (data) => executionDefaultsFromFrontmatter(data, {
      kind: document.type === "command" ? "command" : "persona",
      allowTopLevelEngine: true,
      toolsKeys: ["tools"]
    })
  });
}
function buildOverlayContext(root, relPathInput, raw) {
  const absPath = path22.join(root, relPathInput);
  const relPath = path22.relative(root, absPath).replace(/\\/g, "/");
  const ext = path22.extname(absPath).toLowerCase();
  const fileName = path22.basename(absPath);
  const parentDirAbs = path22.dirname(absPath);
  const parentDir = path22.basename(parentDirAbs);
  const relDir = path22.dirname(relPath).replace(/\\/g, "/");
  const ancestorDirs = relDir === "." ? [] : relDir.split("/").filter((seg) => seg.length > 0);
  let cachedFrontmatter;
  let frontmatterComputed = false;
  return {
    absPath,
    relPath,
    ext,
    fileName,
    parentDir,
    parentDirAbs,
    ancestorDirs,
    stashRoot: root,
    content: () => raw,
    frontmatter: () => {
      if (!frontmatterComputed) {
        const parsed = parseFrontmatter(raw);
        cachedFrontmatter = Object.keys(parsed.data).length > 0 ? parsed.data : null;
        frontmatterComputed = true;
      }
      return cachedFrontmatter ?? null;
    },
    stat: () => {
      throw new Error("stat() is unavailable in a validate overlay FileContext");
    }
  };
}
async function validate2(c, changes, ctx) {
  const diagnostics = [];
  const seenSkillDirs = new Set;
  for (const change of changes) {
    if (change.op === "delete")
      continue;
    const raw = change.after ?? await ctx.readFile(change.path);
    if (typeof raw !== "string")
      continue;
    const overlay = buildOverlayContext(c.root, change.path, raw);
    const match = recognizeMatch(overlay);
    const type = match?.type;
    if (type === "workflow" && overlay.ext === ".yml") {
      diagnostics.push(...workflowYamlSourceDiagnostics(change.path, raw, change.path, c.root).errors);
      continue;
    }
    let parsed;
    if (type === "task") {
      parsed = { data: {}, content: raw, frontmatter: null };
    } else {
      const p = parseFrontmatter(raw);
      parsed = { data: p.data, content: p.content, frontmatter: p.frontmatter };
    }
    diagnostics.push(...await runBaseValidateChecks(change.path, parsed, c.root, ctx));
    diagnostics.push(...await perTypeValidateChecks({
      type,
      relPath: change.path,
      raw,
      data: parsed.data,
      frontmatter: parsed.frontmatter,
      body: parsed.content,
      ext: overlay.ext,
      ctx,
      workspaceRoot: c.root
    }));
    diagnostics.push(...await skillDirectoryDiagnostics(change.path, seenSkillDirs, ctx));
  }
  return diagnostics;
}
var akmAdapter = {
  id: "akm",
  version: "0.9.0",
  extensions: [
    ".md",
    ".yaml",
    ".yml",
    ".env",
    ".sh",
    ".ts",
    ".js",
    ".ps1",
    ".cmd",
    ".bat",
    ".py",
    ".rb",
    ".go",
    ".pl",
    ".php",
    ".lua",
    ".r",
    ".swift",
    ".kt",
    ".kts"
  ],
  recognize: recognize2,
  renderExecutionSource,
  validate: validate2,
  readCandidates(c, conceptId) {
    const posix = conceptId.replace(/\\/g, "/");
    const slash = posix.indexOf("/");
    if (slash <= 0)
      return [{ path: path22.join(c.root, `${posix}.md`), conceptId: posix }];
    const head = posix.slice(0, slash);
    const rest = posix.slice(slash + 1);
    const type = stashDirToType(head);
    if (type === undefined || rest.length === 0)
      return [];
    const canonical = assetPathCandidatesForName(type, path22.join(c.root, head), rest);
    const loose = assetPathCandidatesForName(type, c.root, rest);
    return [...new Set([...canonical, ...loose])].map((candidatePath) => ({
      path: candidatePath,
      conceptId: posix
    }));
  },
  placeNew(c, conceptId) {
    const posix = conceptId.replace(/\\/g, "/");
    const slash = posix.indexOf("/");
    if (slash > 0) {
      const head = posix.slice(0, slash);
      const rest = posix.slice(slash + 1);
      const type = stashDirToType(head);
      if (type !== undefined && rest.length > 0) {
        const typeDir = path22.join(c.root, head);
        return assetPathForName(type, typeDir, rest);
      }
    }
    return path22.join(c.root, `${posix}.md`);
  },
  directoryList(_c) {
    return [...new Set(stashDirNames())];
  },
  looksLikeRoot(root) {
    try {
      if (fs17.statSync(path22.join(root, ".stash")).isDirectory())
        return true;
    } catch {}
    const ownedDirNames = new Set(stashDirNames());
    let entries;
    try {
      entries = fs17.readdirSync(root, { withFileTypes: true });
    } catch {
      return false;
    }
    const ownedDirs = entries.filter((entry) => entry.isDirectory() && ownedDirNames.has(entry.name));
    if (ownedDirs.length >= 2)
      return true;
    const only = ownedDirs[0];
    if (!only)
      return false;
    const expectedType = stashDirToType(only.name);
    try {
      const markdown = fs17.readdirSync(path22.join(root, only.name), { withFileTypes: true }).find((entry) => entry.isFile() && entry.name.toLowerCase().endsWith(".md"));
      if (!markdown)
        return true;
      const data = parseFrontmatter(fs17.readFileSync(path22.join(root, only.name, markdown.name), "utf8")).data;
      const declaredType = typeof data.type === "string" ? data.type.trim() : "";
      return !declaredType || declaredType === expectedType;
    } catch {
      return true;
    }
  }
};

// src/core/adapter/adapters/akm-task-adapter.ts
import fs18 from "node:fs";
import path23 from "node:path";
var COMPONENT_ID2 = "main";
var TASK_EXT = TASK_EXTENSION;
function recognize3(c, file) {
  if (file.ext !== TASK_EXT)
    return null;
  const conceptId = toPosix(file.relPath).replace(/\.yml$/i, "");
  const name = conceptId.split("/").pop() ?? conceptId;
  const raw = file.content();
  return {
    ref: `${c.id}//${conceptId}`,
    bundle: c.id,
    component: COMPONENT_ID2,
    conceptId,
    path: file.absPath,
    hash: hashContent(raw),
    adapterId: "akm-task",
    type: "task",
    name,
    content: raw
  };
}
async function validate3(c, changes, ctx) {
  const diagnostics = [];
  for (const change of changes) {
    if (change.op === "delete")
      continue;
    const raw = change.after ?? await ctx.readFile(change.path);
    if (typeof raw !== "string")
      continue;
    const ext = path23.extname(change.path).toLowerCase();
    if (ext !== TASK_EXT && ext !== TASK_NEAR_MISS_EXTENSION)
      continue;
    const relPath = toPosix(change.path);
    if (ext === TASK_NEAR_MISS_EXTENSION) {
      diagnostics.push({
        file: relPath,
        issue: "invalid-task-yaml",
        detail: taskExtensionDetail(relPath),
        fixed: false
      });
      continue;
    }
    try {
      parseTaskSource({ yaml: raw, filePath: relPath, workspaceRoot: c.root });
    } catch (cause) {
      diagnostics.push({
        file: relPath,
        issue: "invalid-task-yaml",
        detail: taskSourceErrorDetail(cause),
        fixed: false
      });
    }
  }
  return diagnostics;
}
var akmTaskAdapter = {
  id: "akm-task",
  version: "0.9.2",
  extensions: [TASK_EXT, TASK_NEAR_MISS_EXTENSION],
  recognize: recognize3,
  validate: validate3,
  readCandidates(c, conceptId) {
    const posix = toPosix(conceptId).replace(/\.ya?ml$/i, "");
    return [
      { path: path23.join(c.root, `${posix}.yml`), conceptId: posix },
      { path: path23.join(c.root, `${posix}.yaml`), conceptId: posix }
    ];
  },
  placeNew(c, conceptId) {
    const posix = toPosix(conceptId);
    return path23.join(c.root, /\.yml$/i.test(posix) ? posix : `${posix}.yml`);
  },
  directoryList() {
    return ["."];
  },
  looksLikeRoot(root) {
    let entries;
    try {
      entries = fs18.readdirSync(root, { withFileTypes: true });
    } catch {
      return false;
    }
    for (const entry of entries) {
      if (!entry.isFile() || path23.extname(entry.name).toLowerCase() !== TASK_EXT)
        continue;
      let raw;
      try {
        raw = fs18.readFileSync(path23.join(root, entry.name), "utf8");
      } catch {
        continue;
      }
      try {
        parseTaskSource({ yaml: raw, filePath: entry.name, workspaceRoot: root });
        return true;
      } catch {
        if (isLegacyTaskDocument(raw, entry.name))
          return true;
      }
    }
    return false;
  }
};
var LEGACY_TASK_TARGET_KEYS = {
  2: ["workflow", "prompt", "command"],
  3: ["uses", "run"]
};
function isLegacyTaskDocument(yaml, filePath) {
  let root;
  try {
    root = readBoundedTaskSourceYaml({ yaml, filePath }, { sourceLabel: "task source" }).root;
  } catch {
    return false;
  }
  const keys = LEGACY_TASK_TARGET_KEYS[peekTaskSourceVersion(root) ?? 0];
  return keys !== undefined && keys.some((key) => Object.hasOwn(root, key));
}

// src/core/adapter/adapters/akm-workflow-adapter.ts
import fs19 from "node:fs";
import path24 from "node:path";
var COMPONENT_ID3 = "main";
var WORKFLOW_EXTS = new Set([".md", ".yml"]);
function conceptIdOf(relPath) {
  return toPosix(relPath).replace(/\.(?:md|yml)$/i, "");
}
function isReservedDocFile(fileName) {
  return fileName.toLowerCase() === "readme.md";
}
function isWorkflowFile(raw) {
  const data = parseFrontmatter(raw).data;
  const type = data.type;
  return type === undefined || type === "workflow";
}
function recognize4(c, file) {
  if (!WORKFLOW_EXTS.has(file.ext))
    return null;
  if (isReservedDocFile(file.fileName))
    return null;
  const raw = file.content();
  if (file.ext === ".md" && !isWorkflowFile(raw))
    return null;
  const conceptId = conceptIdOf(file.relPath);
  const name = conceptId.split("/").pop() ?? conceptId;
  const parsed = parseFrontmatter(raw);
  const description = file.ext === ".md" ? nonEmptyString2(parsed.data.description) : undefined;
  const body = file.ext === ".md" ? parsed.content : raw;
  const tags = file.ext === ".md" ? readTags(parsed.data.tags) : undefined;
  const doc = {
    ref: `${c.id}//${conceptId}`,
    bundle: c.id,
    component: COMPONENT_ID3,
    conceptId,
    path: file.absPath,
    hash: hashContent(raw),
    adapterId: "akm-workflow",
    type: "workflow",
    name,
    content: body
  };
  if (description !== undefined)
    doc.description = description;
  if (tags !== undefined)
    doc.tags = tags;
  return doc;
}
async function validate4(c, changes, ctx) {
  const diagnostics = [];
  for (const change of changes) {
    if (change.op === "delete")
      continue;
    const raw = change.after ?? await ctx.readFile(change.path);
    if (typeof raw !== "string")
      continue;
    const ext = path24.extname(change.path).toLowerCase();
    if (!WORKFLOW_EXTS.has(ext) || isReservedDocFile(path24.basename(change.path)))
      continue;
    const relPath = toPosix(change.path);
    if (ext === ".yml") {
      diagnostics.push(...workflowYamlSourceDiagnostics(relPath, raw, relPath, c.root).errors);
      continue;
    }
    if (!isWorkflowFile(raw))
      continue;
    const p = parseFrontmatter(raw);
    const parsed = { data: p.data, content: p.content, frontmatter: p.frontmatter };
    diagnostics.push(...await runBaseValidateChecks(relPath, parsed, c.root, ctx));
    diagnostics.push(...await perTypeValidateChecks({
      type: "workflow",
      relPath,
      raw,
      data: parsed.data,
      frontmatter: parsed.frontmatter,
      body: parsed.content,
      ext,
      ctx
    }));
  }
  return diagnostics;
}
function hasTopLevelWorkflowFile(root, entries) {
  for (const entry of entries) {
    if (!entry.isFile())
      continue;
    const ext = path24.extname(entry.name).toLowerCase();
    if (!WORKFLOW_EXTS.has(ext) || isReservedDocFile(entry.name))
      continue;
    let raw;
    try {
      raw = fs19.readFileSync(path24.join(root, entry.name), "utf8");
    } catch {
      continue;
    }
    if (ext === ".yml" && looksLikeGithubWorkflowSource(raw))
      return true;
    if (ext === ".md" && parseFrontmatter(raw).data.type === "workflow")
      return true;
  }
  return false;
}
var akmWorkflowAdapter = {
  id: "akm-workflow",
  version: "0.9.2",
  extensions: [".md", ".yml"],
  recognize: recognize4,
  validate: validate4,
  readCandidates(c, conceptId) {
    const posix = toPosix(conceptId);
    const canonical = posix.replace(/\.(?:md|yml)$/i, "");
    return /\.(?:md|yml)$/i.test(posix) ? [{ path: path24.join(c.root, posix), conceptId: canonical }] : [
      { path: path24.join(c.root, `${posix}.md`), conceptId: canonical },
      { path: path24.join(c.root, `${posix}.yml`), conceptId: canonical }
    ];
  },
  placeNew(c, conceptId) {
    const posix = toPosix(conceptId);
    if (/\.(?:md|yml)$/i.test(posix))
      return path24.join(c.root, posix);
    return path24.join(c.root, `${posix}.md`);
  },
  directoryList() {
    return ["."];
  },
  looksLikeRoot(root) {
    let entries;
    try {
      entries = fs19.readdirSync(root, { withFileTypes: true });
    } catch {
      return false;
    }
    return hasTopLevelWorkflowFile(root, entries);
  }
};

// src/core/adapter/adapters/claude-adapter.ts
import fs20 from "node:fs";
import path26 from "node:path";

// src/core/adapter/adapters/tool-dir-shared.ts
import path25 from "node:path";
var CANONICAL_COMMAND_DIR = "commands";
var CANONICAL_AGENT_DIR = "agents";
var CANONICAL_SKILL_DIR = "skills";
var SKILL_MANIFEST2 = "SKILL.md";
function isReserved(base) {
  return RESERVED_FILES.has(base.toLowerCase());
}
function classify(relPath, layout) {
  const posix = toPosix(relPath);
  const segs = posix.split("/").filter((s) => s.length > 0);
  if (segs.length === 0)
    return null;
  const base = segs[segs.length - 1];
  if (isReserved(base))
    return null;
  if (segs.length === 1 && base === layout.instructionFile) {
    return { type: "instruction", conceptId: layout.instructionConceptId, name: layout.instructionConceptId };
  }
  const head = segs[0];
  const ext = path25.extname(base).toLowerCase();
  if (layout.skillDirs.has(head)) {
    if (segs.length === 3 && base === SKILL_MANIFEST2) {
      return { type: "skill", conceptId: `${segs[0]}/${segs[1]}`, name: segs[1] };
    }
    return null;
  }
  if (layout.commandDirs.has(head) && ext === ".md" && segs.length >= 2) {
    return { type: "command", conceptId: posix.replace(/\.md$/i, ""), name: base.replace(/\.md$/i, "") };
  }
  if (layout.agentDirs.has(head) && ext === ".md" && segs.length >= 2) {
    return { type: "agent", conceptId: posix.replace(/\.md$/i, ""), name: base.replace(/\.md$/i, "") };
  }
  return null;
}
function recognizeToolDir(layout, c, file) {
  const cls = classify(file.relPath, layout);
  if (cls === null)
    return null;
  const raw = file.content();
  const parsed = parseFrontmatter(raw);
  const data = parsed.data;
  const body = parsed.content;
  const name = cls.type === "skill" ? nonEmptyString2(data.name) ?? cls.name : cls.name;
  const description = nonEmptyString2(data.description);
  const tags = readTags(data.tags);
  const doc = {
    ref: `${c.id}//${cls.conceptId}`,
    bundle: c.id,
    component: layout.componentId,
    conceptId: cls.conceptId,
    path: file.absPath,
    hash: hashContent(raw),
    adapterId: layout.adapterId,
    type: cls.type,
    name,
    content: body
  };
  if (cls.type === "instruction")
    doc.ownsPresentation = true;
  if (description !== undefined)
    doc.description = description;
  if (tags !== undefined)
    doc.tags = tags;
  return doc;
}
function placeNewToolDir(layout, c, conceptId) {
  const posix = toPosix(conceptId);
  if (posix === layout.instructionConceptId)
    return path25.join(c.root, layout.instructionFile);
  const segs = posix.split("/").filter((s) => s.length > 0);
  const head = segs[0];
  const rest = segs.slice(1).join("/");
  if (rest.length > 0) {
    if (layout.skillDirs.has(head))
      return path25.join(c.root, CANONICAL_SKILL_DIR, rest, SKILL_MANIFEST2);
    if (layout.commandDirs.has(head))
      return path25.join(c.root, CANONICAL_COMMAND_DIR, `${rest}.md`);
    if (layout.agentDirs.has(head))
      return path25.join(c.root, CANONICAL_AGENT_DIR, `${rest}.md`);
  }
  return path25.join(c.root, `${posix}.md`);
}
function readCandidatesToolDir(layout, c, conceptId) {
  const posix = toPosix(conceptId);
  if (posix === layout.instructionConceptId) {
    return [{ path: path25.join(c.root, layout.instructionFile), conceptId: posix }];
  }
  const segs = posix.split("/").filter((segment) => segment.length > 0);
  const head = segs[0];
  const rest = segs.slice(1).join("/");
  if (!head || !rest)
    return [];
  if (layout.skillDirs.has(head)) {
    return segs.length === 2 ? [{ path: path25.join(c.root, head, rest, SKILL_MANIFEST2), conceptId: posix }] : [];
  }
  if (layout.commandDirs.has(head) || layout.agentDirs.has(head)) {
    return [{ path: path25.join(c.root, head, `${rest}.md`), conceptId: posix }];
  }
  return [];
}
function nameOrSignalDiagnostics(type, relPath, data, body) {
  if (nonEmptyString2(data.name) !== undefined || nonEmptyString2(data.description) !== undefined)
    return [];
  if (type === "command" && (/\$ARGUMENTS\b/.test(body) || /\$\d/.test(body) || nonEmptyString2(data.agent) !== undefined)) {
    return [];
  }
  return [
    {
      file: relPath,
      issue: "missing-name-or-type",
      detail: `${type} has neither a name/description nor a ${type}-shaped signal`,
      fixed: false
    }
  ];
}
async function validateToolDir(layout, c, changes, ctx) {
  const diagnostics = [];
  const seenSkillDirs = new Set;
  for (const change of changes) {
    if (change.op === "delete")
      continue;
    const raw = change.after ?? await ctx.readFile(change.path);
    if (typeof raw !== "string")
      continue;
    const relPath = toPosix(change.path);
    diagnostics.push(...await skillDirectoryDiagnostics(relPath, seenSkillDirs, ctx, layout.skillDirs));
    const cls = classify(change.path, layout);
    if (cls === null)
      continue;
    if (cls.type === "instruction") {
      diagnostics.push(...await runBaseValidateChecks(relPath, parseFrontmatter(raw), c.root, ctx));
    } else if (cls.type === "command" || cls.type === "agent") {
      const parsed = parseFrontmatter(raw);
      diagnostics.push(...nameOrSignalDiagnostics(cls.type, relPath, parsed.data, parsed.content));
    }
  }
  return diagnostics;
}
function nativeExecutionExtensions(layout, cls, data) {
  const values = {};
  if (layout.adapterId === "claude" && cls.type === "command" && Object.hasOwn(data, "argument-hint")) {
    if (typeof data["argument-hint"] !== "string") {
      throw new TypeError("frontmatter.argument-hint must be a string");
    }
    values.argumentHint = data["argument-hint"];
  }
  if (layout.adapterId === "opencode" && Object.hasOwn(data, "mode")) {
    if (typeof data.mode !== "string")
      throw new TypeError("frontmatter.mode must be a string");
    values.mode = data.mode;
  }
  return Object.keys(values).length > 0 ? createAdapterExtensions(layout.adapterId, values) : undefined;
}
function renderToolDirExecutionSource(layout, c, file) {
  const cls = classify(file.relPath, layout);
  if (cls?.type !== "command" && cls?.type !== "agent")
    return null;
  const raw = file.content();
  return renderMarkdownExecutionSource({
    kind: cls.type === "command" ? "command" : "persona",
    raw,
    identity: {
      ref: `${c.id}//${cls.conceptId}`,
      bundle: c.id,
      adapter: layout.adapterId,
      file: file.relPath
    },
    defaults: (data) => executionDefaultsFromFrontmatter(data, {
      kind: cls.type === "command" ? "command" : "persona",
      toolsKeys: layout.adapterId === "claude" && cls.type === "command" ? ["allowed-tools", "tools"] : ["tools"]
    }),
    extensions: (data) => nativeExecutionExtensions(layout, cls, data)
  });
}
function makeToolDirAdapter(layout, looksLikeRoot) {
  return {
    id: layout.adapterId,
    version: "0.9.0",
    extensions: [".md"],
    recognize: (c, file) => recognizeToolDir(layout, c, file),
    renderExecutionSource: (c, file) => renderToolDirExecutionSource(layout, c, file),
    validate: (c, changes, ctx) => validateToolDir(layout, c, changes, ctx),
    readCandidates: (c, conceptId) => readCandidatesToolDir(layout, c, conceptId),
    placeNew: (c, conceptId) => placeNewToolDir(layout, c, conceptId),
    directoryList: () => [CANONICAL_COMMAND_DIR, CANONICAL_AGENT_DIR, CANONICAL_SKILL_DIR],
    looksLikeRoot
  };
}

// src/core/adapter/adapters/claude-adapter.ts
var LAYOUT = {
  adapterId: "claude",
  componentId: ".claude",
  instructionFile: "CLAUDE.md",
  instructionConceptId: "CLAUDE",
  commandDirs: new Set(["commands"]),
  agentDirs: new Set(["agents"]),
  skillDirs: new Set(["skills"])
};
function dirExists(p) {
  try {
    return fs20.statSync(p).isDirectory();
  } catch {
    return false;
  }
}
function claudeLooksLikeRoot(root) {
  try {
    if (!fs20.existsSync(path26.join(root, "CLAUDE.md")))
      return false;
  } catch {
    return false;
  }
  return ["commands", "agents", "skills"].some((d) => dirExists(path26.join(root, d)));
}
var claudeAdapter = makeToolDirAdapter(LAYOUT, claudeLooksLikeRoot);

// src/core/adapter/adapters/dotenv-adapter.ts
import fs21 from "node:fs";
import path27 from "node:path";
var COMPONENT_ID4 = "main";
var ENV_DIR = "env";
var SECRETS_DIR = "secrets";
var SECRET_SKIP_SUFFIXES = [".lock", ".sensitive"];
function classify2(relPath) {
  const posix = toPosix(relPath);
  const segs = posix.split("/").filter((s) => s.length > 0);
  if (segs.length < 2)
    return null;
  const head = segs[0];
  const base = segs[segs.length - 1];
  if (head === ENV_DIR) {
    return base === ".env" || base.endsWith(".env") ? "env" : null;
  }
  if (head === SECRETS_DIR) {
    return SECRET_SKIP_SUFFIXES.some((s) => base.endsWith(s)) ? null : "secret";
  }
  return null;
}
function hasSensitiveMarker(absPath, type) {
  const marker = type === "env" ? absPath.replace(/\.env$/i, ".sensitive") : `${absPath}.sensitive`;
  return marker !== absPath && fs21.existsSync(marker);
}
function conceptIdForPath(type, relativePath) {
  const posix = toPosix(relativePath);
  if (type === "secret")
    return posix;
  const stripped = posix.replace(/\.env$/i, "");
  return stripped.endsWith("/") ? `${stripped}default` : stripped;
}
function recognize5(c, file) {
  const type = classify2(file.relPath);
  if (type === null)
    return null;
  if (hasSensitiveMarker(file.absPath, type))
    return null;
  const posix = toPosix(file.relPath);
  const raw = file.content();
  if (type === "env") {
    const conceptId = conceptIdForPath(type, posix);
    const name2 = (conceptId.split("/").pop() ?? conceptId) || "default";
    const keys = scanEnvKeyNames(raw);
    const doc = {
      ref: `${c.id}//${conceptId}`,
      bundle: c.id,
      component: COMPONENT_ID4,
      conceptId,
      path: file.absPath,
      hash: hashContent(raw),
      adapterId: "dotenv",
      type: "env",
      name: name2
    };
    if (keys.length > 0)
      doc.hints = keys;
    return doc;
  }
  const name = posix.split("/").pop() ?? posix;
  return {
    ref: `${c.id}//${posix}`,
    bundle: c.id,
    component: COMPONENT_ID4,
    conceptId: posix,
    path: file.absPath,
    hash: hashContent(raw),
    adapterId: "dotenv",
    type: "secret",
    name
  };
}
async function validate5(_c, changes, ctx) {
  const diagnostics = [];
  for (const change of changes) {
    if (change.op === "delete")
      continue;
    const raw = change.after ?? await ctx.readFile(change.path);
    if (typeof raw !== "string")
      continue;
    const type = classify2(change.path);
    if (type === null)
      continue;
    diagnostics.push(...dangerousEnvKeyDiagnostics(type, toPosix(change.path), raw));
  }
  return diagnostics;
}
var dotenvAdapter = {
  id: "dotenv",
  version: "0.9.0",
  extensions: [".env"],
  recognize: recognize5,
  validate: validate5,
  readCandidates(c, conceptId) {
    const posix = toPosix(conceptId);
    const slash = posix.indexOf("/");
    if (slash <= 0)
      return [];
    const head = posix.slice(0, slash);
    const rest = posix.slice(slash + 1);
    const type = typeForStashDir(head);
    if (type !== "env" && type !== "secret" || rest.length === 0)
      return [];
    const primaries = assetPathCandidatesForName(type, path27.join(c.root, head), rest);
    const expanded = primaries.flatMap((primary) => type === "env" ? [primary, primary.replace(/\.env$/i, ".sensitive")] : [primary, `${primary}.sensitive`, `${primary}.lock`]);
    return expanded.map((candidatePath) => ({ path: candidatePath, conceptId: posix }));
  },
  placeNew(c, conceptId) {
    const posix = toPosix(conceptId);
    const slash = posix.indexOf("/");
    if (slash > 0) {
      const head = posix.slice(0, slash);
      const rest = posix.slice(slash + 1);
      const type = typeForStashDir(head);
      if ((type === "env" || type === "secret") && rest.length > 0) {
        return assetPathForName(type, path27.join(c.root, head), rest);
      }
    }
    return path27.join(c.root, posix);
  },
  directoryList() {
    return [ENV_DIR, SECRETS_DIR];
  },
  looksLikeRoot(root) {
    let entries;
    try {
      entries = fs21.readdirSync(root, { withFileTypes: true });
    } catch {
      return false;
    }
    const dirs = entries.filter((e) => e.isDirectory()).map((e) => e.name);
    if (dirs.length === 0)
      return false;
    if (!dirs.every((d) => d === ENV_DIR || d === SECRETS_DIR))
      return false;
    return dirs.includes(ENV_DIR) || dirs.includes(SECRETS_DIR);
  }
};

// src/core/adapter/adapters/generic-files-adapter.ts
import path28 from "node:path";
var COMPONENT_ID5 = "main";
var DOCUMENT_EXTENSIONS = new Set([".md", ".markdown", ".txt", ".text"]);
function isReserved2(base) {
  return RESERVED_FILES.has(base.toLowerCase());
}
function classify3(ext) {
  if (SCRIPT_EXTENSIONS.has(ext))
    return "script";
  if (DOCUMENT_EXTENSIONS.has(ext))
    return "document";
  return "file";
}
function recognize6(c, file) {
  const posix = toPosix(file.relPath);
  const base = posix.split("/").pop() ?? posix;
  if (isReserved2(base))
    return null;
  const type = classify3(file.ext);
  const conceptId = type === "document" ? posix.replace(/\.[^./]+$/, "") : posix;
  const name = conceptId.split("/").pop() ?? conceptId;
  const raw = file.content();
  const parsed = parseFrontmatter(raw);
  const body = parsed.content;
  const doc = {
    ref: `${c.id}//${conceptId}`,
    bundle: c.id,
    component: COMPONENT_ID5,
    conceptId,
    path: file.absPath,
    hash: hashContent(raw),
    adapterId: "generic-files",
    type,
    name,
    content: body
  };
  if (type !== "script")
    doc.ownsPresentation = true;
  const description = nonEmptyString2(parsed.data.description);
  if (description !== undefined)
    doc.description = description;
  const tags = readTags(parsed.data.tags);
  if (tags !== undefined)
    doc.tags = tags;
  return doc;
}
async function validate6(c, changes, ctx) {
  const diagnostics = [];
  for (const change of changes) {
    if (change.op === "delete")
      continue;
    const raw = change.after ?? await ctx.readFile(change.path);
    if (typeof raw !== "string")
      continue;
    diagnostics.push(...await runBaseValidateChecks(toPosix(change.path), parseFrontmatter(raw), c.root, ctx));
  }
  return diagnostics;
}
var genericFilesAdapter = {
  id: "generic-files",
  version: "0.9.0",
  extensions: [".md", ".txt"],
  recognize: recognize6,
  validate: validate6,
  readCandidates(c, conceptId) {
    const posix = toPosix(conceptId);
    const extension = path28.extname(posix).toLowerCase();
    const documentCandidates = [...DOCUMENT_EXTENSIONS].map((candidateExtension) => ({
      path: path28.join(c.root, `${posix}${candidateExtension}`),
      conceptId: posix
    }));
    return DOCUMENT_EXTENSIONS.has(extension) ? documentCandidates : [{ path: path28.join(c.root, posix), conceptId: posix }, ...documentCandidates];
  },
  placeNew(c, conceptId) {
    const posix = toPosix(conceptId);
    const hasExt = path28.extname(posix) !== "";
    return path28.join(c.root, hasExt ? posix : `${posix}.md`);
  },
  looksLikeRoot() {
    return false;
  }
};

// src/core/adapter/adapters/llm-wiki-adapter.ts
import fs22 from "node:fs";
import path29 from "node:path";
var WIKI_COMPONENT_ID = "main";
var WIKI_SOURCE_TYPE = "wiki-source";
var DEFAULT_PAGE_KIND = "note";
var RESERVED_ROOT_FILES = new Set(["schema.md", "index.md", "log.md"]);
var RAW_SUBDIR = "raw";
var PAGES_SUBDIR = "pages";
function conceptIdOf2(relPath) {
  return toPosix(relPath).replace(/\.md$/i, "");
}
function parseWikiFrontmatter(raw) {
  const out = { xrefs: [], sources: [] };
  const block = parseFrontmatterBlock(raw);
  let data = {};
  if (block) {
    try {
      const value = $parse(block.frontmatter);
      if (value && typeof value === "object" && !Array.isArray(value)) {
        data = value;
      }
    } catch {
      try {
        data = parseFrontmatter(raw).data;
      } catch {
        data = {};
      }
    }
  }
  out.description = nonEmptyString2(data.description);
  out.pageKind = nonEmptyString2(data.pageKind);
  out.wikiRole = nonEmptyString2(data.wikiRole);
  if (Array.isArray(data.xrefs)) {
    out.xrefs = data.xrefs.filter((x) => typeof x === "string" && x.trim().length > 0).map((x) => x.trim());
  }
  if (Array.isArray(data.sources)) {
    out.sources = data.sources.filter((s) => typeof s === "string" && s.trim().length > 0).map((s) => s.trim());
  }
  return out;
}
function isReservedRootFile(relPath) {
  const posix = toPosix(relPath);
  if (posix.includes("/"))
    return false;
  return RESERVED_ROOT_FILES.has(posix.toLowerCase());
}
function firstSegment(relPath) {
  const posix = toPosix(relPath);
  const slash = posix.indexOf("/");
  return slash < 0 ? posix : posix.slice(0, slash);
}
function resolveXref(xref, bundleId) {
  const prefix = `wiki:${bundleId}/`;
  if (!xref.startsWith(prefix))
    return null;
  const target = xref.slice(prefix.length).replace(/\.md$/i, "");
  return target.length > 0 ? target : null;
}
function resolveBodyLinks(body, fileRelPath) {
  const dir = path29.posix.dirname(toPosix(fileRelPath));
  const linkRe = /\[[^\]]*\]\(([^)]+)\)/g;
  const out = [];
  const seen = new Set;
  let match;
  while ((match = linkRe.exec(body)) !== null) {
    let target = match[1].trim();
    const wsIdx = target.search(/\s/);
    if (wsIdx >= 0)
      target = target.slice(0, wsIdx);
    const hashIdx = target.indexOf("#");
    if (hashIdx >= 0)
      target = target.slice(0, hashIdx);
    const queryIdx = target.indexOf("?");
    if (queryIdx >= 0)
      target = target.slice(0, queryIdx);
    if (!target)
      continue;
    if (/^[a-z][a-z0-9+.-]*:/i.test(target))
      continue;
    if (target.startsWith("//"))
      continue;
    if (!target.toLowerCase().endsWith(".md"))
      continue;
    let resolved;
    if (target.startsWith("/")) {
      resolved = path29.posix.normalize(target.slice(1));
    } else {
      const base = dir === "." ? "" : dir;
      resolved = path29.posix.normalize(path29.posix.join(base, target));
    }
    if (resolved.startsWith("../") || resolved === ".." || resolved.startsWith("/"))
      continue;
    const conceptId = resolved.replace(/\.md$/i, "");
    if (!conceptId || seen.has(conceptId))
      continue;
    seen.add(conceptId);
    out.push(conceptId);
  }
  return out;
}
function resolvePageLinks(fm, body, fileRelPath, bundleId) {
  const out = [];
  const seen = new Set;
  const push = (conceptId) => {
    if (conceptId.length > 0 && !seen.has(conceptId)) {
      seen.add(conceptId);
      out.push(conceptId);
    }
  };
  for (const xref of fm.xrefs) {
    const resolved = resolveXref(xref, bundleId);
    if (resolved !== null)
      push(resolved);
  }
  for (const link of resolveBodyLinks(body, fileRelPath))
    push(link);
  return out;
}
function resolveSources(fm) {
  const out = [];
  const seen = new Set;
  for (const src of fm.sources) {
    const match = src.match(/^raw\/([^/\s]+?)(?:\.md)?$/i);
    if (!match)
      continue;
    const conceptId = `raw/${match[1]}`;
    if (!seen.has(conceptId)) {
      seen.add(conceptId);
      out.push(conceptId);
    }
  }
  return out;
}
function recognize7(c, file) {
  if (file.ext !== ".md")
    return null;
  const relPath = toPosix(file.relPath);
  if (isReservedRootFile(relPath))
    return null;
  const head = firstSegment(relPath);
  const isRaw = head === RAW_SUBDIR && relPath.includes("/");
  const isPage = head === PAGES_SUBDIR && relPath.includes("/");
  if (!isRaw && !isPage)
    return null;
  const conceptId = conceptIdOf2(relPath);
  const lastSegment = conceptId.split("/").pop() ?? conceptId;
  const raw = file.content();
  const fm = parseWikiFrontmatter(raw);
  const body = parseFrontmatter(raw).content;
  const doc = {
    ref: `${c.id}//${conceptId}`,
    bundle: c.id,
    component: WIKI_COMPONENT_ID,
    conceptId,
    path: file.absPath,
    hash: hashContent(raw),
    adapterId: "llm-wiki",
    ownsPresentation: true,
    type: isRaw ? WIKI_SOURCE_TYPE : fm.pageKind ?? DEFAULT_PAGE_KIND,
    name: lastSegment,
    content: body
  };
  if (fm.description !== undefined)
    doc.description = fm.description;
  if (isPage) {
    const links = resolvePageLinks(fm, body, relPath, c.id);
    if (links.length > 0)
      doc.links = links;
    const sources = resolveSources(fm);
    const extras = { pageKind: fm.pageKind ?? DEFAULT_PAGE_KIND, sources };
    if (fm.wikiRole !== undefined)
      extras.wikiRole = fm.wikiRole;
    doc.documentJson = extras;
  } else {
    doc.documentJson = { wikiRole: fm.wikiRole ?? "source" };
  }
  return doc;
}
async function validate7(c, changes, ctx) {
  const items = [];
  for (const change of changes) {
    if (change.op === "delete")
      continue;
    const raw = change.after ?? await ctx.readFile(change.path);
    if (typeof raw !== "string")
      continue;
    const relPath = toPosix(change.path);
    if (isReservedRootFile(relPath))
      continue;
    const head = firstSegment(relPath);
    const isRaw = head === RAW_SUBDIR && relPath.includes("/");
    const isPage = head === PAGES_SUBDIR && relPath.includes("/");
    if (!isRaw && !isPage)
      continue;
    items.push({
      relPath,
      conceptId: conceptIdOf2(relPath),
      kind: isRaw ? "raw" : "page",
      fm: parseWikiFrontmatter(raw),
      body: parseFrontmatter(raw).content
    });
  }
  const existingConceptIds = new Set(items.map((i) => i.conceptId));
  const citedRawConceptIds = new Set;
  for (const item of items) {
    if (item.kind !== "page")
      continue;
    for (const src of resolveSources(item.fm))
      citedRawConceptIds.add(src);
  }
  const diagnostics = [];
  for (const item of items) {
    if (item.kind === "raw") {
      if (!citedRawConceptIds.has(item.conceptId)) {
        diagnostics.push({
          file: item.relPath,
          issue: "uncited-raw",
          detail: `warning: raw source ${item.conceptId} is not cited by any page's sources: frontmatter (non-blocking).`,
          fixed: false
        });
      }
      continue;
    }
    if (item.fm.description === undefined) {
      diagnostics.push({
        file: item.relPath,
        issue: "missing-description",
        detail: "warning: page is missing a frontmatter `description` (non-blocking).",
        fixed: false
      });
    }
    const targets = new Set;
    for (const xref of item.fm.xrefs) {
      const resolved = resolveXref(xref, c.id);
      if (resolved !== null)
        targets.add(resolved);
    }
    for (const link of resolveBodyLinks(item.body, item.relPath))
      targets.add(link);
    for (const target of targets) {
      if (!existingConceptIds.has(target)) {
        diagnostics.push({
          file: item.relPath,
          issue: "broken-xref",
          detail: `warning: cross-reference target not found: ${target} ` + "(non-blocking; cross-references must point at pages that actually exist — wiki schema hard rule).",
          fixed: false
        });
      }
    }
    for (const source of resolveSources(item.fm)) {
      if (!existingConceptIds.has(source)) {
        diagnostics.push({
          file: item.relPath,
          issue: "broken-source",
          detail: `warning: page references missing raw source ${source} (non-blocking).`,
          fixed: false
        });
      }
    }
  }
  return diagnostics;
}
var llmWikiAdapter = {
  id: "llm-wiki",
  version: "0.9.0",
  extensions: [".md"],
  recognize: recognize7,
  validate: validate7,
  readCandidates(c, conceptId) {
    const canonical = toPosix(conceptId).replace(/\.md$/i, "");
    return [{ path: path29.join(c.root, `${canonical}.md`), conceptId: canonical }];
  },
  placeNew(c, conceptId) {
    return path29.join(c.root, `${conceptId}.md`);
  },
  directoryList(_c) {
    return ["."];
  },
  looksLikeRoot(root) {
    try {
      if (!fs22.existsSync(path29.join(root, "schema.md")))
        return false;
      return fs22.statSync(path29.join(root, PAGES_SUBDIR)).isDirectory();
    } catch {
      return false;
    }
  }
};

// src/core/adapter/adapters/okf-adapter.ts
import fs23 from "node:fs";
import path30 from "node:path";
var CONSUMED_FRONTMATTER_KEYS = [
  "type",
  "title",
  "description",
  "tags",
  "timestamp",
  "generated",
  "verified",
  "sources",
  "status",
  "stale_after",
  "okf_version"
];
function parseActorMapping(value) {
  if (!isRecord(value))
    return;
  const by = nonEmptyString2(value.by);
  if (by === undefined)
    return;
  const at = nonEmptyString2(value.at);
  return at !== undefined ? { by, at } : { by };
}
function parseVerified(value) {
  if (value === undefined || value === null)
    return;
  const candidates = Array.isArray(value) ? value : [value];
  const out = [];
  for (const candidate of candidates) {
    const parsed = parseActorMapping(candidate);
    if (parsed)
      out.push(parsed);
  }
  return out.length > 0 ? out : undefined;
}
function parseOkfSources(value) {
  if (!Array.isArray(value))
    return;
  const out = [];
  for (const item of value) {
    if (!isRecord(item))
      continue;
    const resource = nonEmptyString2(item.resource);
    if (resource === undefined)
      continue;
    const entry = { resource };
    const id = nonEmptyString2(item.id);
    if (id !== undefined)
      entry.id = id;
    const title = nonEmptyString2(item.title);
    if (title !== undefined)
      entry.title = title;
    const author = nonEmptyString2(item.author);
    if (author !== undefined)
      entry.author = author;
    if (typeof item.usage_count === "number" && Number.isFinite(item.usage_count)) {
      entry.usage_count = item.usage_count;
    }
    const lastModified = nonEmptyString2(item.last_modified);
    if (lastModified !== undefined)
      entry.last_modified = lastModified;
    out.push(entry);
  }
  return out.length > 0 ? out : undefined;
}
function parseLifecycleStatus(value) {
  return value === "draft" || value === "stable" || value === "deprecated" ? value : undefined;
}
function isReservedFileName2(name) {
  return RESERVED_FILES.has(name.toLowerCase());
}
function resolveOkfLinks(body, fileRelPath) {
  const dir = path30.posix.dirname(toPosix(fileRelPath));
  const definitions = new Map;
  for (const match of body.matchAll(/^\s*\[([^\]]+)\]:\s*(\S+)/gm)) {
    definitions.set(match[1].trim().toLowerCase(), match[2]);
  }
  const candidates = [];
  for (const match of body.matchAll(/\[[^\]]*\]\(([^)]+)\)/g)) {
    candidates.push({ index: match.index, target: match[1] });
  }
  for (const match of body.matchAll(/(?<!!)\[[^\]]*\]\[([^\]]+)\]/g)) {
    const target = definitions.get(match[1].trim().toLowerCase());
    if (target)
      candidates.push({ index: match.index, target });
  }
  candidates.sort((a, b) => a.index - b.index);
  const out = [];
  const seen = new Set;
  for (const candidate of candidates) {
    let target = candidate.target.trim();
    const wsIdx = target.search(/\s/);
    if (wsIdx >= 0)
      target = target.slice(0, wsIdx);
    const hashIdx = target.indexOf("#");
    if (hashIdx >= 0)
      target = target.slice(0, hashIdx);
    const queryIdx = target.indexOf("?");
    if (queryIdx >= 0)
      target = target.slice(0, queryIdx);
    if (!target)
      continue;
    if (/^[a-z][a-z0-9+.-]*:/i.test(target))
      continue;
    if (target.startsWith("//"))
      continue;
    if (!target.toLowerCase().endsWith(".md"))
      continue;
    let resolved;
    if (target.startsWith("/")) {
      resolved = path30.posix.normalize(target.slice(1));
    } else {
      const base = dir === "." ? "" : dir;
      resolved = path30.posix.normalize(path30.posix.join(base, target));
    }
    if (resolved.startsWith("../") || resolved === ".." || resolved.startsWith("/"))
      continue;
    const conceptId = resolved.replace(/\.md$/i, "");
    if (!conceptId || seen.has(conceptId))
      continue;
    seen.add(conceptId);
    out.push(conceptId);
  }
  return out;
}
function recognize8(c, file) {
  if (file.ext !== ".md")
    return null;
  if (isReservedFileName2(file.fileName))
    return null;
  const conceptId = toPosix(file.relPath).replace(/\.md$/i, "");
  const raw = file.content();
  const parsed = parseFrontmatter(raw);
  const data = parsed.data;
  const body = parsed.content;
  const type = nonEmptyString2(data.type) ?? "knowledge";
  const lastSegment = conceptId.split("/").pop() ?? conceptId;
  const name = nonEmptyString2(data.title) ?? lastSegment;
  const description = nonEmptyString2(data.description);
  const tags = readTags(data.tags);
  const links = resolveOkfLinks(body, file.relPath);
  const generatedMapping = isRecord(data.generated) ? data.generated : undefined;
  const generatedAt = generatedMapping ? nonEmptyString2(generatedMapping.at) : undefined;
  const generatedBy = generatedMapping ? nonEmptyString2(generatedMapping.by) : undefined;
  const legacyTimestamp = nonEmptyString2(data.timestamp);
  const updated = generatedAt ?? legacyTimestamp;
  const verified = parseVerified(data.verified);
  const okfSources = parseOkfSources(data.sources);
  const provenance = generatedBy !== undefined || generatedAt !== undefined || verified !== undefined || okfSources !== undefined ? {
    ...generatedBy !== undefined ? { generatedBy } : {},
    ...generatedAt !== undefined ? { generatedAt } : {},
    ...verified !== undefined ? { verified } : {},
    ...okfSources !== undefined ? { sources: okfSources } : {}
  } : undefined;
  const lifecycleStatus = parseLifecycleStatus(data.status);
  const staleAfter = nonEmptyString2(data.stale_after);
  const okfVersion = nonEmptyString2(data.okf_version);
  const doc = {
    ref: `${c.id}//${conceptId}`,
    bundle: c.id,
    component: c.id,
    conceptId,
    path: file.absPath,
    hash: hashContent(raw),
    adapterId: "okf",
    ownsPresentation: true,
    type,
    name,
    content: body
  };
  if (description !== undefined)
    doc.description = description;
  if (tags !== undefined)
    doc.tags = tags;
  if (updated !== undefined)
    doc.updated = updated;
  if (links.length > 0)
    doc.links = links;
  if (provenance !== undefined)
    doc.provenance = provenance;
  if (lifecycleStatus !== undefined)
    doc.lifecycleStatus = lifecycleStatus;
  if (staleAfter !== undefined)
    doc.staleAfter = staleAfter;
  if (okfVersion !== undefined)
    doc.okfVersion = okfVersion;
  const extras = Object.fromEntries(Object.entries(data).filter(([key]) => !CONSUMED_FRONTMATTER_KEYS.includes(key)));
  if (Object.keys(extras).length > 0)
    doc.documentJson = extras;
  return doc;
}
async function validate8(c, changes, ctx) {
  const diagnostics = [];
  for (const change of changes) {
    if (change.op === "delete")
      continue;
    const raw = change.after ?? await ctx.readFile(change.path);
    if (typeof raw !== "string")
      continue;
    const relPath = toPosix(change.path);
    const fileName = relPath.split("/").pop() ?? relPath;
    const reserved = isReservedFileName2(fileName);
    const parsed = parseFrontmatter(raw);
    const base = await runBaseValidateChecks(relPath, parsed, c.root, ctx);
    for (const diag of base) {
      if (diag.issue === "missing-updated")
        continue;
      diagnostics.push(diag);
    }
    if (reserved)
      continue;
    if (nonEmptyString2(parsed.data.type) === undefined) {
      diagnostics.push({
        file: relPath,
        issue: "missing-type",
        detail: "info: no frontmatter `type`; defaults to `knowledge` (OKF leniency, non-blocking)",
        fixed: false
      });
    }
    for (const conceptId of resolveOkfLinks(parsed.content, relPath)) {
      const { exists } = await ctx.resolveRef(conceptId);
      if (!exists) {
        diagnostics.push({
          file: relPath,
          issue: "missing-ref",
          detail: `warning: OKF link target not found: ${conceptId} (non-blocking, consumers tolerate broken links)`,
          fixed: false
        });
      }
    }
  }
  return diagnostics;
}
var okfAdapter = {
  id: "okf",
  version: "0.9.0",
  extensions: [".md"],
  recognize: recognize8,
  validate: validate8,
  readCandidates(c, conceptId) {
    const canonical = conceptId.replace(/\\/g, "/").replace(/\.md$/i, "");
    return [{ path: path30.join(c.root, `${canonical}.md`), conceptId: canonical }];
  },
  directoryList(_c) {
    return ["."];
  },
  looksLikeRoot(root) {
    if (fs23.existsSync(path30.join(root, "index.md")))
      return true;
    const stack = [root];
    while (stack.length > 0) {
      const current = stack.pop();
      if (!current)
        continue;
      let entries;
      try {
        entries = fs23.readdirSync(current, { withFileTypes: true });
      } catch {
        continue;
      }
      for (const entry of entries) {
        if (entry.isSymbolicLink() || entry.name === ".git")
          continue;
        const absolute = path30.join(current, entry.name);
        if (entry.isDirectory()) {
          stack.push(absolute);
          continue;
        }
        if (!entry.isFile() || !entry.name.toLowerCase().endsWith(".md") || isReservedFileName2(entry.name))
          continue;
        const type = nonEmptyString2(parseFrontmatter(fs23.readFileSync(absolute, "utf8")).data.type);
        if (type)
          return true;
      }
    }
    return false;
  }
};

// src/core/adapter/adapters/opencode-adapter.ts
import fs24 from "node:fs";
import path31 from "node:path";
var LAYOUT2 = {
  adapterId: "opencode",
  componentId: ".opencode",
  instructionFile: "AGENTS.md",
  instructionConceptId: "AGENTS",
  commandDirs: new Set(["commands"]),
  agentDirs: new Set(["agents"]),
  skillDirs: new Set(["skills"])
};
var CONFIG_FILES = ["opencode.json", "opencode.jsonc"];
var TOOL_DIRS = ["commands", "agents", "skills"];
function fileExists(p) {
  try {
    return fs24.existsSync(p);
  } catch {
    return false;
  }
}
function dirExists2(p) {
  try {
    return fs24.statSync(p).isDirectory();
  } catch {
    return false;
  }
}
function opencodeLooksLikeRoot(root) {
  if (CONFIG_FILES.some((f) => fileExists(path31.join(root, f))))
    return true;
  if (!fileExists(path31.join(root, "AGENTS.md")))
    return false;
  return TOOL_DIRS.some((d) => dirExists2(path31.join(root, d)));
}
var opencodeAdapter = makeToolDirAdapter(LAYOUT2, opencodeLooksLikeRoot);

// src/core/adapter/adapters/website-snapshot-adapter.ts
import fs25 from "node:fs";
import path32 from "node:path";
var COMPONENT_ID6 = "main";
var PAGES_PREFIX = "stash/knowledge/";
var MANIFEST_FILE = "manifest.json";
var WEBSITE_TAG = "website";
function parseSnapshotFrontmatter(raw) {
  const out = { tags: [] };
  const block = parseFrontmatterBlock(raw);
  if (!block)
    return out;
  let data = {};
  try {
    const value = $parse(block.frontmatter);
    if (value && typeof value === "object" && !Array.isArray(value))
      data = value;
  } catch {
    return out;
  }
  out.title = nonEmptyString2(data.title);
  out.description = nonEmptyString2(data.description);
  out.sourceUrl = nonEmptyString2(data.sourceUrl);
  if (Array.isArray(data.tags)) {
    out.tags = data.tags.filter((t) => typeof t === "string" && t.trim().length > 0).map((t) => t.trim());
  }
  return out;
}
function isSnapshotPage(relPath) {
  const posix = toPosix(relPath);
  return posix.startsWith(PAGES_PREFIX) && posix.toLowerCase().endsWith(".md");
}
function isReTypeGated(fm) {
  return fm.sourceUrl !== undefined || fm.tags.includes(WEBSITE_TAG);
}
function conceptIdOf3(relPath) {
  return toPosix(relPath).slice(PAGES_PREFIX.length).replace(/\.md$/i, "");
}
function recognize9(c, file) {
  if (file.ext !== ".md" || !isSnapshotPage(file.relPath))
    return null;
  const raw = file.content();
  const fm = parseSnapshotFrontmatter(raw);
  if (!isReTypeGated(fm))
    return null;
  const conceptId = conceptIdOf3(file.relPath);
  const name = fm.title ?? conceptId.split("/").pop() ?? conceptId;
  const body = parseFrontmatter(raw).content;
  const doc = {
    ref: `${c.id}//${conceptId}`,
    bundle: c.id,
    component: COMPONENT_ID6,
    conceptId,
    path: file.absPath,
    hash: hashContent(raw),
    adapterId: "website-snapshot",
    ownsPresentation: true,
    type: "website",
    name,
    content: body
  };
  if (fm.description !== undefined)
    doc.description = fm.description;
  if (fm.sourceUrl !== undefined)
    doc.documentJson = { sourceRef: fm.sourceUrl };
  return doc;
}
async function validate9(c, changes, ctx) {
  const diagnostics = [];
  for (const change of changes) {
    if (change.op === "delete")
      continue;
    const raw = change.after ?? await ctx.readFile(change.path);
    if (typeof raw !== "string")
      continue;
    if (!isSnapshotPage(change.path))
      continue;
    const base = await runBaseValidateChecks(toPosix(change.path), parseFrontmatter(raw), c.root, ctx);
    diagnostics.push(...base.filter((d) => d.issue !== "missing-updated"));
  }
  return diagnostics;
}
var websiteSnapshotAdapter = {
  id: "website-snapshot",
  version: "0.9.0",
  extensions: [".md"],
  recognize: recognize9,
  validate: validate9,
  readCandidates(c, conceptId) {
    const canonical = toPosix(conceptId).replace(/\.md$/i, "");
    return [{ path: path32.join(c.root, PAGES_PREFIX, `${canonical}.md`), conceptId: canonical }];
  },
  looksLikeRoot(root) {
    let raw;
    try {
      raw = fs25.readFileSync(path32.join(root, MANIFEST_FILE), "utf8");
    } catch {
      return false;
    }
    try {
      const manifest = JSON.parse(raw);
      return typeof manifest.url === "string" && typeof manifest.fetchedAt === "string";
    } catch {
      return false;
    }
  }
};

// src/core/adapter/adapters/index.ts
var BUILTIN_ADAPTERS = Object.freeze([
  websiteSnapshotAdapter,
  agentSkillsAdapter,
  claudeAdapter,
  opencodeAdapter,
  dotenvAdapter,
  akmWorkflowAdapter,
  akmTaskAdapter,
  llmWikiAdapter,
  akmAdapter,
  okfAdapter,
  genericFilesAdapter
]);
{
  const actualIds = BUILTIN_ADAPTERS.map((a) => a.id);
  const expectedIds = [...ADAPTER_ID_TABLE];
  if (actualIds.length !== expectedIds.length || actualIds.some((id, i) => id !== expectedIds[i])) {
    throw new Error(`adapter-ids.ts ADAPTER_ID_TABLE (${expectedIds.join(", ")}) does not match ` + `BUILTIN_ADAPTERS (${actualIds.join(", ")}) — update adapter-ids.ts to match.`);
  }
}

// src/core/adapter/registry.ts
var BY_ID = new Map(BUILTIN_ADAPTERS.map((a) => [a.id, a]));
function getAdapters() {
  return [...BUILTIN_ADAPTERS];
}
function adapterForId(id) {
  return BY_ID.get(id);
}

// src/sources/include.ts
import fs26 from "node:fs";
import path33 from "node:path";
var INCLUDE_CONFIG_KEYS = ["akm"];
function readPackageJsonAt(dirPath) {
  try {
    const raw = fs26.readFileSync(path33.join(dirPath, "package.json"), "utf8");
    const parsed = JSON.parse(raw);
    if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
      return parsed;
    }
    return;
  } catch {
    return;
  }
}
function extractIncludeList(pkg) {
  if (!pkg)
    return;
  for (const key of INCLUDE_CONFIG_KEYS) {
    const config = pkg[key];
    if (typeof config !== "object" || config === null || Array.isArray(config))
      continue;
    const { include } = config;
    if (!Array.isArray(include))
      continue;
    const list = include.filter((v) => typeof v === "string").map((v) => v.trim()).filter(Boolean);
    if (list.length > 0)
      return list;
  }
  return;
}
function findNearestIncludeConfig(startDir, boundary) {
  let current = path33.resolve(startDir);
  const resolvedBoundary = path33.resolve(boundary);
  while (isWithin(current, resolvedBoundary)) {
    const pkg = readPackageJsonAt(current);
    const include = extractIncludeList(pkg);
    if (include && include.length > 0) {
      return { baseDir: current, include };
    }
    if (current === resolvedBoundary)
      break;
    const parent = path33.dirname(current);
    if (parent === current)
      break;
    current = parent;
  }
  return;
}
function isIncludeEntryPattern(entry) {
  return /[*?]/.test(entry);
}
function includeEntryToRegExp(entry) {
  const normalized = entry.split(path33.sep).join("/");
  let pattern = "";
  for (let i = 0;i < normalized.length; ) {
    if (normalized.startsWith("**", i)) {
      const consumesSlash = normalized[i + 2] === "/";
      pattern += consumesSlash ? "(?:.*/)?" : ".*";
      i += consumesSlash ? 3 : 2;
      continue;
    }
    const char = normalized[i];
    if (char === "*")
      pattern += "[^/]*";
    else if (char === "?")
      pattern += "[^/]";
    else
      pattern += char.replace(/[.+^${}()|[\]\\]/g, "\\$&");
    i += 1;
  }
  return new RegExp(`^${pattern}$`);
}
function isBrokenSymlink(candidate) {
  try {
    return fs26.lstatSync(candidate).isSymbolicLink();
  } catch {
    return false;
  }
}
function listAllRelativePaths(dir, base) {
  const out = [];
  let entries;
  try {
    entries = fs26.readdirSync(dir, { withFileTypes: true });
  } catch {
    return out;
  }
  for (const entry of entries) {
    if (entry.name === ".git")
      continue;
    const absolute = path33.join(dir, entry.name);
    out.push(path33.relative(base, absolute).split(path33.sep).join("/"));
    if (entry.isDirectory())
      out.push(...listAllRelativePaths(absolute, base));
  }
  return out;
}
function resolveIncludeEntry(entry, sourceDir) {
  if (!isIncludeEntryPattern(entry))
    return [path33.resolve(sourceDir, entry)];
  const pattern = includeEntryToRegExp(entry);
  return listAllRelativePaths(sourceDir, sourceDir).filter((relative) => pattern.test(relative)).map((relative) => path33.join(sourceDir, relative));
}
function copyIncludedPaths(includeGlobs, sourceDir, destDir) {
  for (const entry of includeGlobs) {
    const resolvedPaths = resolveIncludeEntry(entry, sourceDir);
    if (resolvedPaths.length === 0) {
      warnOnce(`akm-include-missing:${sourceDir}:${entry}`, `[akm] Skipping "${entry}" in akm.include: no matching file or directory.`);
      continue;
    }
    for (const resolvedSource of resolvedPaths) {
      if (!isWithin(resolvedSource, sourceDir)) {
        throw new Error(`Path in akm.include escapes the package root: ${entry}`);
      }
      if (!fs26.existsSync(resolvedSource) && !isBrokenSymlink(resolvedSource)) {
        warnOnce(`akm-include-missing:${sourceDir}:${entry}`, `[akm] Skipping "${entry}" in akm.include: no matching file or directory.`);
        continue;
      }
      if (path33.basename(resolvedSource) === ".git")
        continue;
      const relativePath = path33.relative(sourceDir, resolvedSource);
      if (!relativePath || relativePath === ".") {
        copyDirectoryContents(sourceDir, destDir, sourceDir);
        continue;
      }
      copyPath(resolvedSource, path33.join(destDir, relativePath), sourceDir);
    }
  }
}
function copyDirectoryContents(sourceDir, destinationDir, containmentRoot) {
  for (const entry of fs26.readdirSync(sourceDir, { withFileTypes: true })) {
    if (entry.name === ".git")
      continue;
    copyPath(path33.join(sourceDir, entry.name), path33.join(destinationDir, entry.name), containmentRoot);
  }
}
function copyPath(sourcePath, destinationPath, containmentRoot) {
  const stat = fs26.lstatSync(sourcePath);
  if (stat.isSymbolicLink()) {
    let resolved;
    try {
      resolved = fs26.realpathSync(sourcePath);
    } catch {
      warnOnce(`akm-include-broken-symlink:${sourcePath}`, `[akm] Skipping broken symlink in akm.include: ${path33.relative(containmentRoot, sourcePath)}`);
      return;
    }
    if (!isWithin(resolved, containmentRoot)) {
      warnOnce(`akm-include-symlink-escape:${sourcePath}`, `[akm] Skipping symlink in akm.include that points outside the package: ${path33.relative(containmentRoot, sourcePath)}`);
      return;
    }
    const resolvedStat = fs26.statSync(resolved);
    fs26.mkdirSync(path33.dirname(destinationPath), { recursive: true });
    if (resolvedStat.isDirectory()) {
      fs26.mkdirSync(destinationPath, { recursive: true });
      copyDirectoryContents(resolved, destinationPath, containmentRoot);
      return;
    }
    fs26.copyFileSync(resolved, destinationPath);
    return;
  }
  fs26.mkdirSync(path33.dirname(destinationPath), { recursive: true });
  if (stat.isDirectory()) {
    fs26.mkdirSync(destinationPath, { recursive: true });
    copyDirectoryContents(sourcePath, destinationPath, containmentRoot);
    return;
  }
  fs26.copyFileSync(sourcePath, destinationPath);
}

// src/sources/providers/provider-utils.ts
var REGISTRY_STASH_DIR_NAMES = new Set(stashDirNames());
function sanitizeString(value, maxLength = 255) {
  if (typeof value !== "string")
    return "";
  return value.replace(/[\u0000-\u001f\u007f]/g, "").slice(0, maxLength);
}
function isExpired(mtimeMs, ttlMs) {
  return Date.now() - mtimeMs > ttlMs;
}
function looksLikeAnyBundleRoot(root) {
  for (const adapter of getAdapters()) {
    try {
      if (adapter.looksLikeRoot?.(root) === true)
        return true;
    } catch {}
  }
  return false;
}
function detectStashRoot(extractedDir) {
  const root = path34.resolve(extractedDir);
  if (looksLikeAnyBundleRoot(root)) {
    return root;
  }
  const shallowest = findShallowestStashRoot(root);
  if (shallowest)
    return shallowest;
  return root;
}
function uniqueSlug() {
  return randomUUID2();
}
function buildInstallCacheDir(cacheRootDir, source, id, version) {
  const safeId = id.replace(/[^a-zA-Z0-9_.-]+/g, "-").replace(/^-+|-+$/g, "");
  const identitySuffix = version === "writable" ? `-${createHash4("sha256").update(`${source}:${id}`).digest("hex").slice(0, 12)}` : "";
  const slug = `${source}-${safeId}${identitySuffix}`;
  const versionSlug = source === "local" ? uniqueSlug() : version?.replace(/[^a-zA-Z0-9_.-]+/g, "-") ?? uniqueSlug();
  return path34.join(cacheRootDir, slug || source, versionSlug);
}
function applyAkmIncludeConfig(sourceRoot, cacheDir, searchRoot = sourceRoot) {
  const includeConfig = findNearestIncludeConfig(sourceRoot, searchRoot);
  if (!includeConfig)
    return;
  const selectedDir = path34.join(cacheDir, "selected");
  fs27.rmSync(selectedDir, { recursive: true, force: true });
  fs27.mkdirSync(selectedDir, { recursive: true });
  copyIncludedPaths(includeConfig.include, includeConfig.baseDir, selectedDir);
  return selectedDir;
}
async function downloadArchive(url, destination) {
  const response = await fetchRegistry(url, { timeoutMs: 120000 });
  await writeResponseToFileCapped(destination, response);
}
async function computeFileHash(filePath) {
  const data = fs27.readFileSync(filePath);
  const hash = createHash4("sha256").update(data).digest("hex");
  return `sha256:${hash}`;
}
function isDirectory(target) {
  try {
    return fs27.statSync(target).isDirectory();
  } catch {
    return false;
  }
}
function countStashDirs(dirPath) {
  if (!isDirectory(dirPath))
    return 0;
  const entries = fs27.readdirSync(dirPath, { withFileTypes: true });
  return entries.filter((entry) => entry.isDirectory() && REGISTRY_STASH_DIR_NAMES.has(entry.name)).length;
}
var BFS_MAX_DEPTH = 5;
function findShallowestStashRoot(root) {
  const queue = [{ dir: root, depth: 0 }];
  while (queue.length > 0) {
    const item = queue.shift();
    if (!item) {
      continue;
    }
    const { dir: current, depth } = item;
    if (current !== root) {
      if (isDirectory(path34.join(current, ".stash"))) {
        return current;
      }
      if (countStashDirs(current) >= 2) {
        return current;
      }
    }
    if (depth >= BFS_MAX_DEPTH)
      continue;
    let children;
    try {
      children = fs27.readdirSync(current, { withFileTypes: true });
    } catch {
      continue;
    }
    for (const child of children) {
      if (!child.isDirectory())
        continue;
      if (child.name === ".git" || child.name === "node_modules")
        continue;
      queue.push({ dir: path34.join(current, child.name), depth: depth + 1 });
    }
  }
  return;
}

// src/sources/providers/git-install.ts
function runGit(args, options) {
  return spawnSync4("git", args, {
    encoding: "utf8",
    ...options,
    env: { ...process.env, ...options?.env, GIT_TERMINAL_PROMPT: "0" }
  });
}
function inspectGitUpstream(repoDir, credential) {
  const remotes = runGit(["-C", repoDir, "remote"]);
  if (remotes.status !== 0)
    throw new UsageError(`Cannot inspect Git remotes at ${repoDir}: ${remotes.stderr.trim()}`);
  if (!remotes.stdout.trim())
    return { hasRemote: false, ahead: 0, behind: 0 };
  const fetch2 = runGit(["-C", repoDir, "fetch", "--prune"], {
    timeout: 120000,
    env: gitCredentialEnvironment(credential)
  });
  if (fetch2.status !== 0)
    throw new UsageError(`Cannot refresh Git target at ${repoDir}: ${fetch2.stderr.trim()}`);
  const upstream = runGit(["-C", repoDir, "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"]);
  if (upstream.status !== 0 || !upstream.stdout.trim()) {
    throw new UsageError(`Git target at ${repoDir} has a remote but no upstream branch; configure one before writing.`);
  }
  const relation = gitRelation(repoDir, upstream.stdout.trim());
  return { hasRemote: true, upstream: upstream.stdout.trim(), ...relation };
}
function gitRelation(repoDir, target) {
  const result = runGit(["-C", repoDir, "rev-list", "--left-right", "--count", `HEAD...${target}`]);
  const match = result.stdout.trim().match(/^(\d+)\s+(\d+)$/);
  if (result.status !== 0 || !match) {
    throw new UsageError(`Cannot compare Git history at ${repoDir}: ${result.stderr.trim() || "unknown relation"}`);
  }
  return { ahead: Number(match[1]), behind: Number(match[2]) };
}
function assertNoIgnoredPathOverwrite(repoDir, targetRevision) {
  const ignored = runGit(["-C", repoDir, "ls-files", "--others", "--ignored", "--exclude-standard", "-z"]);
  if (ignored.status !== 0) {
    throw new UsageError(`Cannot inspect ignored files at ${repoDir}: ${ignored.stderr.trim()}`);
  }
  const ignoredPaths = ignored.stdout.split("\x00").filter(Boolean);
  if (ignoredPaths.length === 0)
    return;
  const changed = runGit(["-C", repoDir, "diff", "--name-only", "--no-renames", "-z", "HEAD", targetRevision]);
  if (changed.status !== 0) {
    throw new UsageError(`Cannot inspect incoming Git paths at ${repoDir}: ${changed.stderr.trim()}`);
  }
  const changedPaths = changed.stdout.split("\x00").filter(Boolean);
  const conflict = ignoredPaths.find((ignoredPath) => changedPaths.some((changedPath) => changedPath === ignoredPath || changedPath.startsWith(`${ignoredPath}/`) || ignoredPath.startsWith(`${changedPath}/`)));
  if (conflict) {
    throw new UsageError(`Git update would overwrite ignored local path ${path35.join(repoDir, conflict)}; move or remove it before update.`);
  }
}
function replaceDirectory(stagedDir, destination) {
  const backup = `${destination}.backup-${randomBytes(4).toString("hex")}`;
  fs28.mkdirSync(path35.dirname(destination), { recursive: true });
  const hadDestination = fs28.existsSync(destination);
  if (hadDestination)
    fs28.renameSync(destination, backup);
  try {
    fs28.renameSync(stagedDir, destination);
  } catch (error2) {
    if (hadDestination && fs28.existsSync(backup))
      fs28.renameSync(backup, destination);
    throw error2;
  }
  if (hadDestination) {
    try {
      fs28.rmSync(backup, { recursive: true, force: true });
    } catch {}
  }
}
function cloneRepo(cloneUrl, ref, destDir, writable = false, credential) {
  const tmpDir = `${destDir}.tmp-${randomBytes(4).toString("hex")}`;
  const args = ["clone"];
  if (!writable)
    args.push("--depth", "1");
  if (ref)
    args.push("--branch", ref);
  args.push(cloneUrl, tmpDir);
  const result = runGit(args, { timeout: 120000, env: gitCredentialEnvironment(credential) });
  if (result.status !== 0) {
    fs28.rmSync(tmpDir, { recursive: true, force: true });
    throw new Error(classifyCloneFailure(cloneUrl, result.stderr, result.error));
  }
  try {
    if (!writable) {
      const gitDir = path35.join(tmpDir, ".git");
      if (fs28.existsSync(gitDir))
        fs28.rmSync(gitDir, { recursive: true, force: true });
    }
    replaceDirectory(tmpDir, destDir);
  } catch (err) {
    fs28.rmSync(tmpDir, { recursive: true, force: true });
    throw err;
  }
}
function classifyCloneFailure(url, stderr, spawnError) {
  const safeUrl = redactUrlUserinfo(url);
  const raw = (stderr ?? "").trim();
  const spawnMsg = spawnError?.message ?? "";
  if (spawnError?.code === "ENOENT") {
    return `Failed to clone ${safeUrl}: 'git' is not installed or not on PATH. Install git, then re-run.`;
  }
  if (/could not read Username|terminal prompts disabled|Authentication failed|fatal: Authentication/i.test(raw)) {
    return `Failed to clone ${safeUrl}: repository not found or private. ` + `If the repository is public, double-check the URL and try again. ` + `If it is private, set GH_TOKEN (or configure a git credential helper) before re-running.`;
  }
  if (/repository '.*' not found|HTTP 404|fatal: remote error|not found:|Not Found/i.test(raw)) {
    return `Failed to clone ${safeUrl}: repository not found. ` + `Check the URL — for GitHub, the form is 'owner/repo' or 'github:owner/repo'.`;
  }
  if (/Permission denied \(publickey\)|kex_exchange_identification|Connection refused|Connection timed out/i.test(raw)) {
    return `Failed to clone ${safeUrl}: network or SSH failure. ` + `Check connectivity, your SSH agent, and the remote host's availability.`;
  }
  if (/Remote branch .* not found in upstream origin|couldn't find remote ref/i.test(raw)) {
    return `Failed to clone ${safeUrl}: the requested branch/tag does not exist on the remote. ` + `Verify the ref name and re-run.`;
  }
  const detail = raw || spawnMsg || "unknown error";
  return `Failed to clone ${safeUrl}: ${redactUrlUserinfo(detail)}`;
}
function redactUrlUserinfo(text) {
  return text.replace(/\b([A-Za-z][A-Za-z0-9+.-]*:\/\/)([^\s/@]+)@/g, "$1[REDACTED]@");
}
// src/sources/providers/git-provider.ts
import { createHash as createHash5 } from "node:crypto";
import fs30 from "node:fs";
import path36 from "node:path";

// src/sources/freshness.ts
import fs29 from "node:fs";
async function withFreshnessCache(options) {
  const usable = options.isUsable ?? (() => true);
  let mtime = 0;
  try {
    mtime = fs29.statSync(options.markerPath).mtimeMs;
  } catch {}
  if (!options.force && mtime && !isExpired(mtime, options.ttlMs) && usable()) {
    return;
  }
  try {
    await options.refresh();
  } catch (err) {
    if (options.allowStaleOnRefreshFailure !== false && mtime && !isExpired(mtime, options.staleMs) && usable()) {
      return;
    }
    throw err;
  }
}

// src/sources/providers/git-provider.ts
var CACHE_TTL_MS = 12 * 60 * 60 * 1000;
var CACHE_STALE_MS = 7 * 24 * 60 * 60 * 1000;

class GitSourceProvider {
  kind = "git";
  name;
  #config;
  #path = null;
  constructor(config) {
    this.#config = config;
    this.name = config.name ?? "git";
  }
  path() {
    if (this.#path == null) {
      this.#path = resolveGitContentDir(this.#config);
    }
    return this.#path;
  }
  async sync(options) {
    await syncMirroredRepo(this.#config, {
      force: options?.force,
      ...this.#config.credential ? { credential: resolveSecret(this.#config.credential, options?.secrets?.resolveSecret) } : {}
    });
  }
}
function resolveGitContentDir(config) {
  if (config.path)
    return config.path;
  if (config.url) {
    const repo = parseGitRepoUrl(config.url);
    return getCachePaths(repo.canonicalUrl).repoDir;
  }
  throw new ConfigError("git source entry must have either `path` or `url`");
}
function getCachePaths(repoUrl, cacheRootOverride) {
  const key = createHash5("sha256").update(repoUrl).digest("hex").slice(0, 16);
  const cacheRoot = cacheRootOverride ?? getRegistryIndexCacheDir();
  const rootDir = path36.join(cacheRoot, `git-${key}`);
  return {
    rootDir,
    repoDir: path36.join(rootDir, "repo"),
    indexPath: path36.join(rootDir, "index.json")
  };
}
async function ensureGitMirror(repo, cachePaths, options) {
  const requireRepoDir = options?.requireRepoDir === true;
  const writable = options?.writable === true;
  await withFreshnessCache({
    markerPath: cachePaths.indexPath,
    ttlMs: CACHE_TTL_MS,
    staleMs: CACHE_STALE_MS,
    force: options?.force === true,
    allowStaleOnRefreshFailure: !(options?.force === true && writable),
    isUsable: () => !requireRepoDir || hasExtractedRepo(cachePaths.repoDir),
    refresh: async () => {
      fs30.mkdirSync(cachePaths.rootDir, { recursive: true });
      if (writable && fs30.existsSync(path36.join(cachePaths.repoDir, ".git"))) {
        pullRepo(cachePaths.repoDir, options?.credential);
      } else {
        cloneRepo(repo.cloneUrl, repo.ref, cachePaths.repoDir, writable, options?.credential);
      }
      fs30.writeFileSync(cachePaths.indexPath, "[]", { encoding: "utf8", mode: 384 });
    }
  });
}
async function syncMirroredRepo(config, options) {
  if (!config.url) {
    throw new ConfigError("git stash entry requires a URL when no install ref is supplied");
  }
  const repo = parseGitRepoUrl(config.url);
  const cachePaths = getCachePaths(repo.canonicalUrl, options?.cacheRootDir);
  await ensureGitMirror(repo, cachePaths, {
    requireRepoDir: true,
    writable: options?.writable ?? config.writable === true,
    force: options?.force,
    credential: options?.credential
  });
  const syncedAt = (options?.now ?? new Date).toISOString();
  const contentDir = cachePaths.repoDir;
  return {
    id: repo.canonicalUrl,
    source: "git",
    ref: repo.canonicalUrl,
    artifactUrl: repo.canonicalUrl,
    contentDir,
    cacheDir: cachePaths.rootDir,
    extractedDir: contentDir,
    writable: options?.writable ?? config.writable === true,
    syncedAt
  };
}
function pullRepo(repoDir, credential) {
  const status = runGit(["-C", repoDir, "status", "--porcelain"]);
  if (status.status !== 0 || status.stdout.trim()) {
    throw new UsageError(`Writable Git source at ${repoDir} has uncommitted changes; refusing to update it.`);
  }
  const relation = inspectGitUpstream(repoDir, credential);
  if (relation.behind > 0 && relation.upstream) {
    if (relation.ahead > 0) {
      throw new UsageError(`Writable Git source at ${repoDir} has unpushed commits; refusing to update it.`);
    }
    const statusBeforeMerge = runGit(["-C", repoDir, "status", "--porcelain"]);
    if (statusBeforeMerge.status !== 0 || statusBeforeMerge.stdout.trim()) {
      throw new UsageError(`Writable Git source at ${repoDir} changed while its update was prepared; refusing to merge.`);
    }
    assertNoIgnoredPathOverwrite(repoDir, relation.upstream);
    const merge = runGit(["-C", repoDir, "merge", "--ff-only", "--no-overwrite-ignore", relation.upstream], {
      timeout: 120000
    });
    if (merge.status !== 0) {
      throw new Error(`Failed to fast-forward ${repoDir}: ${merge.stderr?.trim() || "unknown error"}`);
    }
  }
}
function hasExtractedRepo(repoDir) {
  try {
    if (!fs30.statSync(repoDir).isDirectory())
      return false;
    if (fs30.statSync(path36.join(repoDir, "content")).isDirectory())
      return true;
  } catch {}
  try {
    if (!fs30.statSync(repoDir).isDirectory())
      return false;
    const ownedDirs = akmAdapter.directoryList?.({ id: "akm", adapter: "akm", root: repoDir, writable: false }) ?? stashDirNames();
    return ownedDirs.some((dirName) => fs30.existsSync(path36.join(repoDir, dirName)));
  } catch {
    return false;
  }
}
function parseGitRepoUrl(rawUrl) {
  if (!rawUrl) {
    throw new ConfigError("Git provider requires a repository URL");
  }
  if (/^git@[^:]+:.+$/.test(rawUrl)) {
    return { cloneUrl: rawUrl, ref: null, canonicalUrl: rawUrl };
  }
  try {
    validateGitUrl(rawUrl);
  } catch (err) {
    if (err instanceof UsageError)
      throw new ConfigError(err.message);
    throw err;
  }
  let parsed;
  try {
    parsed = new URL(rawUrl);
  } catch {
    throw new ConfigError(`Git provider URL is not valid: "${rawUrl}"`);
  }
  if (parsed.hostname === "github.com" && parsed.protocol === "https:") {
    const segments = parsed.pathname.split("/").filter(Boolean);
    if (segments.length < 2) {
      throw new ConfigError(`Git provider URL must point to a repository, got "${rawUrl}"`);
    }
    const owner = sanitizeString(segments[0]);
    const repo = sanitizeString(segments[1].replace(/\.git$/i, ""));
    if (!owner || !repo || !/^[A-Za-z0-9_.-]+$/.test(owner) || !/^[A-Za-z0-9_.-]+$/.test(repo)) {
      throw new ConfigError(`Unsupported repository URL: "${rawUrl}"`);
    }
    let ref = null;
    if (segments[2] === "tree" && segments.length >= 4) {
      const rawRef = sanitizeString(segments.slice(3).join("/"), 255);
      if (rawRef && !rawRef.includes("..") && /^[A-Za-z0-9._/-]+$/.test(rawRef)) {
        ref = rawRef;
      }
    }
    const cloneUrl = `https://github.com/${owner}/${repo}`;
    const canonicalUrl2 = ref ? `${cloneUrl}/tree/${ref}` : cloneUrl;
    return { cloneUrl, ref, canonicalUrl: canonicalUrl2 };
  }
  let canonicalUrl = rawUrl;
  try {
    const u = new URL(rawUrl);
    u.username = "";
    u.password = "";
    u.search = "";
    u.hash = "";
    canonicalUrl = u.toString();
  } catch {}
  return { cloneUrl: rawUrl, ref: null, canonicalUrl };
}
// src/core/adapter/detect-adapter.ts
import fs31 from "node:fs";
import path37 from "node:path";
var SHADOWABLE_ADAPTER_IDS = new Set(["agent-skills", "claude", "opencode"]);
function hasExtraAkmContent(root, winnerId) {
  const akm = adapterForId("akm");
  if (akm?.looksLikeRoot?.(root) !== true)
    return false;
  const winner = adapterForId(winnerId);
  const stubComponent = { id: "detect", adapter: winnerId, root, writable: false };
  const ownedDirs = new Set(winner?.directoryList?.(stubComponent) ?? []);
  let entries;
  try {
    entries = fs31.readdirSync(root, { withFileTypes: true });
  } catch {
    return false;
  }
  for (const entry of entries) {
    if (!entry.isDirectory() || entry.name.startsWith("."))
      continue;
    if (ownedDirs.has(entry.name))
      continue;
    if (winnerId === "agent-skills") {
      try {
        if (fs31.statSync(path37.join(root, entry.name, "SKILL.md")).isFile())
          continue;
      } catch {}
    }
    let children;
    try {
      children = fs31.readdirSync(path37.join(root, entry.name), { withFileTypes: true });
    } catch {
      continue;
    }
    if (children.some((child) => child.isFile() && !child.name.startsWith(".")))
      return true;
  }
  return false;
}
function detectAdapterId(root, fallback = "akm") {
  for (const adapter of getAdapters()) {
    try {
      if (adapter.looksLikeRoot?.(root) === true) {
        if (SHADOWABLE_ADAPTER_IDS.has(adapter.id) && hasExtraAkmContent(root, adapter.id)) {
          return "akm";
        }
        return adapter.id;
      }
    } catch {}
  }
  return fallback;
}

// src/core/write-source.ts
function resolveWritable(entry) {
  if (typeof entry.writable === "boolean")
    return entry.writable;
  return entry.type === "filesystem";
}
var WINDOWS_RESERVED_DEVICE_NAMES = new Set([
  "con",
  "prn",
  "aux",
  "nul",
  ...Array.from({ length: 9 }, (_, i) => `com${i + 1}`),
  ...Array.from({ length: 9 }, (_, i) => `lpt${i + 1}`)
]);
var pendingGitPaths = new Map;

// src/sources/providers/npm.ts
import fs33 from "node:fs";
import path39 from "node:path";

// src/sources/providers/tar-utils.ts
import { createHash as createHash6 } from "node:crypto";
import fs32 from "node:fs";
import path38 from "node:path";
function verifyArchiveIntegrity(archivePath, expected, source) {
  if (!expected)
    return;
  if (source === "github" || source === "git")
    return;
  const fileBuffer = fs32.readFileSync(archivePath);
  if (expected.startsWith("sha256-") || expected.startsWith("sha512-")) {
    const dashIndex = expected.indexOf("-");
    const algorithm = expected.slice(0, dashIndex);
    const expectedBase64 = expected.slice(dashIndex + 1);
    const actualBase64 = createHash6(algorithm).update(fileBuffer).digest("base64");
    if (actualBase64 !== expectedBase64) {
      fs32.unlinkSync(archivePath);
      throw new Error(`Integrity check failed for ${archivePath}: expected ${algorithm} digest ${expectedBase64}, got ${actualBase64}`);
    }
    return;
  }
  if (/^[0-9a-f]{40}$/i.test(expected)) {
    const actualHex = createHash6("sha1").update(fileBuffer).digest("hex");
    if (actualHex.toLowerCase() !== expected.toLowerCase()) {
      fs32.unlinkSync(archivePath);
      throw new Error(`Integrity check failed for ${archivePath}: expected sha1 ${expected}, got ${actualHex}`);
    }
    return;
  }
  warn("Unrecognized integrity format: %s — verification skipped", expected);
}
function extractTarGzSecure(archivePath, destinationDir) {
  const listResult = spawnSync(["tar", "tzf", archivePath]);
  if (!listResult.success) {
    const err = listResult.stderr?.toString().trim() || "unknown error";
    throw new Error(`Failed to inspect archive ${archivePath}: ${err}`);
  }
  validateTarEntries(listResult.stdout.toString());
  fs32.rmSync(destinationDir, { recursive: true, force: true });
  fs32.mkdirSync(destinationDir, { recursive: true });
  const extractResult = spawnSync([
    "tar",
    "xzf",
    archivePath,
    "--no-same-owner",
    "--strip-components=1",
    "-C",
    destinationDir
  ]);
  if (!extractResult.success) {
    const err = extractResult.stderr?.toString().trim() || "unknown error";
    throw new Error(`Failed to extract archive ${archivePath}: ${err}`);
  }
  scanExtractedFiles(destinationDir, destinationDir);
}
function scanExtractedFiles(dir, root) {
  const entries = fs32.readdirSync(dir, { withFileTypes: true });
  for (const entry of entries) {
    const fullPath = path38.join(dir, entry.name);
    if (entry.name === ".." || entry.name === ".") {
      throw new Error(`Post-extraction scan: suspicious entry name: ${fullPath}`);
    }
    if (entry.isSymbolicLink()) {
      const target = fs32.realpathSync(fullPath);
      if (!isWithin(target, root)) {
        throw new Error(`Post-extraction scan: symlink escapes destination directory: ${fullPath} -> ${target}`);
      }
    }
    if (!entry.isSymbolicLink()) {
      const resolved = path38.resolve(fullPath);
      if (!isWithin(resolved, root)) {
        throw new Error(`Post-extraction scan: entry escapes destination directory: ${fullPath}`);
      }
    }
    if (entry.isDirectory()) {
      scanExtractedFiles(fullPath, root);
    }
  }
}
function validateTarEntries(listOutput) {
  const lines = listOutput.split(/\r?\n/).filter(Boolean);
  for (const rawLine of lines) {
    const entry = rawLine.trim();
    if (!entry || entry.includes("\x00")) {
      throw new Error(`Archive contains an invalid entry: ${JSON.stringify(rawLine)}`);
    }
    if (entry.startsWith("/")) {
      throw new Error(`Archive contains an absolute path entry: ${entry}`);
    }
    const normalized = path38.posix.normalize(entry);
    if (normalized === ".." || normalized.startsWith("../")) {
      throw new Error(`Archive contains a path traversal entry: ${entry}`);
    }
    const parts = normalized.split("/").filter(Boolean);
    const stripped = parts.slice(1).join("/");
    if (!stripped)
      continue;
    const normalizedStripped = path38.posix.normalize(stripped);
    if (normalizedStripped === ".." || normalizedStripped.startsWith("../") || path38.posix.isAbsolute(normalizedStripped)) {
      throw new Error(`Archive contains an unsafe entry after strip-components: ${entry}`);
    }
  }
}

// src/sources/providers/npm.ts
class NpmSourceProvider {
  kind = "npm";
  name;
  #config;
  constructor(config) {
    this.#config = config;
    this.name = config.name ?? config.url ?? "npm";
  }
  path() {
    if (this.#config.path)
      return this.#config.path;
    throw new ConfigError(`npm source "${this.name}" has no resolved content path — run \`akm bundle update\` to sync it before indexing.`);
  }
  async sync(options) {
    const ref = npmRefFromConfig(this.#config);
    await syncNpmRef(ref, { force: options?.force });
  }
}
function npmRefFromConfig(config) {
  const candidate = config.path;
  if (typeof candidate !== "string" || !candidate) {
    throw new UsageError('npm source entry must include a package ref (e.g. "npm:my-pkg@1.2.3")');
  }
  return candidate.startsWith("npm:") ? candidate : `npm:${candidate}`;
}
async function syncNpmRef(ref, options) {
  const parsed = parseRegistryRef(ref);
  if (parsed.source !== "npm") {
    throw new UsageError(`syncNpmRef requires an npm: ref, got "${ref}"`);
  }
  return doSyncNpm(parsed, options);
}
async function doSyncNpm(parsed, options) {
  const resolved = await resolveRegistryArtifact(parsed);
  const syncedAt = (options?.now ?? new Date).toISOString();
  const cacheRootDir = options?.cacheRootDir ?? getRegistryCacheDir();
  const cacheDir = buildInstallCacheDir(cacheRootDir, resolved.source, resolved.id, resolved.resolvedVersion ?? resolved.resolvedRevision);
  const archivePath = path39.join(cacheDir, "artifact.tar.gz");
  const extractedDir = path39.join(cacheDir, "extracted");
  if (!options?.force && isDirectory(extractedDir)) {
    try {
      const cachedStashRoot = detectStashRoot(extractedDir);
      if (cachedStashRoot) {
        const integrity2 = fs33.existsSync(archivePath) ? await computeFileHash(archivePath) : undefined;
        return {
          id: resolved.id,
          source: resolved.source,
          ref: resolved.ref,
          artifactUrl: resolved.artifactUrl,
          resolvedVersion: resolved.resolvedVersion,
          resolvedRevision: resolved.resolvedRevision,
          contentDir: cachedStashRoot,
          cacheDir,
          extractedDir,
          integrity: integrity2,
          writable: options?.writable,
          syncedAt
        };
      }
    } catch {}
  }
  fs33.mkdirSync(cacheDir, { recursive: true });
  let integrity;
  let provisionalBundleRoot;
  let installRoot;
  let stashRoot;
  try {
    await downloadArchive(resolved.artifactUrl, archivePath);
    verifyArchiveIntegrity(archivePath, resolved.resolvedRevision, resolved.source);
    integrity = await computeFileHash(archivePath);
    extractTarGzSecure(archivePath, extractedDir);
    const detectedProvisionalBundleRoot = detectStashRoot(extractedDir);
    if (!detectedProvisionalBundleRoot) {
      throw new UsageError(`Unable to detect a stash root in extracted npm package: ${resolved.ref}`);
    }
    provisionalBundleRoot = detectedProvisionalBundleRoot;
    installRoot = applyAkmIncludeConfig(provisionalBundleRoot, cacheDir, extractedDir) ?? provisionalBundleRoot;
    const detectedStashRoot = detectStashRoot(installRoot);
    if (!detectedStashRoot) {
      throw new UsageError(`Unable to detect a stash root after applying akm.include (package.json) configuration for npm package: ${resolved.ref}`);
    }
    stashRoot = detectedStashRoot;
  } catch (err) {
    try {
      fs33.rmSync(cacheDir, { recursive: true, force: true });
    } catch {}
    throw err;
  }
  return {
    id: resolved.id,
    source: resolved.source,
    ref: resolved.ref,
    artifactUrl: resolved.artifactUrl,
    resolvedVersion: resolved.resolvedVersion,
    resolvedRevision: resolved.resolvedRevision,
    contentDir: stashRoot,
    cacheDir,
    extractedDir,
    integrity,
    writable: options?.writable,
    syncedAt
  };
}

// src/sources/snapshot-fetchers/content-extract.ts
var import_turndown = __toESM(require_turndown_cjs(), 1);
var DANGEROUS_TAGS = ["script", "style", "noscript", "template"];
var DANGEROUS_TAG_PATTERNS = DANGEROUS_TAGS.map((tag) => ({
  full: new RegExp(`<${tag}\\b[^>]*>[\\s\\S]*?<\\/\\s*${tag}\\b[^>]*>`, "gi"),
  unterminated: new RegExp(`<${tag}\\b[^>]*>[\\s\\S]*$`, "i"),
  stray: new RegExp(`<\\/?\\s*${tag}\\b[^>]*>`, "gi")
}));
var ARTICLE_METADATA_SELECTORS = new Set([".article-content", ".entry-content", ".post-content"]);
var VOID_ELEMENTS = new Set([
  "area",
  "base",
  "br",
  "col",
  "embed",
  "hr",
  "img",
  "input",
  "link",
  "meta",
  "param",
  "source",
  "track",
  "wbr"
]);

// src/sources/snapshot-fetchers/registry.ts
import path40 from "node:path";

// src/sources/snapshot-fetchers/bluesky.ts
var BSKY_HOSTS = new Set(["bsky.app", "www.bsky.app"]);
var BSKY_BYTE_CAP = 4 * 1024 * 1024;

// src/sources/snapshot-fetchers/github.ts
var GITHUB_HOSTS = new Set(["github.com", "www.github.com"]);
var RESERVED_GITHUB_ROOTS = new Set([
  "apps",
  "collections",
  "codespaces",
  "customer-stories",
  "education",
  "enterprise",
  "events",
  "explore",
  "features",
  "issues",
  "login",
  "marketplace",
  "new",
  "notifications",
  "orgs",
  "organizations",
  "pricing",
  "pulls",
  "search",
  "security",
  "settings",
  "solutions",
  "sponsors",
  "topics",
  "trending",
  "users"
]);
var GITHUB_README_BYTE_CAP = 5 * 1024 * 1024;

// node_modules/fast-xml-parser/src/util.js
var nameStartChar = ":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";
var nameChar = nameStartChar + "\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
var nameRegexp = "[" + nameStartChar + "][" + nameChar + "]*";
var regexName = new RegExp("^" + nameRegexp + "$");
function getAllMatches(string, regex) {
  const matches = [];
  let match = regex.exec(string);
  while (match) {
    const allmatches = [];
    allmatches.startIndex = regex.lastIndex - match[0].length;
    const len = match.length;
    for (let index = 0;index < len; index++) {
      allmatches.push(match[index]);
    }
    matches.push(allmatches);
    match = regex.exec(string);
  }
  return matches;
}
var isName = function(string) {
  const match = regexName.exec(string);
  return !(match === null || typeof match === "undefined");
};
function isExist(v) {
  return typeof v !== "undefined";
}
var DANGEROUS_PROPERTY_NAMES = [
  "hasOwnProperty",
  "toString",
  "valueOf",
  "__defineGetter__",
  "__defineSetter__",
  "__lookupGetter__",
  "__lookupSetter__"
];
var criticalProperties = ["__proto__", "constructor", "prototype"];

// node_modules/fast-xml-parser/src/validator.js
var defaultOptions = {
  allowBooleanAttributes: false,
  unpairedTags: []
};
function validate10(xmlData, options) {
  options = Object.assign({}, defaultOptions, options);
  const tags = [];
  let tagFound = false;
  let reachedRoot = false;
  if (xmlData[0] === "\uFEFF") {
    xmlData = xmlData.substr(1);
  }
  for (let i = 0;i < xmlData.length; i++) {
    if (xmlData[i] === "<" && xmlData[i + 1] === "?") {
      i += 2;
      i = readPI(xmlData, i);
      if (i.err)
        return i;
    } else if (xmlData[i] === "<") {
      let tagStartPos = i;
      i++;
      if (xmlData[i] === "!") {
        i = readCommentAndCDATA(xmlData, i);
        continue;
      } else {
        let closingTag = false;
        if (xmlData[i] === "/") {
          closingTag = true;
          i++;
        }
        let tagName = "";
        for (;i < xmlData.length && xmlData[i] !== ">" && xmlData[i] !== " " && xmlData[i] !== "\t" && xmlData[i] !== `
` && xmlData[i] !== "\r"; i++) {
          tagName += xmlData[i];
        }
        tagName = tagName.trim();
        if (tagName[tagName.length - 1] === "/") {
          tagName = tagName.substring(0, tagName.length - 1);
          i--;
        }
        if (!validateTagName(tagName)) {
          let msg;
          if (tagName.trim().length === 0) {
            msg = "Invalid space after '<'.";
          } else {
            msg = "Tag '" + tagName + "' is an invalid name.";
          }
          return getErrorObject("InvalidTag", msg, getLineNumberForPosition(xmlData, i));
        }
        const result = readAttributeStr(xmlData, i);
        if (result === false) {
          return getErrorObject("InvalidAttr", "Attributes for '" + tagName + "' have open quote.", getLineNumberForPosition(xmlData, i));
        }
        let attrStr = result.value;
        i = result.index;
        if (attrStr[attrStr.length - 1] === "/") {
          const attrStrStart = i - attrStr.length;
          attrStr = attrStr.substring(0, attrStr.length - 1);
          const isValid2 = validateAttributeString(attrStr, options);
          if (isValid2 === true) {
            tagFound = true;
          } else {
            return getErrorObject(isValid2.err.code, isValid2.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid2.err.line));
          }
        } else if (closingTag) {
          if (!result.tagClosed) {
            return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' doesn't have proper closing.", getLineNumberForPosition(xmlData, i));
          } else if (attrStr.trim().length > 0) {
            return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' can't have attributes or invalid starting.", getLineNumberForPosition(xmlData, tagStartPos));
          } else if (tags.length === 0) {
            return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' has not been opened.", getLineNumberForPosition(xmlData, tagStartPos));
          } else {
            const otg = tags.pop();
            if (tagName !== otg.tagName) {
              let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos);
              return getErrorObject("InvalidTag", "Expected closing tag '" + otg.tagName + "' (opened in line " + openPos.line + ", col " + openPos.col + ") instead of closing tag '" + tagName + "'.", getLineNumberForPosition(xmlData, tagStartPos));
            }
            if (tags.length == 0) {
              reachedRoot = true;
            }
          }
        } else {
          const isValid2 = validateAttributeString(attrStr, options);
          if (isValid2 !== true) {
            return getErrorObject(isValid2.err.code, isValid2.err.msg, getLineNumberForPosition(xmlData, i - attrStr.length + isValid2.err.line));
          }
          if (reachedRoot === true) {
            return getErrorObject("InvalidXml", "Multiple possible root nodes found.", getLineNumberForPosition(xmlData, i));
          } else if (options.unpairedTags.indexOf(tagName) !== -1) {} else {
            tags.push({ tagName, tagStartPos });
          }
          tagFound = true;
        }
        for (i++;i < xmlData.length; i++) {
          if (xmlData[i] === "<") {
            if (xmlData[i + 1] === "!") {
              i++;
              i = readCommentAndCDATA(xmlData, i);
              continue;
            } else if (xmlData[i + 1] === "?") {
              i = readPI(xmlData, ++i);
              if (i.err)
                return i;
            } else {
              break;
            }
          } else if (xmlData[i] === "&") {
            const afterAmp = validateAmpersand(xmlData, i);
            if (afterAmp == -1)
              return getErrorObject("InvalidChar", "char '&' is not expected.", getLineNumberForPosition(xmlData, i));
            i = afterAmp;
          } else {
            if (reachedRoot === true && !isWhiteSpace(xmlData[i])) {
              return getErrorObject("InvalidXml", "Extra text at the end", getLineNumberForPosition(xmlData, i));
            }
          }
        }
        if (xmlData[i] === "<") {
          i--;
        }
      }
    } else {
      if (isWhiteSpace(xmlData[i])) {
        continue;
      }
      return getErrorObject("InvalidChar", "char '" + xmlData[i] + "' is not expected.", getLineNumberForPosition(xmlData, i));
    }
  }
  if (!tagFound) {
    return getErrorObject("InvalidXml", "Start tag expected.", 1);
  } else if (tags.length == 1) {
    return getErrorObject("InvalidTag", "Unclosed tag '" + tags[0].tagName + "'.", getLineNumberForPosition(xmlData, tags[0].tagStartPos));
  } else if (tags.length > 0) {
    return getErrorObject("InvalidXml", "Invalid '" + JSON.stringify(tags.map((t) => t.tagName), null, 4).replace(/\r?\n/g, "") + "' found.", { line: 1, col: 1 });
  }
  return true;
}
function isWhiteSpace(char) {
  return char === " " || char === "\t" || char === `
` || char === "\r";
}
function readPI(xmlData, i) {
  const start = i;
  for (;i < xmlData.length; i++) {
    if (xmlData[i] == "?" || xmlData[i] == " ") {
      const tagname = xmlData.substr(start, i - start);
      if (i > 5 && tagname === "xml") {
        return getErrorObject("InvalidXml", "XML declaration allowed only at the start of the document.", getLineNumberForPosition(xmlData, i));
      } else if (xmlData[i] == "?" && xmlData[i + 1] == ">") {
        i++;
        break;
      } else {
        continue;
      }
    }
  }
  return i;
}
function readCommentAndCDATA(xmlData, i) {
  if (xmlData.length > i + 5 && xmlData[i + 1] === "-" && xmlData[i + 2] === "-") {
    for (i += 3;i < xmlData.length; i++) {
      if (xmlData[i] === "-" && xmlData[i + 1] === "-" && xmlData[i + 2] === ">") {
        i += 2;
        break;
      }
    }
  } else if (xmlData.length > i + 8 && xmlData[i + 1] === "D" && xmlData[i + 2] === "O" && xmlData[i + 3] === "C" && xmlData[i + 4] === "T" && xmlData[i + 5] === "Y" && xmlData[i + 6] === "P" && xmlData[i + 7] === "E") {
    let angleBracketsCount = 1;
    for (i += 8;i < xmlData.length; i++) {
      if (xmlData[i] === "<") {
        angleBracketsCount++;
      } else if (xmlData[i] === ">") {
        angleBracketsCount--;
        if (angleBracketsCount === 0) {
          break;
        }
      }
    }
  } else if (xmlData.length > i + 9 && xmlData[i + 1] === "[" && xmlData[i + 2] === "C" && xmlData[i + 3] === "D" && xmlData[i + 4] === "A" && xmlData[i + 5] === "T" && xmlData[i + 6] === "A" && xmlData[i + 7] === "[") {
    for (i += 8;i < xmlData.length; i++) {
      if (xmlData[i] === "]" && xmlData[i + 1] === "]" && xmlData[i + 2] === ">") {
        i += 2;
        break;
      }
    }
  }
  return i;
}
var doubleQuote = '"';
var singleQuote = "'";
function readAttributeStr(xmlData, i) {
  let attrStr = "";
  let startChar = "";
  let tagClosed = false;
  for (;i < xmlData.length; i++) {
    if (xmlData[i] === doubleQuote || xmlData[i] === singleQuote) {
      if (startChar === "") {
        startChar = xmlData[i];
      } else if (startChar !== xmlData[i]) {} else {
        startChar = "";
      }
    } else if (xmlData[i] === ">") {
      if (startChar === "") {
        tagClosed = true;
        break;
      }
    }
    attrStr += xmlData[i];
  }
  if (startChar !== "") {
    return false;
  }
  return {
    value: attrStr,
    index: i,
    tagClosed
  };
}
var validAttrStrRegxp = new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`, "g");
function validateAttributeString(attrStr, options) {
  const matches = getAllMatches(attrStr, validAttrStrRegxp);
  const attrNames = {};
  for (let i = 0;i < matches.length; i++) {
    if (matches[i][1].length === 0) {
      return getErrorObject("InvalidAttr", "Attribute '" + matches[i][2] + "' has no space in starting.", getPositionFromMatch(matches[i]));
    } else if (matches[i][3] !== undefined && matches[i][4] === undefined) {
      return getErrorObject("InvalidAttr", "Attribute '" + matches[i][2] + "' is without value.", getPositionFromMatch(matches[i]));
    } else if (matches[i][3] === undefined && !options.allowBooleanAttributes) {
      return getErrorObject("InvalidAttr", "boolean attribute '" + matches[i][2] + "' is not allowed.", getPositionFromMatch(matches[i]));
    }
    const attrName = matches[i][2];
    if (!validateAttrName(attrName)) {
      return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is an invalid name.", getPositionFromMatch(matches[i]));
    }
    if (!Object.prototype.hasOwnProperty.call(attrNames, attrName)) {
      attrNames[attrName] = 1;
    } else {
      return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is repeated.", getPositionFromMatch(matches[i]));
    }
  }
  return true;
}
function validateNumberAmpersand(xmlData, i) {
  let re = /\d/;
  if (xmlData[i] === "x") {
    i++;
    re = /[\da-fA-F]/;
  }
  for (;i < xmlData.length; i++) {
    if (xmlData[i] === ";")
      return i;
    if (!xmlData[i].match(re))
      break;
  }
  return -1;
}
function validateAmpersand(xmlData, i) {
  i++;
  if (xmlData[i] === ";")
    return -1;
  if (xmlData[i] === "#") {
    i++;
    return validateNumberAmpersand(xmlData, i);
  }
  let count = 0;
  for (;i < xmlData.length; i++, count++) {
    if (xmlData[i].match(/\w/) && count < 20)
      continue;
    if (xmlData[i] === ";")
      break;
    return -1;
  }
  return i;
}
function getErrorObject(code, message, lineNumber) {
  return {
    err: {
      code,
      msg: message,
      line: lineNumber.line || lineNumber,
      col: lineNumber.col
    }
  };
}
function validateAttrName(attrName) {
  return isName(attrName);
}
function validateTagName(tagname) {
  return isName(tagname);
}
function getLineNumberForPosition(xmlData, index) {
  const lines = xmlData.substring(0, index).split(/\r?\n/);
  return {
    line: lines.length,
    col: lines[lines.length - 1].length + 1
  };
}
function getPositionFromMatch(match) {
  return match.startIndex + match[1].length;
}

// node_modules/@nodable/entities/src/entities.js
var CURRENCY = {
  cent: "¢",
  pound: "£",
  curren: "¤",
  yen: "¥",
  euro: "€",
  dollar: "$",
  fnof: "ƒ",
  inr: "₹",
  af: "؋",
  birr: "ብር",
  peso: "₱",
  rub: "₽",
  won: "₩",
  yuan: "¥",
  cedil: "¸"
};
var XML = {
  amp: "&",
  apos: "'",
  gt: ">",
  lt: "<",
  quot: '"'
};
var COMMON_HTML = {
  nbsp: " ",
  copy: "©",
  reg: "®",
  trade: "™",
  mdash: "—",
  ndash: "–",
  hellip: "…",
  laquo: "«",
  raquo: "»",
  lsquo: "‘",
  rsquo: "’",
  ldquo: "“",
  rdquo: "”",
  bull: "•",
  para: "¶",
  sect: "§",
  deg: "°",
  frac12: "½",
  frac14: "¼",
  frac34: "¾"
};

// node_modules/@nodable/entities/src/EntityDecoder.js
var ENTITY_ACTION = Object.freeze({
  ALLOW: "allow",
  BLOCK: "block",
  THROW: "throw"
});
var SPECIAL_CHARS = new Set("!?\\\\/[]$%{}^&*()<>|+");
function validateEntityName(name) {
  if (name[0] === "#") {
    throw new Error(`[EntityReplacer] Invalid character '#' in entity name: "${name}"`);
  }
  for (const ch of name) {
    if (SPECIAL_CHARS.has(ch)) {
      throw new Error(`[EntityReplacer] Invalid character '${ch}' in entity name: "${name}"`);
    }
  }
  return name;
}
function mergeEntityMaps(...maps) {
  const out = Object.create(null);
  for (const map of maps) {
    if (!map)
      continue;
    for (const key of Object.keys(map)) {
      const raw = map[key];
      if (typeof raw === "string") {
        out[key] = raw;
      } else if (raw && typeof raw === "object" && raw.val !== undefined) {
        const val = raw.val;
        if (typeof val === "string") {
          out[key] = val;
        }
      }
    }
  }
  return out;
}
var LIMIT_TIER_EXTERNAL = "external";
var LIMIT_TIER_BASE = "base";
var LIMIT_TIER_ALL = "all";
function parseLimitTiers(raw) {
  if (!raw || raw === LIMIT_TIER_EXTERNAL)
    return new Set([LIMIT_TIER_EXTERNAL]);
  if (raw === LIMIT_TIER_ALL)
    return new Set([LIMIT_TIER_ALL]);
  if (raw === LIMIT_TIER_BASE)
    return new Set([LIMIT_TIER_BASE]);
  if (Array.isArray(raw))
    return new Set(raw);
  return new Set([LIMIT_TIER_EXTERNAL]);
}
var NCR_LEVEL = Object.freeze({ allow: 0, leave: 1, remove: 2, throw: 3 });
var XML10_ALLOWED_C0 = new Set([9, 10, 13]);
function parseNCRConfig(ncr) {
  if (!ncr) {
    return { xmlVersion: 1, onLevel: NCR_LEVEL.allow, nullLevel: NCR_LEVEL.remove };
  }
  const xmlVersion = ncr.xmlVersion === 1.1 ? 1.1 : 1;
  const onLevel = NCR_LEVEL[ncr.onNCR] ?? NCR_LEVEL.allow;
  const nullLevel = NCR_LEVEL[ncr.nullNCR] ?? NCR_LEVEL.remove;
  const clampedNull = Math.max(nullLevel, NCR_LEVEL.remove);
  return { xmlVersion, onLevel, nullLevel: clampedNull };
}

class EntityDecoder {
  constructor(options = {}) {
    this._limit = options.limit || {};
    this._maxTotalExpansions = this._limit.maxTotalExpansions || 0;
    this._maxExpandedLength = this._limit.maxExpandedLength || 0;
    this._postCheck = typeof options.postCheck === "function" ? options.postCheck : (r) => r;
    this._limitTiers = parseLimitTiers(this._limit.applyLimitsTo ?? LIMIT_TIER_EXTERNAL);
    this._numericAllowed = options.numericAllowed ?? true;
    this._baseMap = mergeEntityMaps(XML, options.namedEntities || null);
    this._externalMap = Object.create(null);
    this._inputMap = Object.create(null);
    this._totalExpansions = 0;
    this._expandedLength = 0;
    this._removeSet = new Set(options.remove && Array.isArray(options.remove) ? options.remove : []);
    this._leaveSet = new Set(options.leave && Array.isArray(options.leave) ? options.leave : []);
    const ncrCfg = parseNCRConfig(options.ncr);
    this._ncrXmlVersion = ncrCfg.xmlVersion;
    this._ncrOnLevel = ncrCfg.onLevel;
    this._ncrNullLevel = ncrCfg.nullLevel;
    this._onExternalEntity = typeof options.onExternalEntity === "function" ? options.onExternalEntity : null;
    this._onInputEntity = typeof options.onInputEntity === "function" ? options.onInputEntity : null;
  }
  _applyRegistrationHook(hook, name, value, context) {
    if (!hook)
      return true;
    const action = hook(name, value);
    if (action === ENTITY_ACTION.BLOCK)
      return false;
    if (action === ENTITY_ACTION.THROW) {
      throw new Error(`[EntityDecoder] Registration of ${context} entity "&${name};" was rejected by hook`);
    }
    return true;
  }
  setExternalEntities(map) {
    if (map) {
      for (const key of Object.keys(map)) {
        validateEntityName(key);
      }
    }
    if (!this._onExternalEntity) {
      this._externalMap = mergeEntityMaps(map);
      return;
    }
    const flat = mergeEntityMaps(map);
    const filtered = Object.create(null);
    for (const [name, value] of Object.entries(flat)) {
      if (this._applyRegistrationHook(this._onExternalEntity, name, value, "external")) {
        filtered[name] = value;
      }
    }
    this._externalMap = filtered;
  }
  addExternalEntity(key, value) {
    validateEntityName(key);
    if (typeof value === "string" && value.indexOf("&") === -1) {
      if (this._applyRegistrationHook(this._onExternalEntity, key, value, "external")) {
        this._externalMap[key] = value;
      }
    }
  }
  addInputEntities(map) {
    this._totalExpansions = 0;
    this._expandedLength = 0;
    if (!this._onInputEntity) {
      this._inputMap = mergeEntityMaps(map);
      return;
    }
    const flat = mergeEntityMaps(map);
    const filtered = Object.create(null);
    for (const [name, value] of Object.entries(flat)) {
      if (this._applyRegistrationHook(this._onInputEntity, name, value, "input")) {
        filtered[name] = value;
      }
    }
    this._inputMap = filtered;
  }
  reset() {
    this._inputMap = Object.create(null);
    this._totalExpansions = 0;
    this._expandedLength = 0;
    return this;
  }
  setXmlVersion(version) {
    this._ncrXmlVersion = version === 1.1 ? 1.1 : 1;
  }
  decode(str) {
    if (typeof str !== "string" || str.length === 0)
      return str;
    if (str.indexOf("&") === -1)
      return str;
    const original = str;
    const chunks = [];
    const len = str.length;
    let last = 0;
    let i = 0;
    const limitExpansions = this._maxTotalExpansions > 0;
    const limitLength = this._maxExpandedLength > 0;
    const checkLimits = limitExpansions || limitLength;
    while (i < len) {
      if (str.charCodeAt(i) !== 38) {
        i++;
        continue;
      }
      let j = i + 1;
      while (j < len && str.charCodeAt(j) !== 59 && j - i <= 32)
        j++;
      if (j >= len || str.charCodeAt(j) !== 59) {
        i++;
        continue;
      }
      const token = str.slice(i + 1, j);
      if (token.length === 0) {
        i++;
        continue;
      }
      let replacement;
      let tier;
      if (this._removeSet.has(token)) {
        replacement = "";
        if (tier === undefined) {
          tier = LIMIT_TIER_EXTERNAL;
        }
      } else if (this._leaveSet.has(token)) {
        i++;
        continue;
      } else if (token.charCodeAt(0) === 35) {
        const ncrResult = this._resolveNCR(token);
        if (ncrResult === undefined) {
          i++;
          continue;
        }
        replacement = ncrResult;
        tier = LIMIT_TIER_BASE;
      } else {
        const resolved = this._resolveName(token);
        replacement = resolved?.value;
        tier = resolved?.tier;
      }
      if (replacement === undefined) {
        i++;
        continue;
      }
      if (i > last)
        chunks.push(str.slice(last, i));
      chunks.push(replacement);
      last = j + 1;
      i = last;
      if (checkLimits && this._tierCounts(tier)) {
        if (limitExpansions) {
          this._totalExpansions++;
          if (this._totalExpansions > this._maxTotalExpansions) {
            throw new Error(`[EntityReplacer] Entity expansion count limit exceeded: ` + `${this._totalExpansions} > ${this._maxTotalExpansions}`);
          }
        }
        if (limitLength) {
          const delta = replacement.length - (token.length + 2);
          if (delta > 0) {
            this._expandedLength += delta;
            if (this._expandedLength > this._maxExpandedLength) {
              throw new Error(`[EntityReplacer] Expanded content length limit exceeded: ` + `${this._expandedLength} > ${this._maxExpandedLength}`);
            }
          }
        }
      }
    }
    if (last < len)
      chunks.push(str.slice(last));
    const result = chunks.length === 0 ? str : chunks.join("");
    return this._postCheck(result, original);
  }
  _tierCounts(tier) {
    if (this._limitTiers.has(LIMIT_TIER_ALL))
      return true;
    return this._limitTiers.has(tier);
  }
  _resolveName(name) {
    if (name in this._inputMap)
      return { value: this._inputMap[name], tier: LIMIT_TIER_EXTERNAL };
    if (name in this._externalMap)
      return { value: this._externalMap[name], tier: LIMIT_TIER_EXTERNAL };
    if (name in this._baseMap)
      return { value: this._baseMap[name], tier: LIMIT_TIER_BASE };
    return;
  }
  _classifyNCR(cp) {
    if (cp === 0)
      return this._ncrNullLevel;
    if (cp >= 55296 && cp <= 57343)
      return NCR_LEVEL.remove;
    if (this._ncrXmlVersion === 1) {
      if (cp >= 1 && cp <= 31 && !XML10_ALLOWED_C0.has(cp))
        return NCR_LEVEL.remove;
    }
    return -1;
  }
  _applyNCRAction(action, token, cp) {
    switch (action) {
      case NCR_LEVEL.allow:
        return String.fromCodePoint(cp);
      case NCR_LEVEL.remove:
        return "";
      case NCR_LEVEL.leave:
        return;
      case NCR_LEVEL.throw:
        throw new Error(`[EntityDecoder] Prohibited numeric character reference ` + `&${token}; (U+${cp.toString(16).toUpperCase().padStart(4, "0")})`);
      default:
        return String.fromCodePoint(cp);
    }
  }
  _resolveNCR(token) {
    const second = token.charCodeAt(1);
    let cp;
    if (second === 120 || second === 88) {
      cp = parseInt(token.slice(2), 16);
    } else {
      cp = parseInt(token.slice(1), 10);
    }
    if (Number.isNaN(cp) || cp < 0 || cp > 1114111)
      return;
    const minimum = this._classifyNCR(cp);
    if (!this._numericAllowed && minimum < NCR_LEVEL.remove)
      return;
    const effective = minimum === -1 ? this._ncrOnLevel : Math.max(this._ncrOnLevel, minimum);
    return this._applyNCRAction(effective, token, cp);
  }
}
// node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js
var defaultOnDangerousProperty = (name) => {
  if (DANGEROUS_PROPERTY_NAMES.includes(name)) {
    return "__" + name;
  }
  return name;
};
var defaultOptions2 = {
  preserveOrder: false,
  attributeNamePrefix: "@_",
  attributesGroupName: false,
  textNodeName: "#text",
  ignoreAttributes: true,
  removeNSPrefix: false,
  allowBooleanAttributes: false,
  parseTagValue: true,
  parseAttributeValue: false,
  trimValues: true,
  cdataPropName: false,
  numberParseOptions: {
    hex: true,
    leadingZeros: true,
    eNotation: true,
    unicode: false
  },
  tagValueProcessor: function(tagName, val) {
    return val;
  },
  attributeValueProcessor: function(attrName, val) {
    return val;
  },
  stopNodes: [],
  alwaysCreateTextNode: false,
  isArray: () => false,
  commentPropName: false,
  unpairedTags: [],
  processEntities: true,
  htmlEntities: false,
  entityDecoder: null,
  ignoreDeclaration: false,
  ignorePiTags: false,
  transformTagName: false,
  transformAttributeName: false,
  updateTag: function(tagName, jPath, attrs) {
    return tagName;
  },
  captureMetaData: false,
  maxNestedTags: 100,
  strictReservedNames: true,
  jPath: true,
  onDangerousProperty: defaultOnDangerousProperty
};
function validatePropertyName(propertyName, optionName) {
  if (typeof propertyName !== "string") {
    return;
  }
  const normalized = propertyName.toLowerCase();
  if (DANGEROUS_PROPERTY_NAMES.some((dangerous) => normalized === dangerous.toLowerCase())) {
    throw new Error(`[SECURITY] Invalid ${optionName}: "${propertyName}" is a reserved JavaScript keyword that could cause prototype pollution`);
  }
  if (criticalProperties.some((dangerous) => normalized === dangerous.toLowerCase())) {
    throw new Error(`[SECURITY] Invalid ${optionName}: "${propertyName}" is a reserved JavaScript keyword that could cause prototype pollution`);
  }
}
function normalizeProcessEntities(value, htmlEntities) {
  if (typeof value === "boolean") {
    return {
      enabled: value,
      maxEntitySize: 1e4,
      maxExpansionDepth: 1e4,
      maxTotalExpansions: Infinity,
      maxExpandedLength: 1e5,
      maxEntityCount: 1000,
      allowedTags: null,
      tagFilter: null,
      appliesTo: "all"
    };
  }
  if (typeof value === "object" && value !== null) {
    return {
      enabled: value.enabled !== false,
      maxEntitySize: Math.max(1, value.maxEntitySize ?? 1e4),
      maxExpansionDepth: Math.max(1, value.maxExpansionDepth ?? 1e4),
      maxTotalExpansions: Math.max(1, value.maxTotalExpansions ?? Infinity),
      maxExpandedLength: Math.max(1, value.maxExpandedLength ?? 1e5),
      maxEntityCount: Math.max(1, value.maxEntityCount ?? 1000),
      allowedTags: value.allowedTags ?? null,
      tagFilter: value.tagFilter ?? null,
      appliesTo: value.appliesTo ?? "all"
    };
  }
  return normalizeProcessEntities(true);
}
var buildOptions = function(options) {
  const built = Object.assign({}, defaultOptions2, options);
  const propertyNameOptions = [
    { value: built.attributeNamePrefix, name: "attributeNamePrefix" },
    { value: built.attributesGroupName, name: "attributesGroupName" },
    { value: built.textNodeName, name: "textNodeName" },
    { value: built.cdataPropName, name: "cdataPropName" },
    { value: built.commentPropName, name: "commentPropName" }
  ];
  for (const { value, name } of propertyNameOptions) {
    if (value) {
      validatePropertyName(value, name);
    }
  }
  if (built.onDangerousProperty === null) {
    built.onDangerousProperty = defaultOnDangerousProperty;
  }
  built.processEntities = normalizeProcessEntities(built.processEntities, built.htmlEntities);
  built.unpairedTagsSet = new Set(built.unpairedTags);
  if (built.stopNodes && Array.isArray(built.stopNodes)) {
    built.stopNodes = built.stopNodes.map((node) => {
      if (typeof node === "string" && node.startsWith("*.")) {
        return ".." + node.substring(2);
      }
      return node;
    });
  }
  return built;
};

// node_modules/fast-xml-parser/src/xmlparser/xmlNode.js
var METADATA_SYMBOL;
if (typeof Symbol !== "function") {
  METADATA_SYMBOL = "@@xmlMetadata";
} else {
  METADATA_SYMBOL = Symbol("XML Node Metadata");
}

class XmlNode {
  constructor(tagname) {
    this.tagname = tagname;
    this.child = [];
    this[":@"] = Object.create(null);
  }
  add(key, val) {
    if (key === "__proto__")
      key = "#__proto__";
    this.child.push({ [key]: val });
  }
  addChild(node, startIndex) {
    if (node.tagname === "__proto__")
      node.tagname = "#__proto__";
    if (node[":@"] && Object.keys(node[":@"]).length > 0) {
      this.child.push({ [node.tagname]: node.child, [":@"]: node[":@"] });
    } else {
      this.child.push({ [node.tagname]: node.child });
    }
    if (startIndex !== undefined) {
      this.child[this.child.length - 1][METADATA_SYMBOL] = { startIndex };
    }
  }
  static getMetaDataSymbol() {
    return METADATA_SYMBOL;
  }
}

// node_modules/xml-naming/src/index.js
var nameStartChar10 = ":A-Za-z_" + "À-ÖØ-öø-˿" + "Ͱ-ͽ" + "Ϳ-҆҈-῿" + "‌-‍" + "⁰-↏" + "Ⰰ-⿯" + "、-퟿" + "豈-﷏" + "ﷰ-�";
var nameChar10 = nameStartChar10 + "\\-\\.\\d" + "·" + "̀-ͯ" + "‿-⁀";
var nameStartChar11 = ":A-Za-z_" + "À-˿" + "Ͱ-ͽ" + "Ϳ-҆҈-῿" + "‌-‍" + "⁰-↏" + "Ⰰ-⿯" + "、-퟿" + "豈-﷏" + "ﷰ-�" + "\uD800\uDC00-\uDB7F\uDFFF";
var nameChar11 = nameStartChar11 + "\\-\\.\\d" + "·" + "̀-ͯ" + "҇" + "‿-⁀";
var buildRegexes = (startChar, char, flags = "") => {
  const ncStart = startChar.replace(":", "");
  const ncChar = char.replace(":", "");
  const ncNamePat = `[${ncStart}][${ncChar}]*`;
  return {
    name: new RegExp(`^[${startChar}][${char}]*$`, flags),
    ncName: new RegExp(`^${ncNamePat}$`, flags),
    qName: new RegExp(`^${ncNamePat}(?::${ncNamePat})?$`, flags),
    nmToken: new RegExp(`^[${char}]+$`, flags),
    nmTokens: new RegExp(`^[${char}]+(?:\\s+[${char}]+)*$`, flags)
  };
};
var regexes10 = buildRegexes(nameStartChar10, nameChar10);
var regexes11 = buildRegexes(nameStartChar11, nameChar11, "u");
var nameStartCharAscii = ":A-Za-z_";
var nameCharAscii = nameStartCharAscii + "\\-\\.\\d";
var regexesAscii = buildRegexes(nameStartCharAscii, nameCharAscii);
var getRegexes = (xmlVersion = "1.0", asciiOnly = false) => {
  if (asciiOnly)
    return regexesAscii;
  return xmlVersion === "1.1" ? regexes11 : regexes10;
};
var qName = (str, { xmlVersion = "1.0", asciiOnly = false } = {}) => getRegexes(xmlVersion, asciiOnly).qName.test(str);

// node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js
class DocTypeReader {
  constructor(options, xmlVersion) {
    this.suppressValidationErr = !options;
    this.options = options;
    this.xmlVersion = xmlVersion || 1;
  }
  setXmlVersion(xmlVersion = 1) {
    this.xmlVersion = xmlVersion;
  }
  readDocType(xmlData, i) {
    const entities = Object.create(null);
    let entityCount = 0;
    if (xmlData[i + 3] === "O" && xmlData[i + 4] === "C" && xmlData[i + 5] === "T" && xmlData[i + 6] === "Y" && xmlData[i + 7] === "P" && xmlData[i + 8] === "E") {
      i = i + 9;
      let angleBracketsCount = 1;
      let hasBody = false, comment = false;
      let exp = "";
      for (;i < xmlData.length; i++) {
        if (xmlData[i] === "<" && !comment) {
          if (hasBody && hasSeq(xmlData, "!ENTITY", i)) {
            i += 7;
            let entityName, val;
            [entityName, val, i] = this.readEntityExp(xmlData, i + 1, this.suppressValidationErr);
            if (val.indexOf("&") === -1) {
              if (this.options.enabled !== false && this.options.maxEntityCount != null && entityCount >= this.options.maxEntityCount) {
                throw new Error(`Entity count (${entityCount + 1}) exceeds maximum allowed (${this.options.maxEntityCount})`);
              }
              entities[entityName] = val;
              entityCount++;
            }
          } else if (hasBody && hasSeq(xmlData, "!ELEMENT", i)) {
            i += 8;
            const { index } = this.readElementExp(xmlData, i + 1);
            i = index;
          } else if (hasBody && hasSeq(xmlData, "!ATTLIST", i)) {
            i += 8;
          } else if (hasBody && hasSeq(xmlData, "!NOTATION", i)) {
            i += 9;
            const { index } = this.readNotationExp(xmlData, i + 1, this.suppressValidationErr);
            i = index;
          } else if (hasSeq(xmlData, "!--", i))
            comment = true;
          else
            throw new Error(`Invalid DOCTYPE`);
          angleBracketsCount++;
          exp = "";
        } else if (xmlData[i] === ">") {
          if (comment) {
            if (xmlData[i - 1] === "-" && xmlData[i - 2] === "-") {
              comment = false;
              angleBracketsCount--;
            }
          } else {
            angleBracketsCount--;
          }
          if (angleBracketsCount === 0) {
            break;
          }
        } else if (xmlData[i] === "[") {
          hasBody = true;
        } else {
          exp += xmlData[i];
        }
      }
      if (angleBracketsCount !== 0) {
        throw new Error(`Unclosed DOCTYPE`);
      }
    } else {
      throw new Error(`Invalid Tag instead of DOCTYPE`);
    }
    return { entities, i };
  }
  readEntityExp(xmlData, i) {
    i = skipWhitespace(xmlData, i);
    const startIndex = i;
    while (i < xmlData.length && !/\s/.test(xmlData[i]) && xmlData[i] !== '"' && xmlData[i] !== "'") {
      i++;
    }
    let entityName = xmlData.substring(startIndex, i);
    validateEntityName2(entityName, { xmlVersion: this.xmlVersion });
    i = skipWhitespace(xmlData, i);
    if (!this.suppressValidationErr) {
      if (xmlData.substring(i, i + 6).toUpperCase() === "SYSTEM") {
        throw new Error("External entities are not supported");
      } else if (xmlData[i] === "%") {
        throw new Error("Parameter entities are not supported");
      }
    }
    let entityValue = "";
    [i, entityValue] = this.readIdentifierVal(xmlData, i, "entity");
    if (this.options.enabled !== false && this.options.maxEntitySize != null && entityValue.length > this.options.maxEntitySize) {
      throw new Error(`Entity "${entityName}" size (${entityValue.length}) exceeds maximum allowed size (${this.options.maxEntitySize})`);
    }
    i--;
    return [entityName, entityValue, i];
  }
  readNotationExp(xmlData, i) {
    i = skipWhitespace(xmlData, i);
    const startIndex = i;
    while (i < xmlData.length && !/\s/.test(xmlData[i])) {
      i++;
    }
    let notationName = xmlData.substring(startIndex, i);
    !this.suppressValidationErr && validateEntityName2(notationName, { xmlVersion: this.xmlVersion });
    i = skipWhitespace(xmlData, i);
    const identifierType = xmlData.substring(i, i + 6).toUpperCase();
    if (!this.suppressValidationErr && identifierType !== "SYSTEM" && identifierType !== "PUBLIC") {
      throw new Error(`Expected SYSTEM or PUBLIC, found "${identifierType}"`);
    }
    i += identifierType.length;
    i = skipWhitespace(xmlData, i);
    let publicIdentifier = null;
    let systemIdentifier = null;
    if (identifierType === "PUBLIC") {
      [i, publicIdentifier] = this.readIdentifierVal(xmlData, i, "publicIdentifier");
      i = skipWhitespace(xmlData, i);
      if (xmlData[i] === '"' || xmlData[i] === "'") {
        [i, systemIdentifier] = this.readIdentifierVal(xmlData, i, "systemIdentifier");
      }
    } else if (identifierType === "SYSTEM") {
      [i, systemIdentifier] = this.readIdentifierVal(xmlData, i, "systemIdentifier");
      if (!this.suppressValidationErr && !systemIdentifier) {
        throw new Error("Missing mandatory system identifier for SYSTEM notation");
      }
    }
    return { notationName, publicIdentifier, systemIdentifier, index: --i };
  }
  readIdentifierVal(xmlData, i, type) {
    let identifierVal = "";
    const startChar = xmlData[i];
    if (startChar !== '"' && startChar !== "'") {
      throw new Error(`Expected quoted string, found "${startChar}"`);
    }
    i++;
    const startIndex = i;
    while (i < xmlData.length && xmlData[i] !== startChar) {
      i++;
    }
    identifierVal = xmlData.substring(startIndex, i);
    if (xmlData[i] !== startChar) {
      throw new Error(`Unterminated ${type} value`);
    }
    i++;
    return [i, identifierVal];
  }
  readElementExp(xmlData, i) {
    i = skipWhitespace(xmlData, i);
    const startIndex = i;
    while (i < xmlData.length && !/\s/.test(xmlData[i])) {
      i++;
    }
    let elementName = xmlData.substring(startIndex, i);
    if (!this.suppressValidationErr && !qName(elementName, { xmlVersion: this.xmlVersion })) {
      throw new Error(`Invalid element name: "${elementName}"`);
    }
    i = skipWhitespace(xmlData, i);
    let contentModel = "";
    if (xmlData[i] === "E" && hasSeq(xmlData, "MPTY", i))
      i += 4;
    else if (xmlData[i] === "A" && hasSeq(xmlData, "NY", i))
      i += 2;
    else if (xmlData[i] === "(") {
      i++;
      const startIndex2 = i;
      while (i < xmlData.length && xmlData[i] !== ")") {
        i++;
      }
      contentModel = xmlData.substring(startIndex2, i);
      if (xmlData[i] !== ")") {
        throw new Error("Unterminated content model");
      }
    } else if (!this.suppressValidationErr) {
      throw new Error(`Invalid Element Expression, found "${xmlData[i]}"`);
    }
    return {
      elementName,
      contentModel: contentModel.trim(),
      index: i
    };
  }
  readAttlistExp(xmlData, i) {
    i = skipWhitespace(xmlData, i);
    let startIndex = i;
    while (i < xmlData.length && !/\s/.test(xmlData[i])) {
      i++;
    }
    let elementName = xmlData.substring(startIndex, i);
    validateEntityName2(elementName, { xmlVersion: this.xmlVersion });
    i = skipWhitespace(xmlData, i);
    startIndex = i;
    while (i < xmlData.length && !/\s/.test(xmlData[i])) {
      i++;
    }
    let attributeName = xmlData.substring(startIndex, i);
    if (!validateEntityName2(attributeName, { xmlVersion: this.xmlVersion })) {
      throw new Error(`Invalid attribute name: "${attributeName}"`);
    }
    i = skipWhitespace(xmlData, i);
    let attributeType = "";
    if (xmlData.substring(i, i + 8).toUpperCase() === "NOTATION") {
      attributeType = "NOTATION";
      i += 8;
      i = skipWhitespace(xmlData, i);
      if (xmlData[i] !== "(") {
        throw new Error(`Expected '(', found "${xmlData[i]}"`);
      }
      i++;
      let allowedNotations = [];
      while (i < xmlData.length && xmlData[i] !== ")") {
        const startIndex2 = i;
        while (i < xmlData.length && xmlData[i] !== "|" && xmlData[i] !== ")") {
          i++;
        }
        let notation = xmlData.substring(startIndex2, i);
        notation = notation.trim();
        if (!validateEntityName2(notation, { xmlVersion: this.xmlVersion })) {
          throw new Error(`Invalid notation name: "${notation}"`);
        }
        allowedNotations.push(notation);
        if (xmlData[i] === "|") {
          i++;
          i = skipWhitespace(xmlData, i);
        }
      }
      if (xmlData[i] !== ")") {
        throw new Error("Unterminated list of notations");
      }
      i++;
      attributeType += " (" + allowedNotations.join("|") + ")";
    } else {
      const startIndex2 = i;
      while (i < xmlData.length && !/\s/.test(xmlData[i])) {
        i++;
      }
      attributeType += xmlData.substring(startIndex2, i);
      const validTypes = ["CDATA", "ID", "IDREF", "IDREFS", "ENTITY", "ENTITIES", "NMTOKEN", "NMTOKENS"];
      if (!this.suppressValidationErr && !validTypes.includes(attributeType.toUpperCase())) {
        throw new Error(`Invalid attribute type: "${attributeType}"`);
      }
    }
    i = skipWhitespace(xmlData, i);
    let defaultValue = "";
    if (xmlData.substring(i, i + 8).toUpperCase() === "#REQUIRED") {
      defaultValue = "#REQUIRED";
      i += 8;
    } else if (xmlData.substring(i, i + 7).toUpperCase() === "#IMPLIED") {
      defaultValue = "#IMPLIED";
      i += 7;
    } else {
      [i, defaultValue] = this.readIdentifierVal(xmlData, i, "ATTLIST");
    }
    return {
      elementName,
      attributeName,
      attributeType,
      defaultValue,
      index: i
    };
  }
}
var skipWhitespace = (data, index) => {
  while (index < data.length && /\s/.test(data[index])) {
    index++;
  }
  return index;
};
function hasSeq(data, seq, i) {
  for (let j = 0;j < seq.length; j++) {
    if (seq[j] !== data[i + j + 1])
      return false;
  }
  return true;
}
function validateEntityName2(name, xmlVersion) {
  if (qName(name, { xmlVersion }))
    return name;
  else
    throw new Error(`Invalid entity name ${name}`);
}

// node_modules/anynum/digitTable.js
var SCRIPT_ZEROS = [
  48,
  1632,
  1776,
  2406,
  2534,
  2662,
  2790,
  2918,
  3046,
  3174,
  3302,
  3430,
  3558,
  3664,
  3792,
  3872,
  4160,
  4240,
  6112,
  6160,
  6470,
  6608,
  6784,
  6800,
  6992,
  7088,
  7232,
  7248,
  65296,
  120782,
  120792,
  120802,
  120812,
  120822,
  66720,
  68912,
  69734,
  69872,
  69942,
  70096,
  70384,
  70736,
  70864,
  71248,
  71360,
  71472,
  71904,
  72016,
  72688,
  72784,
  73040,
  73120,
  73552,
  92768,
  92864,
  93008,
  123200,
  123632,
  124144,
  125264,
  130032
];
var NOT_DIGIT = 255;
var HIGH_MAP = new Map;
var LOW_MAX = 65535;
var LOW_MIN = 1632;
var TABLE_OFFSET = LOW_MIN;
var TABLE_SIZE = LOW_MAX - LOW_MIN + 1;
var TABLE = new Uint8Array(TABLE_SIZE).fill(NOT_DIGIT);
for (const zero of SCRIPT_ZEROS) {
  for (let d = 0;d < 10; d++) {
    const cp = zero + d;
    if (cp <= LOW_MAX) {
      TABLE[cp - TABLE_OFFSET] = d;
    } else {
      HIGH_MAP.set(cp, d);
    }
  }
}

// node_modules/anynum/anynum.js
var CHAR_0 = 48;
var CHAR_9 = 57;
var CHAR_MINUS = 45;
var MINUS_SET = new Set([8722, 65293, 65123]);
function anynum(str) {
  if (typeof str !== "string")
    return str;
  const len = str.length;
  if (len === 0)
    return str;
  let firstHit = -1;
  for (let i = 0;i < len; i++) {
    const cc = str.charCodeAt(i);
    if (cc >= CHAR_0 && cc <= CHAR_9 || cc === CHAR_MINUS)
      continue;
    if (cc < TABLE_OFFSET) {
      if (MINUS_SET.has(cc)) {
        firstHit = i;
        break;
      }
      continue;
    }
    if (cc >= 55296 && cc <= 56319) {
      if (i + 1 < len) {
        const low = str.charCodeAt(i + 1);
        if (low >= 56320 && low <= 57343) {
          const cp = 65536 + (cc - 55296 << 10) + (low - 56320);
          if (HIGH_MAP.has(cp)) {
            firstHit = i;
            break;
          }
        }
      }
      continue;
    }
    if (TABLE[cc - TABLE_OFFSET] !== NOT_DIGIT || MINUS_SET.has(cc)) {
      firstHit = i;
      break;
    }
  }
  if (firstHit === -1)
    return str;
  const chars = [];
  if (firstHit > 0)
    chars.push(str.slice(0, firstHit));
  for (let i = firstHit;i < len; i++) {
    const cc = str.charCodeAt(i);
    if (cc >= CHAR_0 && cc <= CHAR_9 || cc === CHAR_MINUS) {
      chars.push(str[i]);
      continue;
    }
    if (cc < TABLE_OFFSET) {
      chars.push(MINUS_SET.has(cc) ? "-" : str[i]);
      continue;
    }
    if (cc >= 55296 && cc <= 56319) {
      if (i + 1 < len) {
        const low = str.charCodeAt(i + 1);
        if (low >= 56320 && low <= 57343) {
          const cp = 65536 + (cc - 55296 << 10) + (low - 56320);
          const d2 = HIGH_MAP.get(cp);
          if (d2 !== undefined) {
            chars.push(String.fromCharCode(d2 + 48));
            i++;
            continue;
          }
        }
      }
      chars.push(str[i]);
      continue;
    }
    if (MINUS_SET.has(cc)) {
      chars.push("-");
      continue;
    }
    const d = TABLE[cc - TABLE_OFFSET];
    chars.push(d !== NOT_DIGIT ? String.fromCharCode(d + 48) : str[i]);
  }
  return chars.join("");
}
var anynum_default = anynum;

// node_modules/strnum/strnum.js
var hexRegex = /^[-+]?0x[a-fA-F0-9]+$/;
var binRegex = /^0b[01]+$/;
var octRegex = /^0o[0-7]+$/;
var numRegex = /^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/;
var consider = {
  hex: true,
  binary: false,
  octal: false,
  leadingZeros: true,
  decimalPoint: ".",
  eNotation: true,
  infinity: "original",
  unicode: false
};
function toNumber(str, options = {}) {
  options = Object.assign({}, consider, options);
  if (!str || typeof str !== "string")
    return str;
  let trimmedStr = str.trim();
  if (trimmedStr.length === 0)
    return str;
  else if (options.skipLike !== undefined && options.skipLike.test(trimmedStr))
    return str;
  else if (trimmedStr === "0")
    return 0;
  if (options.unicode) {
    trimmedStr = anynum_default(trimmedStr);
    if (trimmedStr === "0")
      return 0;
  }
  if (options.hex && hexRegex.test(trimmedStr)) {
    return parse_int(trimmedStr, 16);
  } else if (options.binary && binRegex.test(trimmedStr)) {
    return parse_int(trimmedStr, 2);
  } else if (options.octal && octRegex.test(trimmedStr)) {
    return parse_int(trimmedStr, 8);
  } else if (!isFinite(trimmedStr)) {
    return handleInfinity(str, Number(trimmedStr), options);
  } else if (trimmedStr.includes("e") || trimmedStr.includes("E")) {
    return resolveEnotation(str, trimmedStr, options);
  } else {
    const match = numRegex.exec(trimmedStr);
    if (match) {
      const sign = match[1] || "";
      const leadingZeros = match[2];
      let numTrimmedByZeros = trimZeros(match[3]);
      const decimalAdjacentToLeadingZeros = sign ? str[leadingZeros.length + 1] === "." : str[leadingZeros.length] === ".";
      if (!options.leadingZeros && (leadingZeros.length > 1 || leadingZeros.length === 1 && !decimalAdjacentToLeadingZeros)) {
        return str;
      } else {
        const num2 = Number(trimmedStr);
        const parsedStr = String(num2);
        if (num2 === 0)
          return num2;
        if (parsedStr.search(/[eE]/) !== -1) {
          if (options.eNotation)
            return num2;
          else
            return str;
        } else if (trimmedStr.indexOf(".") !== -1) {
          if (parsedStr === "0")
            return num2;
          else if (parsedStr === numTrimmedByZeros)
            return num2;
          else if (parsedStr === `${sign}${numTrimmedByZeros}`)
            return num2;
          else
            return str;
        }
        let n = leadingZeros ? numTrimmedByZeros : trimmedStr;
        if (leadingZeros) {
          return n === parsedStr || sign + n === parsedStr ? num2 : str;
        } else {
          return n === parsedStr || n === sign + parsedStr ? num2 : str;
        }
      }
    } else {
      return str;
    }
  }
}
var eNotationRegx = /^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;
function resolveEnotation(str, trimmedStr, options) {
  if (!options.eNotation)
    return str;
  const notation = trimmedStr.match(eNotationRegx);
  if (notation) {
    let sign = notation[1] || "";
    const eChar = notation[3].indexOf("e") === -1 ? "E" : "e";
    const leadingZeros = notation[2];
    const eAdjacentToLeadingZeros = sign ? str[leadingZeros.length + 1] === eChar : str[leadingZeros.length] === eChar;
    if (leadingZeros.length > 1 && eAdjacentToLeadingZeros)
      return str;
    else if (leadingZeros.length === 1 && (notation[3].startsWith(`.${eChar}`) || notation[3][0] === eChar)) {
      return Number(trimmedStr);
    } else if (leadingZeros.length > 0) {
      if (options.leadingZeros && !eAdjacentToLeadingZeros) {
        trimmedStr = (notation[1] || "") + notation[3];
        return Number(trimmedStr);
      } else
        return str;
    } else {
      return Number(trimmedStr);
    }
  } else {
    return str;
  }
}
function trimZeros(numStr) {
  if (numStr && numStr.indexOf(".") !== -1) {
    numStr = numStr.replace(/0+$/, "");
    if (numStr === ".")
      numStr = "0";
    else if (numStr[0] === ".")
      numStr = "0" + numStr;
    else if (numStr[numStr.length - 1] === ".")
      numStr = numStr.substring(0, numStr.length - 1);
    return numStr;
  }
  return numStr;
}
function parse_int(numStr, base) {
  const str = numStr.trim();
  if (base === 2 || base === 8)
    numStr = str.substring(2);
  if (parseInt)
    return parseInt(numStr, base);
  else if (Number.parseInt)
    return Number.parseInt(numStr, base);
  else if (window && window.parseInt)
    return window.parseInt(numStr, base);
  else
    throw new Error("parseInt, Number.parseInt, window.parseInt are not supported");
}
function handleInfinity(str, num2, options) {
  const isPositive = num2 === Infinity;
  switch (options.infinity.toLowerCase()) {
    case "null":
      return null;
    case "infinity":
      return num2;
    case "string":
      return isPositive ? "Infinity" : "-Infinity";
    case "original":
    default:
      return str;
  }
}

// node_modules/fast-xml-parser/src/ignoreAttributes.js
function getIgnoreAttributesFn(ignoreAttributes) {
  if (typeof ignoreAttributes === "function") {
    return ignoreAttributes;
  }
  if (Array.isArray(ignoreAttributes)) {
    return (attrName) => {
      for (const pattern of ignoreAttributes) {
        if (typeof pattern === "string" && attrName === pattern) {
          return true;
        }
        if (pattern instanceof RegExp && pattern.test(attrName)) {
          return true;
        }
      }
    };
  }
  return () => false;
}

// node_modules/path-expression-matcher/src/Expression.js
class Expression {
  constructor(pattern, options = {}, data) {
    this.pattern = pattern;
    this.separator = options.separator || ".";
    this.segments = this._parse(pattern);
    this.data = data;
    this._hasDeepWildcard = this.segments.some((seg) => seg.type === "deep-wildcard");
    this._hasAttributeCondition = this.segments.some((seg) => seg.attrName !== undefined);
    this._hasPositionSelector = this.segments.some((seg) => seg.position !== undefined);
  }
  _parse(pattern) {
    const segments = [];
    let i = 0;
    let currentPart = "";
    while (i < pattern.length) {
      if (pattern[i] === this.separator) {
        if (i + 1 < pattern.length && pattern[i + 1] === this.separator) {
          if (currentPart.trim()) {
            segments.push(this._parseSegment(currentPart.trim()));
            currentPart = "";
          }
          segments.push({ type: "deep-wildcard" });
          i += 2;
        } else {
          if (currentPart.trim()) {
            segments.push(this._parseSegment(currentPart.trim()));
          }
          currentPart = "";
          i++;
        }
      } else {
        currentPart += pattern[i];
        i++;
      }
    }
    if (currentPart.trim()) {
      segments.push(this._parseSegment(currentPart.trim()));
    }
    return segments;
  }
  _parseSegment(part) {
    const segment = { type: "tag" };
    let bracketContent = null;
    let withoutBrackets = part;
    const bracketMatch = part.match(/^([^\[]+)(\[[^\]]*\])(.*)$/);
    if (bracketMatch) {
      withoutBrackets = bracketMatch[1] + bracketMatch[3];
      if (bracketMatch[2]) {
        const content = bracketMatch[2].slice(1, -1);
        if (content) {
          bracketContent = content;
        }
      }
    }
    let namespace = undefined;
    let tagAndPosition = withoutBrackets;
    if (withoutBrackets.includes("::")) {
      const nsIndex = withoutBrackets.indexOf("::");
      namespace = withoutBrackets.substring(0, nsIndex).trim();
      tagAndPosition = withoutBrackets.substring(nsIndex + 2).trim();
      if (!namespace) {
        throw new Error(`Invalid namespace in pattern: ${part}`);
      }
    }
    let tag = undefined;
    let positionMatch = null;
    if (tagAndPosition.includes(":")) {
      const colonIndex = tagAndPosition.lastIndexOf(":");
      const tagPart = tagAndPosition.substring(0, colonIndex).trim();
      const posPart = tagAndPosition.substring(colonIndex + 1).trim();
      const isPositionKeyword = ["first", "last", "odd", "even"].includes(posPart) || /^nth\(\d+\)$/.test(posPart);
      if (isPositionKeyword) {
        tag = tagPart;
        positionMatch = posPart;
      } else {
        tag = tagAndPosition;
      }
    } else {
      tag = tagAndPosition;
    }
    if (!tag) {
      throw new Error(`Invalid segment pattern: ${part}`);
    }
    segment.tag = tag;
    if (namespace) {
      segment.namespace = namespace;
    }
    if (bracketContent) {
      if (bracketContent.includes("=")) {
        const eqIndex = bracketContent.indexOf("=");
        segment.attrName = bracketContent.substring(0, eqIndex).trim();
        segment.attrValue = bracketContent.substring(eqIndex + 1).trim();
      } else {
        segment.attrName = bracketContent.trim();
      }
    }
    if (positionMatch) {
      const nthMatch = positionMatch.match(/^nth\((\d+)\)$/);
      if (nthMatch) {
        segment.position = "nth";
        segment.positionValue = parseInt(nthMatch[1], 10);
      } else {
        segment.position = positionMatch;
      }
    }
    return segment;
  }
  get length() {
    return this.segments.length;
  }
  hasDeepWildcard() {
    return this._hasDeepWildcard;
  }
  hasAttributeCondition() {
    return this._hasAttributeCondition;
  }
  hasPositionSelector() {
    return this._hasPositionSelector;
  }
  toString() {
    return this.pattern;
  }
}

// node_modules/path-expression-matcher/src/ExpressionSet.js
class ExpressionSet {
  constructor() {
    this._byDepthAndTag = new Map;
    this._wildcardByDepth = new Map;
    this._deepWildcards = [];
    this._deepByTerminalTag = new Map;
    this._patterns = new Set;
    this._sealed = false;
  }
  add(expression) {
    if (this._sealed) {
      throw new TypeError("ExpressionSet is sealed. Create a new ExpressionSet to add more expressions.");
    }
    if (this._patterns.has(expression.pattern))
      return this;
    this._patterns.add(expression.pattern);
    if (expression.hasDeepWildcard()) {
      const lastSeg2 = expression.segments[expression.segments.length - 1];
      if (lastSeg2 && lastSeg2.type !== "deep-wildcard" && lastSeg2.tag !== "*") {
        const tag2 = lastSeg2.tag;
        if (!this._deepByTerminalTag.has(tag2))
          this._deepByTerminalTag.set(tag2, []);
        this._deepByTerminalTag.get(tag2).push(expression);
      } else {
        this._deepWildcards.push(expression);
      }
      return this;
    }
    const depth = expression.length;
    const lastSeg = expression.segments[expression.segments.length - 1];
    const tag = lastSeg?.tag;
    if (!tag || tag === "*") {
      if (!this._wildcardByDepth.has(depth))
        this._wildcardByDepth.set(depth, []);
      this._wildcardByDepth.get(depth).push(expression);
    } else {
      const key = `${depth}:${tag}`;
      if (!this._byDepthAndTag.has(key))
        this._byDepthAndTag.set(key, []);
      this._byDepthAndTag.get(key).push(expression);
    }
    return this;
  }
  addAll(expressions) {
    for (const expr of expressions)
      this.add(expr);
    return this;
  }
  has(expression) {
    return this._patterns.has(expression.pattern);
  }
  get size() {
    return this._patterns.size;
  }
  seal() {
    this._sealed = true;
    return this;
  }
  get isSealed() {
    return this._sealed;
  }
  matchesAny(matcher) {
    return this.findMatch(matcher) !== null;
  }
  findMatch(matcher) {
    const depth = matcher.getDepth();
    const tag = matcher.getCurrentTag();
    const exactKey = `${depth}:${tag}`;
    const exactBucket = this._byDepthAndTag.get(exactKey);
    if (exactBucket) {
      for (let i = 0;i < exactBucket.length; i++) {
        if (matcher.matches(exactBucket[i]))
          return exactBucket[i];
      }
    }
    const wildcardBucket = this._wildcardByDepth.get(depth);
    if (wildcardBucket) {
      for (let i = 0;i < wildcardBucket.length; i++) {
        if (matcher.matches(wildcardBucket[i]))
          return wildcardBucket[i];
      }
    }
    const deepBucket = this._deepByTerminalTag.get(tag);
    if (deepBucket) {
      for (let i = 0;i < deepBucket.length; i++) {
        if (matcher.matches(deepBucket[i]))
          return deepBucket[i];
      }
    }
    for (let i = 0;i < this._deepWildcards.length; i++) {
      if (matcher.matches(this._deepWildcards[i]))
        return this._deepWildcards[i];
    }
    return null;
  }
}

// node_modules/path-expression-matcher/src/Matcher.js
class MatcherView {
  constructor(matcher) {
    this._matcher = matcher;
  }
  get separator() {
    return this._matcher.separator;
  }
  getCurrentTag() {
    const path40 = this._matcher.path;
    return path40.length > 0 ? path40[path40.length - 1].tag : undefined;
  }
  getCurrentNamespace() {
    const path40 = this._matcher.path;
    return path40.length > 0 ? path40[path40.length - 1].namespace : undefined;
  }
  getAttrValue(attrName) {
    const path40 = this._matcher.path;
    if (path40.length === 0)
      return;
    return path40[path40.length - 1].values?.[attrName];
  }
  hasAttr(attrName) {
    const path40 = this._matcher.path;
    if (path40.length === 0)
      return false;
    const current = path40[path40.length - 1];
    return current.values !== undefined && attrName in current.values;
  }
  getAnyParentAttr(attrName) {
    return this._matcher.getAnyParentAttr(attrName);
  }
  hasAnyParentAttr(attrName) {
    return this._matcher.hasAnyParentAttr(attrName);
  }
  getPosition() {
    const path40 = this._matcher.path;
    if (path40.length === 0)
      return -1;
    return path40[path40.length - 1].position ?? 0;
  }
  getCounter() {
    const path40 = this._matcher.path;
    if (path40.length === 0)
      return -1;
    return path40[path40.length - 1].counter ?? 0;
  }
  getIndex() {
    return this.getPosition();
  }
  getDepth() {
    return this._matcher.path.length;
  }
  toString(separator, includeNamespace = true) {
    return this._matcher.toString(separator, includeNamespace);
  }
  toArray() {
    return this._matcher.path.map((n) => n.tag);
  }
  matches(expression) {
    return this._matcher.matches(expression);
  }
  matchesAny(exprSet) {
    return exprSet.matchesAny(this._matcher);
  }
}

class Matcher {
  constructor(options = {}) {
    this.separator = options.separator || ".";
    this.path = [];
    this.siblingStacks = [];
    this._pathStringCache = null;
    this._view = new MatcherView(this);
    this._keptAttrs = [];
  }
  push(tagName, attrValues = null, namespace = null, options = null) {
    this._pathStringCache = null;
    if (this.path.length > 0) {
      this.path[this.path.length - 1].values = undefined;
    }
    const currentLevel = this.path.length;
    let level = this.siblingStacks[currentLevel];
    if (!level) {
      level = { counts: new Map, total: 0 };
      this.siblingStacks[currentLevel] = level;
    }
    const siblingKey = namespace ? `${namespace}:${tagName}` : tagName;
    const counter = level.counts.get(siblingKey) || 0;
    const position = level.total;
    level.counts.set(siblingKey, counter + 1);
    level.total++;
    const node = {
      tag: tagName,
      position,
      counter
    };
    if (namespace !== null && namespace !== undefined) {
      node.namespace = namespace;
    }
    if (attrValues !== null && attrValues !== undefined) {
      node.values = attrValues;
    }
    this.path.push(node);
    const depth = this.path.length;
    const keep = options !== null ? options.keep : null;
    if (keep !== null && keep !== undefined && keep.length > 0 && attrValues) {
      for (let i = 0;i < keep.length; i++) {
        const name = keep[i];
        if (attrValues[name] !== undefined) {
          this._keptAttrs.push({ depth, name, value: attrValues[name] });
        }
      }
    }
  }
  pop() {
    if (this.path.length === 0)
      return;
    this._pathStringCache = null;
    const node = this.path.pop();
    if (this.siblingStacks.length > this.path.length + 1) {
      this.siblingStacks.length = this.path.length + 1;
    }
    const poppedDepth = this.path.length + 1;
    while (this._keptAttrs.length > 0 && this._keptAttrs[this._keptAttrs.length - 1].depth >= poppedDepth) {
      this._keptAttrs.pop();
    }
    return node;
  }
  updateCurrent(attrValues) {
    if (this.path.length > 0) {
      const current = this.path[this.path.length - 1];
      if (attrValues !== null && attrValues !== undefined) {
        current.values = attrValues;
      }
    }
  }
  getCurrentTag() {
    return this.path.length > 0 ? this.path[this.path.length - 1].tag : undefined;
  }
  getCurrentNamespace() {
    return this.path.length > 0 ? this.path[this.path.length - 1].namespace : undefined;
  }
  getAttrValue(attrName) {
    if (this.path.length === 0)
      return;
    return this.path[this.path.length - 1].values?.[attrName];
  }
  hasAttr(attrName) {
    if (this.path.length === 0)
      return false;
    const current = this.path[this.path.length - 1];
    return current.values !== undefined && attrName in current.values;
  }
  getAnyParentAttr(attrName) {
    const kept = this._keptAttrs;
    for (let i = kept.length - 1;i >= 0; i--) {
      if (kept[i].name === attrName)
        return kept[i].value;
    }
    return;
  }
  hasAnyParentAttr(attrName) {
    const kept = this._keptAttrs;
    for (let i = kept.length - 1;i >= 0; i--) {
      if (kept[i].name === attrName)
        return true;
    }
    return false;
  }
  getPosition() {
    if (this.path.length === 0)
      return -1;
    return this.path[this.path.length - 1].position ?? 0;
  }
  getCounter() {
    if (this.path.length === 0)
      return -1;
    return this.path[this.path.length - 1].counter ?? 0;
  }
  getIndex() {
    return this.getPosition();
  }
  getDepth() {
    return this.path.length;
  }
  toString(separator, includeNamespace = true) {
    const sep = separator || this.separator;
    const isDefault = sep === this.separator && includeNamespace === true;
    if (isDefault) {
      if (this._pathStringCache !== null) {
        return this._pathStringCache;
      }
      const result = this.path.map((n) => n.namespace ? `${n.namespace}:${n.tag}` : n.tag).join(sep);
      this._pathStringCache = result;
      return result;
    }
    return this.path.map((n) => includeNamespace && n.namespace ? `${n.namespace}:${n.tag}` : n.tag).join(sep);
  }
  toArray() {
    return this.path.map((n) => n.tag);
  }
  reset() {
    this._pathStringCache = null;
    this.path = [];
    this.siblingStacks = [];
    this._keptAttrs = [];
  }
  matches(expression) {
    const segments = expression.segments;
    if (segments.length === 0) {
      return false;
    }
    if (expression.hasDeepWildcard()) {
      return this._matchWithDeepWildcard(segments);
    }
    return this._matchSimple(segments);
  }
  _matchSimple(segments) {
    if (this.path.length !== segments.length) {
      return false;
    }
    for (let i = 0;i < segments.length; i++) {
      if (!this._matchSegment(segments[i], this.path[i], i === this.path.length - 1)) {
        return false;
      }
    }
    return true;
  }
  _matchWithDeepWildcard(segments) {
    let pathIdx = this.path.length - 1;
    let segIdx = segments.length - 1;
    while (segIdx >= 0 && pathIdx >= 0) {
      const segment = segments[segIdx];
      if (segment.type === "deep-wildcard") {
        segIdx--;
        if (segIdx < 0) {
          return true;
        }
        const nextSeg = segments[segIdx];
        let found = false;
        for (let i = pathIdx;i >= 0; i--) {
          if (this._matchSegment(nextSeg, this.path[i], i === this.path.length - 1)) {
            pathIdx = i - 1;
            segIdx--;
            found = true;
            break;
          }
        }
        if (!found) {
          return false;
        }
      } else {
        if (!this._matchSegment(segment, this.path[pathIdx], pathIdx === this.path.length - 1)) {
          return false;
        }
        pathIdx--;
        segIdx--;
      }
    }
    return segIdx < 0;
  }
  _matchSegment(segment, node, isCurrentNode) {
    if (segment.tag !== "*" && segment.tag !== node.tag) {
      return false;
    }
    if (segment.namespace !== undefined) {
      if (segment.namespace !== "*" && segment.namespace !== node.namespace) {
        return false;
      }
    }
    if (segment.attrName !== undefined) {
      if (!isCurrentNode) {
        return false;
      }
      if (!node.values || !(segment.attrName in node.values)) {
        return false;
      }
      if (segment.attrValue !== undefined) {
        if (String(node.values[segment.attrName]) !== String(segment.attrValue)) {
          return false;
        }
      }
    }
    if (segment.position !== undefined) {
      if (!isCurrentNode) {
        return false;
      }
      const counter = node.counter ?? 0;
      if (segment.position === "first" && counter !== 0) {
        return false;
      } else if (segment.position === "odd" && counter % 2 !== 1) {
        return false;
      } else if (segment.position === "even" && counter % 2 !== 0) {
        return false;
      } else if (segment.position === "nth" && counter !== segment.positionValue) {
        return false;
      }
    }
    return true;
  }
  matchesAny(exprSet) {
    return exprSet.matchesAny(this);
  }
  snapshot() {
    return {
      path: this.path.map((node) => ({ ...node })),
      siblingStacks: this.siblingStacks.map((level) => level ? { counts: new Map(level.counts), total: level.total } : level),
      keptAttrs: this._keptAttrs.map((entry) => ({ ...entry }))
    };
  }
  restore(snapshot) {
    this._pathStringCache = null;
    this.path = snapshot.path.map((node) => ({ ...node }));
    this.siblingStacks = snapshot.siblingStacks.map((level) => level ? { counts: new Map(level.counts), total: level.total } : level);
    this._keptAttrs = (snapshot.keptAttrs || []).map((entry) => ({ ...entry }));
  }
  readOnly() {
    return this._view;
  }
}

// node_modules/is-unsafe/src/contexts/html.js
var HTML_PATTERNS = [
  {
    id: "html-script-open",
    description: "<script opening tag",
    pattern: /<script[\s>/]/i
  },
  {
    id: "html-script-close",
    description: "</script closing tag",
    pattern: /<\/script[\s>]/i
  },
  {
    id: "html-javascript-protocol",
    description: "javascript: URI scheme (with optional whitespace/encoding)",
    pattern: /j[\t\n\r ]*a[\t\n\r ]*v[\t\n\r ]*a[\t\n\r ]*s[\t\n\r ]*c[\t\n\r ]*r[\t\n\r ]*i[\t\n\r ]*p[\t\n\r ]*t[\t\n\r ]*:/i
  },
  {
    id: "html-vbscript-protocol",
    description: "vbscript: URI scheme",
    pattern: /vbscript[\t\n\r ]*:/i
  },
  {
    id: "html-data-html",
    description: "data:text/html URI — can execute scripts in browsers",
    pattern: /data[\t\n\r ]*:[\t\n\r ]*text\/html/i
  },
  {
    id: "html-data-xhtml",
    description: "data:application/xhtml+xml URI",
    pattern: /data[\t\n\r ]*:[\t\n\r ]*application\/xhtml/i
  },
  {
    id: "html-data-svg",
    description: "data:image/svg+xml URI — can execute scripts",
    pattern: /data[\t\n\r ]*:[\t\n\r ]*image\/svg\+xml/i
  },
  {
    id: "html-inline-event-handler",
    description: "Inline event handler attributes: onclick=, onerror=, onload=, etc.",
    pattern: /\bon\w{1,30}\s*=/i
  },
  {
    id: "html-entity-obfuscated-script",
    description: "HTML-entity-encoded <script (e.g. &#x3C;script or &lt;script)",
    pattern: /(?:&#x0*3[Cc];?|&#0*60;?|&lt;)\s*script/i
  },
  {
    id: "html-entity-obfuscated-javascript",
    description: 'HTML-entity-encoded javascript: (partial — catches common &#106; or &#x6a; for "j")',
    pattern: /(?:&#x0*6[Aa];?|&#0*106;?)\s*(?:&#x0*61;?|a)[\s\S]{0,80}script\s*:/i
  },
  {
    id: "html-style-expression",
    description: "CSS expression() — IE-era code execution in style attributes",
    pattern: /style[\s\S]{0,20}expression\s*\(/i
  },
  {
    id: "html-object-embed",
    description: "<object or <embed tags that can load active content",
    pattern: /<(?:object|embed)[\s>/]/i
  },
  {
    id: "html-base-tag",
    description: "<base href= — can hijack all relative URLs on a page",
    pattern: /<base[\s>]/i
  },
  {
    id: "html-meta-refresh",
    description: '<meta http-equiv="refresh" — can redirect users',
    pattern: /<meta[\s\S]{0,40}http-equiv[\s\S]{0,20}refresh/i
  },
  {
    id: "html-srcdoc",
    description: "srcdoc= attribute on iframes — embeds HTML that can run scripts",
    pattern: /srcdoc\s*=/i
  },
  {
    id: "html-iframe",
    description: "<iframe tag",
    pattern: /<iframe[\s>/]/i
  },
  {
    id: "html-form",
    description: "<form tag — can be used for phishing / credential harvesting injection",
    pattern: /<form[\s>/]/i
  }
];
var html_default = HTML_PATTERNS;
// node_modules/is-unsafe/src/contexts/xml.js
var XML_PATTERNS = [
  {
    id: "xml-cdata-injection",
    description: "CDATA section injection: <![CDATA[ breaks out of text node context",
    pattern: /<!\[CDATA\[/i
  },
  {
    id: "xml-cdata-close",
    description: "CDATA close sequence: ]]> can terminate an enclosing CDATA section",
    pattern: /\]\]>/
  },
  {
    id: "xml-processing-instruction",
    description: "XML processing instruction: <?xml-stylesheet or <?php etc.",
    pattern: /<\?(?:xml[\- ]|php|asp)/i
  },
  {
    id: "xml-doctype-injection",
    description: "DOCTYPE declaration embedded in content — can define entities",
    pattern: /<!DOCTYPE(?:[\s[]|$)/i
  },
  {
    id: "xml-entity-system",
    description: "SYSTEM keyword — used in external entity declarations (XXE)",
    pattern: /\bSYSTEM\s+["']/i
  },
  {
    id: "xml-entity-public",
    description: "PUBLIC keyword — used in external entity declarations (XXE)",
    pattern: /\bPUBLIC\s+["']/i
  },
  {
    id: "xml-entity-declaration",
    description: "<!ENTITY declaration — defines entities, potential XXE or entity expansion",
    pattern: /<!ENTITY[\s%]/i
  },
  {
    id: "xml-billion-laughs",
    description: "Entity reference chaining / billion laughs: repeated &eX; style references",
    pattern: /(?:&\w{1,20};){3,}/
  },
  {
    id: "xml-namespace-confusion",
    description: "xmlns: attribute injection — can redefine namespaces to confuse parsers",
    pattern: /\bxmlns\s*(?::\w{1,40})?\s*=/i
  },
  {
    id: "xml-comment-injection",
    description: "<!-- comment injection — can hide content from some parsers",
    pattern: /<!--/
  },
  {
    id: "xml-comment-close",
    description: "--> closes an enclosing XML comment",
    pattern: /-->/
  },
  {
    id: "xml-pi-close",
    description: "?> closes an enclosing processing instruction",
    pattern: /\?>/
  }
];
var xml_default = XML_PATTERNS;
// node_modules/is-unsafe/src/contexts/svg.js
var SVG_PATTERNS = [
  {
    id: "svg-script-element",
    description: "<script element inside SVG executes JavaScript",
    pattern: /<script[\s>/]/i
  },
  {
    id: "svg-xlink-href-javascript",
    description: "xlink:href with javascript: — classic SVG XSS via <a> or <use>",
    pattern: /xlink\s*:\s*href\s*=\s*["']?\s*javascript\s*:/i
  },
  {
    id: "svg-href-javascript",
    description: "href= with javascript: in SVG context (<a>, <animate>, etc.)",
    pattern: /href\s*=\s*["']?\s*javascript\s*:/i
  },
  {
    id: "svg-foreignobject",
    description: "<foreignObject embeds HTML inside SVG — can execute scripts",
    pattern: /<foreignObject[\s>/]/i
  },
  {
    id: "svg-use-external",
    description: "<use xlink:href or href pointing to external resource (non-fragment URL)",
    pattern: /<use[\s\S]{0,60}(?:xlink\s*:\s*)?href\s*=\s*(?:["'][^#]|[^"'#\s>])/i
  },
  {
    id: "svg-animate-href",
    description: '<animate attributeName="href" — can dynamically change href to javascript:',
    pattern: /<animate[\s\S]{0,80}attributeName\s*=\s*["'][\s]*href["']/i
  },
  {
    id: "svg-animate-xlinkhref",
    description: '<animate attributeName="xlink:href"',
    pattern: /<animate[\s\S]{0,80}attributeName\s*=\s*["'][\s]*xlink\s*:\s*href["']/i
  },
  {
    id: "svg-set-javascript",
    description: '<set to="javascript:..." — sets an attribute to a javascript: URI',
    pattern: /<set[\s\S]{0,80}to\s*=\s*["']?\s*javascript\s*:/i
  },
  {
    id: "svg-event-handler",
    description: "SVG-specific event handler attributes: onload=, onerror=, onactivate=, etc.",
    pattern: /\bon(?:load|error|activate|begin|end|repeat|focus|blur|click|mouse\w{1,20}|key\w{1,20})\s*=/i
  },
  {
    id: "svg-handler-generic",
    description: "Generic on* handler catch-all for SVG attributes",
    pattern: /\bon\w{1,30}\s*=/i
  },
  {
    id: "svg-filter-feimage",
    description: "<feImage href= — filter primitive that can load external resources",
    pattern: /<feImage[\s\S]{0,80}(?:xlink\s*:\s*)?href\s*=/i
  },
  {
    id: "svg-image-external",
    description: "<image xlink:href with http/https or javascript protocol",
    pattern: /<image[\s\S]{0,80}(?:xlink\s*:\s*)?href\s*=\s*["']?\s*(?:https?|javascript)\s*:/i
  },
  {
    id: "svg-style-javascript",
    description: "style= attribute containing javascript: (e.g. background:url(javascript:...))",
    pattern: /style\s*=[\s\S]{0,60}javascript\s*:/i
  }
];
var svg_default = SVG_PATTERNS;

// node_modules/is-unsafe/src/contexts/sql.js
var SQL_PATTERNS = [
  {
    id: "sql-block-comment-open",
    description: "SQL block comment open: /* ... */ — unusual in legitimate user text",
    pattern: /\/\*/
  },
  {
    id: "sql-union-select",
    description: "UNION SELECT — most common SQL injection aggregation attack",
    pattern: /\bUNION\s{1,20}(?:ALL\s{1,20})?SELECT\b/i
  },
  {
    id: "sql-drop-table",
    description: "DROP TABLE — destructive DDL injection",
    pattern: /\bDROP\s{1,20}TABLE\b/i
  },
  {
    id: "sql-drop-database",
    description: "DROP DATABASE — destructive DDL injection",
    pattern: /\bDROP\s{1,20}DATABASE\b/i
  },
  {
    id: "sql-insert-into",
    description: "INSERT INTO — data injection",
    pattern: /\bINSERT\s{1,20}INTO\b/i
  },
  {
    id: "sql-delete-from",
    description: "DELETE FROM — data deletion injection",
    pattern: /\bDELETE\s{1,20}FROM\b/i
  },
  {
    id: "sql-update-set",
    description: "UPDATE ... SET — data modification injection",
    pattern: /\bUPDATE\b[\s\S]{1,60}\bSET\b/i
  },
  {
    id: "sql-exec-xp",
    description: "EXEC xp_ — MSSQL extended stored procedure execution",
    pattern: /\bEXEC(?:UTE)?\s{1,20}xp_/i
  },
  {
    id: "sql-tautology-string",
    description: `Classic string tautology: ' OR '1'='1 or " OR "1"="1"`,
    pattern: /'\s{0,10}OR\s{0,10}'[^']{0,20}'\s*=\s*'[^']{0,20}/i
  },
  {
    id: "sql-tautology-numeric",
    description: "Numeric tautology: OR 1=1",
    pattern: /\bOR\s{1,10}1\s*=\s*1\b/i
  },
  {
    id: "sql-always-true-zero",
    description: "Numeric tautology: OR 0=0",
    pattern: /\bOR\s{1,10}0\s*=\s*0\b/i
  },
  {
    id: "sql-sleep-benchmark",
    description: "Time-based blind injection: SLEEP() or BENCHMARK()",
    pattern: /\b(?:SLEEP|BENCHMARK)\s*\(/i
  },
  {
    id: "sql-waitfor-delay",
    description: "MSSQL time-based blind injection: WAITFOR DELAY",
    pattern: /\bWAITFOR\s{1,20}DELAY\b/i
  },
  {
    id: "sql-char-function",
    description: "CHAR() function — used to obfuscate injected strings",
    pattern: /\bCHAR\s*\(\s*\d{1,3}/i
  },
  {
    id: "sql-information-schema",
    description: "INFORMATION_SCHEMA — reconnaissance query for table/column enumeration",
    pattern: /\bINFORMATION_SCHEMA\b/i
  }
];
var sql_default = SQL_PATTERNS;

// node_modules/is-unsafe/src/contexts/shell.js
var SHELL_PATTERNS = [
  {
    id: "shell-path-traversal-unix",
    description: "Unix path traversal: ../  — climbing the directory tree",
    pattern: /\.\.\//
  },
  {
    id: "shell-path-traversal-windows",
    description: "Windows path traversal: ..\\ — climbing the directory tree",
    pattern: /\.\.\\/
  },
  {
    id: "shell-path-traversal-encoded",
    description: "URL-encoded path traversal: %2e%2e or %2f variants",
    pattern: /%2e%2e|%2f\.\.|\.\.%2f/i
  },
  {
    id: "shell-null-byte",
    description: "Null byte injection: \\x00 or %00 — truncates strings in C-backed functions",
    pattern: /\x00|%00/
  },
  {
    id: "shell-semicolon",
    description: "Semicolon command separator: cmd1; cmd2",
    pattern: /;/
  },
  {
    id: "shell-pipe",
    description: "Pipe operator: cmd1 | cmd2",
    pattern: /\|/
  },
  {
    id: "shell-and-operator",
    description: "AND operator: cmd1 && cmd2",
    pattern: /&&/
  },
  {
    id: "shell-or-operator",
    description: "OR operator: cmd1 || cmd2",
    pattern: /\|\|/
  },
  {
    id: "shell-backtick",
    description: "Backtick command substitution: `cmd`",
    pattern: /`/
  },
  {
    id: "shell-dollar-paren",
    description: "Dollar-paren command substitution: $(cmd)",
    pattern: /\$\(/
  },
  {
    id: "shell-dollar-brace",
    description: "Dollar-brace variable expansion: ${var} — can be abused for injection",
    pattern: /\$\{/
  },
  {
    id: "shell-redirect-out",
    description: "Output redirection: cmd > file or cmd >> file",
    pattern: />{1,2}/
  },
  {
    id: "shell-redirect-in",
    description: "Input redirection: cmd < file",
    pattern: /</
  },
  {
    id: "shell-newline-injection",
    description: "Newline injection: \\n or \\r — can inject new shell commands",
    pattern: /[\n\r]/
  },
  {
    id: "shell-glob-star",
    description: "Glob expansion: * or ? — can expand to unintended files",
    pattern: /[/\\][*?]/
  },
  {
    id: "shell-absolute-root",
    description: "Absolute root path injection: string starting with / or \\ (Windows UNC)",
    pattern: /^(?:\/|\\\\)/
  },
  {
    id: "shell-windows-drive",
    description: "Windows drive letter path injection: C:\\ or D:/",
    pattern: /^[a-zA-Z]:[/\\]/
  },
  {
    id: "shell-curl-wget",
    description: "curl/wget with URL or flags — can exfiltrate data or download payloads",
    pattern: /\b(?:curl|wget)\s+(?:https?:\/\/|ftp:\/\/|-)/i
  }
];
var shell_default = SHELL_PATTERNS;

// node_modules/is-unsafe/src/contexts/redos.js
var REDOS_PATTERNS = [
  {
    id: "redos-nested-quantifier-plus",
    description: "Nested + quantifier inside a group with outer quantifier: (a+)+, (.+b)*, etc.",
    pattern: /\([^)]*\+[^)]*\)[+*]/
  },
  {
    id: "redos-nested-quantifier-star",
    description: "Nested * quantifier: (a*)* or (a*)+ — catastrophic backtracking",
    pattern: /\([^)]*\*[^)]*\)[*+]/
  },
  {
    id: "redos-nested-groups",
    description: "Doubly nested quantified groups: ((a+)+) — guaranteed catastrophic",
    pattern: /\(\([^)]{0,40}\)[+*]\)[+*]/
  },
  {
    id: "redos-alternation-overlap",
    description: "Overlapping alternation under quantifier: (a|a)+ — ambiguous NFA paths",
    pattern: /\(([^|()]{1,20})\|(?:\1)(?:\|[^|()]{1,20}){0,5}\)[+*?]{1,2}/
  },
  {
    id: "redos-star-plus-concat",
    description: "(x*x)+ pattern — triggers super-linear backtracking",
    pattern: /\([^)]{0,10}\*[^)]{0,10}\)[+*]/
  },
  {
    id: "redos-dot-star-greedy",
    description: "(.*){n,} or (.+){n,} — repeated greedy dot quantifiers",
    pattern: /\(\.[*+]\)\{?\d/
  },
  {
    id: "redos-large-repetition",
    description: "Very large fixed or range repetition count {1000,} or {1000,n} — denial of service via backtracking",
    pattern: /\{\d{4,}(?:,\d*)?\}/
  },
  {
    id: "redos-catastrophic-alternation",
    description: "Long alternation with many similar branches — polynomial backtracking risk",
    pattern: /\([^)]{0,200}(?:\|[^|)]{0,50}){9,}\)/
  }
];
var redos_default = REDOS_PATTERNS;

// node_modules/is-unsafe/src/contexts/nosql.js
var sep = `["'\\s]*:`;
var NOSQL_PATTERNS = [
  {
    id: "nosql-where-operator",
    description: "$where — executes arbitrary JavaScript server-side in MongoDB",
    pattern: new RegExp(`\\$where${sep}`, "i")
  },
  {
    id: "nosql-ne-operator",
    description: '$ne — "not equal" operator used to bypass equality checks',
    pattern: new RegExp(`\\$ne${sep}`, "i")
  },
  {
    id: "nosql-gt-operator",
    description: '$gt — "greater than" used to bypass password/value checks',
    pattern: new RegExp(`\\$gte?${sep}`, "i")
  },
  {
    id: "nosql-lt-operator",
    description: '$lt / $lte — "less than" bypass variants',
    pattern: new RegExp(`\\$lte?${sep}`, "i")
  },
  {
    id: "nosql-regex-operator",
    description: "$regex — can be used to extract data character by character (blind injection)",
    pattern: new RegExp(`\\$regex${sep}`, "i")
  },
  {
    id: "nosql-or-operator",
    description: "$or — logical OR; used to create always-true conditions",
    pattern: new RegExp(`\\$or${sep}\\s*\\[`, "i")
  },
  {
    id: "nosql-and-operator",
    description: "$and — logical AND operator injection",
    pattern: new RegExp(`\\$and${sep}\\s*\\[`, "i")
  },
  {
    id: "nosql-nor-operator",
    description: "$nor — logical NOR operator injection",
    pattern: new RegExp(`\\$nor${sep}\\s*\\[`, "i")
  },
  {
    id: "nosql-exists-operator",
    description: "$exists — can enumerate fields to determine schema",
    pattern: new RegExp(`\\$exists${sep}`, "i")
  },
  {
    id: "nosql-in-operator",
    description: "$in — matches any value in a list; can enumerate values",
    pattern: new RegExp(`\\$in${sep}\\s*\\[`, "i")
  },
  {
    id: "nosql-expr-operator",
    description: "$expr — allows aggregation expressions in queries (MongoDB 3.6+)",
    pattern: new RegExp(`\\$expr${sep}`, "i")
  },
  {
    id: "nosql-function-operator",
    description: "$function — executes arbitrary JavaScript in MongoDB 4.4+",
    pattern: new RegExp(`\\$function${sep}`, "i")
  },
  {
    id: "nosql-accumulator-operator",
    description: "$accumulator — custom aggregation with arbitrary JS execution",
    pattern: new RegExp(`\\$accumulator${sep}`, "i")
  },
  {
    id: "nosql-proto-pollution",
    description: "__proto__ — prototype pollution via object key injection",
    pattern: /__proto__/
  },
  {
    id: "nosql-constructor-prototype",
    description: "constructor.prototype — alternative prototype pollution vector (dot notation or JSON key)",
    pattern: /constructor[\s"':.,{\[]*prototype/i
  },
  {
    id: "nosql-proto-bracket",
    description: '["__proto__"] — bracket-notation prototype pollution',
    pattern: /\[["']__proto__["']\]/
  }
];
var nosql_default = NOSQL_PATTERNS;

// node_modules/is-unsafe/src/contexts/log.js
var LOG_PATTERNS = [
  {
    id: "log-crlf-injection",
    description: "CRLF injection: literal \\r or \\n embeds fake log lines",
    pattern: /[\r\n]/
  },
  {
    id: "log-url-encoded-crlf",
    description: "URL-encoded CRLF: %0d, %0a, %0D, %0A — decoded by some log parsers",
    pattern: /%0[dDaA]/
  },
  {
    id: "log-unicode-newline",
    description: "Unicode newline variants: U+2028 (line separator), U+2029 (paragraph separator)",
    pattern: /[\u2028\u2029]/
  },
  {
    id: "log-log4shell-jndi",
    description: "Log4Shell: ${jndi:...} triggers remote code execution in Apache Log4j",
    pattern: /\$\{jndi\s*:/i
  },
  {
    id: "log-log4shell-obfuscated",
    description: "Obfuscated Log4Shell: ${::-j}... lookup-bypass prefix used to evade WAF detection",
    pattern: /\$\{::-/
  },
  {
    id: "log-log4j-lookup",
    description: "Log4j lookup syntax: ${env:...}, ${sys:...}, ${ctx:...} — data exfiltration",
    pattern: /\$\{(?:env|sys|ctx|main|map|sd|web|docker|k8s|spring)\s*:/i
  },
  {
    id: "log-ssti-double-brace",
    description: "SSTI double-brace: {{expression}} — Jinja2, Twig, Handlebars, etc.",
    pattern: /\{\{[\s\S]{0,80}\}\}/
  },
  {
    id: "log-ssti-hash-brace",
    description: "SSTI hash-brace: #{expression} — Thymeleaf, Velocity, Ruby ERB",
    pattern: /#\{[\s\S]{0,80}\}/
  },
  {
    id: "log-ssti-dollar-brace",
    description: "SSTI/EL injection: ${expression with operators or method calls} — JSP EL, Freemarker, SpEL",
    pattern: /\$\{[^}]*(?:\.|\(|\*|\+|\bclass\b|\bruntime\b|\bprocess\b|\bexec\b)[^}]{0,80}\}/i
  },
  {
    id: "log-ssti-percent-tag",
    description: "SSTI ERB/ASP tag: <%= expression %> — Ruby ERB, ASP",
    pattern: /<%=[\s\S]{0,80}%>/
  },
  {
    id: "log-null-byte",
    description: "Null byte: \\x00 or %00 — can truncate log entries in C-backed loggers",
    pattern: /\x00|%00/
  },
  {
    id: "log-ansi-escape",
    description: "ANSI escape sequence: ESC[ — can manipulate terminal output when logs are tailed",
    pattern: /\x1b\[/
  }
];
var log_default = LOG_PATTERNS;

// node_modules/is-unsafe/src/contexts/sql-strict.js
var SQL_STRICT_EXTRA = [
  {
    id: "sql-line-comment",
    description: "SQL line comment: -- followed by whitespace or end of string",
    pattern: /--(?:\s|$)/
  },
  {
    id: "sql-stacked-query",
    description: "Stacked queries: semicolon immediately followed by a SQL keyword",
    pattern: /;\s{0,10}(?:SELECT|INSERT|UPDATE|DELETE|DROP|CREATE|ALTER|EXEC)\b/i
  },
  {
    id: "sql-hex-encoding",
    description: "Hex-encoded string injection: 0x41414141 style (MySQL)",
    pattern: /\b0x[0-9a-f]{4,}/i
  }
];
var SQL_STRICT_PATTERNS = [...sql_default, ...SQL_STRICT_EXTRA];
var sql_strict_default = SQL_STRICT_PATTERNS;

// node_modules/is-unsafe/src/index.js
html_default.label = "HTML";
xml_default.label = "XML";
svg_default.label = "SVG";
sql_default.label = "SQL";
sql_strict_default.label = "SQL-STRICT";
shell_default.label = "SHELL";
redos_default.label = "REDOS";
nosql_default.label = "NOSQL";
log_default.label = "LOG";
var VALID_CONTEXTS = Object.freeze({
  HTML: html_default,
  XML: xml_default,
  SVG: svg_default,
  SQL: sql_default,
  "SQL-STRICT": sql_strict_default,
  SHELL: shell_default,
  REDOS: redos_default,
  NOSQL: nosql_default,
  LOG: log_default
});
function assertString(value) {
  if (typeof value !== "string") {
    throw new TypeError(`is-unsafe: first argument must be a string, got ${typeof value}`);
  }
}
function assertContext(context) {
  if (context instanceof RegExp)
    return;
  if (Array.isArray(context)) {
    if (context.length === 0) {
      throw new TypeError("is-unsafe: context must not be an empty array");
    }
    if (Array.isArray(context[0])) {
      for (const list of context) {
        if (!Array.isArray(list) || list.length === 0) {
          throw new TypeError("is-unsafe: each context in the array must be a non-empty pattern array (PatternList)");
        }
      }
    }
    return;
  }
  throw new TypeError(`is-unsafe: second argument must be a PatternList (e.g. HTML), ` + `an array of PatternLists (e.g. [HTML, XML]), or a RegExp. Got: ${typeof context}`);
}
function normalise(context) {
  if (context instanceof RegExp)
    return { lists: null, regex: context };
  if (Array.isArray(context[0]))
    return { lists: context, regex: null };
  return { lists: [context], regex: null };
}
function matchList(value, list) {
  const label = list.label ?? "CUSTOM";
  for (const rule of list) {
    if (rule.pattern.test(value)) {
      return { context: label, id: rule.id, description: rule.description, pattern: rule.pattern };
    }
  }
  return null;
}
function isUnsafe(value, context) {
  assertString(value);
  assertContext(context);
  const { lists, regex } = normalise(context);
  if (regex)
    return regex.test(value);
  for (const list of lists) {
    if (matchList(value, list) !== null)
      return true;
  }
  return false;
}

// node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js
function extractRawAttributes(prefixedAttrs, options) {
  if (!prefixedAttrs)
    return {};
  const attrs = options.attributesGroupName ? prefixedAttrs[options.attributesGroupName] : prefixedAttrs;
  if (!attrs)
    return {};
  const rawAttrs = {};
  for (const key in attrs) {
    if (key.startsWith(options.attributeNamePrefix)) {
      const rawName = key.substring(options.attributeNamePrefix.length);
      rawAttrs[rawName] = attrs[key];
    } else {
      rawAttrs[key] = attrs[key];
    }
  }
  return rawAttrs;
}
function extractNamespace(rawTagName) {
  if (!rawTagName || typeof rawTagName !== "string")
    return;
  const colonIndex = rawTagName.indexOf(":");
  if (colonIndex !== -1 && colonIndex > 0) {
    const ns = rawTagName.substring(0, colonIndex);
    if (ns !== "xmlns") {
      return ns;
    }
  }
  return;
}

class OrderedObjParser {
  constructor(options, externalEntities) {
    this.options = options;
    this.currentNode = null;
    this.tagsNodeStack = [];
    this.parseXml = parseXml;
    this.parseTextData = parseTextData;
    this.resolveNameSpace = resolveNameSpace;
    this.buildAttributesMap = buildAttributesMap;
    this.isItStopNode = isItStopNode;
    this.replaceEntitiesValue = replaceEntitiesValue;
    this.readStopNodeData = readStopNodeData;
    this.saveTextToParentTag = saveTextToParentTag;
    this.addChild = addChild;
    this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes);
    this.entityExpansionCount = 0;
    this.currentExpandedLength = 0;
    this.doctypefound = false;
    let namedEntities = { ...XML };
    if (this.options.entityDecoder) {
      this.entityDecoder = this.options.entityDecoder;
    } else {
      if (typeof this.options.htmlEntities === "object")
        namedEntities = this.options.htmlEntities;
      else if (this.options.htmlEntities === true)
        namedEntities = { ...COMMON_HTML, ...CURRENCY };
      this.entityDecoder = new EntityDecoder({
        namedEntities: { ...namedEntities, ...externalEntities },
        numericAllowed: this.options.htmlEntities,
        limit: {
          maxTotalExpansions: this.options.processEntities.maxTotalExpansions,
          maxExpandedLength: this.options.processEntities.maxExpandedLength,
          applyLimitsTo: this.options.processEntities.appliesTo
        },
        onInputEntity: (name, value) => isUnsafe(value, [html_default, xml_default]) ? ENTITY_ACTION.BLOCK : ENTITY_ACTION.ALLOW
      });
    }
    this.matcher = new Matcher;
    this.readonlyMatcher = this.matcher.readOnly();
    this.isCurrentNodeStopNode = false;
    this.stopNodeExpressionsSet = new ExpressionSet;
    const stopNodesOpts = this.options.stopNodes;
    if (stopNodesOpts && stopNodesOpts.length > 0) {
      for (let i = 0;i < stopNodesOpts.length; i++) {
        const stopNodeExp = stopNodesOpts[i];
        if (typeof stopNodeExp === "string") {
          this.stopNodeExpressionsSet.add(new Expression(stopNodeExp));
        } else if (stopNodeExp instanceof Expression) {
          this.stopNodeExpressionsSet.add(stopNodeExp);
        }
      }
      this.stopNodeExpressionsSet.seal();
    }
  }
}
function parseTextData(val, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) {
  const options = this.options;
  if (val !== undefined) {
    if (options.trimValues && !dontTrim) {
      val = val.trim();
    }
    if (val.length > 0) {
      if (!escapeEntities)
        val = this.replaceEntitiesValue(val, tagName, jPath);
      const jPathOrMatcher = options.jPath ? jPath.toString() : jPath;
      const newval = options.tagValueProcessor(tagName, val, jPathOrMatcher, hasAttributes, isLeafNode);
      if (newval === null || newval === undefined) {
        return val;
      } else if (typeof newval !== typeof val || newval !== val) {
        return newval;
      } else if (options.trimValues) {
        return parseValue(val, options.parseTagValue, options.numberParseOptions);
      } else {
        const trimmedVal = val.trim();
        if (trimmedVal === val) {
          return parseValue(val, options.parseTagValue, options.numberParseOptions);
        } else {
          return val;
        }
      }
    }
  }
}
function resolveNameSpace(tagname) {
  if (this.options.removeNSPrefix) {
    const tags = tagname.split(":");
    const prefix = tagname.charAt(0) === "/" ? "/" : "";
    if (tags[0] === "xmlns") {
      return "";
    }
    if (tags.length === 2) {
      tagname = prefix + tags[1];
    }
  }
  return tagname;
}
var attrsRegx = new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`, "gm");
function buildAttributesMap(attrStr, jPath, tagName, force = false) {
  const options = this.options;
  if (force === true || options.ignoreAttributes !== true && typeof attrStr === "string") {
    const matches = getAllMatches(attrStr, attrsRegx);
    const len = matches.length;
    const attrs = {};
    const processedVals = new Array(len);
    let hasRawAttrs = false;
    const rawAttrsForMatcher = {};
    for (let i = 0;i < len; i++) {
      const attrName = this.resolveNameSpace(matches[i][1]);
      const oldVal = matches[i][4];
      if (attrName.length && oldVal !== undefined) {
        let val = oldVal;
        if (options.trimValues)
          val = val.trim();
        val = this.replaceEntitiesValue(val, tagName, this.readonlyMatcher);
        processedVals[i] = val;
        rawAttrsForMatcher[attrName] = val;
        hasRawAttrs = true;
      }
    }
    if (hasRawAttrs && typeof jPath === "object" && jPath.updateCurrent) {
      jPath.updateCurrent(rawAttrsForMatcher);
    }
    const jPathStr = options.jPath ? jPath.toString() : this.readonlyMatcher;
    let hasAttrs = false;
    for (let i = 0;i < len; i++) {
      const attrName = this.resolveNameSpace(matches[i][1]);
      if (this.ignoreAttributesFn(attrName, jPathStr))
        continue;
      let aName = options.attributeNamePrefix + attrName;
      if (attrName.length) {
        if (options.transformAttributeName) {
          aName = options.transformAttributeName(aName);
        }
        aName = sanitizeName(aName, options);
        if (matches[i][4] !== undefined) {
          const oldVal = processedVals[i];
          const newVal = options.attributeValueProcessor(attrName, oldVal, jPathStr);
          if (newVal === null || newVal === undefined) {
            attrs[aName] = oldVal;
          } else if (typeof newVal !== typeof oldVal || newVal !== oldVal) {
            attrs[aName] = newVal;
          } else {
            attrs[aName] = parseValue(oldVal, options.parseAttributeValue, options.numberParseOptions);
          }
          hasAttrs = true;
        } else if (options.allowBooleanAttributes) {
          attrs[aName] = true;
          hasAttrs = true;
        }
      }
    }
    if (!hasAttrs)
      return;
    if (options.attributesGroupName && !options.preserveOrder) {
      const attrCollection = {};
      attrCollection[options.attributesGroupName] = attrs;
      return attrCollection;
    }
    return attrs;
  }
}
var parseXml = function(xmlData) {
  xmlData = xmlData.replace(/\r\n?/g, `
`);
  const xmlObj = new XmlNode("!xml");
  let currentNode = xmlObj;
  let textData = "";
  this.matcher.reset();
  this.entityDecoder.reset();
  this.entityExpansionCount = 0;
  this.currentExpandedLength = 0;
  this.doctypefound = false;
  const options = this.options;
  const docTypeReader = new DocTypeReader(options.processEntities);
  const xmlLen = xmlData.length;
  for (let i = 0;i < xmlLen; i++) {
    const ch = xmlData[i];
    if (ch === "<") {
      const c1 = xmlData.charCodeAt(i + 1);
      if (c1 === 47) {
        const closeIndex = findClosingIndex(xmlData, ">", i, "Closing Tag is not closed.");
        let tagName = xmlData.substring(i + 2, closeIndex).trim();
        if (options.removeNSPrefix) {
          const colonIndex = tagName.indexOf(":");
          if (colonIndex !== -1) {
            tagName = tagName.substr(colonIndex + 1);
          }
        }
        tagName = transformTagName(options.transformTagName, tagName, "", options).tagName;
        if (currentNode) {
          textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);
        }
        const lastTagName = this.matcher.getCurrentTag();
        if (tagName && options.unpairedTagsSet.has(tagName)) {
          throw new Error(`Unpaired tag can not be used as closing tag: </${tagName}>`);
        }
        if (lastTagName && options.unpairedTagsSet.has(lastTagName)) {
          this.matcher.pop();
          this.tagsNodeStack.pop();
        }
        this.matcher.pop();
        this.isCurrentNodeStopNode = false;
        currentNode = this.tagsNodeStack.pop();
        textData = "";
        i = closeIndex;
      } else if (c1 === 63) {
        let tagData = readTagExp(xmlData, i, false, "?>");
        if (!tagData)
          throw new Error("Pi Tag is not closed.");
        textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);
        const attsMap = this.buildAttributesMap(tagData.tagExp, this.matcher, tagData.tagName, true);
        if (attsMap) {
          const ver = attsMap[this.options.attributeNamePrefix + "version"];
          this.entityDecoder.setXmlVersion(Number(ver) || 1);
          docTypeReader.setXmlVersion(Number(ver) || 1);
        }
        if (options.ignoreDeclaration && tagData.tagName === "?xml" || options.ignorePiTags) {} else {
          const childNode = new XmlNode(tagData.tagName);
          childNode.add(options.textNodeName, "");
          if (tagData.tagName !== tagData.tagExp && tagData.attrExpPresent && options.ignoreAttributes !== true) {
            childNode[":@"] = attsMap;
          }
          this.addChild(currentNode, childNode, this.readonlyMatcher, i);
        }
        i = tagData.closeIndex + 1;
      } else if (c1 === 33 && xmlData.charCodeAt(i + 2) === 45 && xmlData.charCodeAt(i + 3) === 45) {
        const endIndex = findClosingIndex(xmlData, "-->", i + 4, "Comment is not closed.");
        if (options.commentPropName) {
          const comment = xmlData.substring(i + 4, endIndex - 2);
          textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);
          currentNode.add(options.commentPropName, [{ [options.textNodeName]: comment }]);
        }
        i = endIndex;
      } else if (c1 === 33 && xmlData.charCodeAt(i + 2) === 68) {
        if (this.doctypefound)
          throw new Error("Multiple DOCTYPE declarations found.");
        this.doctypefound = true;
        const result = docTypeReader.readDocType(xmlData, i);
        this.entityDecoder.addInputEntities(result.entities);
        i = result.i;
      } else if (c1 === 33 && xmlData.charCodeAt(i + 2) === 91) {
        const closeIndex = findClosingIndex(xmlData, "]]>", i, "CDATA is not closed.") - 2;
        const tagExp = xmlData.substring(i + 9, closeIndex);
        textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);
        let val = this.parseTextData(tagExp, currentNode.tagname, this.readonlyMatcher, true, false, true, true);
        if (val == undefined)
          val = "";
        if (options.cdataPropName) {
          currentNode.add(options.cdataPropName, [{ [options.textNodeName]: tagExp }]);
        } else {
          currentNode.add(options.textNodeName, val);
        }
        i = closeIndex + 2;
      } else {
        let result = readTagExp(xmlData, i, options.removeNSPrefix);
        if (!result) {
          const context = xmlData.substring(Math.max(0, i - 50), Math.min(xmlLen, i + 50));
          throw new Error(`readTagExp returned undefined at position ${i}. Context: "${context}"`);
        }
        let tagName = result.tagName;
        const rawTagName = result.rawTagName;
        let tagExp = result.tagExp;
        let attrExpPresent = result.attrExpPresent;
        let closeIndex = result.closeIndex;
        ({ tagName, tagExp } = transformTagName(options.transformTagName, tagName, tagExp, options));
        if (options.strictReservedNames && (tagName === options.commentPropName || tagName === options.cdataPropName || tagName === options.textNodeName || tagName === options.attributesGroupName)) {
          throw new Error(`Invalid tag name: ${tagName}`);
        }
        if (currentNode && textData) {
          if (currentNode.tagname !== "!xml") {
            textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher, false);
          }
        }
        const lastTag = currentNode;
        if (lastTag && options.unpairedTagsSet.has(lastTag.tagname)) {
          currentNode = this.tagsNodeStack.pop();
          this.matcher.pop();
        }
        let isSelfClosing = false;
        if (tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1) {
          isSelfClosing = true;
          if (tagName[tagName.length - 1] === "/") {
            tagName = tagName.substr(0, tagName.length - 1);
            tagExp = tagName;
          } else {
            tagExp = tagExp.substr(0, tagExp.length - 1);
          }
          attrExpPresent = tagName !== tagExp;
        }
        let prefixedAttrs = null;
        let rawAttrs = {};
        let namespace = undefined;
        namespace = extractNamespace(rawTagName);
        if (tagName !== xmlObj.tagname) {
          this.matcher.push(tagName, {}, namespace);
        }
        if (tagName !== tagExp && attrExpPresent) {
          prefixedAttrs = this.buildAttributesMap(tagExp, this.matcher, tagName);
          if (prefixedAttrs) {
            rawAttrs = extractRawAttributes(prefixedAttrs, options);
          }
        }
        if (tagName !== xmlObj.tagname) {
          this.isCurrentNodeStopNode = this.isItStopNode();
        }
        const startIndex = i;
        if (this.isCurrentNodeStopNode) {
          let tagContent = "";
          if (isSelfClosing) {
            i = result.closeIndex;
          } else if (options.unpairedTagsSet.has(tagName)) {
            i = result.closeIndex;
          } else {
            const result2 = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1);
            if (!result2)
              throw new Error(`Unexpected end of ${rawTagName}`);
            i = result2.i;
            tagContent = result2.tagContent;
          }
          const childNode = new XmlNode(tagName);
          if (prefixedAttrs) {
            childNode[":@"] = prefixedAttrs;
          }
          childNode.add(options.textNodeName, tagContent);
          this.matcher.pop();
          this.isCurrentNodeStopNode = false;
          this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);
        } else {
          if (isSelfClosing) {
            ({ tagName, tagExp } = transformTagName(options.transformTagName, tagName, tagExp, options));
            const childNode = new XmlNode(tagName);
            if (prefixedAttrs) {
              childNode[":@"] = prefixedAttrs;
            }
            this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);
            this.matcher.pop();
            this.isCurrentNodeStopNode = false;
          } else if (options.unpairedTagsSet.has(tagName)) {
            const childNode = new XmlNode(tagName);
            if (prefixedAttrs) {
              childNode[":@"] = prefixedAttrs;
            }
            this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);
            this.matcher.pop();
            this.isCurrentNodeStopNode = false;
            i = result.closeIndex;
            continue;
          } else {
            const childNode = new XmlNode(tagName);
            if (this.tagsNodeStack.length > options.maxNestedTags) {
              throw new Error("Maximum nested tags exceeded");
            }
            this.tagsNodeStack.push(currentNode);
            if (prefixedAttrs) {
              childNode[":@"] = prefixedAttrs;
            }
            this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);
            currentNode = childNode;
          }
          textData = "";
          i = closeIndex;
        }
      }
    } else {
      textData += xmlData[i];
    }
  }
  return xmlObj.child;
};
function addChild(currentNode, childNode, matcher, startIndex) {
  if (!this.options.captureMetaData)
    startIndex = undefined;
  const jPathOrMatcher = this.options.jPath ? matcher.toString() : matcher;
  const result = this.options.updateTag(childNode.tagname, jPathOrMatcher, childNode[":@"]);
  if (result === false) {} else if (typeof result === "string") {
    childNode.tagname = result;
    currentNode.addChild(childNode, startIndex);
  } else {
    currentNode.addChild(childNode, startIndex);
  }
}
function replaceEntitiesValue(val, tagName, jPath) {
  const entityConfig = this.options.processEntities;
  if (!entityConfig || !entityConfig.enabled) {
    return val;
  }
  if (entityConfig.allowedTags) {
    const jPathOrMatcher = this.options.jPath ? jPath.toString() : jPath;
    const allowed = Array.isArray(entityConfig.allowedTags) ? entityConfig.allowedTags.includes(tagName) : entityConfig.allowedTags(tagName, jPathOrMatcher);
    if (!allowed) {
      return val;
    }
  }
  if (entityConfig.tagFilter) {
    const jPathOrMatcher = this.options.jPath ? jPath.toString() : jPath;
    if (!entityConfig.tagFilter(tagName, jPathOrMatcher)) {
      return val;
    }
  }
  return this.entityDecoder.decode(val);
}
function saveTextToParentTag(textData, parentNode, matcher, isLeafNode) {
  if (textData) {
    if (isLeafNode === undefined)
      isLeafNode = parentNode.child.length === 0;
    textData = this.parseTextData(textData, parentNode.tagname, matcher, false, parentNode[":@"] ? Object.keys(parentNode[":@"]).length !== 0 : false, isLeafNode);
    if (textData !== undefined && textData !== "")
      parentNode.add(this.options.textNodeName, textData);
    textData = "";
  }
  return textData;
}
function isItStopNode() {
  if (this.stopNodeExpressionsSet.size === 0)
    return false;
  return this.matcher.matchesAny(this.stopNodeExpressionsSet);
}
function tagExpWithClosingIndex(xmlData, i, closingChar = ">") {
  let attrBoundary = 0;
  const len = xmlData.length;
  const closeCode0 = closingChar.charCodeAt(0);
  const closeCode1 = closingChar.length > 1 ? closingChar.charCodeAt(1) : -1;
  let result = "";
  let segmentStart = i;
  for (let index = i;index < len; index++) {
    const code = xmlData.charCodeAt(index);
    if (attrBoundary) {
      if (code === attrBoundary)
        attrBoundary = 0;
    } else if (code === 34 || code === 39) {
      attrBoundary = code;
    } else if (code === closeCode0) {
      if (closeCode1 !== -1) {
        if (xmlData.charCodeAt(index + 1) === closeCode1) {
          result += xmlData.substring(segmentStart, index);
          return { data: result, index };
        }
      } else {
        result += xmlData.substring(segmentStart, index);
        return { data: result, index };
      }
    } else if (code === 9 && !attrBoundary) {
      result += xmlData.substring(segmentStart, index) + " ";
      segmentStart = index + 1;
    }
  }
}
function findClosingIndex(xmlData, str, i, errMsg) {
  const closingIndex = xmlData.indexOf(str, i);
  if (closingIndex === -1) {
    throw new Error(errMsg);
  } else {
    return closingIndex + str.length - 1;
  }
}
function findClosingChar(xmlData, char, i, errMsg) {
  const closingIndex = xmlData.indexOf(char, i);
  if (closingIndex === -1)
    throw new Error(errMsg);
  return closingIndex;
}
function readTagExp(xmlData, i, removeNSPrefix, closingChar = ">") {
  const result = tagExpWithClosingIndex(xmlData, i + 1, closingChar);
  if (!result)
    return;
  let tagExp = result.data;
  const closeIndex = result.index;
  const separatorIndex = tagExp.search(/\s/);
  let tagName = tagExp;
  let attrExpPresent = true;
  if (separatorIndex !== -1) {
    tagName = tagExp.substring(0, separatorIndex);
    tagExp = tagExp.substring(separatorIndex + 1).trimStart();
  }
  const rawTagName = tagName;
  if (removeNSPrefix) {
    const colonIndex = tagName.indexOf(":");
    if (colonIndex !== -1) {
      tagName = tagName.substr(colonIndex + 1);
      attrExpPresent = tagName !== result.data.substr(colonIndex + 1);
    }
  }
  return {
    tagName,
    tagExp,
    closeIndex,
    attrExpPresent,
    rawTagName
  };
}
function readStopNodeData(xmlData, tagName, i) {
  const startIndex = i;
  let openTagCount = 1;
  const xmllen = xmlData.length;
  for (;i < xmllen; i++) {
    if (xmlData[i] === "<") {
      const c1 = xmlData.charCodeAt(i + 1);
      if (c1 === 47) {
        const closeIndex = findClosingChar(xmlData, ">", i, `${tagName} is not closed`);
        let closeTagName = xmlData.substring(i + 2, closeIndex).trim();
        if (closeTagName === tagName) {
          openTagCount--;
          if (openTagCount === 0) {
            return {
              tagContent: xmlData.substring(startIndex, i),
              i: closeIndex
            };
          }
        }
        i = closeIndex;
      } else if (c1 === 63) {
        const closeIndex = findClosingIndex(xmlData, "?>", i + 1, "StopNode is not closed.");
        i = closeIndex;
      } else if (c1 === 33 && xmlData.charCodeAt(i + 2) === 45 && xmlData.charCodeAt(i + 3) === 45) {
        const closeIndex = findClosingIndex(xmlData, "-->", i + 3, "StopNode is not closed.");
        i = closeIndex;
      } else if (c1 === 33 && xmlData.charCodeAt(i + 2) === 91) {
        const closeIndex = findClosingIndex(xmlData, "]]>", i, "StopNode is not closed.") - 2;
        i = closeIndex;
      } else {
        const tagData = readTagExp(xmlData, i, false);
        if (tagData) {
          const openTagName = tagData && tagData.tagName;
          if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length - 1] !== "/") {
            openTagCount++;
          }
          i = tagData.closeIndex;
        }
      }
    }
  }
}
function parseValue(val, shouldParse, options) {
  if (shouldParse && typeof val === "string") {
    const newval = val.trim();
    if (newval === "true")
      return true;
    else if (newval === "false")
      return false;
    else
      return toNumber(val, options);
  } else {
    if (isExist(val)) {
      return val;
    } else {
      return "";
    }
  }
}
function transformTagName(fn, tagName, tagExp, options) {
  if (fn) {
    const newTagName = fn(tagName);
    if (tagExp === tagName) {
      tagExp = newTagName;
    }
    tagName = newTagName;
  }
  tagName = sanitizeName(tagName, options);
  return { tagName, tagExp };
}
function sanitizeName(name, options) {
  if (criticalProperties.includes(name)) {
    throw new Error(`[SECURITY] Invalid name: "${name}" is a reserved JavaScript keyword that could cause prototype pollution`);
  } else if (DANGEROUS_PROPERTY_NAMES.includes(name)) {
    return options.onDangerousProperty(name);
  }
  return name;
}

// node_modules/fast-xml-parser/src/xmlparser/node2json.js
var METADATA_SYMBOL2 = XmlNode.getMetaDataSymbol();
function stripAttributePrefix(attrs, prefix) {
  if (!attrs || typeof attrs !== "object")
    return {};
  if (!prefix)
    return attrs;
  const rawAttrs = {};
  for (const key in attrs) {
    if (key.startsWith(prefix)) {
      const rawName = key.substring(prefix.length);
      rawAttrs[rawName] = attrs[key];
    } else {
      rawAttrs[key] = attrs[key];
    }
  }
  return rawAttrs;
}
function prettify(node, options, matcher, readonlyMatcher) {
  return compress(node, options, matcher, readonlyMatcher);
}
function compress(arr, options, matcher, readonlyMatcher) {
  let text;
  const compressedObj = {};
  for (let i = 0;i < arr.length; i++) {
    const tagObj = arr[i];
    const property = propName(tagObj);
    if (property !== undefined && property !== options.textNodeName) {
      const rawAttrs = stripAttributePrefix(tagObj[":@"] || {}, options.attributeNamePrefix);
      matcher.push(property, rawAttrs);
    }
    if (property === options.textNodeName) {
      if (text === undefined)
        text = tagObj[property];
      else
        text += "" + tagObj[property];
    } else if (property === undefined) {
      continue;
    } else if (tagObj[property]) {
      let val = compress(tagObj[property], options, matcher, readonlyMatcher);
      const isLeaf = isLeafTag(val, options);
      if (Object.keys(val).length === 0 && options.alwaysCreateTextNode) {
        val[options.textNodeName] = "";
      }
      if (tagObj[":@"]) {
        assignAttributes(val, tagObj[":@"], readonlyMatcher, options);
      } else if (Object.keys(val).length === 1 && val[options.textNodeName] !== undefined && !options.alwaysCreateTextNode) {
        val = val[options.textNodeName];
      } else if (Object.keys(val).length === 0) {
        if (options.alwaysCreateTextNode)
          val[options.textNodeName] = "";
        else
          val = "";
      }
      if (tagObj[METADATA_SYMBOL2] !== undefined && typeof val === "object" && val !== null) {
        val[METADATA_SYMBOL2] = tagObj[METADATA_SYMBOL2];
      }
      if (compressedObj[property] !== undefined && Object.prototype.hasOwnProperty.call(compressedObj, property)) {
        if (!Array.isArray(compressedObj[property])) {
          compressedObj[property] = [compressedObj[property]];
        }
        compressedObj[property].push(val);
      } else {
        const jPathOrMatcher = options.jPath ? readonlyMatcher.toString() : readonlyMatcher;
        if (options.isArray(property, jPathOrMatcher, isLeaf)) {
          compressedObj[property] = [val];
        } else {
          compressedObj[property] = val;
        }
      }
      if (property !== undefined && property !== options.textNodeName) {
        matcher.pop();
      }
    }
  }
  if (typeof text === "string") {
    if (text.length > 0)
      compressedObj[options.textNodeName] = text;
  } else if (text !== undefined)
    compressedObj[options.textNodeName] = text;
  return compressedObj;
}
function propName(obj) {
  const keys = Object.keys(obj);
  for (let i = 0;i < keys.length; i++) {
    const key = keys[i];
    if (key !== ":@")
      return key;
  }
}
function assignAttributes(obj, attrMap, readonlyMatcher, options) {
  if (attrMap) {
    const keys = Object.keys(attrMap);
    const len = keys.length;
    for (let i = 0;i < len; i++) {
      const atrrName = keys[i];
      const rawAttrName = atrrName.startsWith(options.attributeNamePrefix) ? atrrName.substring(options.attributeNamePrefix.length) : atrrName;
      const jPathOrMatcher = options.jPath ? readonlyMatcher.toString() + "." + rawAttrName : readonlyMatcher;
      if (options.isArray(atrrName, jPathOrMatcher, true, true)) {
        obj[atrrName] = [attrMap[atrrName]];
      } else {
        obj[atrrName] = attrMap[atrrName];
      }
    }
  }
}
function isLeafTag(obj, options) {
  const { textNodeName } = options;
  const propCount = Object.keys(obj).length;
  if (propCount === 0) {
    return true;
  }
  if (propCount === 1 && (obj[textNodeName] || typeof obj[textNodeName] === "boolean" || obj[textNodeName] === 0)) {
    return true;
  }
  return false;
}

// node_modules/fast-xml-parser/src/xmlparser/XMLParser.js
class XMLParser {
  constructor(options) {
    this.externalEntities = {};
    this.options = buildOptions(options);
  }
  parse(xmlData, validationOption) {
    if (typeof xmlData !== "string" && xmlData.toString) {
      xmlData = xmlData.toString();
    } else if (typeof xmlData !== "string") {
      throw new Error("XML data is accepted in String or Bytes[] form.");
    }
    if (validationOption) {
      if (validationOption === true)
        validationOption = {};
      const result = validate10(xmlData, validationOption);
      if (result !== true) {
        throw Error(`${result.err.msg}:${result.err.line}:${result.err.col}`);
      }
    }
    const orderedObjParser = new OrderedObjParser(this.options, this.externalEntities);
    const orderedResult = orderedObjParser.parseXml(xmlData);
    if (this.options.preserveOrder || orderedResult === undefined)
      return orderedResult;
    else
      return prettify(orderedResult, this.options, orderedObjParser.matcher, orderedObjParser.readonlyMatcher);
  }
  addEntity(key, value) {
    if (value.indexOf("&") !== -1) {
      throw new Error("Entity value can't have '&'");
    } else if (key.indexOf("&") !== -1 || key.indexOf(";") !== -1) {
      throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");
    } else if (value === "&") {
      throw new Error("An entity with value '&' is not permitted");
    } else {
      this.externalEntities[key] = value;
    }
  }
  static getMetaDataSymbol() {
    return XmlNode.getMetaDataSymbol();
  }
}

// src/sources/snapshot-fetchers/rss.ts
var FEED_BYTE_CAP = 5 * 1024 * 1024;
var xmlParser = new XMLParser({
  ignoreAttributes: false,
  attributeNamePrefix: "@_",
  textNodeName: "#text",
  isArray: (name) => ["item", "entry"].includes(name),
  trimValues: true,
  parseTagValue: false,
  processEntities: true
});

// src/sources/snapshot-fetchers/x.ts
var X_HOSTS = new Set(["x.com", "www.x.com", "twitter.com", "www.twitter.com"]);
var X_BYTE_CAP = 4 * 1024 * 1024;
var X_PAGE_BYTE_CAP = 5 * 1024 * 1024;
var RESERVED_X_PATHS = new Set([
  "home",
  "explore",
  "notifications",
  "messages",
  "search",
  "settings",
  "i",
  "intent",
  "share",
  "compose",
  "login",
  "signup",
  "about",
  "tos",
  "privacy"
]);
var EXECUTABLE_SCRIPT_TYPES = new Set([
  "module",
  "application/ecmascript",
  "application/javascript",
  "application/x-ecmascript",
  "application/x-javascript",
  "text/ecmascript",
  "text/javascript",
  "text/javascript1.0",
  "text/javascript1.1",
  "text/javascript1.2",
  "text/javascript1.3",
  "text/javascript1.4",
  "text/javascript1.5",
  "text/jscript",
  "text/livescript",
  "text/x-ecmascript",
  "text/x-javascript"
]);
var EXECUTABLE_SCRIPT_LANGUAGES = new Set([
  "ecmascript",
  "javascript",
  "javascript1.0",
  "javascript1.1",
  "javascript1.2",
  "javascript1.3",
  "javascript1.4",
  "javascript1.5",
  "jscript",
  "livescript"
]);
var CONTROL_CONDITION_KEYWORDS = new Set(["catch", "for", "if", "switch", "while", "with"]);
var REGEX_PREFIX_KEYWORDS = new Set([
  "await",
  "case",
  "delete",
  "do",
  "else",
  "in",
  "instanceof",
  "new",
  "of",
  "return",
  "throw",
  "typeof",
  "void",
  "yield"
]);

// src/sources/snapshot-fetchers/youtube.ts
var YOUTUBE_HOSTS = new Set(["www.youtube.com", "youtube.com", "m.youtube.com", "youtu.be"]);

// src/sources/snapshot-fetchers/registry.ts
var FETCHER_DIR = path40.join("scripts", "wiki-fetchers");

// src/sources/snapshot-fetchers/robots.ts
var ROBOTS_BYTE_CAP = 512 * 1024;
var EMPTY_ROBOTS_RULES = Object.freeze([]);
var ALLOW_ALL_RULES = Object.freeze({
  disallowAll: false,
  rules: EMPTY_ROBOTS_RULES,
  crawlDelayMs: null
});
var DISALLOW_ALL_RULES = Object.freeze({
  disallowAll: true,
  rules: EMPTY_ROBOTS_RULES,
  crawlDelayMs: null
});
var compiledPatternCache = new WeakMap;

// src/sources/snapshot-fetchers/website-ingest.ts
var CACHE_REFRESH_INTERVAL_MS = 12 * 60 * 60 * 1000;
var CACHE_STALE_MS2 = 7 * 24 * 60 * 60 * 1000;
var LLMS_TXT_BYTE_CAP = 512 * 1024;
var WEBSITE_PAGE_BYTE_CAP = 5 * 1024 * 1024;
var WEBSITE_CRAWL_WALL_CLOCK_MS = 10 * 60 * 1000;
var SNAPSHOT_STAGING_SWEEP_AGE_MS = 60 * 60 * 1000;

// src/indexer/search/search-source.ts
var SUSPICIOUS_ROOTS = new Set(["/", "/etc", "/bin", "/sbin", "/usr", "/var", "/tmp", "/dev", "/proc", "/sys"]);

// src/core/activation-policy.ts
var INTERACTIVE_TOOL_ENV_KEYS = new Set(["EDITOR", "VISUAL", "PAGER"]);
// src/integrations/harnesses/shared.ts
function caps(c) {
  return {
    sessionLogs: false,
    agentDispatch: false,
    detection: false,
    configImport: false,
    ...c
  };
}

// src/integrations/harnesses/types.ts
function isSessionLogHarness(h) {
  return h.capabilities.sessionLogs;
}

class BaseHarness {
  setupDetectionDir;
  agentBuilder;
  executionLowerer;
  identityEnv;
  presenceEnv;
  resultExtractor;
}

// src/integrations/agent/builder-shared.ts
function resolveDispatchModel(request, _profile, _platform) {
  return request.model;
}
function modelFromArgs(args) {
  let model;
  for (let index = 0;index < args.length; index += 1) {
    const arg = args[index];
    if (arg === "--model")
      model = args[index + 1];
    else if (arg?.startsWith("--model="))
      model = arg.slice("--model=".length);
  }
  return model;
}
function normalizeTools(tools) {
  if (typeof tools === "string")
    return tools;
  if (Array.isArray(tools))
    return tools.join(",");
  return JSON.stringify(tools);
}

// src/core/structured.ts
function withSchemaInstruction(prompt, schema) {
  return `${prompt}

Respond with ONLY a JSON value matching this JSON Schema (no prose, no code fences):
${JSON.stringify(schema)}`;
}

// src/integrations/agent/conversation-fallback.ts
var CONVERSATION_FALLBACK_BEGIN = "<AKM_CONVERSATION_JSON>";
var CONVERSATION_FALLBACK_END = "</AKM_CONVERSATION_JSON>";
function composeConversationFallbackPrompt(conversation, command) {
  const json = JSON.stringify(conversation.map((message) => ({ role: message.role, content: message.content })));
  const byteLength = new TextEncoder().encode(json).byteLength;
  return `${CONVERSATION_FALLBACK_BEGIN} ${byteLength}
${json}
${CONVERSATION_FALLBACK_END}

${command}`;
}

// src/integrations/agent/persona-fallback.ts
var PERSONA_FALLBACK_NOTICE_CODE = "persona-prompt-composed";
var PERSONA_FALLBACK_BEGIN = "<AKM_PERSONA>";
var PERSONA_FALLBACK_END = "</AKM_PERSONA>";
function withTrailingNewline(value) {
  return value.endsWith(`
`) ? value : `${value}
`;
}
function composePersonaFallbackPrompt(persona, command, adapter) {
  if (typeof persona !== "string" || typeof command !== "string") {
    throw new TypeError("persona fallback content must be strings");
  }
  if (typeof adapter !== "string" || adapter.length === 0) {
    throw new TypeError("persona fallback adapter must be a non-empty string");
  }
  const notice = Object.freeze({
    code: PERSONA_FALLBACK_NOTICE_CODE,
    severity: "info",
    adapter,
    field: "persona",
    message: "The selected engine has no native persona channel; AKM composed the persona into the prompt."
  });
  const notices = Object.freeze([notice]);
  return Object.freeze({
    prompt: `${PERSONA_FALLBACK_BEGIN}
${withTrailingNewline(persona)}${PERSONA_FALLBACK_END}

${command}`,
    notices
  });
}

// src/integrations/agent/request-lowering.ts
function hasToolSelection(value) {
  if (value === null || value === undefined)
    return false;
  if (typeof value === "string" || Array.isArray(value))
    return value.length > 0;
  return Object.keys(value).length > 0;
}
function translatesTools(mode, value) {
  if (mode === "all")
    return true;
  if (typeof value === "string" || Array.isArray(value))
    return mode === "flat" || mode === "sdk";
  return mode === "sdk" && value !== null && Object.values(value).every((entry) => typeof entry === "boolean");
}
function untranslated(adapter, field) {
  return {
    code: "untranslated-field",
    severity: "warning",
    adapter,
    field,
    message: `The ${adapter} lowerer does not translate resolved field ${field}; dispatch will continue optimistically.`
  };
}
function extensionFields(request) {
  return [
    ...request.extensions ? ["extensions"] : [],
    ...request.command.extensions ? ["command.extensions"] : [],
    ...request.persona?.extensions ? ["persona.extensions"] : [],
    ...request.engine.extensions ? ["engine.extensions"] : [],
    ...request.runtime.extensions ? ["runtime.extensions"] : []
  ];
}
function createAgentRequestLowerer(options) {
  const supportedInference = new Set(options.inference ?? []);
  return (_profile, request) => {
    const modelWork = request.authorization.policy?.id === MODEL_WORK_POLICY_ID;
    const notices = [];
    const skip = (field) => {
      notices.push(untranslated(options.adapter, field));
    };
    let prompt = request.command.content;
    if (request.conversation && request.conversation.length > 0) {
      prompt = composeConversationFallbackPrompt(request.conversation, prompt);
      notices.push({
        code: "conversation-prompt-composed",
        severity: "warning",
        adapter: options.adapter,
        field: "conversation",
        message: `The ${options.adapter} transport has no native multi-message channel; AKM composed the conversation prefix into one deterministic JSON prompt block.`
      });
    }
    const dispatch = { prompt };
    if (request.persona) {
      if (options.personaChannel === "native")
        dispatch.systemPrompt = request.persona.content;
      else {
        const composed = composePersonaFallbackPrompt(request.persona.content, prompt, options.adapter);
        prompt = composed.prompt;
        notices.push(...composed.notices);
      }
    } else if (typeof request.agent === "string") {
      if (!options.nativeAgentSelector) {
        throw new ConfigError(`The ${options.adapter} transport cannot consume native agent selector ${JSON.stringify(request.agent)}.`, "INVALID_CONFIG_FILE");
      }
      dispatch.agent = request.agent;
    }
    if (request.outputSchema) {
      prompt = withSchemaInstruction(prompt, request.outputSchema);
      dispatch.schema = request.outputSchema;
    }
    dispatch.prompt = prompt;
    if (request.model)
      dispatch.model = request.model.resolved;
    if (Object.hasOwn(request, "inference")) {
      dispatch.inference = request.inference ?? null;
      for (const key of Object.keys(request.inference ?? {}).sort()) {
        if (!(modelWork && supportedInference.has(key)))
          skip(`inference.${key}`);
      }
    }
    if (modelWork) {
      if (!HARNESS_MODEL_WORK_IDS.has(options.adapter)) {
        throw new ConfigError(`The ${options.adapter} transport cannot enforce the model-work tool policy.`, "INVALID_CONFIG_FILE");
      }
      if (dispatch.agent) {
        throw new ConfigError(`The ${options.adapter} transport cannot run native agent ${JSON.stringify(dispatch.agent)} under the model-work tool policy.`, "INVALID_CONFIG_FILE");
      }
      dispatch.modelWork = true;
    } else if (request.tools !== undefined) {
      if (hasToolSelection(request.tools) && !translatesTools(options.tools, request.tools)) {
        throw new ConfigError(`The ${options.adapter} transport cannot enforce the resolved tool policy.`, "INVALID_CONFIG_FILE");
      }
      dispatch.tools = request.tools;
    }
    const settings = request.runtime.settings;
    if (settings && Object.keys(settings).length > 0)
      skip("runtime.settings");
    for (const field of extensionFields(request))
      skip(field);
    return { prompt, dispatch, notices };
  };
}

// src/integrations/harnesses/aider/agent-builder.ts
var AIDER_PLATFORM = "aider";
function buildMessagePayload(req) {
  const sections = [];
  if (req.systemPrompt)
    sections.push(req.systemPrompt);
  sections.push(req.prompt);
  return sections.join(`

`);
}
var aiderBuilder = {
  platform: AIDER_PLATFORM,
  personaChannel: "prompt",
  lower: createAgentRequestLowerer({
    adapter: AIDER_PLATFORM,
    personaChannel: "prompt",
    tools: "none"
  }),
  build(profile, req) {
    const args = [...profile.args];
    if (req.model) {
      const resolved = resolveDispatchModel(req, profile, AIDER_PLATFORM);
      args.push("--model", resolved);
    }
    args.push("--yes-always");
    args.push("--no-pretty");
    args.push(`--message=${buildMessagePayload(req)}`);
    return { argv: [profile.bin, ...args] };
  }
};

// src/integrations/harnesses/aider/result-extractor.ts
var ANSI_ESCAPE_RE = new RegExp(`${String.fromCharCode(27)}\\[[0-9;?]*[ -/]*[@-~]`, "g");
var NOISE_LINE_PATTERNS = [
  /^aider v\d/,
  /^(Main model|Weak model|Editor model|Model):\s/,
  /^Git repo:\s/,
  /^Repo-map:\s/,
  /^Added .+ to the chat\.?$/,
  /^Restored previous conversation history\.?$/,
  /^Use \/help\b/,
  /^Tokens: .+/,
  /^Cost: .+/,
  /^Applied edit to .+/,
  /^Commit [0-9a-f]{6,}\b/,
  /^You can use \/undo\b/,
  /^[─━-]{4,}$/
];
function isNoiseLine(line) {
  return NOISE_LINE_PATTERNS.some((pattern) => pattern.test(line));
}
var aiderResultExtractor = (result) => {
  const raw = result.stdout.replace(ANSI_ESCAPE_RE, "").trim();
  const kept = raw.split(`
`).filter((line) => !isNoiseLine(line.trim())).join(`
`).trim();
  const text = kept.length > 0 ? kept : raw;
  return result.sessionId === undefined ? { text } : { text, sessionId: result.sessionId };
};

// src/integrations/harnesses/aider/index.ts
class AiderHarness extends BaseHarness {
  id = "aider";
  displayName = "Aider";
  agentBuilder = aiderBuilder;
  resultExtractor = aiderResultExtractor;
  capabilities = caps({
    agentDispatch: true,
    detection: true
  });
}

// src/integrations/harnesses/amazonq/agent-builder.ts
var AMAZONQ_PLATFORM = "amazonq";
function toolPolicyEntries(tools) {
  if (typeof tools === "string") {
    return tools.split(",").map((t) => t.trim()).filter(Boolean);
  }
  if (Array.isArray(tools)) {
    return tools.map((t) => t.trim()).filter(Boolean);
  }
  return;
}
function buildPromptPayload(req) {
  const sections = [];
  if (req.systemPrompt)
    sections.push(req.systemPrompt);
  sections.push(req.prompt);
  return sections.join(`

`);
}
var amazonqBuilder = {
  platform: AMAZONQ_PLATFORM,
  personaChannel: "prompt",
  lower: createAgentRequestLowerer({
    adapter: AMAZONQ_PLATFORM,
    personaChannel: "prompt",
    tools: "flat"
  }),
  build(profile, req) {
    const extra = profile.args[0] === "chat" ? profile.args.slice(1) : [...profile.args];
    const args = ["chat", ...extra];
    args.push("--no-interactive");
    if (req.tools) {
      const entries = toolPolicyEntries(req.tools);
      if (entries !== undefined) {
        args.push(`--trust-tools=${entries.join(",")}`);
      }
    } else {
      args.push("--trust-all-tools");
    }
    if (req.model) {
      const resolved = resolveDispatchModel(req, profile, AMAZONQ_PLATFORM);
      args.push("--model", resolved);
    }
    args.push("--");
    args.push(buildPromptPayload(req));
    return { argv: [profile.bin, ...args] };
  }
};

// src/integrations/harnesses/amazonq/result-extractor.ts
var ESC = "\x1B";
var BEL = "\x07";
var ANSI_SEQUENCE = new RegExp(`${ESC}\\[[0-9;?]*[ -/]*[@-~]` + `|${ESC}\\][^${BEL}${ESC}]*(?:${BEL}|${ESC}\\\\)`, "g");
function resolveCarriageReturns(line) {
  const lastCr = line.lastIndexOf("\r");
  return lastCr === -1 ? line : line.slice(lastCr + 1);
}
function stripTerminalFraming(raw) {
  const lines = raw.split(/\r?\n/).map((line) => resolveCarriageReturns(line).replace(ANSI_SEQUENCE, ""));
  for (let i = 0;i < lines.length; i++) {
    const line = lines[i] ?? "";
    if (line.trim().length === 0)
      continue;
    if (line.startsWith("> "))
      lines[i] = line.slice(2);
    break;
  }
  return lines.join(`
`).trim();
}
var amazonqResultExtractor = (result) => {
  const sessionId = result.sessionId;
  const text = typeof result.parsed === "string" ? result.parsed.trim() : stripTerminalFraming(result.stdout);
  return { text, ...sessionId ? { sessionId } : {} };
};

// src/integrations/harnesses/amazonq/index.ts
class AmazonqHarness extends BaseHarness {
  id = "amazonq";
  displayName = "Amazon Q Developer CLI";
  agentBuilder = amazonqBuilder;
  resultExtractor = amazonqResultExtractor;
  capabilities = caps({
    agentDispatch: true,
    detection: true
  });
}

// src/integrations/harnesses/claude/agent-builder.ts
var MODEL_WORK_CLAUDE_FLAGS = Object.freeze([
  "--restricted",
  "--strict-mcp-config",
  "--tools",
  "Read,Edit,Bash",
  "--allowedTools",
  "Read,Edit,Bash(akm search *),Bash(akm show *)",
  "--permission-mode",
  "dontAsk"
]);
var claudeBuilder = {
  platform: "claude",
  personaChannel: "native",
  lower: createAgentRequestLowerer({
    adapter: "claude",
    personaChannel: "native",
    nativeAgentSelector: true,
    tools: "all"
  }),
  build(profile, req) {
    const modelWork = req.modelWork === true;
    const args = modelWork ? [...MODEL_WORK_CLAUDE_FLAGS] : [...profile.args];
    if (req.agent) {
      args.push("--agent", req.agent);
    }
    if (req.systemPrompt) {
      args.push("--system-prompt", req.systemPrompt);
    }
    if (req.model) {
      const resolved = resolveDispatchModel(req, profile, "claude");
      args.push("--model", resolved);
    } else if (modelWork) {
      const model = modelFromArgs(profile.args);
      if (model)
        args.push("--model", model);
    }
    if (req.tools) {
      args.push("--allowedTools", normalizeTools(req.tools));
    }
    if (req.schema) {
      args.push("--output-format", "json");
    }
    args.push("--print");
    args.push("--");
    args.push(req.prompt);
    return { argv: [profile.bin, ...args] };
  }
};

// src/integrations/harnesses/claude/result-extractor.ts
function isResultEnvelope(value) {
  if (value.type === "result")
    return true;
  return typeof value.result === "string" && asNonEmptyString(value.session_id) !== undefined;
}
var claudeResultExtractor = (result) => {
  const fallbackSessionId = result.sessionId;
  const raw = result.stdout;
  const trimmed = raw.trim();
  if (trimmed.startsWith("{")) {
    const whole = result.parsed !== undefined ? result.parsed : tryParseJson(trimmed);
    if (isRecord(whole) && isResultEnvelope(whole)) {
      const text = typeof whole.result === "string" ? whole.result : trimmed;
      const sessionId = asNonEmptyString(whole.session_id) ?? fallbackSessionId;
      return { text, ...sessionId ? { sessionId } : {} };
    }
  }
  return { text: raw, ...fallbackSessionId ? { sessionId: fallbackSessionId } : {} };
};

// src/integrations/harnesses/claude/session-log.ts
import fs35 from "node:fs";
import os4 from "node:os";
import path42 from "node:path";

// src/integrations/session-logs/inline-refs.ts
var REMEMBER_RE = /\bakm\s+remember\s+(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)')/g;
var FEEDBACK_RE = /\bakm\s+feedback\s+(\S+)(?:\s+--[a-z-]+)*\s+(?:--note|-n)\s+(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)')/g;
function extractInlineRefMentions(text, ts) {
  if (!text || text.length < 10)
    return [];
  const out = [];
  REMEMBER_RE.lastIndex = 0;
  for (const m of text.matchAll(REMEMBER_RE)) {
    const body = m[1] ?? m[2] ?? "";
    if (!body.trim())
      continue;
    out.push({
      kind: "remember",
      text: body,
      ...ts !== undefined ? { ts } : {}
    });
  }
  FEEDBACK_RE.lastIndex = 0;
  for (const m of text.matchAll(FEEDBACK_RE)) {
    const ref = m[1] ?? "";
    const note = m[2] ?? m[3] ?? "";
    if (!ref)
      continue;
    out.push({
      kind: "feedback",
      ref,
      text: note,
      ...ts !== undefined ? { ts } : {}
    });
  }
  return out;
}

// src/integrations/session-logs/provider-base.ts
import fs34 from "node:fs";
import path41 from "node:path";

class AbstractSessionLogProvider {
  isAvailable() {
    return fs34.existsSync(this.availabilityRoot());
  }
  statSafe(target) {
    try {
      return fs34.statSync(target);
    } catch {
      return;
    }
  }
  *walkFiles(dir, matches) {
    try {
      for (const entry of fs34.readdirSync(dir, { withFileTypes: true })) {
        const full = path41.join(dir, entry.name);
        if (entry.isDirectory())
          yield* this.walkFiles(full, matches);
        else if (matches(entry.name))
          yield full;
      }
    } catch {}
  }
  sessionRef(input) {
    return {
      harness: this.name,
      sessionId: input.sessionId,
      filePath: input.filePath,
      ...input.startedAt !== undefined ? { startedAt: input.startedAt } : {},
      ...input.endedAt !== undefined ? { endedAt: input.endedAt } : {},
      ...input.projectHint ? { projectHint: input.projectHint } : {},
      ...input.title ? { title: input.title } : {}
    };
  }
  listSessionsFromFiles(input) {
    const summaries = [];
    try {
      for (const filePath of input.enumerate()) {
        const stat = this.statSafe(filePath);
        if (!stat)
          continue;
        if (stat.mtimeMs < input.sinceMs)
          continue;
        const summary = input.summarize(filePath, stat);
        if (summary)
          summaries.push(summary);
      }
    } catch {}
    return summaries.sort((a, b) => (b.endedAt ?? 0) - (a.endedAt ?? 0));
  }
}

// src/integrations/harnesses/claude/session-log.ts
function claudeProjectsDir() {
  return process.env.AKM_CLAUDE_PROJECTS_DIR ?? path42.join(os4.homedir(), ".claude", "projects");
}
var SUBAGENTS_DIR = "subagents";
function subagentProvenance(jsonlPath) {
  let agentType;
  let description;
  try {
    const meta = JSON.parse(fs35.readFileSync(jsonlPath.replace(/\.jsonl$/, ".meta.json"), "utf8"));
    if (typeof meta.agentType === "string")
      agentType = meta.agentType;
    if (typeof meta.description === "string")
      description = meta.description;
  } catch {}
  return `[subagent:${agentType ?? "unknown"}]${description ? ` ${description}` : ""}`;
}
function parseClaudeEvent(entry, sessionId, filePath, fallbackTsMs) {
  if (!entry || typeof entry !== "object")
    return;
  const e = entry;
  const tsRaw = e.timestamp;
  const ts = typeof tsRaw === "number" ? tsRaw : typeof tsRaw === "string" ? Date.parse(tsRaw) || fallbackTsMs : fallbackTsMs;
  const message = e.message ?? undefined;
  const role = typeof message?.role === "string" ? message.role : e.type ?? "unknown";
  const content = message?.content;
  let text = "";
  if (typeof content === "string") {
    text = content;
  } else if (Array.isArray(content)) {
    const parts = [];
    for (const block of content) {
      if (!block || typeof block !== "object")
        continue;
      const b = block;
      if (b.type === "text" && typeof b.text === "string")
        parts.push(b.text);
      else if (b.type === "thinking" && typeof b.thinking === "string")
        parts.push(b.thinking);
      else if (b.type === "tool_use") {
        const toolName2 = typeof b.name === "string" ? b.name : "tool";
        const inputObj = b.input;
        let inputText = "";
        if (inputObj && typeof inputObj === "object") {
          const cmd = inputObj.command;
          inputText = typeof cmd === "string" ? cmd : JSON.stringify(inputObj);
        } else if (typeof inputObj === "string") {
          inputText = inputObj;
        }
        parts.push(`[tool:${toolName2}] ${inputText}`);
      } else if (b.type === "tool_result") {
        const out = typeof b.content === "string" ? b.content : JSON.stringify(b.content ?? "");
        parts.push(`[tool_result] ${out}`);
      }
    }
    text = parts.join(`
`);
  }
  if (!text || text.length < 1)
    return;
  return {
    harness: "claude",
    text,
    ts,
    sessionId,
    role,
    filePath
  };
}

class ClaudeCodeProvider extends AbstractSessionLogProvider {
  name = "claude";
  availabilityRoot() {
    return claudeProjectsDir();
  }
  listSessions(input = {}) {
    const root = input.location ?? claudeProjectsDir();
    return this.listSessionsFromFiles({
      sinceMs: input.sinceMs ?? 0,
      enumerate: () => this.#walkJsonl(root),
      summarize: (jsonlPath, stat) => {
        const peek = this.#peekJsonl(jsonlPath);
        return this.sessionRef({
          sessionId: path42.basename(jsonlPath, ".jsonl"),
          filePath: jsonlPath,
          startedAt: peek.firstTsMs ?? stat.ctimeMs,
          endedAt: peek.lastTsMs ?? stat.mtimeMs,
          projectHint: path42.basename(path42.dirname(jsonlPath)),
          title: peek.title
        });
      }
    });
  }
  readSession(ref) {
    const stat = fs35.statSync(ref.filePath);
    const projectHint = path42.basename(path42.dirname(ref.filePath));
    const parent = this.#readTranscript(ref.filePath, ref.sessionId, stat.mtimeMs);
    const events = parent.events;
    const inlineRefs = parent.inlineRefs;
    for (const subagentPath of this.walkFiles(path42.join(path42.dirname(ref.filePath), path42.basename(ref.filePath, ".jsonl"), SUBAGENTS_DIR), (name) => name.endsWith(".jsonl"))) {
      const subagent = this.#readTranscript(subagentPath, ref.sessionId, stat.mtimeMs, subagentProvenance(subagentPath));
      events.push(...subagent.events);
      inlineRefs.push(...subagent.inlineRefs);
    }
    events.sort((a, b) => (a.ts ?? 0) - (b.ts ?? 0));
    return {
      ref: this.sessionRef({
        sessionId: ref.sessionId,
        filePath: ref.filePath,
        startedAt: events[0]?.ts ?? stat.ctimeMs,
        endedAt: events[events.length - 1]?.ts ?? stat.mtimeMs,
        projectHint,
        title: parent.title
      }),
      events,
      inlineRefs
    };
  }
  #readTranscript(filePath, sessionId, fallbackTsMs, provenance) {
    const events = [];
    const inlineRefs = [];
    let title;
    const lines = fs35.readFileSync(filePath, "utf8").split(`
`).filter(Boolean);
    for (const line of lines) {
      let entry;
      try {
        entry = JSON.parse(line);
      } catch {
        continue;
      }
      if (!entry)
        continue;
      if (entry.type === "custom-title" && typeof entry.customTitle === "string") {
        title = entry.customTitle;
        continue;
      }
      const parsed = parseClaudeEvent(entry, sessionId, filePath, fallbackTsMs);
      if (!parsed)
        continue;
      events.push(provenance ? { ...parsed, text: `${provenance}
${parsed.text}` } : parsed);
      inlineRefs.push(...extractInlineRefMentions(parsed.text, parsed.ts));
    }
    return { events, inlineRefs, ...title ? { title } : {} };
  }
  #peekJsonl(filePath) {
    const result = {};
    try {
      const fd = fs35.openSync(filePath, "r");
      try {
        const stat = fs35.fstatSync(fd);
        const headSize = Math.min(stat.size, 4096);
        const head = Buffer.alloc(headSize);
        fs35.readSync(fd, head, 0, headSize, 0);
        const headLines = head.toString("utf8").split(`
`).filter(Boolean);
        for (const line of headLines) {
          try {
            const e = JSON.parse(line);
            if (e.type === "custom-title" && typeof e.customTitle === "string") {
              result.title = e.customTitle;
            }
            if (typeof e.timestamp === "string") {
              const t = Date.parse(e.timestamp);
              if (!Number.isNaN(t)) {
                if (result.firstTsMs === undefined)
                  result.firstTsMs = t;
                result.lastTsMs = t;
              }
            }
          } catch {}
        }
        if (stat.size > 4096) {
          const tailSize = Math.min(stat.size, 4096);
          const tail = Buffer.alloc(tailSize);
          fs35.readSync(fd, tail, 0, tailSize, stat.size - tailSize);
          const tailLines = tail.toString("utf8").split(`
`).filter(Boolean);
          for (let i = tailLines.length - 1;i >= 0; i--) {
            try {
              const e = JSON.parse(tailLines[i] ?? "");
              if (typeof e.timestamp === "string") {
                const t = Date.parse(e.timestamp);
                if (!Number.isNaN(t)) {
                  result.lastTsMs = t;
                  break;
                }
              }
            } catch {}
          }
        }
      } finally {
        fs35.closeSync(fd);
      }
    } catch {}
    return result;
  }
  *#walkJsonl(dir) {
    for (const filePath of this.walkFiles(dir, (name) => name.endsWith(".jsonl") && name !== "journal.jsonl")) {
      const segments = path42.relative(dir, filePath).split(path42.sep);
      if (segments.slice(1, -1).includes(SUBAGENTS_DIR))
        continue;
      yield filePath;
    }
  }
}

// src/integrations/harnesses/claude/index.ts
class ClaudeHarness extends BaseHarness {
  id = "claude";
  displayName = "Claude Code";
  setupDetectionDir = ".claude";
  agentBuilder = claudeBuilder;
  resultExtractor = claudeResultExtractor;
  identityEnv = ["CLAUDE_SESSION_ID"];
  sessionLogProvider = () => new ClaudeCodeProvider;
  capabilities = caps({
    sessionLogs: true,
    agentDispatch: true,
    detection: true,
    configImport: true
  });
}

// src/integrations/harnesses/codex/agent-builder.ts
import { mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
function writeCodexOutputSchemaFile(schema) {
  const dir = mkdtempSync(join(tmpdir(), "akm-codex-schema-"));
  const file = join(dir, "output-schema.json");
  writeFileSync(file, `${JSON.stringify(schema, null, 2)}
`, "utf8");
  return file;
}
function ensureSandboxFlags(base) {
  const out = [...base];
  if (!out.includes("--sandbox") && !out.includes("-s")) {
    out.push("--sandbox", "workspace-write");
  }
  return out;
}
var codexBuilder = {
  platform: "codex",
  personaChannel: "prompt",
  lower: createAgentRequestLowerer({
    adapter: "codex",
    personaChannel: "prompt",
    tools: "none"
  }),
  build(profile, req) {
    const extra = profile.args[0] === "exec" ? profile.args.slice(1) : [...profile.args];
    const sandboxArgs = ensureSandboxFlags(extra);
    const args = ["exec", ...sandboxArgs];
    if (req.model) {
      const resolved = resolveDispatchModel(req, profile, "codex");
      args.push("--model", resolved);
    }
    args.push("--json");
    if (req.schema) {
      args.push("--output-schema", writeCodexOutputSchemaFile(req.schema));
    }
    const prompt = req.systemPrompt ? `${req.systemPrompt}

${req.prompt}` : req.prompt;
    args.push("--");
    args.push(prompt);
    return { argv: [profile.bin, ...args] };
  }
};

// src/integrations/harnesses/codex/result-extractor.ts
function interpretEvent(event) {
  const msg = event.msg;
  if (isRecord(msg)) {
    switch (msg.type) {
      case "session_configured":
        return { sessionId: asNonEmptyString(msg.session_id) };
      case "agent_message":
        return { agentMessage: asNonEmptyString(msg.message) };
      case "task_complete":
        return { finalMessage: asNonEmptyString(msg.last_agent_message) };
      default:
        return {};
    }
  }
  switch (event.type) {
    case "thread.started":
      return { sessionId: asNonEmptyString(event.thread_id) };
    case "item.completed": {
      const item = event.item;
      if (isRecord(item) && item.type === "agent_message") {
        return { agentMessage: asNonEmptyString(item.text) };
      }
      return {};
    }
    default:
      return {};
  }
}
var codexResultExtractor = (result) => {
  let sessionId = result.sessionId;
  let lastAgentMessage;
  let finalMessage;
  for (const line of result.stdout.split(`
`)) {
    const trimmed = line.trim();
    if (!trimmed.startsWith("{"))
      continue;
    let parsed;
    try {
      parsed = JSON.parse(trimmed);
    } catch {
      continue;
    }
    if (!isRecord(parsed))
      continue;
    const contribution = interpretEvent(parsed);
    if (contribution.sessionId)
      sessionId = contribution.sessionId;
    if (contribution.agentMessage)
      lastAgentMessage = contribution.agentMessage;
    if (contribution.finalMessage)
      finalMessage = contribution.finalMessage;
  }
  const text = finalMessage ?? lastAgentMessage ?? result.stdout.trim();
  return sessionId === undefined ? { text } : { text, sessionId };
};

// src/integrations/harnesses/codex/session-log.ts
import fs36 from "node:fs";
import os5 from "node:os";
import path43 from "node:path";
function codexSessionsDir() {
  return path43.join(process.env.CODEX_HOME || path43.join(os5.homedir(), ".codex"), "sessions");
}
var META_PEEK_BYTES = 128 * 1024;
var INJECTED_CONTEXT_RE = /^\s*(?:# AGENTS\.md instructions[\s\S]*<\/INSTRUCTIONS>|<(environment_context|user_instructions|recommended_plugins|skill|turn_aborted)>[\s\S]*<\/\1>)\s*$/i;
function parseSessionMeta(entry) {
  const e = entry;
  if (e?.type !== "session_meta" || !e.payload)
    return;
  const { timestamp, cwd, source } = e.payload;
  const startedAt = typeof timestamp === "string" ? Date.parse(timestamp) : Number.NaN;
  return {
    ...Number.isNaN(startedAt) ? {} : { startedAt },
    ...typeof cwd === "string" ? { cwd } : {},
    isAgent: typeof source === "object" && source !== null && (("subagent" in source) || ("internal" in source))
  };
}
function blockText(blocks, keep = () => true) {
  if (typeof blocks === "string")
    return blocks;
  if (!Array.isArray(blocks))
    return "";
  const parts = [];
  for (const block of blocks) {
    const text = block?.text;
    if (typeof text === "string" && keep(text))
      parts.push(text);
  }
  return parts.join(`
`);
}
function toolInputText(input) {
  let args = input;
  if (typeof input === "string") {
    try {
      args = JSON.parse(input);
    } catch {
      return input;
    }
  }
  const fields = args && typeof args === "object" ? args : {};
  const cmd = fields.cmd ?? fields.command;
  if (typeof cmd === "string")
    return cmd;
  if (Array.isArray(cmd))
    return cmd.join(" ");
  return typeof input === "string" ? input : JSON.stringify(input) ?? "";
}
function parseCodexRecord(entry, sessionId, filePath, fallbackTsMs) {
  const e = entry;
  const item = e?.type === "response_item" ? e.payload : undefined;
  if (!item)
    return;
  const toolName2 = typeof item.name === "string" ? item.name : "tool";
  let role = "assistant";
  let text;
  switch (item.type) {
    case "message":
      if (item.role !== "user" && item.role !== "assistant")
        return;
      role = item.role;
      text = blockText(item.content, item.role === "user" ? (t) => !INJECTED_CONTEXT_RE.test(t) : undefined);
      break;
    case "function_call":
      text = `[tool:${toolName2}] ${toolInputText(item.arguments)}`;
      break;
    case "custom_tool_call":
      text = `[tool:${toolName2}] ${typeof item.input === "string" ? item.input : ""}`;
      break;
    case "local_shell_call":
      text = `[tool:shell] ${toolInputText(item.action)}`;
      break;
    case "function_call_output":
    case "custom_tool_call_output": {
      role = "tool";
      const output = blockText(item.output);
      text = output ? `[tool_result] ${output}` : "";
      break;
    }
    default:
      return;
  }
  if (!text.trim())
    return;
  const ts = typeof e?.timestamp === "string" ? Date.parse(e.timestamp) || fallbackTsMs : fallbackTsMs;
  return { harness: "codex", text, ts, sessionId, role, filePath };
}

class CodexProvider extends AbstractSessionLogProvider {
  name = "codex";
  availabilityRoot() {
    return codexSessionsDir();
  }
  listSessions(input = {}) {
    return this.listSessionsFromFiles({
      sinceMs: input.sinceMs ?? 0,
      enumerate: () => this.walkFiles(input.location ?? codexSessionsDir(), (name) => /^rollout-.+\.jsonl$/.test(name)),
      summarize: (rolloutPath, stat) => {
        const meta = this.#peekMeta(rolloutPath);
        if (meta?.isAgent)
          return;
        return this.sessionRef({
          sessionId: path43.basename(rolloutPath, ".jsonl").slice(-36),
          filePath: rolloutPath,
          startedAt: meta?.startedAt ?? stat.ctimeMs,
          endedAt: stat.mtimeMs,
          projectHint: meta?.cwd
        });
      }
    });
  }
  readSession(ref) {
    const stat = fs36.statSync(ref.filePath);
    const events = [];
    const inlineRefs = [];
    let meta;
    for (const line of fs36.readFileSync(ref.filePath, "utf8").split(`
`).filter(Boolean)) {
      let entry;
      try {
        entry = JSON.parse(line);
      } catch {
        continue;
      }
      meta ??= parseSessionMeta(entry);
      const parsed = parseCodexRecord(entry, ref.sessionId, ref.filePath, stat.mtimeMs);
      if (!parsed)
        continue;
      events.push(parsed);
      inlineRefs.push(...extractInlineRefMentions(parsed.text, parsed.ts));
    }
    return {
      ref: this.sessionRef({
        sessionId: ref.sessionId,
        filePath: ref.filePath,
        startedAt: meta?.startedAt ?? events[0]?.ts ?? stat.ctimeMs,
        endedAt: events[events.length - 1]?.ts ?? stat.mtimeMs,
        projectHint: meta?.cwd
      }),
      events,
      inlineRefs
    };
  }
  #peekMeta(filePath) {
    try {
      const fd = fs36.openSync(filePath, "r");
      try {
        const head = Buffer.alloc(META_PEEK_BYTES);
        const firstLine = head.toString("utf8", 0, fs36.readSync(fd, head, 0, head.length, 0)).split(`
`, 1)[0] ?? "";
        return parseSessionMeta(JSON.parse(firstLine));
      } finally {
        fs36.closeSync(fd);
      }
    } catch {
      return;
    }
  }
}

// src/integrations/harnesses/codex/index.ts
class CodexHarness extends BaseHarness {
  id = "codex";
  displayName = "OpenAI Codex CLI";
  agentBuilder = codexBuilder;
  resultExtractor = codexResultExtractor;
  presenceEnv = ["CODEX_SANDBOX"];
  sessionLogProvider = () => new CodexProvider;
  capabilities = caps({
    sessionLogs: true,
    agentDispatch: true,
    detection: true
  });
}

// src/integrations/harnesses/copilot/agent-builder.ts
var COPILOT_PLATFORM = "copilot";
function toolPolicyEntries2(tools) {
  if (typeof tools === "string") {
    return tools.split(",").map((t) => t.trim()).filter(Boolean);
  }
  if (Array.isArray(tools)) {
    return tools.map((t) => t.trim()).filter(Boolean);
  }
  return;
}
function buildPromptPayload2(req) {
  const sections = [];
  if (req.systemPrompt)
    sections.push(req.systemPrompt);
  sections.push(req.prompt);
  return sections.join(`

`);
}
var copilotBuilder = {
  platform: COPILOT_PLATFORM,
  personaChannel: "prompt",
  lower: createAgentRequestLowerer({
    adapter: COPILOT_PLATFORM,
    personaChannel: "prompt",
    tools: "flat"
  }),
  build(profile, req) {
    const args = [...profile.args];
    if (req.model) {
      const resolved = resolveDispatchModel(req, profile, COPILOT_PLATFORM);
      args.push("--model", resolved);
    }
    if (req.tools) {
      const entries = toolPolicyEntries2(req.tools);
      for (const tool of entries ?? []) {
        args.push("--allow-tool", tool);
      }
    } else {
      args.push("--allow-all-tools");
    }
    if (req.schema) {
      args.push("--output-format", "json");
    }
    args.push("-p", buildPromptPayload2(req));
    return { argv: [profile.bin, ...args] };
  }
};

// src/integrations/harnesses/copilot/result-extractor.ts
var TEXT_KEYS = ["result", "response", "text", "output", "content", "message"];
var SESSION_KEYS = ["session_id", "sessionId", "conversation_id", "conversationId", "thread_id", "threadId"];
function textOf(value, depth = 0) {
  if (depth > 4)
    return;
  if (typeof value === "string")
    return value;
  if (Array.isArray(value)) {
    const parts = [];
    for (const block of value) {
      const t = textOf(block, depth + 1);
      if (t)
        parts.push(t);
    }
    return parts.length > 0 ? parts.join(`
`) : undefined;
  }
  if (isRecord(value)) {
    return textOf(value.content ?? value.text, depth + 1);
  }
  return;
}
function extractText(value) {
  if (typeof value === "string")
    return value;
  if (!isRecord(value))
    return;
  for (const key of TEXT_KEYS) {
    if (!(key in value))
      continue;
    const text = textOf(value[key]);
    if (text !== undefined)
      return text;
  }
  return;
}
function extractSessionId(value) {
  if (!isRecord(value))
    return;
  for (const key of SESSION_KEYS) {
    const candidate = value[key];
    if (typeof candidate === "string" && candidate.length > 0)
      return candidate;
  }
  return;
}
var ENVELOPE_TYPES = new Set(["result", "response", "message", "assistant", "error"]);
function isTransportEnvelope(value) {
  const type = value.type;
  if (typeof type === "string" && (ENVELOPE_TYPES.has(type) || type.startsWith("session.")))
    return true;
  return extractSessionId(value) !== undefined;
}
var copilotResultExtractor = (result) => {
  const fallbackSessionId = result.sessionId;
  const raw = result.stdout.trim();
  const whole = result.parsed !== undefined ? result.parsed : raw.length > 0 ? tryParseJson(raw) : undefined;
  if (whole !== undefined) {
    const sessionId = extractSessionId(whole) ?? fallbackSessionId;
    const text = isRecord(whole) && !isTransportEnvelope(whole) ? raw : extractText(whole) ?? raw;
    return { text, ...sessionId ? { sessionId } : {} };
  }
  let lastText;
  let streamSessionId;
  let sawJsonLine = false;
  for (const line of raw.split(`
`)) {
    const trimmed = line.trim();
    if (trimmed.length === 0)
      continue;
    const event = tryParseJson(trimmed);
    if (event === undefined)
      continue;
    sawJsonLine = true;
    streamSessionId ??= extractSessionId(event);
    const text = extractText(event);
    if (text !== undefined)
      lastText = text;
  }
  if (sawJsonLine) {
    const sessionId = streamSessionId ?? fallbackSessionId;
    return { text: lastText ?? raw, ...sessionId ? { sessionId } : {} };
  }
  return { text: raw, ...fallbackSessionId ? { sessionId: fallbackSessionId } : {} };
};

// src/integrations/harnesses/copilot/index.ts
class CopilotHarness extends BaseHarness {
  id = "copilot";
  displayName = "GitHub Copilot CLI";
  agentBuilder = copilotBuilder;
  resultExtractor = copilotResultExtractor;
  identityEnv = ["COPILOT_SESSION_ID"];
  capabilities = caps({
    agentDispatch: true,
    detection: true
  });
}

// src/integrations/harnesses/gemini/agent-builder.ts
var GEMINI_PLATFORM = "gemini";
function toolPolicyEntries3(tools) {
  if (typeof tools === "string") {
    return tools.split(",").map((t) => t.trim()).filter(Boolean);
  }
  if (Array.isArray(tools)) {
    return tools.map((t) => t.trim()).filter(Boolean);
  }
  return;
}
function buildPromptPayload3(req) {
  const sections = [];
  if (req.systemPrompt)
    sections.push(req.systemPrompt);
  sections.push(req.prompt);
  return sections.join(`

`);
}
var geminiBuilder = {
  platform: GEMINI_PLATFORM,
  personaChannel: "prompt",
  lower: createAgentRequestLowerer({
    adapter: GEMINI_PLATFORM,
    personaChannel: "prompt",
    tools: "flat"
  }),
  build(profile, req) {
    const args = [...profile.args];
    if (req.model) {
      const resolved = resolveDispatchModel(req, profile, GEMINI_PLATFORM);
      args.push("--model", resolved);
    }
    if (req.tools) {
      for (const tool of toolPolicyEntries3(req.tools) ?? []) {
        args.push("--allowed-tools", tool);
      }
    }
    if (req.schema) {
      args.push("--output-format", "json");
    }
    args.push("-p", buildPromptPayload3(req));
    return { argv: [profile.bin, ...args] };
  }
};

// src/integrations/harnesses/gemini/result-extractor.ts
var TEXT_KEYS2 = ["response", "result", "text", "output", "content", "message"];
var SESSION_KEYS2 = ["session_id", "sessionId", "conversation_id", "conversationId", "chat_id", "chatId"];
function textOf2(value, depth = 0) {
  if (depth > 4)
    return;
  if (typeof value === "string")
    return value;
  if (Array.isArray(value)) {
    const parts = [];
    for (const block of value) {
      const t = textOf2(block, depth + 1);
      if (t)
        parts.push(t);
    }
    return parts.length > 0 ? parts.join(`
`) : undefined;
  }
  if (isRecord(value)) {
    return textOf2(value.content ?? value.text, depth + 1);
  }
  return;
}
function extractText2(value) {
  if (typeof value === "string")
    return value;
  if (!isRecord(value))
    return;
  for (const key of TEXT_KEYS2) {
    if (!(key in value))
      continue;
    const text = textOf2(value[key]);
    if (text !== undefined)
      return text;
  }
  return;
}
function extractSessionId2(value) {
  if (!isRecord(value))
    return;
  for (const key of SESSION_KEYS2) {
    const candidate = value[key];
    if (typeof candidate === "string" && candidate.length > 0)
      return candidate;
  }
  return;
}
var geminiResultExtractor = (result) => {
  const fallbackSessionId = result.sessionId;
  const raw = result.stdout.trim();
  const whole = result.parsed !== undefined ? result.parsed : raw.length > 0 ? tryParseJson(raw) : undefined;
  if (whole !== undefined) {
    const sessionId = extractSessionId2(whole) ?? fallbackSessionId;
    const text = extractText2(whole) ?? raw;
    return { text, ...sessionId ? { sessionId } : {} };
  }
  let lastText;
  let streamSessionId;
  let sawJsonLine = false;
  for (const line of raw.split(`
`)) {
    const trimmed = line.trim();
    if (trimmed.length === 0)
      continue;
    const event = tryParseJson(trimmed);
    if (event === undefined)
      continue;
    sawJsonLine = true;
    streamSessionId ??= extractSessionId2(event);
    const text = extractText2(event);
    if (text !== undefined)
      lastText = text;
  }
  if (sawJsonLine) {
    const sessionId = streamSessionId ?? fallbackSessionId;
    return { text: lastText ?? raw, ...sessionId ? { sessionId } : {} };
  }
  return { text: raw, ...fallbackSessionId ? { sessionId: fallbackSessionId } : {} };
};

// src/integrations/harnesses/gemini/index.ts
class GeminiHarness extends BaseHarness {
  id = "gemini";
  displayName = "Gemini CLI";
  agentBuilder = geminiBuilder;
  resultExtractor = geminiResultExtractor;
  presenceEnv = ["GEMINI_CLI"];
  capabilities = caps({
    agentDispatch: true,
    detection: true
  });
}

// src/integrations/harnesses/opencode/model-config.ts
var MODEL_WORK_AGENT_INFERENCE = ["temperature", "reasoningEffort", "enableThinking"];
var isPositiveInteger = (value) => typeof value === "number" && Number.isInteger(value) && value > 0;
function opencodeInferenceConfig(inference, modelWork) {
  const { temperature, reasoningEffort, enableThinking, maxTokens, contextLength } = inference ?? {};
  const options = {};
  if (typeof temperature === "number" && Number.isFinite(temperature))
    options.temperature = temperature;
  if (typeof reasoningEffort === "string" && reasoningEffort.length > 0)
    options.reasoningEffort = reasoningEffort;
  if (typeof enableThinking === "boolean") {
    options.chat_template_kwargs = { enable_thinking: enableThinking };
    options.enable_thinking = enableThinking;
  }
  const hasOptions = Object.keys(options).length > 0;
  return {
    entry: {
      ...hasOptions && !modelWork ? { options } : {},
      ...isPositiveInteger(maxTokens) && isPositiveInteger(contextLength) ? { limit: { context: contextLength, output: maxTokens } } : {}
    },
    ...hasOptions && modelWork ? { agentOptions: options } : {}
  };
}

// src/integrations/harnesses/opencode/model-work-agent.ts
import path44 from "node:path";
var MODEL_WORK_OPENCODE_AGENT = "akm-model-work";
var MODEL_WORK_PROMPT = "You do one bounded task for akm. Use tools only to check what the task needs, never repeat a tool call, and reply with exactly what the task asks for.";
function modelWorkPermission(stash) {
  return {
    "*": "deny",
    read: "allow",
    grep: "allow",
    glob: "allow",
    edit: { "*": "allow", ...stash ? { [`${stash.slice(1)}/*`]: "deny" } : {} },
    external_directory: {
      ...stash ? { [`${stash}/*`]: "allow" } : {},
      "~/.local/share/opencode/tool-output/*": "deny"
    },
    akm_search: "allow",
    akm_show: "allow",
    akm_feedback: "deny",
    akm_remember: "deny",
    akm_curate: "deny",
    bash: "deny",
    doom_loop: "deny",
    list: "deny",
    lsp: "deny",
    question: "deny",
    skill: "deny",
    task: "deny",
    todowrite: "deny",
    webfetch: "deny",
    websearch: "deny"
  };
}
function modelWorkPluginEnv() {
  return {
    AKM_AUTO_CURATE: "0",
    AKM_AUTO_LEARNING: "0",
    AKM_AUTO_SKILL_PROPOSALS: "0",
    AKM_WRITE_GATE: "off",
    XDG_STATE_HOME: path44.join(getStateDir(), "opencode-model-work"),
    ...process.platform === "win32" ? {} : { AKM_OPENCODE_CLI: "/bin/true" }
  };
}
function modelWorkOpencodeConfig(options) {
  let stash;
  try {
    stash = resolveStashDir();
  } catch {}
  const permission = modelWorkPermission(stash);
  return {
    permission: { ...permission },
    compaction: { auto: false },
    agent: {
      [MODEL_WORK_OPENCODE_AGENT]: {
        mode: "primary",
        description: "akm unattended model work: read and edit inside its working directory only.",
        prompt: MODEL_WORK_PROMPT,
        ...options ? { options } : {},
        permission: { ...permission }
      }
    }
  };
}

// src/integrations/harnesses/opencode/agent-builder.ts
var opencodeBuilder = {
  platform: "opencode",
  personaChannel: "prompt",
  lower: createAgentRequestLowerer({
    adapter: "opencode",
    personaChannel: "prompt",
    nativeAgentSelector: true,
    tools: "none",
    inference: MODEL_WORK_AGENT_INFERENCE
  }),
  build(profile, req) {
    if (req.modelWork) {
      const model = req.model ?? modelFromArgs(profile.args);
      const { agentOptions } = opencodeInferenceConfig(req.inference, true);
      return {
        argv: [
          profile.bin,
          "run",
          "--agent",
          MODEL_WORK_OPENCODE_AGENT,
          ...model ? ["--model", model] : [],
          "--",
          req.prompt
        ],
        env: {
          ...modelWorkPluginEnv(),
          OPENCODE_CONFIG_CONTENT: JSON.stringify(modelWorkOpencodeConfig(agentOptions))
        }
      };
    }
    const args = req.model ? [] : [...profile.args];
    if (req.model) {
      for (let index = 0;index < profile.args.length; index += 1) {
        const arg = profile.args[index];
        if (arg === undefined)
          continue;
        if (arg === "--model") {
          index += 1;
        } else if (!arg.startsWith("--model=")) {
          args.push(arg);
        }
      }
    }
    if (req.agent) {
      args.push("--agent", req.agent);
    }
    if (req.model) {
      const resolved = resolveDispatchModel(req, profile, "opencode");
      args.push("--model", resolved);
    }
    args.push("--");
    args.push(req.prompt);
    return { argv: [profile.bin, ...args] };
  }
};

// src/integrations/harnesses/opencode/session-log.ts
import fs38 from "node:fs";
import os7 from "node:os";
import path46 from "node:path";

// src/storage/sqlite-read-snapshot.ts
import { spawnSync as spawnSync5 } from "node:child_process";
import fs37 from "node:fs";
import os6 from "node:os";
import path45 from "node:path";
var SNAPSHOT_MAX_ATTEMPTS = 8;
var SNAPSHOT_BACKOFF_MS = 25;

class SqliteReadSnapshotUnavailableError extends Error {
  constructor(message) {
    super(message);
    this.name = "SqliteReadSnapshotUnavailableError";
  }
}
function pathExists(filePath) {
  try {
    fs37.lstatSync(filePath);
    return true;
  } catch (error2) {
    if (error2.code === "ENOENT")
      return false;
    throw error2;
  }
}
function fileFingerprint(filePath) {
  try {
    const stat = fs37.statSync(filePath, { bigint: true });
    return { size: stat.size, mtimeNs: stat.mtimeNs, ctimeNs: stat.ctimeNs };
  } catch (error2) {
    if (error2.code === "ENOENT")
      return;
    throw error2;
  }
}
function databaseFingerprint(dbPath) {
  const main = fileFingerprint(dbPath);
  if (!main) {
    throw new SqliteReadSnapshotUnavailableError("SQLite snapshot source disappeared while it was being inspected");
  }
  const wal = fileFingerprint(`${dbPath}-wal`);
  return { main, ...wal ? { wal } : {} };
}
function fingerprintsEqual(left, right) {
  const sameFile = (a, b) => a?.size === b?.size && a?.mtimeNs === b?.mtimeNs && a?.ctimeNs === b?.ctimeNs;
  return sameFile(left.main, right.main) && sameFile(left.wal, right.wal);
}
function copyFileOutsideThisProcess(source, destination) {
  if (process.platform === "win32") {
    fs37.copyFileSync(source, destination);
    return;
  }
  const result = spawnSync5("cp", ["--", source, destination], {
    encoding: "utf8",
    stdio: ["ignore", "ignore", "pipe"]
  });
  if (result.error) {
    throw new SqliteReadSnapshotUnavailableError(`cannot run cp to copy ${source}: ${result.error.message}`);
  }
  if (result.status === 0)
    return;
  if (fileFingerprint(source) === undefined) {
    throw Object.assign(new Error(`${source} disappeared while it was being copied`), { code: "ENOENT" });
  }
  const reason = result.stderr.trim() || (result.signal ? `killed by ${result.signal}` : `exit status ${result.status}`);
  throw new Error(`cp could not copy ${source}: ${reason}`);
}
function openSqliteReadSnapshot(dbPath) {
  if (!pathExists(dbPath))
    return;
  const snapshotDir = fs37.mkdtempSync(path45.join(os6.tmpdir(), "akm-sqlite-read-"));
  const snapshotPath = path45.join(snapshotDir, "snapshot.db");
  let db;
  try {
    let copied = false;
    for (let attempt = 0;attempt < SNAPSHOT_MAX_ATTEMPTS; attempt++) {
      if (attempt > 0)
        sleepSync(SNAPSHOT_BACKOFF_MS * attempt);
      try {
        if (pathExists(`${dbPath}-journal`))
          continue;
        const before = databaseFingerprint(dbPath);
        copyFileOutsideThisProcess(dbPath, snapshotPath);
        if (before.wal)
          copyFileOutsideThisProcess(`${dbPath}-wal`, `${snapshotPath}-wal`);
        else
          fs37.rmSync(`${snapshotPath}-wal`, { force: true });
        const after = databaseFingerprint(dbPath);
        if (fingerprintsEqual(before, after) && !pathExists(`${dbPath}-journal`)) {
          copied = true;
          break;
        }
      } catch (error2) {
        if (error2.code === "ENOENT")
          continue;
        throw error2;
      }
    }
    if (!copied) {
      throw new SqliteReadSnapshotUnavailableError(`SQLite main/WAL files did not settle after ${SNAPSHOT_MAX_ATTEMPTS} attempts with backoff — ` + "a writer may be continuously active, or a hot rollback journal never cleared");
    }
    db = openDatabaseFinalizing(snapshotPath, { readonly: true, create: false });
    const closeSnapshot = db.close.bind(db);
    let closed = false;
    const cleanup = (bestEffort) => {
      if (closed)
        return;
      closed = true;
      process.removeListener("exit", cleanupOnExit);
      if (bestEffort) {
        try {
          closeSnapshot();
        } catch {}
        try {
          fs37.rmSync(snapshotDir, { recursive: true, force: true });
        } catch {}
        return;
      }
      try {
        closeSnapshot();
      } finally {
        fs37.rmSync(snapshotDir, { recursive: true, force: true });
      }
    };
    const cleanupOnExit = () => cleanup(true);
    process.once("exit", cleanupOnExit);
    db.close = () => cleanup(false);
    return db;
  } catch (error2) {
    try {
      db?.close();
    } finally {
      fs37.rmSync(snapshotDir, { recursive: true, force: true });
    }
    throw error2;
  }
}

// src/integrations/harnesses/opencode/session-log.ts
function getOpenCodeBaseDir() {
  if (process.platform === "darwin") {
    return path46.join(os7.homedir(), "Library", "Application Support", "opencode");
  }
  return path46.join(os7.homedir(), ".local", "share", "opencode");
}
var OPENCODE_DB_FILENAME = "opencode.db";

class OpenCodeProvider extends AbstractSessionLogProvider {
  name = "opencode";
  #baseDir = getOpenCodeBaseDir();
  availabilityRoot() {
    return this.#dbPath(this.#baseDir);
  }
  #dbPath(base) {
    return path46.join(base, OPENCODE_DB_FILENAME);
  }
  listSessions(input = {}) {
    const base = input.location ?? this.#baseDir;
    const sinceMs = input.sinceMs ?? 0;
    const dbPath = this.#dbPath(base);
    if (!fs38.existsSync(dbPath))
      return [];
    return this.#listSessionsFromDb(dbPath, sinceMs, input.isolatedSnapshot ?? false);
  }
  readSession(ref) {
    return this.#readSessionFromDb(ref);
  }
  #listSessionsFromDb(dbPath, sinceMs, isolatedSnapshot) {
    let db;
    try {
      const opened = isolatedSnapshot ? openSqliteReadSnapshot(dbPath) : openDatabase(dbPath, { readonly: true, create: false });
      if (!opened)
        return [];
      db = opened;
    } catch {
      return [];
    }
    try {
      const rows = db.prepare("SELECT id, title, directory, time_created, time_updated FROM session WHERE time_updated >= ? ORDER BY time_updated DESC").all(sinceMs);
      return rows.map((r) => this.sessionRef({
        sessionId: r.id,
        filePath: dbPath,
        startedAt: typeof r.time_created === "number" ? r.time_created : undefined,
        endedAt: typeof r.time_updated === "number" ? r.time_updated : undefined,
        projectHint: typeof r.directory === "string" && r.directory.length > 0 ? r.directory : undefined,
        title: typeof r.title === "string" && r.title.length > 0 ? r.title : undefined
      }));
    } catch {
      return [];
    } finally {
      db.close();
    }
  }
  #readSessionFromDb(ref) {
    const emptyRef = this.sessionRef({ sessionId: ref.sessionId, filePath: ref.filePath });
    let db;
    try {
      db = openDatabase(ref.filePath, { readonly: true, create: false });
    } catch {
      return { ref: emptyRef, events: [], inlineRefs: [] };
    }
    try {
      const meta = db.prepare("SELECT title, directory, time_created, time_updated FROM session WHERE id = ?").get(ref.sessionId);
      const startedAt = typeof meta?.time_created === "number" ? meta.time_created : undefined;
      const endedAt = typeof meta?.time_updated === "number" ? meta.time_updated : undefined;
      const title = typeof meta?.title === "string" && meta.title.length > 0 ? meta.title : undefined;
      const projectHint = typeof meta?.directory === "string" && meta.directory.length > 0 ? meta.directory : undefined;
      const messages = db.prepare("SELECT id, data, time_created FROM message WHERE session_id = ? ORDER BY time_created ASC, id ASC").all(ref.sessionId);
      const parts = db.prepare("SELECT message_id, data FROM part WHERE session_id = ? ORDER BY time_created ASC, id ASC").all(ref.sessionId);
      const textByMessage = new Map;
      for (const part of parts) {
        let parsed;
        try {
          parsed = JSON.parse(part.data);
        } catch {
          continue;
        }
        if (parsed?.type !== "text")
          continue;
        const text = parsed.text;
        if (typeof text !== "string" || text.length < 1)
          continue;
        const bucket = textByMessage.get(part.message_id) ?? [];
        bucket.push(text);
        textByMessage.set(part.message_id, bucket);
      }
      const events = [];
      const inlineRefs = [];
      for (const message of messages) {
        let mdata = {};
        try {
          mdata = JSON.parse(message.data);
        } catch {}
        const role = typeof mdata.role === "string" ? mdata.role : "unknown";
        const mtime = mdata.time?.created;
        const ts = typeof mtime === "number" ? mtime : typeof message.time_created === "number" ? message.time_created : undefined;
        const text = (textByMessage.get(message.id) ?? []).join(`
`).trim();
        if (text.length < 1)
          continue;
        events.push({ harness: this.name, text, ts, sessionId: ref.sessionId, role, filePath: ref.filePath });
        inlineRefs.push(...extractInlineRefMentions(text, ts));
      }
      events.sort((a, b) => (a.ts ?? 0) - (b.ts ?? 0));
      return {
        ref: this.sessionRef({
          sessionId: ref.sessionId,
          filePath: ref.filePath,
          startedAt,
          endedAt,
          projectHint,
          title
        }),
        events,
        inlineRefs
      };
    } catch {
      return { ref: emptyRef, events: [], inlineRefs: [] };
    } finally {
      db.close();
    }
  }
}

// src/integrations/harnesses/opencode/index.ts
class OpencodeHarness extends BaseHarness {
  id = "opencode";
  displayName = "OpenCode";
  setupDetectionDir = ".config/opencode";
  agentBuilder = opencodeBuilder;
  identityEnv = ["OPENCODE_SESSION_ID"];
  sessionLogProvider = () => new OpenCodeProvider;
  capabilities = caps({
    sessionLogs: true,
    agentDispatch: true,
    detection: true,
    configImport: true
  });
}

// src/integrations/harnesses/opencode-sdk/harness.ts
class OpencodeSdkHarness extends BaseHarness {
  id = "opencode-sdk";
  displayName = "OpenCode SDK";
  executionLowerer = {
    platform: "opencode-sdk",
    personaChannel: "native",
    lower: createAgentRequestLowerer({
      adapter: "opencode-sdk",
      personaChannel: "native",
      nativeAgentSelector: true,
      tools: "sdk",
      inference: MODEL_WORK_AGENT_INFERENCE
    })
  };
  capabilities = caps({
    agentDispatch: true,
    detection: true
  });
}

// src/integrations/harnesses/openhands/agent-builder.ts
var OPENHANDS_PLATFORM = "openhands";
var OPENHANDS_MODEL_ENV = "LLM_MODEL";
function buildTaskPayload(req) {
  const sections = [];
  if (req.systemPrompt)
    sections.push(req.systemPrompt);
  sections.push(req.prompt);
  return sections.join(`

`);
}
var openhandsBuilder = {
  platform: OPENHANDS_PLATFORM,
  personaChannel: "prompt",
  lower: createAgentRequestLowerer({
    adapter: OPENHANDS_PLATFORM,
    personaChannel: "prompt",
    tools: "none"
  }),
  build(profile, req) {
    const args = [...profile.args];
    args.push("--headless");
    args.push("--json");
    args.push(`--task=${buildTaskPayload(req)}`);
    let env;
    if (req.model) {
      const resolved = resolveDispatchModel(req, profile, OPENHANDS_PLATFORM);
      env = { [OPENHANDS_MODEL_ENV]: resolved };
    }
    return { argv: [profile.bin, ...args], ...env ? { env } : {} };
  }
};

// src/integrations/harnesses/openhands/result-extractor.ts
var SESSION_KEYS3 = ["session_id", "sessionId", "sid", "conversation_id"];
function extractAgentText(event) {
  if (event.source !== undefined && event.source !== "agent")
    return;
  if (typeof event.action !== "string")
    return;
  const args = isRecord(event.args) ? event.args : undefined;
  if (event.action === "message") {
    return asNonEmptyString(args?.content) ?? asNonEmptyString(event.message);
  }
  if (event.action === "finish") {
    return asNonEmptyString(args?.final_thought) ?? asNonEmptyString(args?.thought) ?? asNonEmptyString(event.message);
  }
  return;
}
function extractSessionId3(event) {
  for (const key of SESSION_KEYS3) {
    const candidate = asNonEmptyString(event[key]);
    if (candidate)
      return candidate;
  }
  return;
}
var openhandsResultExtractor = (result) => {
  const fallbackSessionId = result.sessionId;
  const raw = result.stdout.trim();
  const whole = result.parsed !== undefined ? result.parsed : raw.length > 0 ? tryParseJson(raw) : undefined;
  if (whole !== undefined) {
    if (typeof whole === "string") {
      return { text: whole, ...fallbackSessionId ? { sessionId: fallbackSessionId } : {} };
    }
    if (isRecord(whole)) {
      const sessionId = extractSessionId3(whole) ?? fallbackSessionId;
      const text = extractAgentText(whole) ?? raw;
      return { text, ...sessionId ? { sessionId } : {} };
    }
  }
  let lastText;
  let streamSessionId;
  let sawJsonLine = false;
  for (const line of raw.split(`
`)) {
    const trimmed = line.trim();
    if (trimmed.length === 0)
      continue;
    const event = tryParseJson(trimmed);
    if (event === undefined || !isRecord(event))
      continue;
    sawJsonLine = true;
    streamSessionId ??= extractSessionId3(event);
    const text = extractAgentText(event);
    if (text !== undefined)
      lastText = text;
  }
  if (sawJsonLine) {
    const sessionId = streamSessionId ?? fallbackSessionId;
    return { text: lastText ?? raw, ...sessionId ? { sessionId } : {} };
  }
  return { text: raw, ...fallbackSessionId ? { sessionId: fallbackSessionId } : {} };
};

// src/integrations/harnesses/openhands/index.ts
class OpenhandsHarness extends BaseHarness {
  id = "openhands";
  displayName = "OpenHands";
  agentBuilder = openhandsBuilder;
  resultExtractor = openhandsResultExtractor;
  capabilities = caps({
    agentDispatch: true,
    detection: true
  });
}

// src/integrations/harnesses/pi/agent-builder.ts
var PI_PLATFORM = "pi";
var piBuilder = {
  platform: PI_PLATFORM,
  personaChannel: "native",
  lower: createAgentRequestLowerer({
    adapter: PI_PLATFORM,
    personaChannel: "native",
    tools: "none"
  }),
  build(profile, req) {
    const args = [...profile.args];
    if (req.systemPrompt) {
      args.push("--system-prompt", req.systemPrompt);
    }
    if (req.model) {
      const resolved = resolveDispatchModel(req, profile, PI_PLATFORM);
      args.push("--model", resolved);
    }
    if (req.schema) {
      args.push("--mode", "json");
    }
    args.push("-p");
    args.push("--");
    args.push(req.prompt);
    return { argv: [profile.bin, ...args] };
  }
};

// src/integrations/harnesses/pi/result-extractor.ts
var SESSION_KEYS4 = ["session_id", "sessionId", "session"];
function textOf3(value, depth = 0) {
  if (depth > 4)
    return;
  if (typeof value === "string")
    return value;
  if (Array.isArray(value)) {
    const parts = [];
    for (const block of value) {
      const t = textOf3(block, depth + 1);
      if (t)
        parts.push(t);
    }
    return parts.length > 0 ? parts.join(`
`) : undefined;
  }
  if (isRecord(value)) {
    return textOf3(value.content ?? value.text, depth + 1);
  }
  return;
}
function assistantMessageText(message) {
  if (!isRecord(message) || message.role !== "assistant")
    return;
  return textOf3(message.content ?? message.text);
}
function extractAssistantText(event) {
  const fromEnvelope = assistantMessageText(event.message);
  if (fromEnvelope !== undefined)
    return fromEnvelope;
  const transcript = event.messages;
  if (Array.isArray(transcript)) {
    for (let i = transcript.length - 1;i >= 0; i--) {
      const text = assistantMessageText(transcript[i]);
      if (text !== undefined)
        return text;
    }
    return;
  }
  return assistantMessageText(event);
}
function extractSessionId4(event) {
  for (const key of SESSION_KEYS4) {
    const candidate = event[key];
    if (typeof candidate === "string" && candidate.length > 0)
      return candidate;
  }
  if (typeof event.type === "string" && event.type.startsWith("session") && typeof event.id === "string" && event.id) {
    return event.id;
  }
  return;
}
var piResultExtractor = (result) => {
  const fallbackSessionId = result.sessionId;
  const raw = result.stdout.trim();
  const whole = result.parsed !== undefined ? result.parsed : raw.length > 0 ? tryParseJson(raw) : undefined;
  if (whole !== undefined) {
    if (typeof whole === "string") {
      return { text: whole, ...fallbackSessionId ? { sessionId: fallbackSessionId } : {} };
    }
    if (isRecord(whole)) {
      const sessionId = extractSessionId4(whole) ?? fallbackSessionId;
      const text = extractAssistantText(whole) ?? textOf3(whole) ?? raw;
      return { text, ...sessionId ? { sessionId } : {} };
    }
  }
  let lastText;
  let streamSessionId;
  let sawJsonLine = false;
  for (const line of raw.split(`
`)) {
    const trimmed = line.trim();
    if (trimmed.length === 0)
      continue;
    const event = tryParseJson(trimmed);
    if (event === undefined || !isRecord(event))
      continue;
    sawJsonLine = true;
    streamSessionId ??= extractSessionId4(event);
    const text = extractAssistantText(event);
    if (text !== undefined && text.length > 0)
      lastText = text;
  }
  if (sawJsonLine) {
    const sessionId = streamSessionId ?? fallbackSessionId;
    return { text: lastText ?? raw, ...sessionId ? { sessionId } : {} };
  }
  return { text: raw, ...fallbackSessionId ? { sessionId: fallbackSessionId } : {} };
};

// src/integrations/harnesses/pi/index.ts
class PiHarness extends BaseHarness {
  id = "pi";
  displayName = "Pi";
  agentBuilder = piBuilder;
  resultExtractor = piResultExtractor;
  identityEnv = ["PI_SESSION_ID"];
  capabilities = caps({
    agentDispatch: true,
    detection: true
  });
}

// src/integrations/harnesses/index.ts
var HARNESS_REGISTRY = Object.freeze([
  new OpencodeHarness,
  new ClaudeHarness,
  new OpencodeSdkHarness,
  new CodexHarness,
  new CopilotHarness,
  new PiHarness,
  new GeminiHarness,
  new AiderHarness,
  new AmazonqHarness,
  new OpenhandsHarness
]);
if (HARNESS_REGISTRY.length !== HARNESS_ID_TABLE.length) {
  throw new Error(`harnesses/ids.ts HARNESS_ID_TABLE has ${HARNESS_ID_TABLE.length} entries but HARNESS_REGISTRY has ${HARNESS_REGISTRY.length} — update ids.ts to match.`);
}
HARNESS_REGISTRY.forEach((h, i) => {
  const expected = HARNESS_ID_TABLE[i];
  if (!expected || expected.id !== h.id || expected.agentDispatch !== h.capabilities.agentDispatch) {
    throw new Error(`harnesses/ids.ts HARNESS_ID_TABLE[${i}] (${expected?.id ?? "<missing>"}, agentDispatch=${expected?.agentDispatch}) ` + `does not match HARNESS_REGISTRY[${i}] (${h.id}, agentDispatch=${h.capabilities.agentDispatch}) — update ids.ts to match.`);
  }
});
var HARNESS_BY_ID = new Map(HARNESS_REGISTRY.map((h) => [h.id, h]));
var VALID_HARNESS_IDS2 = Object.freeze(HARNESS_REGISTRY.map((h) => h.id));
var SESSION_LOG_HARNESSES = HARNESS_REGISTRY.filter(isSessionLogHarness);
var AGENT_DISPATCH_HARNESSES = HARNESS_REGISTRY.filter((h) => h.capabilities.agentDispatch);

// src/core/spawn-env.ts
var COMMON_SPAWN_ENV_PASSTHROUGH = [
  "HOME",
  "PATH",
  "USER",
  "LANG",
  "LC_ALL",
  "TERM",
  "TMPDIR",
  "AKM_EVENT_SOURCE"
];
var XDG_BASE_DIR_ENV_PASSTHROUGH = [
  "XDG_CONFIG_HOME",
  "XDG_DATA_HOME",
  "XDG_CACHE_HOME",
  "XDG_STATE_HOME"
];
var supplementedPaths = new Map;

// src/integrations/agent/profiles.ts
var COMMON_PASSTHROUGH = COMMON_SPAWN_ENV_PASSTHROUGH;
var BUILTINS = {
  opencode: {
    name: "opencode",
    bin: "opencode",
    args: ["run"],
    stdio: "interactive",
    envPassthrough: [...COMMON_PASSTHROUGH, "OPENCODE_API_KEY", "OPENCODE_CONFIG", ...XDG_BASE_DIR_ENV_PASSTHROUGH],
    parseOutput: "text"
  },
  claude: {
    name: "claude",
    bin: "claude",
    args: [],
    stdio: "interactive",
    envPassthrough: [...COMMON_PASSTHROUGH, "ANTHROPIC_API_KEY", "CLAUDE_CONFIG"],
    parseOutput: "text"
  },
  codex: {
    name: "codex",
    bin: "codex",
    args: [],
    stdio: "interactive",
    envPassthrough: [...COMMON_PASSTHROUGH, "OPENAI_API_KEY", "CODEX_CONFIG"],
    parseOutput: "text"
  },
  gemini: {
    name: "gemini",
    bin: "gemini",
    args: [],
    stdio: "interactive",
    envPassthrough: [...COMMON_PASSTHROUGH, "GEMINI_API_KEY", "GOOGLE_API_KEY"],
    parseOutput: "text"
  },
  aider: {
    name: "aider",
    bin: "aider",
    args: ["--no-auto-commits"],
    stdio: "interactive",
    envPassthrough: [...COMMON_PASSTHROUGH, "OPENAI_API_KEY", "ANTHROPIC_API_KEY"],
    parseOutput: "text"
  },
  copilot: {
    name: "copilot",
    bin: "copilot",
    args: [],
    stdio: "interactive",
    envPassthrough: [...COMMON_PASSTHROUGH, "GH_TOKEN", "GITHUB_TOKEN"],
    parseOutput: "text"
  },
  pi: {
    name: "pi",
    bin: "pi",
    args: [],
    stdio: "interactive",
    envPassthrough: [...COMMON_PASSTHROUGH, "PI_API_KEY", "ANTHROPIC_API_KEY", "OPENAI_API_KEY"],
    parseOutput: "text"
  },
  amazonq: {
    name: "amazonq",
    bin: "q",
    args: [],
    stdio: "interactive",
    envPassthrough: [...COMMON_PASSTHROUGH, "AWS_PROFILE", "AWS_REGION"],
    parseOutput: "text"
  },
  openhands: {
    name: "openhands",
    bin: "openhands",
    args: [],
    stdio: "interactive",
    envPassthrough: [...COMMON_PASSTHROUGH, "LLM_MODEL", "LLM_API_KEY", "LLM_BASE_URL"],
    parseOutput: "text"
  }
};
var OPENCODE_SDK_SERVER_BIN = "opencode";
var BUILTIN_AGENT_PROFILE_NAMES = Object.freeze(Object.keys(BUILTINS).sort());

// src/integrations/agent/detect.ts
var NON_SPAWNABLE_SUFFIXES = new Set([".cmd", ".bat"]);

// src/integrations/agent/engine-fallback.ts
var FALLBACK_ENGINE_NAME = "opencode-sdk";
var FALLBACK_ANNOUNCEMENT = `No engine is configured; falling back to \`${FALLBACK_ENGINE_NAME}\` via the ` + `\`${OPENCODE_SDK_SERVER_BIN}\` binary on PATH — provider, model, and auth come ` + "from opencode's own configuration. " + "Run `akm setup`, or set `defaults.engine`, to choose explicitly.";
var NO_ENGINE_MESSAGE_SUFFIX = `has no selected engine, and no usable \`${OPENCODE_SDK_SERVER_BIN}\` binary was found to fall back to.`;
var NO_ENGINE_REMEDY = "Run `akm setup` to detect an installed agent, or set one explicitly: " + '`akm config set engines.claude \'{"kind":"agent","platform":"claude"}\'` ' + "then `akm config set defaults.engine claude`. " + `Installing the \`${OPENCODE_SDK_SERVER_BIN}\` binary also works ` + "(`npm i -g opencode-ai`) — akm falls back to it automatically.";

// src/integrations/agent/model-map.ts
var ENGINE_KEY_PATTERN = new RegExp(ENGINE_NAME_PATTERN_SOURCE);
var RESERVED_MAP_KEYS = new Set(["__proto__", "constructor", "prototype", "tostring"]);
var PROFILE_FIELD_KEYS = new Set(["model", "inference", "engine"]);

// src/storage/repositories/improve-ledger-repository.ts
var LEDGER_REJECTION_WINDOW_DAYS = Object.freeze({
  reflect: 14,
  distill: 30
});
var LEDGER_HARD_OUTCOMES = new Set([
  "rejected",
  "quality_rejected",
  "expired"
]);
var hasContentHashColumnCache = new WeakMap;

// src/commands/improve/improve-strategies.ts
var REF_SCOPED_PROCESSES = new Set(["reflect", "distill", "consolidate"]);
var BUILTIN_STRATEGIES = {
  default: default_default,
  quick: quick_default,
  thorough: thorough_default,
  consolidate: consolidate_default,
  catchup: catchup_default,
  "reflect-distill": reflect_distill_default,
  "proactive-maintenance": proactive_maintenance_default
};
if (BUILTIN_IMPROVE_STRATEGY_NAMES.some((name) => !(name in BUILTIN_STRATEGIES))) {
  throw new Error("Built-in improve strategy names are out of sync with their assets");
}
var MODEL_CALLING_PROCESSES = new Set(IMPROVE_ENGINE_PROCESSES.filter((name) => name !== "triage"));

// src/commands/improve/improve-usage-report.ts
function renderFixedWidthTable(headers, rows) {
  const widths = headers.map((header, index) => Math.max(header.length, ...rows.map((row) => row[index]?.length ?? 0)));
  const renderRow = (cells) => cells.map((cell, index) => cell.padEnd(widths[index] ?? 0)).join("  ").trimEnd();
  return [renderRow(headers), ...rows.map(renderRow)];
}
function formatUsageReportTable(usageReport, notes) {
  const lines = ["[improve] usage report (process x engine x model):"];
  if (usageReport.byProcessEngineModel.length === 0) {
    lines.push("  (no LLM calls recorded)");
  } else {
    const headers = ["process", "engine", "model", "calls", "failures", "promptTok", "complTok", "totalTok", "ms"];
    const rows = usageReport.byProcessEngineModel.map((row) => [
      row.process,
      row.engine,
      row.model,
      String(row.calls),
      String(row.failures),
      String(row.promptTokens),
      String(row.completionTokens),
      String(row.totalTokens),
      String(row.totalDurationMs)
    ]);
    for (const line of renderFixedWidthTable(headers, rows))
      lines.push(`  ${line}`);
  }
  if (usageReport.noCalls.length > 0) {
    lines.push("[improve] enabled processes with zero calls:");
    const headers = ["process", "engine", "reason"];
    const rows = usageReport.noCalls.map((row) => [row.process, row.engine ?? "-", row.reason]);
    for (const line of renderFixedWidthTable(headers, rows))
      lines.push(`  ${line}`);
  }
  for (const note of notes ?? [])
    lines.push(`  note: ${note}`);
  return lines.join(`
`);
}

// src/output/text/improve-report.ts
function formatImproveReportPlain(result) {
  const usageReport = result.usageReport;
  if (!usageReport)
    return null;
  const lines = [];
  if (result.mode === "since") {
    const runIds = Array.isArray(result.runIds) ? result.runIds : [];
    lines.push(`[improve] report since ${String(result.since ?? "?")} (${runIds.length} run${runIds.length === 1 ? "" : "s"})`);
  } else {
    lines.push(`[improve] report for run ${String(result.runId ?? "?")}${result.strategy ? ` (strategy: ${result.strategy})` : ""}`);
  }
  lines.push(formatUsageReportTable(usageReport, result.notes));
  return lines.join(`
`);
}
var improveReportFormatters = [
  { command: "improve-report", handler: (r) => formatImproveReportPlain(r) }
];

// src/output/text/index.ts
var indexFormatters = [{ command: "index", handler: (r) => formatIndexPlain(r) }];

// src/output/text/info.ts
var infoFormatters = [{ command: "info", handler: (r) => formatInfoPlain(r) }];

// src/output/text/lint.ts
var lintFormatters = [{ command: "lint", handler: (r) => formatLintPlain(r) }];

// src/output/text/list.ts
var listFormatters = [{ command: "list", handler: (r) => formatListPlain(r) }];

// src/output/text/migrate.ts
function planGlyph(status) {
  switch (status) {
    case "current":
      return "✓";
    case "ready":
      return "⚠";
    default:
      return "✗";
  }
}
function formatMigratePlain(result) {
  if (!result || typeof result !== "object")
    return null;
  const plan = result;
  if (typeof plan.status !== "string")
    return null;
  const lines = [`${planGlyph(plan.status)} ${plan.status}`];
  if (plan.taskFiles) {
    const tasks = plan.taskFiles;
    lines.push(`    task files: ${tasks.changed} change, ${tasks.skipped} current, ${tasks.blocked} blocked`);
  }
  if (plan.blockers?.length) {
    lines.push("", "blockers:", ...plan.blockers.map((blocker) => `  - ${blocker}`));
  }
  if (plan.backupPath) {
    lines.push("", `backup: ${plan.backupPath}`);
  }
  if (plan.applied !== undefined)
    lines.push(`applied: ${plan.applied}`);
  return lines.join(`
`);
}
var migrateFormatters = [
  { command: "migrate-status", handler: (r) => formatMigratePlain(r) },
  { command: "migrate-apply", handler: (r) => formatMigratePlain(r) }
];

// src/output/text/models.ts
var modelsFormatters = [
  { command: "models-list", handler: (r) => formatModelsListPlain(r) }
];

// src/output/text/proposal/producer.ts
var proposalProducerFormatters = [
  { command: "reflect", handler: (r) => formatProposalProducerPlain("reflect", r) },
  { command: "proposal-new", handler: (r) => formatProposalProducerPlain("proposal new", r) }
];

// src/output/text/proposal/proposal.ts
var proposalFormatters = [
  { command: "proposal-list", handler: (r) => formatProposalListPlain(r) },
  { command: "proposal-show", handler: (r) => formatProposalShowPlain(r) },
  { command: "proposal-accept", handler: (r) => formatProposalAcceptPlain(r) },
  { command: "proposal-reject", handler: (r) => formatProposalRejectPlain(r) },
  { command: "proposal-reopen", handler: (r) => formatProposalReopenPlain(r) },
  { command: "proposal-reopen-batch", handler: (r) => formatProposalReopenBatchPlain(r) },
  { command: "proposal-diff", handler: (r) => formatProposalDiffPlain(r) },
  { command: "proposal-drain", handler: (r) => formatProposalDrainPlain(r) }
];

// src/output/text/registry.ts
var TEXT_FORMATTER_REGISTRY = createCommandRegistry();
function registerTextFormatters(entries) {
  TEXT_FORMATTER_REGISTRY.registerAll(entries);
}

// src/output/text/registry-commands.ts
var registryCommandFormatters = [
  { command: "registry-list", handler: (r) => formatRegistryListPlain(r) },
  { command: "registry-add", handler: (r) => formatRegistryAddPlain(r) },
  { command: "registry-remove", handler: (r) => formatRegistryRemovePlain(r) },
  { command: "registry-search", handler: (r, detail) => formatRegistrySearchPlain(r, detail) }
];

// src/output/text/remember.ts
var rememberFormatters = [
  { command: "remember", handler: (r) => formatRememberPlain(r) }
];

// src/output/text/remove.ts
var removeFormatters = [{ command: "remove", handler: (r) => formatRemovePlain(r) }];

// src/output/text/search.ts
var searchFormatters = [
  { command: "search", handler: (r, detail) => formatSearchPlain(r, detail) }
];

// src/output/text/show.ts
var showFormatters = [
  { command: "show", handler: (r, detail) => formatShowPlain(r, detail) }
];

// src/output/text/sync.ts
var syncFormatters = [{ command: "sync", handler: (r) => formatSyncPlain(r) }];

// src/output/text/update.ts
var updateFormatters = [{ command: "update", handler: (r) => formatUpdatePlain(r) }];

// src/output/text/upgrade.ts
var upgradeFormatters = [{ command: "upgrade", handler: (r) => formatUpgradePlain(r) }];

// src/output/text/workflow.ts
var workflowFormatters = [
  { command: "workflow-status", handler: (r) => formatWorkflowStatusPlain(r) },
  { command: "workflow-list", handler: (r) => formatWorkflowListPlain(r) },
  { command: "workflow-create", handler: (r) => formatWorkflowCreatePlain(r) },
  { command: "workflow-resume", handler: (r) => formatWorkflowResumePlain(r) },
  { command: "workflow-abandon", handler: (r) => formatWorkflowStatusPlain(r) },
  { command: "workflow-run", handler: (r) => formatWorkflowRunPlain(r) },
  { command: "workflow-plan", handler: (r) => formatWorkflowPlanPlain(r) }
];

// src/output/text.ts
var BUILT_IN_TEXT_FORMATTERS = [
  ...bundleCreateFormatters,
  ...bundleRenameFormatters,
  ...bundleShowFormatters,
  ...indexFormatters,
  ...showFormatters,
  ...searchFormatters,
  ...curateFormatters,
  ...workflowFormatters,
  ...listFormatters,
  ...addFormatters,
  ...removeFormatters,
  ...updateFormatters,
  ...upgradeFormatters,
  ...cloneFormatters,
  ...eventsFormatters,
  ...proposalFormatters,
  ...proposalProducerFormatters,
  ...infoFormatters,
  ...healthFormatters,
  ...improveReportFormatters,
  ...lintFormatters,
  ...configFormatters,
  ...feedbackFormatters,
  ...rememberFormatters,
  ...importFormatters,
  ...syncFormatters,
  ...registryCommandFormatters,
  ...envFormatters,
  ...migrateFormatters,
  ...modelsFormatters
];
registerTextFormatters(BUILT_IN_TEXT_FORMATTERS);
// src/cli/shared.ts
var EXIT_CODES = {
  SUCCESS: 0,
  GENERAL: 1,
  USAGE: 2,
  HEALTH_WARN: 4,
  INTERNAL: 70,
  TEMPFAIL: 75,
  CONFIG: 78
};
function classifyExitCode(error2) {
  if (!(error2 instanceof AkmError))
    return EXIT_CODES.INTERNAL;
  switch (error2.kind) {
    case "usage":
      return EXIT_CODES.USAGE;
    case "config":
      return EXIT_CODES.CONFIG;
    case "not-found":
      return EXIT_CODES.GENERAL;
    case "transient":
      return EXIT_CODES.TEMPFAIL;
    default:
      return assertNever(error2.kind, "classifyExitCode");
  }
}
function extractHint(error2) {
  if (error2 instanceof Error && "hint" in error2 && typeof error2.hint === "function") {
    return error2.hint();
  }
  return;
}
function emitJsonError(error2) {
  const message = error2 instanceof Error ? error2.message : String(error2);
  const hint = extractHint(error2);
  const exitCode = classifyExitCode(error2);
  const code = error2 instanceof AkmError ? error2.code : undefined;
  console.error(JSON.stringify({ ok: false, error: message, ...code ? { code } : {}, hint }, null, 2));
  process.exitCode = exitCode;
}
async function runWithJsonErrors(fn) {
  try {
    await fn();
  } catch (error2) {
    emitJsonError(error2);
  }
}
var GLOBAL_OUTPUT_ARGS = {
  format: { type: "string", description: "Output format: json|jsonl|yaml|text|md|html (global flag)" },
  detail: {
    type: "string",
    description: "Detail level (verbosity): brief|normal|full (global flag)."
  },
  shape: {
    type: "string",
    description: "Output projection: human|agent|summary (global flag). 'agent' trims to agent-essential fields; " + "'summary' only has a dedicated projection on 'akm show' — elsewhere it falls back to 'agent' with a " + "warning. Default: human."
  },
  output: {
    type: "string",
    description: "Write rendered output to a file instead of stdout (all formats except jsonl) (global flag)"
  },
  quiet: {
    type: "boolean",
    alias: "q",
    description: "Suppress non-essential stderr output (banners, spinners, progress info) (global flag). " + "Safety-critical output is never suppressed: errors and destructive-action confirmation prompts " + "always appear regardless of --quiet.",
    default: false
  },
  verbose: {
    type: "boolean",
    description: "Print per-spec diagnostics to stderr (global flag; also honours AKM_VERBOSE env var).",
    default: false
  }
};

// src/cli/shared.ts
var EXIT_CODES2 = {
  SUCCESS: 0,
  GENERAL: 1,
  USAGE: 2,
  HEALTH_WARN: 4,
  INTERNAL: 70,
  TEMPFAIL: 75,
  CONFIG: 78
};
var GLOBAL_OUTPUT_ARGS2 = {
  format: { type: "string", description: "Output format: json|jsonl|yaml|text|md|html (global flag)" },
  detail: {
    type: "string",
    description: "Detail level (verbosity): brief|normal|full (global flag)."
  },
  shape: {
    type: "string",
    description: "Output projection: human|agent|summary (global flag). 'agent' trims to agent-essential fields; " + "'summary' only has a dedicated projection on 'akm show' — elsewhere it falls back to 'agent' with a " + "warning. Default: human."
  },
  output: {
    type: "string",
    description: "Write rendered output to a file instead of stdout (all formats except jsonl) (global flag)"
  },
  quiet: {
    type: "boolean",
    alias: "q",
    description: "Suppress non-essential stderr output (banners, spinners, progress info) (global flag). " + "Safety-critical output is never suppressed: errors and destructive-action confirmation prompts " + "always appear regardless of --quiet.",
    default: false
  },
  verbose: {
    type: "boolean",
    description: "Print per-spec diagnostics to stderr (global flag; also honours AKM_VERBOSE env var).",
    default: false
  }
};

// scripts/akm-migrate/help.txt
var help_default = `Usage: akm-migrate <command> [options]

The one migration tool for an akm installation. The CLI proper reads every
shape akm has ever written (in memory, with a warning); \`apply\` makes the
current shape durable on disk. \`status\` and \`apply\` run every step, in
order, and print one combined JSON plan (exit 1 when any step is blocked):

  1. config.json rewritten in its current shape (unknown keys dropped,
     legacy \`extraParams\` lifted onto engine fields, the legacy source
     layout converted, \`configVersion\` set to the current value) -- backed
     up first
  2. pending state.db migrations, historical-destructive ones included,
     with a verified sibling safety copy (the only path that admits them)
  3. task files at version 2 or 3, and version 4 files still carrying the
     retired \`schedule[].enabled\` key, rewritten as task source v4 under
     one backup directory per run
  4. superseded residue removed: pre-0.9.0 \`.akm\` leftovers in the stash,
     and the transaction-journal, maintenance-barrier, lock-mutex and
     version-stamp files older releases kept under $DATA, $STATE and $CONFIG

\`akm migrate status|apply\` wraps this executable; \`akm upgrade\` runs
\`apply\` after its install step, so an image that ships akm can put either
in its entrypoint (a current installation is a no-op).

Commands:
  status               Inspect every pending migration without changing anything.
  apply [--dry-run]    Back up and apply every pending migration.
`;

// scripts/akm-migrate/migrate/dead-residue.ts
import fs39 from "node:fs";
import path47 from "node:path";
var DEAD_RESIDUE_PATHS = [
  { name: "proposals", reason: "superseded by the `proposals` table in $DATA/state.db (0.9.0)" },
  { prefix: "runs.archived-", reason: "orphaned archive of a directory that no longer exists" },
  {
    name: "archive",
    reason: "legacy consolidation archive; current prune writes .akm/memory-cleanup/archive/ instead"
  },
  { name: "graph.json", reason: "superseded by the graph_* tables in $DATA/index.db" },
  { name: "consolidate-journal.json", reason: "legacy consolidation journal; unused" },
  { name: "proposals.db", reason: "empty legacy database file" },
  { name: "mv-transactions", reason: "legacy fs-txn journal location; unused" }
];
function dirSizeBytes(target) {
  let total = 0;
  let entries;
  try {
    entries = fs39.readdirSync(target, { withFileTypes: true });
  } catch {
    return 0;
  }
  for (const entry of entries) {
    const entryPath = path47.join(target, entry.name);
    if (entry.isDirectory()) {
      total += dirSizeBytes(entryPath);
    } else if (entry.isFile()) {
      try {
        total += fs39.statSync(entryPath).size;
      } catch {}
    }
  }
  return total;
}
function sizeOf(target) {
  const st = fs39.statSync(target);
  return st.isDirectory() ? dirSizeBytes(target) : st.size;
}
function hostResidue() {
  const data = getDataDir();
  const state = getStateDir();
  const configDir = path47.dirname(getConfigPath());
  const named = [
    { absolutePath: path47.join(data, "txn"), reason: "filesystem transaction journals (removed in 0.9.17)" },
    { absolutePath: path47.join(data, "txn-quarantine"), reason: "quarantined transaction journals (removed in 0.9.17)" },
    { absolutePath: path47.join(data, "maintenance.barrier.lock"), reason: "maintenance barrier (removed in 0.9.17)" },
    { absolutePath: path47.join(data, "maintenance-activities"), reason: "per-process activity registry (removed in 0.9.17)" },
    { absolutePath: path47.join(state, "maintenance-activities"), reason: "per-process activity registry (removed in 0.9.17)" },
    { absolutePath: path47.join(state, "version-reconcile.json"), reason: "startup reconcile stamp (removed in 0.9.17)" },
    { absolutePath: path47.join(state, "locks", "version-reconcile.lock"), reason: "startup reconcile lock (removed in 0.9.17)" }
  ];
  const found = [];
  const claimed = new Set;
  for (const entry of named) {
    if (claimed.has(entry.absolutePath) || !fs39.existsSync(entry.absolutePath))
      continue;
    try {
      found.push({ ...entry, relativePath: entry.absolutePath, sizeBytes: sizeOf(entry.absolutePath) });
      claimed.add(entry.absolutePath);
    } catch {}
  }
  for (const root of new Set([data, state, configDir])) {
    for (const sidecar of findSidecars(root, 3, claimed)) {
      try {
        found.push({
          relativePath: sidecar,
          absolutePath: sidecar,
          sizeBytes: sizeOf(sidecar),
          reason: "lock-operation mutex sidecar (removed in 0.9.17)"
        });
      } catch {}
    }
  }
  return found;
}
function findSidecars(root, depth, skip) {
  let entries;
  try {
    entries = fs39.readdirSync(root, { withFileTypes: true });
  } catch {
    return [];
  }
  const found = [];
  for (const entry of entries) {
    const entryPath = path47.join(root, entry.name);
    if (entry.isFile() && entry.name.endsWith(".operations.sensitive"))
      found.push(entryPath);
    else if (entry.isDirectory() && depth > 0 && !skip.has(entryPath)) {
      found.push(...findSidecars(entryPath, depth - 1, skip));
    }
  }
  return found;
}
function findDeadResidueEntries(stashDir) {
  const host = hostResidue();
  if (stashDir === undefined)
    return host;
  const akmDir = path47.join(stashDir, ".akm");
  let names;
  try {
    names = fs39.readdirSync(akmDir);
  } catch {
    return [];
  }
  const found = [];
  for (const spec of DEAD_RESIDUE_PATHS) {
    const matches = spec.name !== undefined ? [spec.name] : names.filter((n) => n.startsWith(spec.prefix ?? "\x00"));
    for (const name of matches) {
      if (!names.includes(name))
        continue;
      const absolutePath = path47.join(akmDir, name);
      let sizeBytes;
      try {
        sizeBytes = sizeOf(absolutePath);
      } catch {
        continue;
      }
      found.push({ relativePath: path47.join(".akm", name), absolutePath, sizeBytes, reason: spec.reason });
    }
  }
  return found;
}
function removeDeadResidue(stashDir) {
  const entries = findDeadResidueEntries(stashDir);
  return entries.map((entry) => {
    try {
      fs39.rmSync(entry.absolutePath, { recursive: true, force: true });
      return { relativePath: entry.relativePath, sizeBytes: entry.sizeBytes, removed: true };
    } catch (error2) {
      return {
        relativePath: entry.relativePath,
        sizeBytes: entry.sizeBytes,
        removed: false,
        error: error2 instanceof Error ? error2.message : String(error2)
      };
    }
  });
}

// scripts/akm-migrate/task-migrate.ts
import { randomUUID as randomUUID3 } from "node:crypto";
import fs41 from "node:fs";
import os8 from "node:os";
import path50 from "node:path";

// scripts/akm-migrate/migrate/task-files.ts
import crypto4 from "node:crypto";
import fs40 from "node:fs";
import path49 from "node:path";

// src/tasks/source/task-to-v4.ts
import crypto3 from "node:crypto";
import path48 from "node:path";

// src/tasks/task-id.ts
var VALID_TASK_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
var TASK_FILE_SUFFIX_RE = /\.(?:yml|yaml)$/i;
var WINDOWS_RESERVED_DEVICE_RE = /^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/i;
var WINDOWS_TASK_PATH_MAX_LENGTH = 238;
var WINDOWS_TASK_FOLDER_PREFIX_LENGTH = "\\akm\\".length;
var PORTABLE_FILENAME_COMPONENT_MAX_LENGTH = 255;
var LAUNCHD_FILENAME_OVERHEAD = "com.akm.task.".length + ".plist".length;
var TASK_FILENAME_OVERHEAD = ".yml".length;
var SCHTASKS_TEMP_FILENAME_OVERHEAD = "akm-task-".length + "-".length + 13 + ".xml".length;
var MAX_PORTABLE_TASK_ID_LENGTH = Math.min(WINDOWS_TASK_PATH_MAX_LENGTH - WINDOWS_TASK_FOLDER_PREFIX_LENGTH, PORTABLE_FILENAME_COMPONENT_MAX_LENGTH - LAUNCHD_FILENAME_OVERHEAD, PORTABLE_FILENAME_COMPONENT_MAX_LENGTH - TASK_FILENAME_OVERHEAD, PORTABLE_FILENAME_COMPONENT_MAX_LENGTH - SCHTASKS_TEMP_FILENAME_OVERHEAD);
function validateTaskId(id) {
  if (!id) {
    throw new UsageError("Task id must be non-empty.", "MISSING_REQUIRED_ARGUMENT");
  }
  if (!VALID_TASK_ID_RE.test(id)) {
    throw new UsageError(`Task id "${id}" is invalid. Use letters, digits, dots, underscores, and dashes only.`, "INVALID_FLAG_VALUE");
  }
  if (id.length > MAX_PORTABLE_TASK_ID_LENGTH) {
    throw new UsageError(`Task id "${id}" is invalid. Use at most ${MAX_PORTABLE_TASK_ID_LENGTH} characters for all supported schedulers.`, "INVALID_FLAG_VALUE");
  }
  if (TASK_FILE_SUFFIX_RE.test(id)) {
    throw new UsageError(`Task id "${id}" is invalid. Use the bare task id without a .yml or .yaml suffix.`, "INVALID_FLAG_VALUE");
  }
  if (id.endsWith(".")) {
    throw new UsageError(`Task id "${id}" is invalid. Trailing periods are not portable across native schedulers.`, "INVALID_FLAG_VALUE");
  }
  if (WINDOWS_RESERVED_DEVICE_RE.test(id)) {
    throw new UsageError(`Task id "${id}" uses a reserved Windows device name. Choose a different task id.`, "INVALID_FLAG_VALUE");
  }
  return id;
}

// src/tasks/source/task-source-v3-frozen.ts
var TASK_V3_SCHEMA_VERSION = 3;
var TASK_V3_HOST_SHELLS2 = ["bash", "sh", "zsh", "pwsh", "powershell", "cmd"];
var TASK_V2_MIGRATION_HINT = "Run `akm migrate apply --dry-run` to preview the task-v2 to task-v3 conversion, then run `akm migrate apply`.";
function taskV2UnsupportedError(filePath, id) {
  const label = id ? `Task "${id}"` : "Task";
  return new UsageError(`TASK_SCHEMA_VERSION_UNSUPPORTED: ${label} uses task schema version 2, which normal execution does not accept. File: ${filePath}`, "TASK_SCHEMA_VERSION_UNSUPPORTED", TASK_V2_MIGRATION_HINT);
}
var SOURCE_LABEL2 = "task v3 source";
function ctxFrom2(options) {
  return {
    filePath: options.filePath,
    sourceLabel: SOURCE_LABEL2,
    ...options.workspaceRoot ? { workspaceRoot: options.workspaceRoot } : {},
    ...options.lineAt ? { lineAt: options.lineAt } : {}
  };
}
var TOP_LEVEL_KEYS2 = ["version", "name", "uses", "run", "with", "env", "shell", "working-directory", "akm", "on"];
var AKM_KEYS = [
  "schedule",
  "enabled",
  "description",
  "when_to_use",
  "tags",
  "agent",
  "engine",
  "model",
  "inference",
  "outputSchema",
  "tools",
  "timeout",
  "redact",
  "maxSteps",
  "maxRetries"
];
var ON_KEYS = ["schedule", "workflow_dispatch"];
var SHELL_SET2 = new Set(TASK_V3_HOST_SHELLS2);
var GITHUB_OWNER = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/;
var GITHUB_REPOSITORY = /^[A-Za-z0-9_.-]+$/;
var GITHUB_ACTION_PATH_SEGMENT = /^[A-Za-z0-9_.-]+$/;
var GITHUB_REF_FORBIDDEN = new Set(["~", "^", ":", "?", "*", "[", "\\"]);
function hasForbiddenGithubRefCharacter(value) {
  for (const character of value) {
    const codePoint = character.codePointAt(0) ?? 0;
    if (codePoint <= 32 || codePoint === 127 || GITHUB_REF_FORBIDDEN.has(character))
      return true;
  }
  return false;
}
function nullableSelector(value, ctx, key) {
  const selector = stringField(value, ctx, ["akm", key], { nullable: true });
  if (selector !== null && selector.trim().length === 0)
    sourceError(ctx, ["akm", key], "must be null or a non-empty string.");
  return selector;
}
function parseAkm(value, ctx) {
  const input = asRecord2(value, ctx, ["akm"]);
  checkKeys(input, AKM_KEYS, ctx, ["akm"]);
  const out = {};
  if (own2(input, "schedule")) {
    const schedule = stringField(input.schedule, ctx, ["akm", "schedule"], { nonempty: true });
    noGithubExpression(schedule, ctx, ["akm", "schedule"]);
    out.schedule = schedule;
  }
  if (own2(input, "enabled")) {
    if (typeof input.enabled !== "boolean")
      sourceError(ctx, ["akm", "enabled"], "must be a boolean.");
    out.enabled = input.enabled;
  }
  for (const key of ["description", "when_to_use"]) {
    if (own2(input, key))
      out[key] = stringField(input[key], ctx, ["akm", key]);
  }
  if (own2(input, "tags"))
    out.tags = parseStringArray(input.tags, ctx, ["akm", "tags"]);
  for (const key of ["agent", "engine", "model"]) {
    if (own2(input, key))
      out[key] = nullableSelector(input[key], ctx, key);
  }
  if (own2(input, "inference")) {
    const inference = presentJsonValue(input.inference, ctx, ["akm", "inference"]);
    out.inference = inference === null ? null : asRecord2(inference, ctx, ["akm", "inference"]);
  }
  if (own2(input, "outputSchema")) {
    const outputSchema = presentJsonValue(input.outputSchema, ctx, ["akm", "outputSchema"]);
    if (outputSchema === null)
      out.outputSchema = null;
    else {
      const schema = asRecord2(outputSchema, ctx, ["akm", "outputSchema"]);
      const issue = checkJsonSchemaDefinition(schema)[0];
      if (issue)
        sourceError(ctx, ["akm", "outputSchema"], `is not a supported JSON schema: ${issue.message}`);
      out.outputSchema = schema;
    }
  }
  if (own2(input, "tools"))
    out.tools = parseTools(presentJsonValue(input.tools, ctx, ["akm", "tools"]), ctx);
  if (own2(input, "timeout"))
    out.timeout = parseTimeout(input.timeout, ctx);
  if (own2(input, "redact")) {
    const names = parseStringArray(input.redact, ctx, ["akm", "redact"], {
      max: TASK_V3_MAX_REDACT_NAMES,
      pattern: WORKFLOW_ENV_VAR_NAME_PATTERN
    });
    if (new Set(names).size !== names.length)
      sourceError(ctx, ["akm", "redact"], "must not contain duplicate names.");
    out.redact = names;
  }
  if (own2(input, "maxSteps")) {
    if (!Number.isSafeInteger(input.maxSteps) || input.maxSteps < 1) {
      sourceError(ctx, ["akm", "maxSteps"], "must be a positive safe integer.");
    }
    out.maxSteps = input.maxSteps;
  }
  if (own2(input, "maxRetries")) {
    if (!Number.isSafeInteger(input.maxRetries) || input.maxRetries < 0) {
      sourceError(ctx, ["akm", "maxRetries"], "must be a non-negative safe integer.");
    }
    out.maxRetries = input.maxRetries;
  }
  return Object.freeze(out);
}
function validGithubRevision(revision) {
  if (revision.length === 0 || hasForbiddenGithubRefCharacter(revision) || revision.startsWith("/") || revision.endsWith("/") || revision.includes("..") || revision.includes("@{") || revision.includes("@")) {
    return false;
  }
  return revision.split("/").every((segment) => segment.length > 0 && segment !== "." && segment !== ".." && !segment.startsWith(".") && !segment.endsWith(".") && !segment.endsWith(".lock"));
}
function classifyTaskV3Uses(value) {
  if (typeof value !== "string" || value.length === 0 || value.trim() !== value || /\s/.test(value) || value.includes("${{")) {
    throw new UsageError("Task v3 uses must be one exact, non-empty executable ref without expressions.", "INVALID_FLAG_VALUE");
  }
  if (value === "akm/command")
    return Object.freeze({ kind: "builtin-command", ref: "akm/command" });
  try {
    const parsed = parseBundleRef(value);
    if (parsed.fragment === undefined && bundleRefToString(parsed) === value) {
      const slash = parsed.conceptId.indexOf("/");
      const family = slash < 0 ? "" : parsed.conceptId.slice(0, slash);
      const name = slash < 0 ? "" : parsed.conceptId.slice(slash + 1);
      if (name.length > 0 && (family === "commands" || family === "workflows" || family === "scripts")) {
        const kind = family === "commands" ? "command" : family === "workflows" ? "workflow" : "script";
        return Object.freeze({ kind, ref: value });
      }
      if (family === "agents") {
        throw new UsageError("An agent ref selects a persona and is not executable through task v3 uses.", "INVALID_FLAG_VALUE");
      }
      if (family === "tasks") {
        throw new UsageError("A task ref is not an executable task-v3 uses target.", "INVALID_FLAG_VALUE");
      }
    }
  } catch (error2) {
    if (error2 instanceof UsageError && /agent ref|task ref/i.test(error2.message))
      throw error2;
  }
  const at = value.lastIndexOf("@");
  if (at > 0 && at === value.indexOf("@")) {
    const locator = value.slice(0, at);
    const revision = value.slice(at + 1);
    const segments = locator.split("/");
    const [owner, repository, ...actionPath] = segments;
    if (owner && repository && GITHUB_OWNER.test(owner) && GITHUB_REPOSITORY.test(repository) && repository !== "." && repository !== ".." && actionPath.every((segment) => GITHUB_ACTION_PATH_SEGMENT.test(segment) && segment !== "." && segment !== "..") && validGithubRevision(revision)) {
      const action = {
        kind: "github-action",
        ref: value,
        owner,
        repository,
        ...actionPath.length > 0 ? { path: actionPath.join("/") } : {},
        revision
      };
      return Object.freeze(action);
    }
  }
  throw new UsageError("Task v3 uses must be akm/command, a canonical commands/, workflows/, or scripts/ asset ref, or owner/repo[/path]@ref. Agent/task/local/Docker/ambiguous targets are not executable.", "INVALID_FLAG_VALUE");
}
function parseOn(value, ctx) {
  const input = asRecord2(value, ctx, ["on"]);
  const keys = Object.keys(input);
  if (keys.length === 0)
    sourceError(ctx, ["on"], "must declare schedule and/or workflow_dispatch.");
  const unsupported = keys.find((key) => !ON_KEYS.includes(key));
  if (unsupported)
    sourceError(ctx, ["on", unsupported], "is an unsupported local service event; no scheduler binding was created.");
  const schedules = [];
  if (own2(input, "schedule")) {
    if (!Array.isArray(input.schedule) || input.schedule.length === 0) {
      sourceError(ctx, ["on", "schedule"], "must be a non-empty list of {cron: string} records.");
    }
    if (input.schedule.length > TASK_V3_MAX_SCHEDULES) {
      sourceError(ctx, ["on", "schedule"], `accepts at most ${TASK_V3_MAX_SCHEDULES} entries.`);
    }
    for (const [index, raw] of input.schedule.entries()) {
      const entry = asRecord2(raw, ctx, ["on", "schedule", index]);
      checkKeys(entry, ["cron"], ctx, ["on", "schedule", index]);
      if (!own2(entry, "cron"))
        sourceError(ctx, ["on", "schedule", index, "cron"], "is required.");
      const cron = stringField(entry.cron, ctx, ["on", "schedule", index, "cron"], { nonempty: true });
      noGithubExpression(cron, ctx, ["on", "schedule", index, "cron"]);
      schedules.push(Object.freeze({ cron, source: `on.schedule[${index}].cron`, ordinal: index }));
    }
  }
  let manual = false;
  if (own2(input, "workflow_dispatch")) {
    const dispatch = input.workflow_dispatch;
    if (dispatch !== null) {
      const mapping = asRecord2(presentJsonValue(dispatch, ctx, ["on", "workflow_dispatch"]), ctx, [
        "on",
        "workflow_dispatch"
      ]);
      if (Object.keys(mapping).length > 0) {
        sourceError(ctx, ["on", "workflow_dispatch"], "must be null or an empty mapping; inputs are unsupported.");
      }
    }
    manual = true;
  }
  return Object.freeze({ manual, schedules: Object.freeze(schedules) });
}
function compileTriggers(input, akm, ctx) {
  const hasSchedule = akm !== undefined && own2(akm, "schedule");
  const hasOn = own2(input, "on");
  if (hasSchedule === hasOn) {
    sourceError(ctx, [], "must declare exactly one scheduling source: akm.schedule or on.");
  }
  if (hasOn)
    return parseOn(presentJsonValue(input.on, ctx, ["on"]), ctx);
  return Object.freeze({
    manual: false,
    schedules: Object.freeze([Object.freeze({ cron: akm?.schedule, source: "akm.schedule", ordinal: 0 })])
  });
}
function parseTaskV3TriggerFields(input, ctx) {
  const akm = own2(input, "akm") ? parseAkm(presentJsonValue(input.akm, ctx, ["akm"]), ctx) : undefined;
  return Object.freeze({ ...akm ? { akm } : {}, triggers: compileTriggers(input, akm, ctx) });
}
function parseTaskV3Document(value, options) {
  const ctx = ctxFrom2(options);
  const cloned = cloneBoundedJson(value, ctx, [], { nodes: 0 });
  const input = asRecord2(cloned, ctx, []);
  if (!own2(input, "version"))
    sourceError(ctx, ["version"], "is required and must be 3.");
  if (input.version === 2)
    throw taskV2UnsupportedError(options.filePath);
  if (input.version !== TASK_V3_SCHEMA_VERSION)
    sourceError(ctx, ["version"], "must be exactly 3.");
  checkKeys(input, TOP_LEVEL_KEYS2, ctx, []);
  const hasUses = own2(input, "uses");
  const hasRun = own2(input, "run");
  if (hasUses === hasRun)
    sourceError(ctx, [], "requires exactly one executable selector: uses or run.");
  const name = own2(input, "name") ? stringField(input.name, ctx, ["name"]) : undefined;
  const env = own2(input, "env") ? parseEnvironment(presentJsonValue(input.env, ctx, ["env"]), ctx) : undefined;
  const { akm, triggers } = parseTaskV3TriggerFields(input, ctx);
  let target;
  if (hasUses) {
    if (own2(input, "shell"))
      sourceError(ctx, ["shell"], "is legal only with run.");
    if (own2(input, "working-directory"))
      sourceError(ctx, ["working-directory"], "is legal only with run.");
    const usesText = stringField(input.uses, ctx, ["uses"], { nonempty: true });
    let uses;
    try {
      uses = classifyTaskV3Uses(usesText);
    } catch (cause) {
      sourceError(ctx, ["uses"], cause instanceof Error ? cause.message : String(cause));
    }
    let withValues;
    if (own2(input, "with"))
      withValues = asRecord2(presentJsonValue(input.with, ctx, ["with"]), ctx, ["with"]);
    if (uses.kind === "builtin-command") {
      let command;
      try {
        command = parseBuiltinCommandAction(withValues);
      } catch (cause) {
        sourceError(ctx, ["with"], cause instanceof Error ? cause.message : String(cause));
      }
      target = Object.freeze({ kind: "uses", uses, ...withValues ? { with: withValues } : {}, command });
    } else {
      target = Object.freeze({ kind: "uses", uses, ...withValues ? { with: withValues } : {} });
    }
  } else {
    if (own2(input, "with"))
      sourceError(ctx, ["with"], "is legal only with uses.");
    const run = stringField(input.run, ctx, ["run"], { nonempty: true });
    let shell;
    if (own2(input, "shell")) {
      const rawShell = stringField(input.shell, ctx, ["shell"], { nonempty: true });
      if (!SHELL_SET2.has(rawShell)) {
        sourceError(ctx, ["shell"], `must be one of the closed host-shell table: ${TASK_V3_HOST_SHELLS2.join(", ")}.`);
      }
      shell = rawShell;
    }
    let workingDirectory;
    if (own2(input, "working-directory")) {
      workingDirectory = stringField(input["working-directory"], ctx, ["working-directory"], {
        nonempty: true
      });
      validateWorkingDirectory(workingDirectory, ctx);
    }
    target = Object.freeze({
      kind: "run",
      run,
      ...shell ? { shell } : {},
      ...workingDirectory ? { workingDirectory } : {}
    });
  }
  return Object.freeze({
    version: TASK_V3_SCHEMA_VERSION,
    ...name !== undefined ? { name } : {},
    target,
    ...env !== undefined ? { env } : {},
    ...akm !== undefined ? { akm } : {},
    triggers,
    source: Object.freeze({ path: options.filePath })
  });
}
function parseTaskV3Yaml(input) {
  const { root, lineAt } = readBoundedTaskSourceYaml(input, { sourceLabel: SOURCE_LABEL2 });
  return parseTaskV3Document(root, {
    filePath: input.filePath,
    ...input.workspaceRoot ? { workspaceRoot: input.workspaceRoot } : {},
    lineAt
  });
}

// src/tasks/source/task-to-v4.ts
var V3_TOP_LEVEL_KEYS = new Set([
  "version",
  "name",
  "uses",
  "run",
  "with",
  "env",
  "shell",
  "working-directory",
  "akm",
  "on"
]);
var V3_AKM_KEYS = new Set([
  "schedule",
  "enabled",
  "description",
  "when_to_use",
  "tags",
  "agent",
  "engine",
  "model",
  "inference",
  "outputSchema",
  "tools",
  "timeout",
  "redact",
  "maxSteps",
  "maxRetries"
]);
var V3_ON_KEYS = new Set(["schedule", "workflow_dispatch"]);
var AKM_HOIST_KEYS = [
  "description",
  "when_to_use",
  "tags",
  "agent",
  "engine",
  "model",
  "inference",
  "tools",
  "timeout",
  "redact",
  "maxSteps",
  "maxRetries"
];
var V2_KEYS = new Set([
  "version",
  "name",
  "description",
  "when_to_use",
  "tags",
  "schedule",
  "enabled",
  "workflow",
  "prompt",
  "command",
  "params",
  "engine",
  "model",
  "timeoutMs",
  "maxSteps",
  "maxRetries",
  "llm",
  "redact"
]);
var V2_SHARED_KEYS = new Set([
  "version",
  "name",
  "description",
  "when_to_use",
  "tags",
  "schedule",
  "enabled",
  "redact"
]);
var V2_LLM_KEYS = new Set([
  "temperature",
  "maxTokens",
  "supportsJsonSchema",
  "extraParams",
  "contextLength",
  "enableThinking",
  "reasoningEffort"
]);
var SAFE_V2_COMMAND_TOKEN = /^[A-Za-z0-9_./:=+,-]+$/;
var SHELL_ASSIGNMENT_WORD = /^[A-Za-z_][A-Za-z0-9_]*=/;
function shellStableV2Executable(executable) {
  return executable === "akm" || executable.includes("/");
}
function skipEnvAssignmentPrefix(tokens) {
  if (tokens[0] !== "env")
    return { tokens, envWrapped: false };
  let index = 1;
  while (index < tokens.length && SHELL_ASSIGNMENT_WORD.test(tokens[index]))
    index += 1;
  if (index >= tokens.length)
    return { tokens, envWrapped: false };
  return { tokens: tokens.slice(index), envWrapped: true };
}
var KNOWN_PROMPT_REF_FAMILIES = new Set([
  "agents",
  "commands",
  "env",
  "facts",
  "instructions",
  "knowledge",
  "lessons",
  "memories",
  "scripts",
  "secrets",
  "sessions",
  "skills",
  "tasks",
  "workflows"
]);
var ARGV_ARRAY_BLOCK_DETAIL = "Manual conversion required: an array `command:` has no safe v3 `run:` string. Rewrite it by hand as " + "`run:` (string) plus `shell:` — see docs/migration/v0.9.1-to-v0.9.2.md for the full v2 to v4 field mapping.";
function hash(bytes) {
  return crypto3.createHash("sha256").update(bytes).digest("hex");
}
function causeMessage(cause) {
  return cause instanceof Error ? cause.message : String(cause);
}
function base(input) {
  return {
    filePath: input.filePath,
    before: Buffer.from(input.bytes),
    beforeHash: hash(input.bytes),
    mode: input.mode,
    writable: input.writable,
    ...input.onDiskWritable !== undefined ? { onDiskWritable: input.onDiskWritable } : {},
    ...input.containmentRoot ? { containmentRoot: input.containmentRoot } : {}
  };
}
function blocked(input, reason, detail) {
  return Object.freeze({ status: "blocked", ...base(input), reason, ...detail ? { detail } : {} });
}
function plainRecord(value, label) {
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
    throw new Error(`${label} must be a mapping`);
  }
  const prototype = Object.getPrototypeOf(value);
  if (prototype !== Object.prototype && prototype !== null) {
    throw new Error(`${label} must use a plain or null prototype`);
  }
  return value;
}
function exactString(value, label, nonempty = false) {
  if (typeof value !== "string" || nonempty && value.trim().length === 0) {
    throw new Error(`${label} must be ${nonempty ? "a non-empty " : "a "}string`);
  }
  return value;
}
function optionalString(value, label) {
  if (value === undefined || value === null)
    return;
  return exactString(value, label);
}
function parseRawTaskYaml(input) {
  let source;
  try {
    source = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(input.bytes);
  } catch {
    throw new Error("task YAML contains invalid UTF-8 bytes");
  }
  const lineCounter2 = new $LineCounter;
  let document;
  try {
    document = $parseDocument(source, { lineCounter: lineCounter2, uniqueKeys: true });
  } catch (cause) {
    throw new Error(`invalid YAML: ${causeMessage(cause)}`);
  }
  const [parseError] = document.errors;
  if (parseError)
    throw new Error(`invalid YAML: ${parseError.message.split(`
`)[0]}`);
  const [parseWarning] = document.warnings;
  if (parseWarning)
    throw new Error(`unsupported YAML construct: ${parseWarning.message}`);
  assertBoundedTaskYamlDocument(document, {
    filePath: input.filePath,
    sourceLabel: "task migration source",
    lineCounter: lineCounter2
  });
  return { data: plainRecord(document.toJS({ maxAliasCount: 0 }), "task YAML"), source };
}
function planV3DataToV4(input, data) {
  const unknownTop = Object.keys(data).filter((key) => !V3_TOP_LEVEL_KEYS.has(key));
  if (unknownTop.length > 0) {
    return blocked(input, "invalid-v3-task", `unknown v3 field(s): ${unknownTop.join(", ")}`);
  }
  const hasUses = Object.hasOwn(data, "uses");
  const hasRun = Object.hasOwn(data, "run");
  if (hasUses === hasRun) {
    return blocked(input, "invalid-v3-task", "requires exactly one executable selector: uses or run");
  }
  let akm;
  if (Object.hasOwn(data, "akm")) {
    try {
      akm = plainRecord(data.akm, "akm");
    } catch (cause) {
      return blocked(input, "invalid-v3-task", causeMessage(cause));
    }
    const unknownAkm = Object.keys(akm).filter((key) => !V3_AKM_KEYS.has(key));
    if (unknownAkm.length > 0) {
      return blocked(input, "unrecognized-akm-member", `akm has unknown field(s): ${unknownAkm.join(", ")}`);
    }
    if (Object.hasOwn(akm, "enabled") && typeof akm.enabled !== "boolean") {
      return blocked(input, "invalid-v3-task", "akm.enabled must be a boolean");
    }
    if (Object.hasOwn(akm, "schedule") && typeof akm.schedule !== "string") {
      return blocked(input, "invalid-v3-task", "akm.schedule must be a string");
    }
  }
  const hasOn = Object.hasOwn(data, "on");
  let onRecord;
  if (hasOn) {
    try {
      onRecord = plainRecord(data.on, "on");
    } catch (cause) {
      return blocked(input, "invalid-v3-task", causeMessage(cause));
    }
    if (Object.keys(onRecord).length === 0) {
      return blocked(input, "invalid-v3-task", "on must declare schedule and/or workflow_dispatch.");
    }
    const unknownOn = Object.keys(onRecord).filter((key) => !V3_ON_KEYS.has(key));
    if (unknownOn.length > 0) {
      return blocked(input, "invalid-v3-task", `on has unknown field(s): ${unknownOn.join(", ")}`);
    }
    if (Object.hasOwn(onRecord, "workflow_dispatch") && onRecord.workflow_dispatch !== null) {
      let dispatchMapping;
      try {
        dispatchMapping = plainRecord(onRecord.workflow_dispatch, "on.workflow_dispatch");
      } catch (cause) {
        return blocked(input, "invalid-v3-task", causeMessage(cause));
      }
      if (Object.keys(dispatchMapping).length > 0) {
        return blocked(input, "invalid-v3-task", "on.workflow_dispatch must be null or an empty mapping; inputs are unsupported.");
      }
    }
  }
  const hasAkmSchedule = akm !== undefined && Object.hasOwn(akm, "schedule");
  if (hasAkmSchedule && hasOn) {
    return blocked(input, "ambiguous-scheduling-source", "declares both akm.schedule and on:; task v3 requires exactly one scheduling source and the migrator will not guess which one wins.");
  }
  if (!hasAkmSchedule && !hasOn) {
    return blocked(input, "invalid-v3-task", "requires exactly one scheduling source: akm.schedule or on.");
  }
  const hasWith = Object.hasOwn(data, "with");
  let usesTarget;
  if (hasUses) {
    let usesValue;
    try {
      usesValue = exactString(data.uses, "uses", true);
    } catch (cause) {
      return blocked(input, "invalid-v3-task", causeMessage(cause));
    }
    try {
      usesTarget = classifyTaskV3Uses(usesValue);
    } catch (cause) {
      return blocked(input, "invalid-v3-task", causeMessage(cause));
    }
    if (usesTarget.kind === "github-action") {
      return blocked(input, "github-action-target-removed", `"${usesValue}" is a github-action target; the github-action uses: variant was removed in task source v4. Use commands/, scripts/, workflows/, or akm/command instead.`);
    }
    if (hasWith && usesTarget.kind !== "builtin-command") {
      return blocked(input, "with-on-non-command-target", `a with: block on "${usesValue}" (a non-akm/command target) has no task source v4 equivalent; task-call inputs are declared and bound separately.`);
    }
  } else if (hasWith) {
    return blocked(input, "invalid-v3-task", "with is legal only with uses");
  }
  if (!input.writable || input.onDiskWritable === false) {
    return blocked(input, "read-only-source", !input.writable ? "the owning source is not writable" : "the source file or publication directory is read-only");
  }
  let scheduleField;
  const notices = [];
  if (hasAkmSchedule) {
    const cron = akm.schedule;
    scheduleField = cron;
  } else {
    const rawSchedule = onRecord !== undefined && Object.hasOwn(onRecord, "schedule") ? onRecord.schedule : undefined;
    if (rawSchedule !== undefined) {
      if (!Array.isArray(rawSchedule) || rawSchedule.length === 0) {
        return blocked(input, "invalid-v3-task", "on.schedule must be a non-empty list of {cron} records");
      }
      const crons = [];
      for (const entry of rawSchedule) {
        let record;
        try {
          record = plainRecord(entry, "on.schedule[]");
        } catch (cause) {
          return blocked(input, "invalid-v3-task", causeMessage(cause));
        }
        const keys = Object.keys(record);
        if (keys.length !== 1 || keys[0] !== "cron" || typeof record.cron !== "string" || record.cron.length === 0) {
          return blocked(input, "invalid-v3-task", "each on.schedule entry must be exactly {cron: <non-empty string>}");
        }
        crons.push(record.cron);
      }
      scheduleField = crons.map((cron) => ({ cron }));
    } else {
      notices.push("schedule: is absent from the migrated document — the source's only trigger was on.workflow_dispatch (manual dispatch); task source v4 tasks are always runnable manually via `akm task run`, so no schedule: entry was emitted.");
    }
  }
  const out = { version: 4 };
  if (Object.hasOwn(data, "name"))
    out.name = data.name;
  if (hasUses)
    out.uses = data.uses;
  else
    out.run = data.run;
  if (Object.hasOwn(data, "shell"))
    out.shell = data.shell;
  if (hasWith)
    out.with = data.with;
  if (Object.hasOwn(data, "env"))
    out.env = data.env;
  if (Object.hasOwn(data, "working-directory"))
    out["working-directory"] = data["working-directory"];
  if (scheduleField !== undefined)
    out.schedule = scheduleField;
  if (akm) {
    for (const key of AKM_HOIST_KEYS) {
      if (Object.hasOwn(akm, key))
        out[key] = akm[key];
    }
    if (Object.hasOwn(akm, "outputSchema") && akm.outputSchema !== null) {
      if (usesTarget !== undefined && (usesTarget.kind === "command" || usesTarget.kind === "builtin-command")) {
        out.output = akm.outputSchema;
      } else {
        const targetLabel = usesTarget === undefined ? "a run: target" : `the "${usesTarget.ref}" target`;
        notices.push(`akm.outputSchema was dropped rather than hoisted to output: — task source v4 accepts output: only with a command target (uses: commands/<ref> or uses: akm/command), and ${targetLabel} never consumed the schema in v3 either, so nothing enforceable was lost.`);
      }
    }
  }
  const afterYaml = $stringify(out);
  const after = Buffer.from(afterYaml, "utf8");
  try {
    parseTaskSourceV4({
      yaml: afterYaml,
      filePath: input.filePath,
      ...input.containmentRoot ? { workspaceRoot: input.containmentRoot } : {}
    });
  } catch (cause) {
    return blocked(input, "generated-v4-validation-failed", causeMessage(cause));
  }
  const notice = notices.join(" ");
  return Object.freeze({
    status: "changed",
    ...base(input),
    reason: "task-converted",
    after,
    afterHash: hash(after),
    ...notice ? { notice } : {}
  });
}
function validateCommonV2(data) {
  const unknown = Object.keys(data).filter((key) => !V2_KEYS.has(key));
  if (unknown.length > 0)
    throw new Error(`unknown v2 field(s): ${unknown.join(", ")}`);
  exactString(data.schedule, "schedule", true);
  if (data.enabled !== undefined && typeof data.enabled !== "boolean")
    throw new Error("enabled must be a boolean");
  for (const key of ["name", "description", "when_to_use"])
    optionalString(data[key], key);
  if (data.tags !== undefined && data.tags !== null) {
    if (!Array.isArray(data.tags) || data.tags.some((entry) => typeof entry !== "string" || entry.length === 0)) {
      throw new Error("tags must be an array of non-empty strings");
    }
  }
  if (data.timeoutMs !== undefined && data.timeoutMs !== null) {
    if (!Number.isInteger(data.timeoutMs) || data.timeoutMs < 1 || data.timeoutMs > WORKFLOW_MAX_TIMEOUT_MS) {
      throw new Error(`timeoutMs must be null or an integer from 1 through ${WORKFLOW_MAX_TIMEOUT_MS}`);
    }
  }
  if (data.redact !== undefined && data.redact !== null) {
    if (!Array.isArray(data.redact) || data.redact.length > TASK_V3_MAX_REDACT_NAMES || data.redact.some((entry) => typeof entry !== "string" || !WORKFLOW_ENV_VAR_NAME_PATTERN.test(entry))) {
      throw new Error("redact must contain only bounded environment variable names");
    }
  }
}
function validateTargetFields(data, allowed) {
  const targetFields = new Set([...allowed, "workflow", "prompt", "command"]);
  const invalid = Object.keys(data).filter((key) => !V2_SHARED_KEYS.has(key) && !targetFields.has(key));
  if (invalid.length > 0)
    throw new Error(`field(s) not valid for this target: ${invalid.join(", ")}`);
}
function validateV2Llm(value) {
  if (value === undefined)
    return;
  const llm = plainRecord(value, "llm");
  const unknown = Object.keys(llm).filter((key) => !V2_LLM_KEYS.has(key));
  if (unknown.length > 0)
    throw new Error(`llm has unknown field(s): ${unknown.join(", ")}`);
  if (llm.temperature !== undefined && (typeof llm.temperature !== "number" || !Number.isFinite(llm.temperature))) {
    throw new Error("llm.temperature must be a finite number");
  }
  for (const key of ["maxTokens", "contextLength"]) {
    if (llm[key] !== undefined && (!Number.isInteger(llm[key]) || llm[key] <= 0)) {
      throw new Error(`llm.${key} must be a positive integer`);
    }
  }
  for (const key of ["supportsJsonSchema", "enableThinking"]) {
    if (llm[key] !== undefined && typeof llm[key] !== "boolean")
      throw new Error(`llm.${key} must be a boolean`);
  }
  if (llm.reasoningEffort !== undefined && (typeof llm.reasoningEffort !== "string" || !llm.reasoningEffort.trim())) {
    throw new Error("llm.reasoningEffort must be a non-empty string");
  }
  if (llm.extraParams !== undefined) {
    const issue = validateExtraParams(llm.extraParams)[0];
    if (issue)
      throw new Error(formatExtraParamsIssue("llm.extraParams", issue));
  }
  return llm;
}
function commonAkm(data) {
  const akm = {
    schedule: exactString(data.schedule, "schedule", true),
    enabled: data.enabled === undefined ? true : data.enabled
  };
  for (const key of ["description", "when_to_use", "tags"]) {
    if (data[key] !== undefined && data[key] !== null)
      akm[key] = data[key];
  }
  return akm;
}
function addRuntimeOverrides(data, akm) {
  for (const key of ["engine", "model"]) {
    const value = optionalString(data[key], key);
    if (value)
      akm[key] = value;
  }
  const llm = validateV2Llm(data.llm);
  if (llm !== undefined)
    akm.inference = llm;
  if (data.timeoutMs !== undefined)
    akm.timeout = data.timeoutMs;
  if (data.redact !== undefined && data.redact !== null) {
    akm.redact = [...new Set(data.redact)];
  }
}
function addSharedNonPromptOverrides(data, akm) {
  if (data.timeoutMs !== undefined)
    akm.timeout = data.timeoutMs;
  if (data.redact !== undefined && data.redact !== null) {
    akm.redact = [...new Set(data.redact)];
  }
}
function promptSourceKind(raw) {
  const trimmed = raw.trim();
  if (trimmed.startsWith("./") || trimmed.startsWith("../") || path48.isAbsolute(trimmed) || /^[A-Za-z]:[\\/]/.test(trimmed)) {
    return "file";
  }
  try {
    const parsed = parseBundleRef(trimmed);
    const family = parsed.conceptId.split("/", 1)[0] ?? "";
    if (bundleRefToString(parsed) !== trimmed || !parsed.conceptId.includes("/")) {
      return "inline";
    }
    if (!KNOWN_PROMPT_REF_FAMILIES.has(family))
      return parsed.bundle === undefined ? "inline" : "other-ref";
    if (family === "agents")
      return "agent";
    if (family === "commands")
      return "command";
    return "other-ref";
  } catch {
    return "inline";
  }
}
function migratedObject(data) {
  validateCommonV2(data);
  const targets = ["workflow", "prompt", "command"].filter((key) => Object.hasOwn(data, key) && data[key] !== null && data[key] !== "");
  if (targets.length !== 1)
    throw new Error("v2 task must declare exactly one of workflow, prompt, or command");
  const output = { version: 3 };
  if (data.name !== undefined && data.name !== null)
    output.name = data.name;
  const akm = commonAkm(data);
  if (targets[0] === "workflow") {
    validateTargetFields(data, ["params", "timeoutMs", "maxSteps", "maxRetries"]);
    const ref = exactString(data.workflow, "workflow", true).trim();
    let target;
    try {
      target = classifyTaskV3Uses(ref);
    } catch {
      throw new Error("workflow is not a canonical v3 asset ref");
    }
    if (target.kind !== "workflow")
      throw new Error("workflow target is not a workflows/ ref");
    output.uses = ref;
    if (data.params !== undefined && data.params !== null) {
      const params = plainRecord(data.params, "params");
      output.with = params;
    }
    if (data.maxSteps !== undefined && data.maxSteps !== null) {
      if (!Number.isSafeInteger(data.maxSteps) || data.maxSteps < 1)
        throw new Error("maxSteps must be positive");
      akm.maxSteps = data.maxSteps;
    }
    if (data.maxRetries !== undefined && data.maxRetries !== null) {
      if (!Number.isSafeInteger(data.maxRetries) || data.maxRetries < 0) {
        throw new Error("maxRetries must be a non-negative integer");
      }
      akm.maxRetries = data.maxRetries;
    }
    addSharedNonPromptOverrides(data, akm);
  } else if (targets[0] === "prompt") {
    validateTargetFields(data, ["engine", "model", "timeoutMs", "llm"]);
    const prompt = exactString(data.prompt, "prompt", true).trim();
    const kind = promptSourceKind(prompt);
    if (kind === "file")
      return "dynamic-file-read-cannot-be-inlined-without-changing-semantics";
    if (kind === "agent")
      return "agent-ref-has-persona-but-no-command-work";
    if (kind === "other-ref")
      return "non-command-asset-has-no-v3-command-ref-equivalent";
    if (kind === "command")
      output.uses = prompt;
    else {
      output.uses = "akm/command";
      output.with = { content: prompt };
    }
    addRuntimeOverrides(data, akm);
  } else {
    validateTargetFields(data, ["timeoutMs"]);
    if (Array.isArray(data.command))
      return "argv-array-has-no-portable-shell-string";
    const command = exactString(data.command, "command", true).trim();
    if (/['"\\]/.test(command))
      return "shell-quoting-changes-v2-whitespace-split-semantics";
    const tokens = command.split(/\s+/).filter(Boolean);
    if (tokens.length === 0 || tokens.some((token) => !SAFE_V2_COMMAND_TOKEN.test(token))) {
      return "shell-operators-change-v2-literal-argv-semantics";
    }
    const { tokens: targetTokens, envWrapped } = skipEnvAssignmentPrefix(tokens);
    const executable = targetTokens[0];
    if (SHELL_ASSIGNMENT_WORD.test(executable) || !envWrapped && !shellStableV2Executable(executable)) {
      return "shell-command-resolution-changes-v2-literal-argv-semantics";
    }
    output.run = tokens.join(" ");
    addSharedNonPromptOverrides(data, akm);
  }
  output.akm = akm;
  return output;
}
function isReason(value) {
  return typeof value === "string";
}
function planV2DataToV4(input, data) {
  if (!input.writable || input.onDiskWritable === false) {
    return blocked(input, "read-only-source", !input.writable ? "the owning source is not writable" : "the source file or publication directory is read-only");
  }
  try {
    validateTaskId(path48.basename(input.filePath, ".yml"));
  } catch (cause) {
    return blocked(input, "invalid-v2-task", causeMessage(cause));
  }
  let migrated;
  try {
    migrated = migratedObject(data);
  } catch (cause) {
    return blocked(input, "invalid-v2-task", causeMessage(cause));
  }
  if (isReason(migrated)) {
    const detail = migrated === "argv-array-has-no-portable-shell-string" ? ARGV_ARRAY_BLOCK_DETAIL : undefined;
    return blocked(input, migrated, detail);
  }
  const v3Yaml = $stringify(migrated);
  try {
    parseTaskV3Yaml({
      yaml: v3Yaml,
      filePath: input.filePath,
      ...input.containmentRoot ? { workspaceRoot: input.containmentRoot } : {}
    });
  } catch (cause) {
    return blocked(input, "generated-v3-validation-failed", causeMessage(cause));
  }
  let v3Data;
  try {
    ({ data: v3Data } = parseRawTaskYaml({ ...input, bytes: Buffer.from(v3Yaml, "utf8") }));
  } catch (cause) {
    return blocked(input, "invalid-task-yaml", causeMessage(cause));
  }
  const v4Outcome = planV3DataToV4(input, v3Data);
  return v4Outcome.status === "changed" ? { ...v4Outcome, reason: "task-converted" } : v4Outcome;
}
function planV4Cleanup(input, source) {
  const document = $parseDocument(source, { uniqueKeys: true });
  const schedule = document.get("schedule", true);
  let removed = false;
  if ($isSeq(schedule)) {
    for (const entry of schedule.items) {
      if (!$isMap(entry) || !entry.has("enabled"))
        continue;
      entry.delete("enabled");
      removed = true;
    }
  }
  if (removed) {
    if (!input.writable || input.onDiskWritable === false) {
      return blocked(input, "read-only-source", !input.writable ? "the owning source is not writable" : "the source file or publication directory is read-only");
    }
    const after = Buffer.from(document.toString(), "utf8");
    try {
      parseTaskSourceV4({
        yaml: after.toString("utf8"),
        filePath: input.filePath,
        ...input.containmentRoot ? { workspaceRoot: input.containmentRoot } : {}
      });
    } catch (cause) {
      return blocked(input, "generated-v4-validation-failed", causeMessage(cause));
    }
    return Object.freeze({
      status: "changed",
      ...base(input),
      reason: "source-enablement-removed",
      after,
      afterHash: hash(after),
      notice: "Removed source-owned schedule enablement; scheduler activation is now host-local config."
    });
  }
  try {
    parseTaskSourceV4({
      yaml: source,
      filePath: input.filePath,
      ...input.containmentRoot ? { workspaceRoot: input.containmentRoot } : {}
    });
    return Object.freeze({ status: "skipped", ...base(input), reason: "already-v4" });
  } catch (cause) {
    return blocked(input, "invalid-v4-task", causeMessage(cause));
  }
}
function planTaskToV4File(input) {
  let data;
  let source;
  try {
    ({ data, source } = parseRawTaskYaml(input));
  } catch (cause) {
    return blocked(input, "invalid-task-yaml", causeMessage(cause));
  }
  if (data.version === 4) {
    return planV4Cleanup(input, source);
  }
  if (data.version === 3) {
    try {
      parseTaskV3Yaml({
        yaml: source,
        filePath: input.filePath,
        ...input.containmentRoot ? { workspaceRoot: input.containmentRoot } : {}
      });
    } catch (cause) {
      return blocked(input, "invalid-v3-task", causeMessage(cause));
    }
    return planV3DataToV4(input, data);
  }
  if (data.version === 2) {
    return planV2DataToV4(input, data);
  }
  return blocked(input, "unsupported-task-version", `expected version 2, 3, or 4, got ${String(data.version)}`);
}
function generationFor(files) {
  const digest = crypto3.createHash("sha256");
  digest.update("akm-task-to-v4-plan-v1\x00");
  for (const file of files) {
    digest.update(file.filePath);
    digest.update("\x00");
    digest.update(file.status);
    digest.update("\x00");
    digest.update(file.reason);
    digest.update("\x00");
    digest.update(String(file.mode));
    digest.update("\x00");
    digest.update(file.writable ? "writable" : "read-only");
    digest.update("\x00");
    digest.update(file.onDiskWritable === false ? "disk-read-only" : "disk-writable-or-unspecified");
    digest.update("\x00");
    if (file.containmentRoot)
      digest.update(file.containmentRoot);
    digest.update("\x00");
    digest.update(file.beforeHash);
    digest.update("\x00");
    if (file.status === "changed")
      digest.update(file.afterHash);
    digest.update("\x00");
    if (file.detail)
      digest.update(file.detail);
    digest.update("\x00");
    if (file.status === "changed" && file.notice)
      digest.update(file.notice);
    digest.update("\x00");
  }
  return digest.digest("hex");
}
function taskToV4PlanFromOutcomes(outcomes) {
  const files = [...outcomes].sort((left, right) => left.filePath < right.filePath ? -1 : left.filePath > right.filePath ? 1 : 0);
  for (let index = 1;index < files.length; index += 1) {
    const previous = files[index - 1];
    const current = files[index];
    if (previous && current && path48.resolve(previous.filePath) === path48.resolve(current.filePath)) {
      throw new Error(`duplicate task migration file path: ${current.filePath}`);
    }
  }
  return Object.freeze({ schemaVersion: 1, generation: generationFor(files), files: Object.freeze(files) });
}

// scripts/akm-migrate/migrate/task-files.ts
function migrationError(detail) {
  return new ConfigError(`Task migration failed: ${detail}`, "INVALID_CONFIG_FILE");
}
function contained2(root, candidate) {
  const relative = path49.relative(root, candidate);
  return relative === "" || !relative.startsWith("..") && !path49.isAbsolute(relative);
}
function realDirectory(filePath) {
  const stat = fs40.lstatSync(filePath);
  if (stat.isSymbolicLink() || !stat.isDirectory())
    throw migrationError(`${filePath} must be a real directory.`);
  return fs40.realpathSync(filePath);
}
function isWritable(filePath) {
  try {
    fs40.accessSync(filePath, fs40.constants.W_OK);
    return true;
  } catch {
    return false;
  }
}
function walkTasks(root, tasksDir, out) {
  const physicalRoot = realDirectory(root.root);
  const physicalBundleRoot = realDirectory(root.bundleRoot ?? root.root);
  if (!contained2(physicalBundleRoot, physicalRoot)) {
    throw migrationError(`${root.root} resolves outside bundle ${root.bundleId}.`);
  }
  const visit2 = (directory) => {
    const physicalDirectory = fs40.realpathSync(directory);
    if (!contained2(physicalRoot, physicalDirectory)) {
      throw migrationError(`${directory} resolves outside bundle ${root.bundleId}.`);
    }
    for (const entry of fs40.readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
      const candidate = path49.join(directory, entry.name);
      if (entry.isSymbolicLink())
        throw migrationError(`task migration does not follow symbolic link ${candidate}.`);
      if (entry.isDirectory()) {
        visit2(candidate);
        continue;
      }
      if (!entry.isFile() || !entry.name.endsWith(".yml"))
        continue;
      const stat = fs40.lstatSync(candidate);
      const mode = stat.mode & 511;
      out.push({
        filePath: candidate,
        bytes: fs40.readFileSync(candidate),
        mode,
        writable: root.writable,
        onDiskWritable: isWritable(candidate) && isWritable(directory) && (mode & 146) !== 0,
        containmentRoot: physicalRoot
      });
    }
  };
  visit2(tasksDir);
}
function inspectTaskFiles(roots) {
  const files = [];
  for (const root of [...roots].sort((a, b) => a.bundleId.localeCompare(b.bundleId))) {
    const tasksDir = root.layout === "akm-task" ? root.root : path49.join(root.root, "tasks");
    try {
      const stat = fs40.lstatSync(tasksDir);
      if (stat.isSymbolicLink())
        throw migrationError(`task migration does not follow symbolic link ${tasksDir}.`);
      if (!stat.isDirectory())
        throw migrationError(`${tasksDir} must be a directory.`);
    } catch (cause) {
      if (cause.code === "ENOENT")
        continue;
      throw cause;
    }
    walkTasks(root, tasksDir, files);
  }
  return files.sort((a, b) => a.filePath.localeCompare(b.filePath));
}
function planTaskFilesMigration(inputs) {
  return taskToV4PlanFromOutcomes(inputs.map(planTaskToV4File));
}
function taskFileBackupPath(backupRoot, filePath) {
  const digest = crypto4.createHash("sha256").update(path49.resolve(filePath)).digest("hex").slice(0, 16);
  return path49.join(backupRoot, "files", `${digest}-${path49.basename(filePath)}`);
}
function fsyncDirectory(directory) {
  if (process.platform === "win32")
    return;
  try {
    const fd = fs40.openSync(directory, "r");
    try {
      fs40.fsyncSync(fd);
    } finally {
      fs40.closeSync(fd);
    }
  } catch (cause) {
    const code = cause.code;
    if (code !== "EINVAL" && code !== "ENOTSUP" && code !== "EISDIR" && code !== "EPERM")
      throw cause;
  }
}
function writeDurable(filePath, bytes, mode, exclusive = false) {
  fs40.mkdirSync(path49.dirname(filePath), { recursive: true });
  const fd = fs40.openSync(filePath, exclusive ? "wx" : "w", mode);
  try {
    fs40.writeFileSync(fd, bytes);
    fs40.fsyncSync(fd);
  } finally {
    fs40.closeSync(fd);
  }
  fs40.chmodSync(filePath, mode);
  fsyncDirectory(path49.dirname(filePath));
}
function replaceAtomically(filePath, bytes, mode) {
  const temporary = path49.join(path49.dirname(filePath), `.${path49.basename(filePath)}.migrate-${crypto4.randomUUID()}`);
  try {
    writeDurable(temporary, bytes, mode, true);
    fs40.renameSync(temporary, filePath);
    fsyncDirectory(path49.dirname(filePath));
  } finally {
    fs40.rmSync(temporary, { force: true });
  }
}
function applyTaskFilesPlan(plan, options) {
  const changes = plan.files.filter((file) => file.status === "changed");
  for (const change of changes) {
    parseTaskSourceV4({
      yaml: change.after.toString("utf8"),
      filePath: change.filePath,
      ...change.containmentRoot ? { workspaceRoot: change.containmentRoot } : {}
    });
  }
  for (const change of changes) {
    writeDurable(taskFileBackupPath(options.backupRoot, change.filePath), change.before, change.mode, true);
  }
  const replaced = [];
  try {
    for (const change of changes) {
      replaceAtomically(change.filePath, change.after, change.mode);
      replaced.push(change);
    }
  } catch (cause) {
    for (const change of [...replaced].reverse()) {
      replaceAtomically(change.filePath, fs40.readFileSync(taskFileBackupPath(options.backupRoot, change.filePath)), change.mode);
    }
    throw cause;
  }
  return { changed: changes.map((file) => file.filePath) };
}

// scripts/akm-migrate/task-migrate.ts
function expandTilde(value) {
  if (value === "~")
    return os8.homedir();
  if (value.startsWith("~/") || value.startsWith("~\\"))
    return path50.join(os8.homedir(), value.slice(2));
  return value;
}
function existingDirectory(target) {
  try {
    return fs41.statSync(target).isDirectory();
  } catch (cause) {
    if (cause.code === "ENOENT")
      return false;
    throw cause;
  }
}
function reconcileDuplicateRoot(existing, candidate, sharedPath) {
  if (existing.writable === candidate.writable && existing.layout === candidate.layout)
    return;
  throw new ConfigError(`Bundles "${existing.bundleId}" and "${candidate.bundleId}" both resolve to the same directory ` + `(${sharedPath}) but disagree on writable/adapter settings. Two bundle ids configured for one ` + "directory must have matching settings, or one of them removed — run `akm bundle list` to see both.", "INVALID_CONFIG_FILE");
}
function taskRoots(config, resolutionBase = process.cwd()) {
  const sources = new Map((bundlesToSourceEntries(config) ?? []).map((source) => [source.name, source]));
  const rootsByPath = new Map;
  for (const [bundleId, bundle] of Object.entries(config.bundles ?? {})) {
    if (bundle.enabled === false)
      continue;
    const source = sources.get(bundleId);
    if (!source)
      continue;
    const configuredRoot = source.type === "filesystem" && source.path ? path50.resolve(resolutionBase, expandTilde(source.path)) : lockContentRootFor(bundleId, source.type);
    if (!configuredRoot || !existingDirectory(configuredRoot))
      continue;
    const bundleRoot = path50.resolve(configuredRoot);
    const component = bundleComponentConfig(bundle);
    const componentRoot = path50.resolve(bundleRoot, component?.root ?? ".");
    const relative = path50.relative(bundleRoot, componentRoot);
    if (relative === ".." || relative.startsWith(`..${path50.sep}`) || path50.isAbsolute(relative)) {
      throw new ConfigError(`Task migration component root ${componentRoot} escapes bundle ${bundleId} at ${bundleRoot}.`, "INVALID_CONFIG_FILE");
    }
    if (!existingDirectory(componentRoot))
      continue;
    const candidate = taskRoot(bundleId, bundleRoot, componentRoot, component?.adapter, () => component?.writable ?? resolveWritable(source));
    if (!candidate)
      continue;
    const existing = rootsByPath.get(componentRoot);
    if (existing) {
      reconcileDuplicateRoot(existing, candidate, componentRoot);
      continue;
    }
    rootsByPath.set(componentRoot, candidate);
  }
  const envStash = process.env.AKM_BUNDLE_DIR?.trim();
  if (envStash && existingDirectory(envStash)) {
    const stashRoot = path50.resolve(envStash);
    if (!rootsByPath.has(stashRoot)) {
      const bundleId = deriveBundleId(undefined, stashRoot, new Set(Object.keys(config.bundles ?? {})));
      const candidate = taskRoot(bundleId, stashRoot, stashRoot, detectAdapterId(stashRoot), () => true);
      if (candidate)
        rootsByPath.set(stashRoot, candidate);
    }
  }
  return [...rootsByPath.values()];
}
function taskRoot(bundleId, bundleRoot, componentRoot, configuredAdapter, writable) {
  const adapter = configuredAdapter ?? detectAdapterId(componentRoot, "");
  if (!configuredAdapter && adapter === "") {
    const flatTasks = fs41.readdirSync(componentRoot, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".yml")).map((entry) => entry.name).sort();
    if (flatTasks.length > 0) {
      throw new ConfigError(`Task migration cannot classify top-level task file(s) ${flatTasks.join(", ")} in bundle ${bundleId}; configure adapter "akm-task" or move them under tasks/.`, "INVALID_CONFIG_FILE");
    }
  }
  if (adapter !== "akm" && adapter !== "akm-task")
    return;
  return {
    bundleId,
    root: componentRoot,
    bundleRoot,
    writable: writable(),
    layout: adapter === "akm-task" ? "akm-task" : "akm-stash"
  };
}
function summarize(plan) {
  const files = plan.files.map((file) => ({
    filePath: file.filePath,
    status: file.status,
    reason: file.reason,
    beforeHash: file.beforeHash,
    ...file.status === "changed" ? { afterHash: file.afterHash } : {},
    ...file.detail ? { detail: file.detail } : {},
    ...file.status === "changed" && file.notice ? { notice: file.notice } : {}
  }));
  return {
    schemaVersion: 1,
    changed: files.filter((file) => file.status === "changed").length,
    skipped: files.filter((file) => file.status === "skipped").length,
    blocked: files.filter((file) => file.status === "blocked").length,
    files
  };
}
function inspectCurrent() {
  resetConfigCache();
  const plan = planTaskFilesMigration(inspectTaskFiles(taskRoots(loadConfig())));
  const blockers = plan.files.flatMap((file) => file.status === "blocked" ? [`${file.filePath}: ${file.reason}${file.detail ? ` (${file.detail})` : ""}`] : []);
  const summary = summarize(plan);
  return {
    plan,
    result: {
      schemaVersion: 1,
      status: blockers.length > 0 ? "blocked" : summary.changed > 0 ? "ready" : "current",
      blockers,
      taskFiles: summary
    }
  };
}
function inspectTaskFilesMigration() {
  return inspectCurrent().result;
}
function applyTaskFilesMigration() {
  return withConfigLock(() => {
    const before = inspectCurrent();
    if (before.result.taskFiles.changed === 0)
      return before.result;
    const backupPath = path50.join(getDataDir(), "backups", "tasks", `${Date.now()}-${randomUUID3()}`);
    const applied = applyTaskFilesPlan(before.plan, { backupRoot: backupPath });
    return { ...inspectCurrent().result, backupPath, applied: applied.changed.length };
  });
}

// scripts/akm-migrate/run-migrate.ts
function worstStatus(left, right) {
  if (left === "blocked" || right === "blocked")
    return "blocked";
  if (left === "ready" || right === "ready")
    return "ready";
  return "current";
}
function migrationStepError(cause) {
  return cause instanceof Error ? cause.message : String(cause);
}
function failedStepBlockers(failedSteps) {
  return failedSteps.map((entry) => `migration step ${JSON.stringify(entry.step)} failed: ${entry.error}`);
}
function statusWithFailedSteps(status, failedSteps) {
  return failedSteps.length > 0 ? worstStatus(status, "blocked") : status;
}
async function migrationStep(failedSteps, step, action, probe) {
  try {
    return await action();
  } catch (cause) {
    failedSteps.push({ step, error: migrationStepError(cause) });
    if (!probe)
      return;
    try {
      return await probe();
    } catch (probeCause) {
      failedSteps.push({ step: `${step} (read-only fallback)`, error: migrationStepError(probeCause) });
      return;
    }
  }
}
function stashDirIfConfigured() {
  try {
    return resolveStashDir();
  } catch (error2) {
    if (error2 instanceof ConfigError && error2.code === "STASH_DIR_NOT_FOUND")
      return;
    throw error2;
  }
}
async function runMigration(options) {
  const { apply } = options;
  const configPath = getConfigPath();
  const failedSteps = [];
  const configFile = await migrationStep(failedSteps, "configFile", () => normalizeConfigFile(configPath, { apply }), apply ? () => normalizeConfigFile(configPath, { apply: false }) : undefined);
  if (apply && configFile?.applied)
    resetConfigCache();
  const stateMigrations = await migrationStep(failedSteps, "stateMigrations", () => apply ? applyStateMigrations() : { pending: listPendingStateMigrations() }, apply ? () => ({ pending: listPendingStateMigrations() }) : undefined);
  const taskFiles = await migrationStep(failedSteps, "taskFiles", () => apply ? applyTaskFilesMigration() : inspectTaskFilesMigration(), apply ? () => inspectTaskFilesMigration() : undefined);
  const stashDir = await migrationStep(failedSteps, "stashDir", () => stashDirIfConfigured());
  const deadResidue = await migrationStep(failedSteps, "deadResidue", () => apply ? { removed: removeDeadResidue(stashDir) } : { pending: findDeadResidueEntries(stashDir) }, apply ? () => ({ pending: findDeadResidueEntries(stashDir) }) : undefined);
  const stateStatus = stateMigrations && "pending" in stateMigrations && stateMigrations.pending.length > 0 ? "ready" : "current";
  const configFileStatus = configFile?.changed && !configFile.applied ? "ready" : "current";
  return {
    schemaVersion: 1,
    status: statusWithFailedSteps(worstStatus(worstStatus(taskFiles?.status ?? "blocked", stateStatus), configFileStatus), failedSteps),
    blockers: [...taskFiles?.blockers ?? [], ...failedStepBlockers(failedSteps)],
    ...failedSteps.length > 0 ? { failedSteps } : {},
    ...configFile !== undefined ? { configFile } : {},
    ...stateMigrations !== undefined ? { stateMigrations } : {},
    ...taskFiles !== undefined ? { taskFiles: taskFiles.taskFiles } : {},
    ...taskFiles?.backupPath !== undefined ? { backupPath: taskFiles.backupPath } : {},
    ...taskFiles?.applied !== undefined ? { applied: taskFiles.applied } : {},
    ...deadResidue !== undefined ? { deadResidue } : {}
  };
}
function applyStateMigrations() {
  const result = upgradeHistoricalStateDatabase();
  return result.safetyCopyPath ? { applied: result.applied, safetyCopyPath: result.safetyCopyPath } : { applied: result.applied };
}

// scripts/akm-migrate/main.ts
function printPlan(plan) {
  console.log(JSON.stringify(plan));
  if (plan.status === "blocked")
    process.exitCode = EXIT_CODES2.GENERAL;
}
async function main(args = process.argv.slice(2)) {
  const [command, ...rest] = args;
  switch (command) {
    case "--help":
    case "-h":
    case "help":
      console.log(help_default.trimEnd());
      return;
    case "status": {
      const unknown = rest[0];
      if (unknown !== undefined)
        throw new UsageError(`\`status\` does not accept ${unknown}.`, "INVALID_FLAG_VALUE");
      printPlan(await runMigration({ apply: false }));
      return;
    }
    case "apply": {
      const unknown = rest.find((arg) => arg !== "--dry-run");
      if (unknown !== undefined)
        throw new UsageError(`\`apply\` does not accept ${unknown}.`, "INVALID_FLAG_VALUE");
      printPlan(await runMigration({ apply: !rest.includes("--dry-run") }));
      return;
    }
    default:
      throw new UsageError("Choose `status` or `apply [--dry-run]`.", "MISSING_REQUIRED_ARGUMENT");
  }
}

// scripts/akm-migrate.ts
var isMain = __require.main == __require.module === true || process.argv[1] !== undefined && pathToFileURL2(process.argv[1]).href === import.meta.url;
if (isMain)
  await runWithJsonErrors(() => main());
export {
  main
};