var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __commonJS = (cb, mod) => function __require() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __publicField = (obj, key, value) => {
  __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
  return value;
};
var __accessCheck = (obj, member, msg) => {
  if (!member.has(obj))
    throw TypeError("Cannot " + msg);
};
var __privateGet = (obj, member, getter) => {
  __accessCheck(obj, member, "read from private field");
  return getter ? getter.call(obj) : member.get(obj);
};
var __privateAdd = (obj, member, value) => {
  if (member.has(obj))
    throw TypeError("Cannot add the same private member more than once");
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
};
var __privateSet = (obj, member, value, setter) => {
  __accessCheck(obj, member, "write to private field");
  setter ? setter.call(obj, value) : member.set(obj, value);
  return value;
};
var __privateMethod = (obj, member, method) => {
  __accessCheck(obj, member, "access private method");
  return method;
};

// node_modules/balanced-match/index.js
var require_balanced_match = __commonJS({
  "node_modules/balanced-match/index.js"(exports, module) {
    "use strict";
    module.exports = balanced;
    function balanced(a, b, str) {
      if (a instanceof RegExp)
        a = maybeMatch(a, str);
      if (b instanceof RegExp)
        b = maybeMatch(b, str);
      var r = range(a, b, str);
      return r && {
        start: r[0],
        end: r[1],
        pre: str.slice(0, r[0]),
        body: str.slice(r[0] + a.length, r[1]),
        post: str.slice(r[1] + b.length)
      };
    }
    function maybeMatch(reg, str) {
      var m = str.match(reg);
      return m ? m[0] : null;
    }
    balanced.range = range;
    function range(a, b, str) {
      var begs, beg, left, right, result;
      var ai = str.indexOf(a);
      var bi = str.indexOf(b, ai + 1);
      var i = ai;
      if (ai >= 0 && bi > 0) {
        if (a === b) {
          return [ai, bi];
        }
        begs = [];
        left = str.length;
        while (i >= 0 && !result) {
          if (i == ai) {
            begs.push(i);
            ai = str.indexOf(a, i + 1);
          } else if (begs.length == 1) {
            result = [begs.pop(), bi];
          } else {
            beg = begs.pop();
            if (beg < left) {
              left = beg;
              right = bi;
            }
            bi = str.indexOf(b, i + 1);
          }
          i = ai < bi && ai >= 0 ? ai : bi;
        }
        if (begs.length) {
          result = [left, right];
        }
      }
      return result;
    }
  }
});

// node_modules/brace-expansion/index.js
var require_brace_expansion = __commonJS({
  "node_modules/brace-expansion/index.js"(exports, module) {
    var balanced = require_balanced_match();
    module.exports = expandTop;
    var escSlash = "\0SLASH" + Math.random() + "\0";
    var escOpen = "\0OPEN" + Math.random() + "\0";
    var escClose = "\0CLOSE" + Math.random() + "\0";
    var escComma = "\0COMMA" + Math.random() + "\0";
    var escPeriod = "\0PERIOD" + Math.random() + "\0";
    function numeric(str) {
      return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0);
    }
    function escapeBraces(str) {
      return str.split("\\\\").join(escSlash).split("\\{").join(escOpen).split("\\}").join(escClose).split("\\,").join(escComma).split("\\.").join(escPeriod);
    }
    function unescapeBraces(str) {
      return str.split(escSlash).join("\\").split(escOpen).join("{").split(escClose).join("}").split(escComma).join(",").split(escPeriod).join(".");
    }
    function parseCommaParts(str) {
      if (!str)
        return [""];
      var parts = [];
      var m = balanced("{", "}", str);
      if (!m)
        return str.split(",");
      var pre = m.pre;
      var body = m.body;
      var post = m.post;
      var p = pre.split(",");
      p[p.length - 1] += "{" + body + "}";
      var postParts = parseCommaParts(post);
      if (post.length) {
        p[p.length - 1] += postParts.shift();
        p.push.apply(p, postParts);
      }
      parts.push.apply(parts, p);
      return parts;
    }
    function expandTop(str) {
      if (!str)
        return [];
      if (str.substr(0, 2) === "{}") {
        str = "\\{\\}" + str.substr(2);
      }
      return expand2(escapeBraces(str), true).map(unescapeBraces);
    }
    function embrace(str) {
      return "{" + str + "}";
    }
    function isPadded(el) {
      return /^-?0\d/.test(el);
    }
    function lte(i, y) {
      return i <= y;
    }
    function gte(i, y) {
      return i >= y;
    }
    function expand2(str, isTop) {
      var expansions = [];
      var m = balanced("{", "}", str);
      if (!m)
        return [str];
      var pre = m.pre;
      var post = m.post.length ? expand2(m.post, false) : [""];
      if (/\$$/.test(m.pre)) {
        for (var k = 0; k < post.length; k++) {
          var expansion = pre + "{" + m.body + "}" + post[k];
          expansions.push(expansion);
        }
      } else {
        var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
        var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
        var isSequence = isNumericSequence || isAlphaSequence;
        var isOptions = m.body.indexOf(",") >= 0;
        if (!isSequence && !isOptions) {
          if (m.post.match(/,.*\}/)) {
            str = m.pre + "{" + m.body + escClose + m.post;
            return expand2(str);
          }
          return [str];
        }
        var n;
        if (isSequence) {
          n = m.body.split(/\.\./);
        } else {
          n = parseCommaParts(m.body);
          if (n.length === 1) {
            n = expand2(n[0], false).map(embrace);
            if (n.length === 1) {
              return post.map(function(p) {
                return m.pre + n[0] + p;
              });
            }
          }
        }
        var N;
        if (isSequence) {
          var x = numeric(n[0]);
          var y = numeric(n[1]);
          var width = Math.max(n[0].length, n[1].length);
          var incr = n.length == 3 ? Math.abs(numeric(n[2])) : 1;
          var test = lte;
          var reverse = y < x;
          if (reverse) {
            incr *= -1;
            test = gte;
          }
          var pad = n.some(isPadded);
          N = [];
          for (var i = x; test(i, y); i += incr) {
            var c;
            if (isAlphaSequence) {
              c = String.fromCharCode(i);
              if (c === "\\")
                c = "";
            } else {
              c = String(i);
              if (pad) {
                var need = width - c.length;
                if (need > 0) {
                  var z = new Array(need + 1).join("0");
                  if (i < 0)
                    c = "-" + z + c.slice(1);
                  else
                    c = z + c;
                }
              }
            }
            N.push(c);
          }
        } else {
          N = [];
          for (var j = 0; j < n.length; j++) {
            N.push.apply(N, expand2(n[j], false));
          }
        }
        for (var j = 0; j < N.length; j++) {
          for (var k = 0; k < post.length; k++) {
            var expansion = pre + N[j] + post[k];
            if (!isTop || isSequence || expansion)
              expansions.push(expansion);
          }
        }
      }
      return expansions;
    }
  }
});

// src/polyfills/bun-capabilities.ts
var WebAssembly2 = globalThis.WebAssembly || {};
var CAPABILITIES = {
  supportsJSPromiseInterface: typeof WebAssembly2.Suspending === "function" && typeof WebAssembly2.promising === "function",
  allowSharedBufferCodec: false,
  manifestSupportsPaths: true,
  crossOriginChecksEnforced: false,
  fsAccess: true,
  hasWorkerCapability: true,
  supportsWasiPreview1: false,
  supportsTimeouts: false,
  extismStdoutEnvVarSet: Boolean(process.env.EXTISM_ENABLE_WASI_OUTPUT)
};

// src/interfaces.ts
var _decoder, _bytes;
var _PluginOutput = class extends DataView {
  constructor(buffer) {
    super(buffer);
    __privateAdd(this, _bytes, null);
  }
  json() {
    return JSON.parse(this.string());
  }
  arrayBuffer() {
    return this.buffer;
  }
  text() {
    return this.string();
  }
  string() {
    return __privateGet(_PluginOutput, _decoder).decode(this.buffer);
  }
  bytes() {
    __privateGet(this, _bytes) ?? __privateSet(this, _bytes, new Uint8Array(this.buffer));
    return __privateGet(this, _bytes);
  }
  setInt8(_byteOffset, _value) {
    throw new Error("Cannot set values on output");
  }
  setInt16(_byteOffset, _value, _littleEndian) {
    throw new Error("Cannot set values on output");
  }
  setInt32(_byteOffset, _value, _littleEndian) {
    throw new Error("Cannot set values on output");
  }
  setUint8(_byteOffset, _value) {
    throw new Error("Cannot set values on output");
  }
  setUint16(_byteOffset, _value, _littleEndian) {
    throw new Error("Cannot set values on output");
  }
  setUint32(_byteOffset, _value, _littleEndian) {
    throw new Error("Cannot set values on output");
  }
  setFloat32(_byteOffset, _value, _littleEndian) {
    throw new Error("Cannot set values on output");
  }
  setFloat64(_byteOffset, _value, _littleEndian) {
    throw new Error("Cannot set values on output");
  }
  setBigInt64(_byteOffset, _value, _littleEndian) {
    throw new Error("Cannot set values on output");
  }
  setBigUint64(_byteOffset, _value, _littleEndian) {
    throw new Error("Cannot set values on output");
  }
};
var PluginOutput = _PluginOutput;
_decoder = new WeakMap();
_bytes = new WeakMap();
__privateAdd(PluginOutput, _decoder, new TextDecoder());
var SAB_BASE_OFFSET = 4;
function logLevelToPriority(level) {
  switch (level) {
    case "trace":
      return 0;
    case "debug":
      return 1;
    case "info":
      return 2;
    case "warn":
      return 3;
    case "error":
      return 4;
    case "silent":
      return 2147483647;
    default:
      throw new TypeError(
        `unrecognized log level "${level}"; expected one of "trace", "debug", "info", "warn", "error", "silent"`
      );
  }
}
function priorityToLogLevel(level) {
  switch (level) {
    case 0:
      return "trace";
    case 1:
      return "debug";
    case 2:
      return "info";
    case 3:
      return "warn";
    case 4:
      return "error";
    case 2147483647:
      return "silent";
    default:
      throw new TypeError(
        `unrecognized log level "${level}"; expected one of "trace", "debug", "info", "warn", "error", "silent"`
      );
  }
}

// src/manifest.ts
import { readFile } from "node:fs/promises";

// src/polyfills/bun-response-to-module.ts
async function responseToModule(response, _hasHash) {
  if (String(response.headers.get("Content-Type")).split(";")[0] === "application/octet-stream") {
    const headers = new Headers(response.headers);
    headers.set("Content-Type", "application/wasm");
    response = new Response(response.body, {
      status: response.status,
      statusText: response.statusText,
      headers
    });
  }
  const data = await response.arrayBuffer();
  const module = await WebAssembly.compile(data);
  return { module, data };
}

// src/manifest.ts
async function _populateWasmField(candidate, _fetch) {
  if (candidate instanceof ArrayBuffer) {
    return { wasm: [{ data: new Uint8Array(candidate) }] };
  }
  if (candidate instanceof WebAssembly.Module) {
    return { wasm: [{ module: candidate }] };
  }
  if (typeof candidate === "string") {
    if (candidate.search(/^\s*\{/g) === 0) {
      return parseManifestFromJson(candidate);
    }
    if (candidate.search(/^(https?|file):\/\//) !== 0) {
      return { wasm: [{ path: candidate }] };
    }
    candidate = new URL(candidate);
  }
  if (candidate instanceof Response || candidate?.constructor?.name === "Response") {
    const response = candidate;
    const contentType = response.headers.get("content-type") || "application/octet-stream";
    switch (contentType.split(";")[0]) {
      case "application/octet-stream":
      case "application/wasm":
        return { wasm: [{ response }] };
      case "application/json":
      case "text/json":
        return _populateWasmField(parseManifestFromJson(await response.text()), _fetch);
      default:
        throw new TypeError(
          `While processing manifest URL "${response.url}"; expected content-type of "text/json", "application/json", "application/octet-stream", or "application/wasm"; got "${contentType}" after stripping off charset.`
        );
    }
  }
  if (candidate instanceof URL) {
    return _populateWasmField(await _fetch(candidate, { redirect: "follow" }), _fetch);
  }
  if (!("wasm" in candidate)) {
    throw new TypeError('Expected "wasm" key in manifest');
  }
  if (!Array.isArray(candidate.wasm)) {
    throw new TypeError('Expected "manifest.wasm" to be array');
  }
  const badItemIdx = candidate.wasm.findIndex(
    (item) => !("data" in item) && !("url" in item) && !("path" in item) && !("module" in item) && !("response" in item)
  );
  if (badItemIdx > -1) {
    throw new TypeError(
      `Expected every item in "manifest.wasm" to include either a "data", "url", or "path" key; got bad item at index ${badItemIdx}`
    );
  }
  return { ...candidate };
}
function parseManifestFromJson(json) {
  const parsed = JSON.parse(json);
  return {
    wasm: parsed.wasm,
    timeoutMs: parsed.timeoutMs ?? parsed.timeout_ms,
    allowedPaths: parsed.allowedPaths ?? parsed.allowed_paths,
    allowedHosts: parsed.allowedHosts ?? parsed.allowed_hosts,
    config: parsed.config,
    ...parsed.memory ? {
      maxHttpResponseBytes: parsed.memory.maxHttpResponseBytes ?? parsed.memory.max_http_response_bytes,
      maxPages: parsed.memory.maxPages ?? parsed.memory.max_pages,
      maxVarBytes: parsed.memory.maxVarBytes ?? parsed.memory.max_var_bytes
    } : {}
  };
}
async function intoManifest(candidate, _fetch = fetch) {
  const manifest = await _populateWasmField(candidate, _fetch);
  manifest.config ??= {};
  return manifest;
}
async function toWasmModuleData(input, _fetch) {
  const names = [];
  const manifest = await intoManifest(input, _fetch);
  const manifestOpts = {
    allowedPaths: manifest.allowedPaths,
    allowedHosts: manifest.allowedHosts,
    config: manifest.config,
    memory: manifest.memory
  };
  const manifestsWasm = await Promise.all(
    manifest.wasm.map(async (item, idx, all) => {
      let module;
      let buffer;
      if (item.data) {
        const data = item.data;
        buffer = data.buffer ? data.buffer : data;
        module = await WebAssembly.compile(data);
      } else if (item.path) {
        const path2 = item.path;
        const data = await readFile(path2);
        buffer = data.buffer;
        module = await WebAssembly.compile(data);
      } else if (item.url) {
        const response = await _fetch(item.url, {
          headers: {
            accept: "application/wasm;q=0.9,application/octet-stream;q=0.8"
          }
        });
        const result = await responseToModule(response, Boolean(item.hash));
        buffer = result.data;
        module = result.module;
      } else if (item.response) {
        const result = await responseToModule(item.response, Boolean(item.hash));
        buffer = result.data;
        module = result.module;
      } else if (item.module) {
        names[idx] = item.name ?? String(idx);
        module = item.module;
      } else {
        throw new Error(
          `Unrecognized wasm item at index ${idx}. Keys include: "${Object.keys(item).sort().join(",")}"`
        );
      }
      let potentialName = String(idx);
      if (item.hash) {
        if (!buffer) {
          throw new Error("Item specified a hash but WebAssembly.Module source data is unavailable for hashing");
        }
        const hashBuffer = new Uint8Array(await crypto.subtle.digest("SHA-256", buffer));
        const checkBuffer = new Uint8Array(32);
        let eq = true;
        for (let i = 0; i < 32; ++i) {
          checkBuffer[i] = parseInt(item.hash.slice(i << 1, (i << 1) + 2), 16);
          eq = eq && checkBuffer[i] === hashBuffer[i];
        }
        const hashAsString = () => [...hashBuffer].map((xs) => xs.toString(16).padStart(2, "0")).join("");
        if (!eq) {
          throw new Error(`Plugin error: hash mismatch. Expected: ${item.hash}. Actual: ${hashAsString()}`);
        }
        potentialName = hashAsString();
      }
      names[idx] = item.name ?? (idx === all.length - 1 ? "main" : potentialName);
      return module;
    })
  );
  if (!names.includes("main")) {
    throw new Error('manifest with multiple modules must designate one "main" module');
  }
  return [manifestOpts, names, manifestsWasm];
}

// src/call-context.ts
var BEGIN = Symbol("begin");
var END = Symbol("end");
var ENV = Symbol("env");
var SET_HOST_CONTEXT = Symbol("set-host-context");
var GET_BLOCK = Symbol("get-block");
var IMPORT_STATE = Symbol("import-state");
var EXPORT_STATE = Symbol("export-state");
var STORE = Symbol("store-value");
var RESET = Symbol("reset");
var Block = class {
  get byteLength() {
    return this.buffer.byteLength;
  }
  constructor(arrayBuffer, local) {
    this.buffer = arrayBuffer;
    this.view = new DataView(this.buffer);
    this.local = local;
  }
  static indexToAddress(idx) {
    return BigInt(idx) << 48n;
  }
  static addressToIndex(addr) {
    return Number(BigInt(addr) >> 48n);
  }
  static maskAddress(addr) {
    return Number(BigInt(addr) & (1n << 48n) - 1n);
  }
};
var _a;
var CallContext = class {
  constructor(type, logger, logLevel, config, memoryOptions) {
    this.#blocks = [];
    this.#vars = /* @__PURE__ */ new Map();
    this[_a] = {
      alloc: (n) => {
        return this.alloc(n);
      },
      free: (addr) => {
        this.#blocks[Block.addressToIndex(addr)] = null;
      },
      load_u8: (addr) => {
        const blockIdx = Block.addressToIndex(addr);
        const offset = Block.maskAddress(addr);
        const block = this.#blocks[blockIdx];
        return block?.view.getUint8(Number(offset));
      },
      load_u64: (addr) => {
        const blockIdx = Block.addressToIndex(addr);
        const offset = Block.maskAddress(addr);
        const block = this.#blocks[blockIdx];
        return block?.view.getBigUint64(Number(offset), true);
      },
      store_u8: (addr, n) => {
        const blockIdx = Block.addressToIndex(addr);
        const offset = Block.maskAddress(addr);
        const block = this.#blocks[blockIdx];
        block?.view.setUint8(Number(offset), Number(n));
      },
      store_u64: (addr, n) => {
        const blockIdx = Block.addressToIndex(addr);
        const offset = Block.maskAddress(addr);
        const block = this.#blocks[blockIdx];
        block?.view.setBigUint64(Number(offset), n, true);
      },
      input_offset: () => {
        const blockIdx = this.#stack[this.#stack.length - 1][0];
        return Block.indexToAddress(blockIdx || 0);
      },
      input_length: () => {
        return BigInt(this.#input?.byteLength ?? 0);
      },
      input_load_u8: (addr) => {
        const offset = Block.maskAddress(addr);
        return this.#input?.view.getUint8(Number(offset));
      },
      input_load_u64: (addr) => {
        const offset = Block.maskAddress(addr);
        return this.#input?.view.getBigUint64(Number(offset), true);
      },
      output_set: (addr, length) => {
        const blockIdx = Block.addressToIndex(addr);
        const block = this.#blocks[blockIdx];
        if (!block) {
          throw new Error(`cannot assign to this block (addr=${addr.toString(16).padStart(16, "0")}; length=${length})`);
        }
        if (length > block.buffer.byteLength) {
          throw new Error("length longer than target block");
        }
        this.#stack[this.#stack.length - 1][1] = blockIdx;
      },
      error_set: (addr) => {
        const blockIdx = Block.addressToIndex(addr);
        const block = this.#blocks[blockIdx];
        if (!block) {
          throw new Error("cannot assign error to this block");
        }
        this.#stack[this.#stack.length - 1][2] = blockIdx;
      },
      error_get: () => {
        const error = this.#stack[this.#stack.length - 1][2];
        if (error) {
          return Block.indexToAddress(error);
        }
        return 0n;
      },
      config_get: (addr) => {
        const item = this.read(addr);
        if (item === null) {
          return 0n;
        }
        try {
          const key = item.string();
          if (key in this.#config) {
            return this.store(this.#config[key]);
          }
        } finally {
          this[ENV].free(addr);
        }
        return 0n;
      },
      var_get: (addr) => {
        const item = this.read(addr);
        if (item === null) {
          return 0n;
        }
        try {
          const key = item.string();
          const result = this.getVariable(key);
          const stored = result ? this[STORE](result.bytes()) || 0 : 0;
          return Block.indexToAddress(stored);
        } finally {
          this[ENV].free(addr);
        }
      },
      var_set: (addr, valueaddr) => {
        const item = this.read(addr);
        if (item === null) {
          this.#logger.error(`attempted to set variable using invalid key address (addr="${addr.toString(16)}H")`);
          return;
        }
        const key = item.string();
        if (valueaddr === 0n) {
          this.deleteVariable(key);
          return;
        }
        const valueBlock = this.#blocks[Block.addressToIndex(valueaddr)];
        if (!valueBlock) {
          this.#logger.error(
            `attempted to set variable to invalid address (key="${key}"; addr="${valueaddr.toString(16)}H")`
          );
          return;
        }
        try {
          const copied = new Uint8Array(valueBlock.buffer.byteLength);
          copied.set(new Uint8Array(valueBlock.buffer), 0);
          this.setVariable(key, copied);
        } catch (err) {
          this.#logger.error(err.message);
          this.setError(err);
          return;
        }
      },
      http_request: (_requestOffset, _bodyOffset) => {
        this.#logger.error("http_request is not enabled");
        return 0n;
      },
      http_status_code: () => {
        this.#logger.error("http_status_code is not enabled");
        return 0;
      },
      http_headers: () => {
        this.#logger.error("http_headers is not enabled");
        return 0n;
      },
      length: (addr) => {
        return this.length(addr);
      },
      length_unsafe: (addr) => {
        return this.length(addr);
      },
      log_warn: this.#handleLog.bind(this, logLevelToPriority("warn"), "warn"),
      log_info: this.#handleLog.bind(this, logLevelToPriority("info"), "info"),
      log_debug: this.#handleLog.bind(this, logLevelToPriority("debug"), "debug"),
      log_error: this.#handleLog.bind(this, logLevelToPriority("error"), "error"),
      log_trace: this.#handleLog.bind(this, logLevelToPriority("trace"), "trace"),
      get_log_level: () => {
        return isFinite(this.#logLevel) ? this.#logLevel : 4294967295;
      }
    };
    this.#arrayBufferType = type;
    this.#logger = logger;
    this.#logLevel = logLevel ?? 2147483647;
    this.#decoder = new TextDecoder();
    this.#encoder = new TextEncoder();
    this.#memoryOptions = memoryOptions;
    this.#varsSize = 0;
    this.#stack = [];
    this.alloc(1);
    this.#config = config;
  }
  #stack;
  #blocks;
  #logger;
  #logLevel;
  #decoder;
  #encoder;
  #arrayBufferType;
  #config;
  #vars;
  #varsSize;
  #memoryOptions;
  #hostContext;
  hostContext() {
    return this.#hostContext;
  }
  alloc(size) {
    const block = new Block(new this.#arrayBufferType(Number(size)), true);
    const index = this.#blocks.length;
    this.#blocks.push(block);
    if (this.#memoryOptions.maxPages) {
      const pageSize = 64 * 1024;
      const totalBytes = this.#blocks.reduce((acc, block2) => acc + (block2?.buffer.byteLength ?? 0), 0);
      const totalPages = Math.ceil(totalBytes / pageSize);
      if (totalPages > this.#memoryOptions.maxPages) {
        this.#logger.error(
          `memory limit exceeded: ${totalPages} pages requested, ${this.#memoryOptions.maxPages} allowed`
        );
        return 0n;
      }
    }
    return Block.indexToAddress(index);
  }
  getVariable(name) {
    if (!this.#vars.has(name)) {
      return null;
    }
    return new PluginOutput(this.#vars.get(name).buffer);
  }
  setVariable(name, value) {
    const buffer = typeof value === "string" ? this.#encoder.encode(value) : value;
    const variable = this.#vars.get(name);
    const newSize = this.#varsSize + buffer.byteLength - (variable?.byteLength || 0);
    if (newSize > (this.#memoryOptions?.maxVarBytes || Infinity)) {
      throw new Error(
        `var memory limit exceeded: ${newSize} bytes requested, ${this.#memoryOptions.maxVarBytes} allowed`
      );
    }
    this.#varsSize = newSize;
    this.#vars.set(name, buffer);
  }
  deleteVariable(name) {
    const variable = this.#vars.get(name);
    if (!variable) {
      return;
    }
    this.#vars.delete(name);
    this.#varsSize -= variable.byteLength;
  }
  read(addr) {
    const blockIdx = Block.addressToIndex(addr);
    const block = this.#blocks[blockIdx];
    if (!block) {
      return null;
    }
    const buffer = !(block.buffer instanceof ArrayBuffer) && !CAPABILITIES.allowSharedBufferCodec ? new Uint8Array(block.buffer).slice().buffer : block.buffer;
    return new PluginOutput(buffer);
  }
  store(input) {
    const idx = this[STORE](input);
    if (!idx) {
      throw new Error("failed to store output");
    }
    return Block.indexToAddress(idx);
  }
  length(addr) {
    const blockIdx = Block.addressToIndex(addr);
    const block = this.#blocks[blockIdx];
    if (!block) {
      return 0n;
    }
    return BigInt(block.buffer.byteLength);
  }
  setError(err = null) {
    const blockIdx = err ? this[STORE](err instanceof Error ? err.message : err) : 0;
    if (!blockIdx) {
      throw new Error("could not store error value");
    }
    this.#stack[this.#stack.length - 1][2] = blockIdx;
  }
  get logLevel() {
    return priorityToLogLevel(this.#logLevel);
  }
  set logLevel(v) {
    this.#logLevel = logLevelToPriority(v);
  }
  #handleLog(incomingLevel, level, addr) {
    const blockIdx = Block.addressToIndex(addr);
    const block = this.#blocks[blockIdx];
    if (!block) {
      this.#logger.error(
        `failed to log(${level}): bad block reference in addr 0x${addr.toString(16).padStart(64, "0")}`
      );
      return;
    }
    try {
      if (this.#logLevel <= incomingLevel) {
        const text = this.#decoder.decode(block.buffer);
        this.#logger[level](text);
      }
    } finally {
      this.#blocks[blockIdx] = null;
    }
  }
  get #input() {
    const idx = this.#stack[this.#stack.length - 1][0];
    if (idx === null) {
      return null;
    }
    return this.#blocks[idx];
  }
  [(_a = ENV, RESET)]() {
    this.#hostContext = null;
    this.#blocks.length = 1;
    this.#stack.length = 0;
  }
  [GET_BLOCK](index) {
    const block = this.#blocks[index];
    if (!block) {
      throw new Error(`invalid block index: ${index}`);
    }
    return block;
  }
  [IMPORT_STATE](state, copy = false) {
    for (let [buf, idx] of state.blocks) {
      if (buf && copy) {
        const dst = new Uint8Array(new this.#arrayBufferType(Number(buf.byteLength)));
        dst.set(new Uint8Array(buf));
        buf = dst.buffer;
      }
      this.#blocks[idx] = buf ? new Block(buf, false) : null;
    }
    this.#stack = state.stack;
  }
  [EXPORT_STATE]() {
    return {
      stack: this.#stack.slice(),
      blocks: this.#blocks.map((block, idx) => {
        if (!block) {
          return [null, idx];
        }
        if (block.local) {
          block.local = false;
          return [block.buffer, idx];
        }
        return null;
      }).filter(Boolean)
    };
  }
  [STORE](input) {
    if (typeof input === "string") {
      input = this.#encoder.encode(input);
    }
    if (!input) {
      return null;
    }
    if (input instanceof Uint8Array) {
      if (input.buffer.constructor === this.#arrayBufferType && input.byteOffset === 0 && input.byteLength === input.buffer.byteLength) {
        const idx2 = this.#blocks.length;
        this.#blocks.push(new Block(input.buffer, true));
        return idx2;
      }
      const idx = Block.addressToIndex(this.alloc(input.length));
      const block = this.#blocks[idx];
      const buf = new Uint8Array(block.buffer);
      buf.set(input, 0);
      return idx;
    }
    return input;
  }
  [SET_HOST_CONTEXT](hostContext) {
    this.#hostContext = hostContext;
  }
  [BEGIN](input) {
    this.#stack.push([input, null, null]);
  }
  [END]() {
    this.#hostContext = null;
    const [, outputIdx, errorIdx] = this.#stack.pop();
    const outputPosition = errorIdx === null ? 1 : 0;
    const idx = errorIdx ?? outputIdx;
    const result = [null, null];
    if (idx === null) {
      return result;
    }
    const block = this.#blocks[idx];
    if (block === null) {
      return result;
    }
    result[outputPosition] = idx;
    return result;
  }
};

// src/polyfills/node-wasi.ts
import { WASI } from "wasi";
import { devNull } from "node:os";
import { open } from "node:fs/promises";
import { closeSync } from "node:fs";
async function createDevNullFDs() {
  const [stdin, stdout] = await Promise.all([open(devNull, "r"), open(devNull, "w")]);
  let needsClose = true;
  let close = async () => {
    closeSync(stdin);
    closeSync(stdout);
  };
  if (typeof stdin !== "number") {
    const fr = new globalThis.FinalizationRegistry((held) => {
      try {
        if (needsClose)
          closeSync(held);
      } catch {
      }
    });
    fr.register(stdin, stdin.fd);
    fr.register(stdout, stdout.fd);
    close = async () => {
      needsClose = false;
      await Promise.all([stdin.close(), stdout.close()]).catch(() => {
      });
    };
  }
  return {
    close,
    fds: [stdin.fd, stdout.fd, stdout.fd]
  };
}
async function loadWasi(allowedPaths, enableWasiOutput) {
  const {
    close,
    fds: [stdin, stdout, stderr]
  } = enableWasiOutput ? { async close() {
  }, fds: [0, 1, 2] } : await createDevNullFDs();
  const context = new WASI({
    version: "preview1",
    preopens: allowedPaths,
    stdin,
    stdout,
    stderr
  });
  return {
    async importObject() {
      return context.wasiImport;
    },
    async close() {
      await close();
    },
    async initialize(instance) {
      const memory = instance.exports.memory;
      if (!memory) {
        throw new Error("The module has to export a default memory.");
      }
      if (instance.exports._initialize) {
        const init = instance.exports._initialize;
        if (context.initialize) {
          context.initialize({
            exports: {
              memory,
              _initialize: () => {
                init();
              }
            }
          });
        } else {
          init();
        }
      } else {
        context.start({
          exports: {
            memory,
            _start: () => {
            }
          }
        });
      }
    }
  };
}

// node_modules/minimatch/dist/mjs/index.js
var import_brace_expansion = __toESM(require_brace_expansion(), 1);

// node_modules/minimatch/dist/mjs/assert-valid-pattern.js
var MAX_PATTERN_LENGTH = 1024 * 64;
var assertValidPattern = (pattern) => {
  if (typeof pattern !== "string") {
    throw new TypeError("invalid pattern");
  }
  if (pattern.length > MAX_PATTERN_LENGTH) {
    throw new TypeError("pattern is too long");
  }
};

// node_modules/minimatch/dist/mjs/brace-expressions.js
var posixClasses = {
  "[:alnum:]": ["\\p{L}\\p{Nl}\\p{Nd}", true],
  "[:alpha:]": ["\\p{L}\\p{Nl}", true],
  "[:ascii:]": ["\\x00-\\x7f", false],
  "[:blank:]": ["\\p{Zs}\\t", true],
  "[:cntrl:]": ["\\p{Cc}", true],
  "[:digit:]": ["\\p{Nd}", true],
  "[:graph:]": ["\\p{Z}\\p{C}", true, true],
  "[:lower:]": ["\\p{Ll}", true],
  "[:print:]": ["\\p{C}", true],
  "[:punct:]": ["\\p{P}", true],
  "[:space:]": ["\\p{Z}\\t\\r\\n\\v\\f", true],
  "[:upper:]": ["\\p{Lu}", true],
  "[:word:]": ["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}", true],
  "[:xdigit:]": ["A-Fa-f0-9", false]
};
var braceEscape = (s) => s.replace(/[[\]\\-]/g, "\\$&");
var regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
var rangesToString = (ranges) => ranges.join("");
var parseClass = (glob, position) => {
  const pos = position;
  if (glob.charAt(pos) !== "[") {
    throw new Error("not in a brace expression");
  }
  const ranges = [];
  const negs = [];
  let i = pos + 1;
  let sawStart = false;
  let uflag = false;
  let escaping = false;
  let negate = false;
  let endPos = pos;
  let rangeStart = "";
  WHILE:
    while (i < glob.length) {
      const c = glob.charAt(i);
      if ((c === "!" || c === "^") && i === pos + 1) {
        negate = true;
        i++;
        continue;
      }
      if (c === "]" && sawStart && !escaping) {
        endPos = i + 1;
        break;
      }
      sawStart = true;
      if (c === "\\") {
        if (!escaping) {
          escaping = true;
          i++;
          continue;
        }
      }
      if (c === "[" && !escaping) {
        for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
          if (glob.startsWith(cls, i)) {
            if (rangeStart) {
              return ["$.", false, glob.length - pos, true];
            }
            i += cls.length;
            if (neg)
              negs.push(unip);
            else
              ranges.push(unip);
            uflag = uflag || u;
            continue WHILE;
          }
        }
      }
      escaping = false;
      if (rangeStart) {
        if (c > rangeStart) {
          ranges.push(braceEscape(rangeStart) + "-" + braceEscape(c));
        } else if (c === rangeStart) {
          ranges.push(braceEscape(c));
        }
        rangeStart = "";
        i++;
        continue;
      }
      if (glob.startsWith("-]", i + 1)) {
        ranges.push(braceEscape(c + "-"));
        i += 2;
        continue;
      }
      if (glob.startsWith("-", i + 1)) {
        rangeStart = c;
        i += 2;
        continue;
      }
      ranges.push(braceEscape(c));
      i++;
    }
  if (endPos < i) {
    return ["", false, 0, false];
  }
  if (!ranges.length && !negs.length) {
    return ["$.", false, glob.length - pos, true];
  }
  if (negs.length === 0 && ranges.length === 1 && /^\\?.$/.test(ranges[0]) && !negate) {
    const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
    return [regexpEscape(r), false, endPos - pos, false];
  }
  const sranges = "[" + (negate ? "^" : "") + rangesToString(ranges) + "]";
  const snegs = "[" + (negate ? "" : "^") + rangesToString(negs) + "]";
  const comb = ranges.length && negs.length ? "(" + sranges + "|" + snegs + ")" : ranges.length ? sranges : snegs;
  return [comb, uflag, endPos - pos, true];
};

// node_modules/minimatch/dist/mjs/unescape.js
var unescape = (s, { windowsPathsNoEscape = false } = {}) => {
  return windowsPathsNoEscape ? s.replace(/\[([^\/\\])\]/g, "$1") : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, "$1$2").replace(/\\([^\/])/g, "$1");
};

// node_modules/minimatch/dist/mjs/ast.js
var types = /* @__PURE__ */ new Set(["!", "?", "+", "*", "@"]);
var isExtglobType = (c) => types.has(c);
var startNoTraversal = "(?!(?:^|/)\\.\\.?(?:$|/))";
var startNoDot = "(?!\\.)";
var addPatternStart = /* @__PURE__ */ new Set(["[", "."]);
var justDots = /* @__PURE__ */ new Set(["..", "."]);
var reSpecials = new Set("().*{}+?[]^$\\!");
var regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
var qmark = "[^/]";
var star = qmark + "*?";
var starNoEmpty = qmark + "+?";
var _root, _hasMagic, _uflag, _parts, _parent, _parentIndex, _negs, _filledNegs, _options, _toString, _emptyExt, _fillNegs, fillNegs_fn, _parseAST, parseAST_fn, _partsToRegExp, partsToRegExp_fn, _parseGlob, parseGlob_fn;
var _AST = class {
  constructor(type, parent, options = {}) {
    __privateAdd(this, _fillNegs);
    __privateAdd(this, _partsToRegExp);
    __publicField(this, "type");
    __privateAdd(this, _root, void 0);
    __privateAdd(this, _hasMagic, void 0);
    __privateAdd(this, _uflag, false);
    __privateAdd(this, _parts, []);
    __privateAdd(this, _parent, void 0);
    __privateAdd(this, _parentIndex, void 0);
    __privateAdd(this, _negs, void 0);
    __privateAdd(this, _filledNegs, false);
    __privateAdd(this, _options, void 0);
    __privateAdd(this, _toString, void 0);
    __privateAdd(this, _emptyExt, false);
    this.type = type;
    if (type)
      __privateSet(this, _hasMagic, true);
    __privateSet(this, _parent, parent);
    __privateSet(this, _root, __privateGet(this, _parent) ? __privateGet(__privateGet(this, _parent), _root) : this);
    __privateSet(this, _options, __privateGet(this, _root) === this ? options : __privateGet(__privateGet(this, _root), _options));
    __privateSet(this, _negs, __privateGet(this, _root) === this ? [] : __privateGet(__privateGet(this, _root), _negs));
    if (type === "!" && !__privateGet(__privateGet(this, _root), _filledNegs))
      __privateGet(this, _negs).push(this);
    __privateSet(this, _parentIndex, __privateGet(this, _parent) ? __privateGet(__privateGet(this, _parent), _parts).length : 0);
  }
  get hasMagic() {
    if (__privateGet(this, _hasMagic) !== void 0)
      return __privateGet(this, _hasMagic);
    for (const p of __privateGet(this, _parts)) {
      if (typeof p === "string")
        continue;
      if (p.type || p.hasMagic)
        return __privateSet(this, _hasMagic, true);
    }
    return __privateGet(this, _hasMagic);
  }
  toString() {
    if (__privateGet(this, _toString) !== void 0)
      return __privateGet(this, _toString);
    if (!this.type) {
      return __privateSet(this, _toString, __privateGet(this, _parts).map((p) => String(p)).join(""));
    } else {
      return __privateSet(this, _toString, this.type + "(" + __privateGet(this, _parts).map((p) => String(p)).join("|") + ")");
    }
  }
  push(...parts) {
    for (const p of parts) {
      if (p === "")
        continue;
      if (typeof p !== "string" && !(p instanceof _AST && __privateGet(p, _parent) === this)) {
        throw new Error("invalid part: " + p);
      }
      __privateGet(this, _parts).push(p);
    }
  }
  toJSON() {
    const ret = this.type === null ? __privateGet(this, _parts).slice().map((p) => typeof p === "string" ? p : p.toJSON()) : [this.type, ...__privateGet(this, _parts).map((p) => p.toJSON())];
    if (this.isStart() && !this.type)
      ret.unshift([]);
    if (this.isEnd() && (this === __privateGet(this, _root) || __privateGet(__privateGet(this, _root), _filledNegs) && __privateGet(this, _parent)?.type === "!")) {
      ret.push({});
    }
    return ret;
  }
  isStart() {
    if (__privateGet(this, _root) === this)
      return true;
    if (!__privateGet(this, _parent)?.isStart())
      return false;
    if (__privateGet(this, _parentIndex) === 0)
      return true;
    const p = __privateGet(this, _parent);
    for (let i = 0; i < __privateGet(this, _parentIndex); i++) {
      const pp = __privateGet(p, _parts)[i];
      if (!(pp instanceof _AST && pp.type === "!")) {
        return false;
      }
    }
    return true;
  }
  isEnd() {
    if (__privateGet(this, _root) === this)
      return true;
    if (__privateGet(this, _parent)?.type === "!")
      return true;
    if (!__privateGet(this, _parent)?.isEnd())
      return false;
    if (!this.type)
      return __privateGet(this, _parent)?.isEnd();
    const pl = __privateGet(this, _parent) ? __privateGet(__privateGet(this, _parent), _parts).length : 0;
    return __privateGet(this, _parentIndex) === pl - 1;
  }
  copyIn(part) {
    if (typeof part === "string")
      this.push(part);
    else
      this.push(part.clone(this));
  }
  clone(parent) {
    const c = new _AST(this.type, parent);
    for (const p of __privateGet(this, _parts)) {
      c.copyIn(p);
    }
    return c;
  }
  static fromGlob(pattern, options = {}) {
    var _a2;
    const ast = new _AST(null, void 0, options);
    __privateMethod(_a2 = _AST, _parseAST, parseAST_fn).call(_a2, pattern, ast, 0, options);
    return ast;
  }
  toMMPattern() {
    if (this !== __privateGet(this, _root))
      return __privateGet(this, _root).toMMPattern();
    const glob = this.toString();
    const [re, body, hasMagic, uflag] = this.toRegExpSource();
    const anyMagic = hasMagic || __privateGet(this, _hasMagic) || __privateGet(this, _options).nocase && !__privateGet(this, _options).nocaseMagicOnly && glob.toUpperCase() !== glob.toLowerCase();
    if (!anyMagic) {
      return body;
    }
    const flags = (__privateGet(this, _options).nocase ? "i" : "") + (uflag ? "u" : "");
    return Object.assign(new RegExp(`^${re}$`, flags), {
      _src: re,
      _glob: glob
    });
  }
  toRegExpSource(allowDot) {
    const dot = allowDot ?? !!__privateGet(this, _options).dot;
    if (__privateGet(this, _root) === this)
      __privateMethod(this, _fillNegs, fillNegs_fn).call(this);
    if (!this.type) {
      const noEmpty = this.isStart() && this.isEnd();
      const src = __privateGet(this, _parts).map((p) => {
        var _a2;
        const [re, _, hasMagic, uflag] = typeof p === "string" ? __privateMethod(_a2 = _AST, _parseGlob, parseGlob_fn).call(_a2, p, __privateGet(this, _hasMagic), noEmpty) : p.toRegExpSource(allowDot);
        __privateSet(this, _hasMagic, __privateGet(this, _hasMagic) || hasMagic);
        __privateSet(this, _uflag, __privateGet(this, _uflag) || uflag);
        return re;
      }).join("");
      let start2 = "";
      if (this.isStart()) {
        if (typeof __privateGet(this, _parts)[0] === "string") {
          const dotTravAllowed = __privateGet(this, _parts).length === 1 && justDots.has(__privateGet(this, _parts)[0]);
          if (!dotTravAllowed) {
            const aps = addPatternStart;
            const needNoTrav = dot && aps.has(src.charAt(0)) || src.startsWith("\\.") && aps.has(src.charAt(2)) || src.startsWith("\\.\\.") && aps.has(src.charAt(4));
            const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));
            start2 = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : "";
          }
        }
      }
      let end = "";
      if (this.isEnd() && __privateGet(__privateGet(this, _root), _filledNegs) && __privateGet(this, _parent)?.type === "!") {
        end = "(?:$|\\/)";
      }
      const final2 = start2 + src + end;
      return [
        final2,
        unescape(src),
        __privateSet(this, _hasMagic, !!__privateGet(this, _hasMagic)),
        __privateGet(this, _uflag)
      ];
    }
    const repeated = this.type === "*" || this.type === "+";
    const start = this.type === "!" ? "(?:(?!(?:" : "(?:";
    let body = __privateMethod(this, _partsToRegExp, partsToRegExp_fn).call(this, dot);
    if (this.isStart() && this.isEnd() && !body && this.type !== "!") {
      const s = this.toString();
      __privateSet(this, _parts, [s]);
      this.type = null;
      __privateSet(this, _hasMagic, void 0);
      return [s, unescape(this.toString()), false, false];
    }
    let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot ? "" : __privateMethod(this, _partsToRegExp, partsToRegExp_fn).call(this, true);
    if (bodyDotAllowed === body) {
      bodyDotAllowed = "";
    }
    if (bodyDotAllowed) {
      body = `(?:${body})(?:${bodyDotAllowed})*?`;
    }
    let final = "";
    if (this.type === "!" && __privateGet(this, _emptyExt)) {
      final = (this.isStart() && !dot ? startNoDot : "") + starNoEmpty;
    } else {
      const close = this.type === "!" ? "))" + (this.isStart() && !dot && !allowDot ? startNoDot : "") + star + ")" : this.type === "@" ? ")" : this.type === "?" ? ")?" : this.type === "+" && bodyDotAllowed ? ")" : this.type === "*" && bodyDotAllowed ? `)?` : `)${this.type}`;
      final = start + body + close;
    }
    return [
      final,
      unescape(body),
      __privateSet(this, _hasMagic, !!__privateGet(this, _hasMagic)),
      __privateGet(this, _uflag)
    ];
  }
};
var AST = _AST;
_root = new WeakMap();
_hasMagic = new WeakMap();
_uflag = new WeakMap();
_parts = new WeakMap();
_parent = new WeakMap();
_parentIndex = new WeakMap();
_negs = new WeakMap();
_filledNegs = new WeakMap();
_options = new WeakMap();
_toString = new WeakMap();
_emptyExt = new WeakMap();
_fillNegs = new WeakSet();
fillNegs_fn = function() {
  if (this !== __privateGet(this, _root))
    throw new Error("should only call on root");
  if (__privateGet(this, _filledNegs))
    return this;
  this.toString();
  __privateSet(this, _filledNegs, true);
  let n;
  while (n = __privateGet(this, _negs).pop()) {
    if (n.type !== "!")
      continue;
    let p = n;
    let pp = __privateGet(p, _parent);
    while (pp) {
      for (let i = __privateGet(p, _parentIndex) + 1; !pp.type && i < __privateGet(pp, _parts).length; i++) {
        for (const part of __privateGet(n, _parts)) {
          if (typeof part === "string") {
            throw new Error("string part in extglob AST??");
          }
          part.copyIn(__privateGet(pp, _parts)[i]);
        }
      }
      p = pp;
      pp = __privateGet(p, _parent);
    }
  }
  return this;
};
_parseAST = new WeakSet();
parseAST_fn = function(str, ast, pos, opt) {
  var _a2, _b;
  let escaping = false;
  let inBrace = false;
  let braceStart = -1;
  let braceNeg = false;
  if (ast.type === null) {
    let i2 = pos;
    let acc2 = "";
    while (i2 < str.length) {
      const c = str.charAt(i2++);
      if (escaping || c === "\\") {
        escaping = !escaping;
        acc2 += c;
        continue;
      }
      if (inBrace) {
        if (i2 === braceStart + 1) {
          if (c === "^" || c === "!") {
            braceNeg = true;
          }
        } else if (c === "]" && !(i2 === braceStart + 2 && braceNeg)) {
          inBrace = false;
        }
        acc2 += c;
        continue;
      } else if (c === "[") {
        inBrace = true;
        braceStart = i2;
        braceNeg = false;
        acc2 += c;
        continue;
      }
      if (!opt.noext && isExtglobType(c) && str.charAt(i2) === "(") {
        ast.push(acc2);
        acc2 = "";
        const ext2 = new _AST(c, ast);
        i2 = __privateMethod(_a2 = _AST, _parseAST, parseAST_fn).call(_a2, str, ext2, i2, opt);
        ast.push(ext2);
        continue;
      }
      acc2 += c;
    }
    ast.push(acc2);
    return i2;
  }
  let i = pos + 1;
  let part = new _AST(null, ast);
  const parts = [];
  let acc = "";
  while (i < str.length) {
    const c = str.charAt(i++);
    if (escaping || c === "\\") {
      escaping = !escaping;
      acc += c;
      continue;
    }
    if (inBrace) {
      if (i === braceStart + 1) {
        if (c === "^" || c === "!") {
          braceNeg = true;
        }
      } else if (c === "]" && !(i === braceStart + 2 && braceNeg)) {
        inBrace = false;
      }
      acc += c;
      continue;
    } else if (c === "[") {
      inBrace = true;
      braceStart = i;
      braceNeg = false;
      acc += c;
      continue;
    }
    if (isExtglobType(c) && str.charAt(i) === "(") {
      part.push(acc);
      acc = "";
      const ext2 = new _AST(c, part);
      part.push(ext2);
      i = __privateMethod(_b = _AST, _parseAST, parseAST_fn).call(_b, str, ext2, i, opt);
      continue;
    }
    if (c === "|") {
      part.push(acc);
      acc = "";
      parts.push(part);
      part = new _AST(null, ast);
      continue;
    }
    if (c === ")") {
      if (acc === "" && __privateGet(ast, _parts).length === 0) {
        __privateSet(ast, _emptyExt, true);
      }
      part.push(acc);
      acc = "";
      ast.push(...parts, part);
      return i;
    }
    acc += c;
  }
  ast.type = null;
  __privateSet(ast, _hasMagic, void 0);
  __privateSet(ast, _parts, [str.substring(pos - 1)]);
  return i;
};
_partsToRegExp = new WeakSet();
partsToRegExp_fn = function(dot) {
  return __privateGet(this, _parts).map((p) => {
    if (typeof p === "string") {
      throw new Error("string type in extglob ast??");
    }
    const [re, _, _hasMagic2, uflag] = p.toRegExpSource(dot);
    __privateSet(this, _uflag, __privateGet(this, _uflag) || uflag);
    return re;
  }).filter((p) => !(this.isStart() && this.isEnd()) || !!p).join("|");
};
_parseGlob = new WeakSet();
parseGlob_fn = function(glob, hasMagic, noEmpty = false) {
  let escaping = false;
  let re = "";
  let uflag = false;
  for (let i = 0; i < glob.length; i++) {
    const c = glob.charAt(i);
    if (escaping) {
      escaping = false;
      re += (reSpecials.has(c) ? "\\" : "") + c;
      continue;
    }
    if (c === "\\") {
      if (i === glob.length - 1) {
        re += "\\\\";
      } else {
        escaping = true;
      }
      continue;
    }
    if (c === "[") {
      const [src, needUflag, consumed, magic] = parseClass(glob, i);
      if (consumed) {
        re += src;
        uflag = uflag || needUflag;
        i += consumed - 1;
        hasMagic = hasMagic || magic;
        continue;
      }
    }
    if (c === "*") {
      if (noEmpty && glob === "*")
        re += starNoEmpty;
      else
        re += star;
      hasMagic = true;
      continue;
    }
    if (c === "?") {
      re += qmark;
      hasMagic = true;
      continue;
    }
    re += regExpEscape(c);
  }
  return [re, unescape(glob), !!hasMagic, uflag];
};
__privateAdd(AST, _parseAST);
__privateAdd(AST, _parseGlob);

// node_modules/minimatch/dist/mjs/escape.js
var escape = (s, { windowsPathsNoEscape = false } = {}) => {
  return windowsPathsNoEscape ? s.replace(/[?*()[\]]/g, "[$&]") : s.replace(/[?*()[\]\\]/g, "\\$&");
};

// node_modules/minimatch/dist/mjs/index.js
var minimatch = (p, pattern, options = {}) => {
  assertValidPattern(pattern);
  if (!options.nocomment && pattern.charAt(0) === "#") {
    return false;
  }
  return new Minimatch(pattern, options).match(p);
};
var starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/;
var starDotExtTest = (ext2) => (f) => !f.startsWith(".") && f.endsWith(ext2);
var starDotExtTestDot = (ext2) => (f) => f.endsWith(ext2);
var starDotExtTestNocase = (ext2) => {
  ext2 = ext2.toLowerCase();
  return (f) => !f.startsWith(".") && f.toLowerCase().endsWith(ext2);
};
var starDotExtTestNocaseDot = (ext2) => {
  ext2 = ext2.toLowerCase();
  return (f) => f.toLowerCase().endsWith(ext2);
};
var starDotStarRE = /^\*+\.\*+$/;
var starDotStarTest = (f) => !f.startsWith(".") && f.includes(".");
var starDotStarTestDot = (f) => f !== "." && f !== ".." && f.includes(".");
var dotStarRE = /^\.\*+$/;
var dotStarTest = (f) => f !== "." && f !== ".." && f.startsWith(".");
var starRE = /^\*+$/;
var starTest = (f) => f.length !== 0 && !f.startsWith(".");
var starTestDot = (f) => f.length !== 0 && f !== "." && f !== "..";
var qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
var qmarksTestNocase = ([$0, ext2 = ""]) => {
  const noext = qmarksTestNoExt([$0]);
  if (!ext2)
    return noext;
  ext2 = ext2.toLowerCase();
  return (f) => noext(f) && f.toLowerCase().endsWith(ext2);
};
var qmarksTestNocaseDot = ([$0, ext2 = ""]) => {
  const noext = qmarksTestNoExtDot([$0]);
  if (!ext2)
    return noext;
  ext2 = ext2.toLowerCase();
  return (f) => noext(f) && f.toLowerCase().endsWith(ext2);
};
var qmarksTestDot = ([$0, ext2 = ""]) => {
  const noext = qmarksTestNoExtDot([$0]);
  return !ext2 ? noext : (f) => noext(f) && f.endsWith(ext2);
};
var qmarksTest = ([$0, ext2 = ""]) => {
  const noext = qmarksTestNoExt([$0]);
  return !ext2 ? noext : (f) => noext(f) && f.endsWith(ext2);
};
var qmarksTestNoExt = ([$0]) => {
  const len = $0.length;
  return (f) => f.length === len && !f.startsWith(".");
};
var qmarksTestNoExtDot = ([$0]) => {
  const len = $0.length;
  return (f) => f.length === len && f !== "." && f !== "..";
};
var defaultPlatform = typeof process === "object" && process ? typeof process.env === "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix";
var path = {
  win32: { sep: "\\" },
  posix: { sep: "/" }
};
var sep = defaultPlatform === "win32" ? path.win32.sep : path.posix.sep;
minimatch.sep = sep;
var GLOBSTAR = Symbol("globstar **");
minimatch.GLOBSTAR = GLOBSTAR;
var qmark2 = "[^/]";
var star2 = qmark2 + "*?";
var twoStarDot = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";
var twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?";
var filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options);
minimatch.filter = filter;
var ext = (a, b = {}) => Object.assign({}, a, b);
var defaults = (def) => {
  if (!def || typeof def !== "object" || !Object.keys(def).length) {
    return minimatch;
  }
  const orig = minimatch;
  const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));
  return Object.assign(m, {
    Minimatch: class Minimatch extends orig.Minimatch {
      constructor(pattern, options = {}) {
        super(pattern, ext(def, options));
      }
      static defaults(options) {
        return orig.defaults(ext(def, options)).Minimatch;
      }
    },
    AST: class AST extends orig.AST {
      constructor(type, parent, options = {}) {
        super(type, parent, ext(def, options));
      }
      static fromGlob(pattern, options = {}) {
        return orig.AST.fromGlob(pattern, ext(def, options));
      }
    },
    unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),
    escape: (s, options = {}) => orig.escape(s, ext(def, options)),
    filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
    defaults: (options) => orig.defaults(ext(def, options)),
    makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
    braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
    match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
    sep: orig.sep,
    GLOBSTAR
  });
};
minimatch.defaults = defaults;
var braceExpand = (pattern, options = {}) => {
  assertValidPattern(pattern);
  if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
    return [pattern];
  }
  return (0, import_brace_expansion.default)(pattern);
};
minimatch.braceExpand = braceExpand;
var makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
minimatch.makeRe = makeRe;
var match = (list, pattern, options = {}) => {
  const mm = new Minimatch(pattern, options);
  list = list.filter((f) => mm.match(f));
  if (mm.options.nonull && !list.length) {
    list.push(pattern);
  }
  return list;
};
minimatch.match = match;
var globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
var regExpEscape2 = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
var Minimatch = class {
  options;
  set;
  pattern;
  windowsPathsNoEscape;
  nonegate;
  negate;
  comment;
  empty;
  preserveMultipleSlashes;
  partial;
  globSet;
  globParts;
  nocase;
  isWindows;
  platform;
  windowsNoMagicRoot;
  regexp;
  constructor(pattern, options = {}) {
    assertValidPattern(pattern);
    options = options || {};
    this.options = options;
    this.pattern = pattern;
    this.platform = options.platform || defaultPlatform;
    this.isWindows = this.platform === "win32";
    this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
    if (this.windowsPathsNoEscape) {
      this.pattern = this.pattern.replace(/\\/g, "/");
    }
    this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
    this.regexp = null;
    this.negate = false;
    this.nonegate = !!options.nonegate;
    this.comment = false;
    this.empty = false;
    this.partial = !!options.partial;
    this.nocase = !!this.options.nocase;
    this.windowsNoMagicRoot = options.windowsNoMagicRoot !== void 0 ? options.windowsNoMagicRoot : !!(this.isWindows && this.nocase);
    this.globSet = [];
    this.globParts = [];
    this.set = [];
    this.make();
  }
  hasMagic() {
    if (this.options.magicalBraces && this.set.length > 1) {
      return true;
    }
    for (const pattern of this.set) {
      for (const part of pattern) {
        if (typeof part !== "string")
          return true;
      }
    }
    return false;
  }
  debug(..._) {
  }
  make() {
    const pattern = this.pattern;
    const options = this.options;
    if (!options.nocomment && pattern.charAt(0) === "#") {
      this.comment = true;
      return;
    }
    if (!pattern) {
      this.empty = true;
      return;
    }
    this.parseNegate();
    this.globSet = [...new Set(this.braceExpand())];
    if (options.debug) {
      this.debug = (...args) => console.error(...args);
    }
    this.debug(this.pattern, this.globSet);
    const rawGlobParts = this.globSet.map((s) => this.slashSplit(s));
    this.globParts = this.preprocess(rawGlobParts);
    this.debug(this.pattern, this.globParts);
    let set = this.globParts.map((s, _, __) => {
      if (this.isWindows && this.windowsNoMagicRoot) {
        const isUNC = s[0] === "" && s[1] === "" && (s[2] === "?" || !globMagic.test(s[2])) && !globMagic.test(s[3]);
        const isDrive = /^[a-z]:/i.test(s[0]);
        if (isUNC) {
          return [...s.slice(0, 4), ...s.slice(4).map((ss) => this.parse(ss))];
        } else if (isDrive) {
          return [s[0], ...s.slice(1).map((ss) => this.parse(ss))];
        }
      }
      return s.map((ss) => this.parse(ss));
    });
    this.debug(this.pattern, set);
    this.set = set.filter((s) => s.indexOf(false) === -1);
    if (this.isWindows) {
      for (let i = 0; i < this.set.length; i++) {
        const p = this.set[i];
        if (p[0] === "" && p[1] === "" && this.globParts[i][2] === "?" && typeof p[3] === "string" && /^[a-z]:$/i.test(p[3])) {
          p[2] = "?";
        }
      }
    }
    this.debug(this.pattern, this.set);
  }
  preprocess(globParts) {
    if (this.options.noglobstar) {
      for (let i = 0; i < globParts.length; i++) {
        for (let j = 0; j < globParts[i].length; j++) {
          if (globParts[i][j] === "**") {
            globParts[i][j] = "*";
          }
        }
      }
    }
    const { optimizationLevel = 1 } = this.options;
    if (optimizationLevel >= 2) {
      globParts = this.firstPhasePreProcess(globParts);
      globParts = this.secondPhasePreProcess(globParts);
    } else if (optimizationLevel >= 1) {
      globParts = this.levelOneOptimize(globParts);
    } else {
      globParts = this.adjascentGlobstarOptimize(globParts);
    }
    return globParts;
  }
  adjascentGlobstarOptimize(globParts) {
    return globParts.map((parts) => {
      let gs = -1;
      while (-1 !== (gs = parts.indexOf("**", gs + 1))) {
        let i = gs;
        while (parts[i + 1] === "**") {
          i++;
        }
        if (i !== gs) {
          parts.splice(gs, i - gs);
        }
      }
      return parts;
    });
  }
  levelOneOptimize(globParts) {
    return globParts.map((parts) => {
      parts = parts.reduce((set, part) => {
        const prev = set[set.length - 1];
        if (part === "**" && prev === "**") {
          return set;
        }
        if (part === "..") {
          if (prev && prev !== ".." && prev !== "." && prev !== "**") {
            set.pop();
            return set;
          }
        }
        set.push(part);
        return set;
      }, []);
      return parts.length === 0 ? [""] : parts;
    });
  }
  levelTwoFileOptimize(parts) {
    if (!Array.isArray(parts)) {
      parts = this.slashSplit(parts);
    }
    let didSomething = false;
    do {
      didSomething = false;
      if (!this.preserveMultipleSlashes) {
        for (let i = 1; i < parts.length - 1; i++) {
          const p = parts[i];
          if (i === 1 && p === "" && parts[0] === "")
            continue;
          if (p === "." || p === "") {
            didSomething = true;
            parts.splice(i, 1);
            i--;
          }
        }
        if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {
          didSomething = true;
          parts.pop();
        }
      }
      let dd = 0;
      while (-1 !== (dd = parts.indexOf("..", dd + 1))) {
        const p = parts[dd - 1];
        if (p && p !== "." && p !== ".." && p !== "**") {
          didSomething = true;
          parts.splice(dd - 1, 2);
          dd -= 2;
        }
      }
    } while (didSomething);
    return parts.length === 0 ? [""] : parts;
  }
  firstPhasePreProcess(globParts) {
    let didSomething = false;
    do {
      didSomething = false;
      for (let parts of globParts) {
        let gs = -1;
        while (-1 !== (gs = parts.indexOf("**", gs + 1))) {
          let gss = gs;
          while (parts[gss + 1] === "**") {
            gss++;
          }
          if (gss > gs) {
            parts.splice(gs + 1, gss - gs);
          }
          let next = parts[gs + 1];
          const p = parts[gs + 2];
          const p2 = parts[gs + 3];
          if (next !== "..")
            continue;
          if (!p || p === "." || p === ".." || !p2 || p2 === "." || p2 === "..") {
            continue;
          }
          didSomething = true;
          parts.splice(gs, 1);
          const other = parts.slice(0);
          other[gs] = "**";
          globParts.push(other);
          gs--;
        }
        if (!this.preserveMultipleSlashes) {
          for (let i = 1; i < parts.length - 1; i++) {
            const p = parts[i];
            if (i === 1 && p === "" && parts[0] === "")
              continue;
            if (p === "." || p === "") {
              didSomething = true;
              parts.splice(i, 1);
              i--;
            }
          }
          if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {
            didSomething = true;
            parts.pop();
          }
        }
        let dd = 0;
        while (-1 !== (dd = parts.indexOf("..", dd + 1))) {
          const p = parts[dd - 1];
          if (p && p !== "." && p !== ".." && p !== "**") {
            didSomething = true;
            const needDot = dd === 1 && parts[dd + 1] === "**";
            const splin = needDot ? ["."] : [];
            parts.splice(dd - 1, 2, ...splin);
            if (parts.length === 0)
              parts.push("");
            dd -= 2;
          }
        }
      }
    } while (didSomething);
    return globParts;
  }
  secondPhasePreProcess(globParts) {
    for (let i = 0; i < globParts.length - 1; i++) {
      for (let j = i + 1; j < globParts.length; j++) {
        const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
        if (!matched)
          continue;
        globParts[i] = matched;
        globParts[j] = [];
      }
    }
    return globParts.filter((gs) => gs.length);
  }
  partsMatch(a, b, emptyGSMatch = false) {
    let ai = 0;
    let bi = 0;
    let result = [];
    let which = "";
    while (ai < a.length && bi < b.length) {
      if (a[ai] === b[bi]) {
        result.push(which === "b" ? b[bi] : a[ai]);
        ai++;
        bi++;
      } else if (emptyGSMatch && a[ai] === "**" && b[bi] === a[ai + 1]) {
        result.push(a[ai]);
        ai++;
      } else if (emptyGSMatch && b[bi] === "**" && a[ai] === b[bi + 1]) {
        result.push(b[bi]);
        bi++;
      } else if (a[ai] === "*" && b[bi] && (this.options.dot || !b[bi].startsWith(".")) && b[bi] !== "**") {
        if (which === "b")
          return false;
        which = "a";
        result.push(a[ai]);
        ai++;
        bi++;
      } else if (b[bi] === "*" && a[ai] && (this.options.dot || !a[ai].startsWith(".")) && a[ai] !== "**") {
        if (which === "a")
          return false;
        which = "b";
        result.push(b[bi]);
        ai++;
        bi++;
      } else {
        return false;
      }
    }
    return a.length === b.length && result;
  }
  parseNegate() {
    if (this.nonegate)
      return;
    const pattern = this.pattern;
    let negate = false;
    let negateOffset = 0;
    for (let i = 0; i < pattern.length && pattern.charAt(i) === "!"; i++) {
      negate = !negate;
      negateOffset++;
    }
    if (negateOffset)
      this.pattern = pattern.slice(negateOffset);
    this.negate = negate;
  }
  matchOne(file, pattern, partial = false) {
    const options = this.options;
    if (this.isWindows) {
      const fileDrive = typeof file[0] === "string" && /^[a-z]:$/i.test(file[0]);
      const fileUNC = !fileDrive && file[0] === "" && file[1] === "" && file[2] === "?" && /^[a-z]:$/i.test(file[3]);
      const patternDrive = typeof pattern[0] === "string" && /^[a-z]:$/i.test(pattern[0]);
      const patternUNC = !patternDrive && pattern[0] === "" && pattern[1] === "" && pattern[2] === "?" && typeof pattern[3] === "string" && /^[a-z]:$/i.test(pattern[3]);
      const fdi = fileUNC ? 3 : fileDrive ? 0 : void 0;
      const pdi = patternUNC ? 3 : patternDrive ? 0 : void 0;
      if (typeof fdi === "number" && typeof pdi === "number") {
        const [fd, pd] = [file[fdi], pattern[pdi]];
        if (fd.toLowerCase() === pd.toLowerCase()) {
          pattern[pdi] = fd;
          if (pdi > fdi) {
            pattern = pattern.slice(pdi);
          } else if (fdi > pdi) {
            file = file.slice(fdi);
          }
        }
      }
    }
    const { optimizationLevel = 1 } = this.options;
    if (optimizationLevel >= 2) {
      file = this.levelTwoFileOptimize(file);
    }
    this.debug("matchOne", this, { file, pattern });
    this.debug("matchOne", file.length, pattern.length);
    for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
      this.debug("matchOne loop");
      var p = pattern[pi];
      var f = file[fi];
      this.debug(pattern, p, f);
      if (p === false) {
        return false;
      }
      if (p === GLOBSTAR) {
        this.debug("GLOBSTAR", [pattern, p, f]);
        var fr = fi;
        var pr = pi + 1;
        if (pr === pl) {
          this.debug("** at the end");
          for (; fi < fl; fi++) {
            if (file[fi] === "." || file[fi] === ".." || !options.dot && file[fi].charAt(0) === ".")
              return false;
          }
          return true;
        }
        while (fr < fl) {
          var swallowee = file[fr];
          this.debug("\nglobstar while", file, fr, pattern, pr, swallowee);
          if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
            this.debug("globstar found match!", fr, fl, swallowee);
            return true;
          } else {
            if (swallowee === "." || swallowee === ".." || !options.dot && swallowee.charAt(0) === ".") {
              this.debug("dot detected!", file, fr, pattern, pr);
              break;
            }
            this.debug("globstar swallow a segment, and continue");
            fr++;
          }
        }
        if (partial) {
          this.debug("\n>>> no match, partial?", file, fr, pattern, pr);
          if (fr === fl) {
            return true;
          }
        }
        return false;
      }
      let hit;
      if (typeof p === "string") {
        hit = f === p;
        this.debug("string match", p, f, hit);
      } else {
        hit = p.test(f);
        this.debug("pattern match", p, f, hit);
      }
      if (!hit)
        return false;
    }
    if (fi === fl && pi === pl) {
      return true;
    } else if (fi === fl) {
      return partial;
    } else if (pi === pl) {
      return fi === fl - 1 && file[fi] === "";
    } else {
      throw new Error("wtf?");
    }
  }
  braceExpand() {
    return braceExpand(this.pattern, this.options);
  }
  parse(pattern) {
    assertValidPattern(pattern);
    const options = this.options;
    if (pattern === "**")
      return GLOBSTAR;
    if (pattern === "")
      return "";
    let m;
    let fastTest = null;
    if (m = pattern.match(starRE)) {
      fastTest = options.dot ? starTestDot : starTest;
    } else if (m = pattern.match(starDotExtRE)) {
      fastTest = (options.nocase ? options.dot ? starDotExtTestNocaseDot : starDotExtTestNocase : options.dot ? starDotExtTestDot : starDotExtTest)(m[1]);
    } else if (m = pattern.match(qmarksRE)) {
      fastTest = (options.nocase ? options.dot ? qmarksTestNocaseDot : qmarksTestNocase : options.dot ? qmarksTestDot : qmarksTest)(m);
    } else if (m = pattern.match(starDotStarRE)) {
      fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
    } else if (m = pattern.match(dotStarRE)) {
      fastTest = dotStarTest;
    }
    const re = AST.fromGlob(pattern, this.options).toMMPattern();
    return fastTest ? Object.assign(re, { test: fastTest }) : re;
  }
  makeRe() {
    if (this.regexp || this.regexp === false)
      return this.regexp;
    const set = this.set;
    if (!set.length) {
      this.regexp = false;
      return this.regexp;
    }
    const options = this.options;
    const twoStar = options.noglobstar ? star2 : options.dot ? twoStarDot : twoStarNoDot;
    const flags = new Set(options.nocase ? ["i"] : []);
    let re = set.map((pattern) => {
      const pp = pattern.map((p) => {
        if (p instanceof RegExp) {
          for (const f of p.flags.split(""))
            flags.add(f);
        }
        return typeof p === "string" ? regExpEscape2(p) : p === GLOBSTAR ? GLOBSTAR : p._src;
      });
      pp.forEach((p, i) => {
        const next = pp[i + 1];
        const prev = pp[i - 1];
        if (p !== GLOBSTAR || prev === GLOBSTAR) {
          return;
        }
        if (prev === void 0) {
          if (next !== void 0 && next !== GLOBSTAR) {
            pp[i + 1] = "(?:\\/|" + twoStar + "\\/)?" + next;
          } else {
            pp[i] = twoStar;
          }
        } else if (next === void 0) {
          pp[i - 1] = prev + "(?:\\/|" + twoStar + ")?";
        } else if (next !== GLOBSTAR) {
          pp[i - 1] = prev + "(?:\\/|\\/" + twoStar + "\\/)" + next;
          pp[i + 1] = GLOBSTAR;
        }
      });
      return pp.filter((p) => p !== GLOBSTAR).join("/");
    }).join("|");
    const [open2, close] = set.length > 1 ? ["(?:", ")"] : ["", ""];
    re = "^" + open2 + re + close + "$";
    if (this.negate)
      re = "^(?!" + re + ").+$";
    try {
      this.regexp = new RegExp(re, [...flags].join(""));
    } catch (ex) {
      this.regexp = false;
    }
    return this.regexp;
  }
  slashSplit(p) {
    if (this.preserveMultipleSlashes) {
      return p.split("/");
    } else if (this.isWindows && /^\/\/[^\/]+/.test(p)) {
      return ["", ...p.split(/\/+/)];
    } else {
      return p.split(/\/+/);
    }
  }
  match(f, partial = this.partial) {
    this.debug("match", f, this.pattern);
    if (this.comment) {
      return false;
    }
    if (this.empty) {
      return f === "";
    }
    if (f === "/" && partial) {
      return true;
    }
    const options = this.options;
    if (this.isWindows) {
      f = f.split("\\").join("/");
    }
    const ff = this.slashSplit(f);
    this.debug(this.pattern, "split", ff);
    const set = this.set;
    this.debug(this.pattern, "set", set);
    let filename = ff[ff.length - 1];
    if (!filename) {
      for (let i = ff.length - 2; !filename && i >= 0; i--) {
        filename = ff[i];
      }
    }
    for (let i = 0; i < set.length; i++) {
      const pattern = set[i];
      let file = ff;
      if (options.matchBase && pattern.length === 1) {
        file = [filename];
      }
      const hit = this.matchOne(file, pattern, partial);
      if (hit) {
        if (options.flipNegate) {
          return true;
        }
        return !this.negate;
      }
    }
    if (options.flipNegate) {
      return false;
    }
    return this.negate;
  }
  static defaults(def) {
    return minimatch.defaults(def).Minimatch;
  }
};
minimatch.AST = AST;
minimatch.Minimatch = Minimatch;
minimatch.escape = escape;
minimatch.unescape = unescape;

// src/polyfills/node-minimatch.ts
function matches(text, pattern) {
  return minimatch(text, pattern);
}

// src/http-context.ts
var HttpContext = class {
  constructor(_fetch, allowedHosts, memoryOptions, allowResponseHeaders) {
    this.fetch = _fetch;
    this.allowedHosts = allowedHosts;
    this.lastStatusCode = 0;
    this.memoryOptions = memoryOptions;
    this.lastHeaders = allowResponseHeaders ? {} : null;
  }
  contribute(functions) {
    functions[EXTISM_ENV] ??= {};
    functions[EXTISM_ENV].http_request = (callContext, reqaddr, bodyaddr) => this.makeRequest(callContext, reqaddr, bodyaddr);
    functions[EXTISM_ENV].http_status_code = () => this.lastStatusCode;
    functions[EXTISM_ENV].http_headers = (callContext) => {
      if (this.lastHeaders === null) {
        return 0n;
      }
      return callContext.store(JSON.stringify(this.lastHeaders));
    };
  }
  async makeRequest(callContext, reqaddr, bodyaddr) {
    if (this.lastHeaders !== null) {
      this.lastHeaders = {};
    }
    this.lastStatusCode = 0;
    const req = callContext.read(reqaddr);
    if (req === null) {
      return 0n;
    }
    const { headers, header, url: rawUrl, method: m } = req.json();
    const method = m?.toUpperCase() ?? "GET";
    const url = new URL(rawUrl);
    const isAllowed = this.allowedHosts.some((allowedHost) => {
      return allowedHost === url.hostname || matches(url.hostname, allowedHost);
    });
    if (!isAllowed) {
      throw new Error(`Call error: HTTP request to "${url}" is not allowed (no allowedHosts match "${url.hostname}")`);
    }
    const body = bodyaddr === 0n || method === "GET" || method === "HEAD" ? null : callContext.read(bodyaddr)?.bytes();
    const fetch2 = this.fetch;
    const response = await fetch2(rawUrl, {
      headers: headers || header,
      method,
      ...body ? { body: body.slice() } : {}
    });
    this.lastStatusCode = response.status;
    if (this.lastHeaders !== null) {
      this.lastHeaders = Object.fromEntries(response.headers);
    }
    try {
      const bytes = this.memoryOptions.maxHttpResponseBytes ? await readBodyUpTo(response, this.memoryOptions.maxHttpResponseBytes) : new Uint8Array(await response.arrayBuffer());
      const result = callContext.store(bytes);
      return result;
    } catch (err) {
      if (err instanceof Error) {
        const ptr = callContext.store(new TextEncoder().encode(err.message));
        callContext[ENV].log_error(ptr);
        return 0n;
      }
      return 0n;
    }
  }
};
async function readBodyUpTo(response, maxBytes) {
  const reader = response.body?.getReader();
  if (!reader) {
    return new Uint8Array(0);
  }
  let receivedLength = 0;
  const chunks = [];
  while (receivedLength < maxBytes) {
    const { done, value } = await reader.read();
    if (done) {
      break;
    }
    chunks.push(value);
    receivedLength += value.length;
    if (receivedLength >= maxBytes) {
      throw new Error(`Response body exceeded ${maxBytes} bytes`);
    }
  }
  const limitedResponseBody = new Uint8Array(receivedLength);
  let position = 0;
  for (const chunk of chunks) {
    limitedResponseBody.set(chunk, position);
    position += chunk.length;
  }
  return limitedResponseBody;
}

// src/foreground-plugin.ts
var EXTISM_ENV = "extism:host/env";
var AsyncFunction = (async () => {
}).constructor;
var Suspending = WebAssembly.Suspending;
var promising = WebAssembly.promising;
var ForegroundPlugin = class {
  #context;
  #instancePair;
  #active = false;
  #wasi;
  #opts;
  #suspendsOnInvoke;
  constructor(opts, context, instancePair, wasi, suspendsOnInvoke) {
    this.#context = context;
    this.#instancePair = instancePair;
    this.#wasi = wasi;
    this.#opts = opts;
    this.#suspendsOnInvoke = suspendsOnInvoke;
  }
  async reset() {
    if (this.isActive()) {
      return false;
    }
    this.#context[RESET]();
    return true;
  }
  isActive() {
    return this.#active;
  }
  async functionExists(funcName) {
    return typeof this.#instancePair[1].exports[funcName] === "function";
  }
  async callBlock(funcName, input) {
    this.#active = true;
    const func = this.#instancePair[1].exports[funcName];
    if (!func) {
      throw Error(`Plugin error: function "${funcName}" does not exist`);
    }
    if (typeof func !== "function") {
      throw Error(`Plugin error: export "${funcName}" is not a function`);
    }
    this.#context[BEGIN](input ?? null);
    try {
      this.#suspendsOnInvoke ? await promising(func)() : func();
      return this.#context[END]();
    } catch (err) {
      this.#context[END]();
      throw err;
    } finally {
      this.#active = false;
    }
  }
  async call(funcName, input, hostContext) {
    this.#context[RESET]();
    const inputIdx = this.#context[STORE](input);
    this.#context[SET_HOST_CONTEXT](hostContext);
    const [errorIdx, outputIdx] = await this.callBlock(funcName, inputIdx);
    const shouldThrow = errorIdx !== null;
    const idx = errorIdx ?? outputIdx;
    if (idx === null) {
      return null;
    }
    const block = this.#context[GET_BLOCK](idx);
    if (!block) {
      return null;
    }
    const output = new PluginOutput(block.buffer);
    if (shouldThrow) {
      throw new Error(`Plugin-originated error: ${output.string()}`);
    }
    return output;
  }
  async getExports() {
    return WebAssembly.Module.exports(this.#instancePair[0]) || [];
  }
  async getImports() {
    return WebAssembly.Module.imports(this.#instancePair[0]) || [];
  }
  async getInstance() {
    return this.#instancePair[1];
  }
  async close() {
    await Promise.all(this.#wasi.map((xs) => xs.close()));
    this.#wasi.length = 0;
  }
};
async function createForegroundPlugin(opts, names, modules, context = new CallContext(ArrayBuffer, opts.logger, opts.logLevel, opts.config, opts.memory)) {
  const imports = {
    [EXTISM_ENV]: context[ENV],
    env: {}
  };
  let suspendsOnInvoke = false;
  for (const namespace in opts.functions) {
    imports[namespace] = imports[namespace] || {};
    for (const [name, func] of Object.entries(opts.functions[namespace])) {
      const isAsync = func.constructor === AsyncFunction;
      suspendsOnInvoke ||= isAsync;
      const wrapped = func.bind(null, context);
      imports[namespace][name] = isAsync ? new Suspending(wrapped) : wrapped;
    }
  }
  if (suspendsOnInvoke && (!Suspending || !promising)) {
    throw new TypeError(
      "This platform does not support async function imports on the main thread; consider using `runInWorker`."
    );
  }
  const mainIndex = names.indexOf("main");
  if (mainIndex === -1) {
    throw new Error('Unreachable: manifests must have at least one "main" module. Enforced by "src/manifest.ts")');
  }
  const seen = /* @__PURE__ */ new Map();
  const wasiList = [];
  const mutableFlags = { suspendsOnInvoke };
  const instance = await instantiateModule(
    context,
    ["main"],
    modules[mainIndex],
    imports,
    opts,
    wasiList,
    names,
    modules,
    seen,
    mutableFlags
  );
  return new ForegroundPlugin(opts, context, [modules[mainIndex], instance], wasiList, mutableFlags.suspendsOnInvoke);
}
async function instantiateModule(context, current, module, imports, opts, wasiList, names, modules, linked, mutableFlags) {
  linked.set(module, null);
  const instantiationImports = {};
  const requested = WebAssembly.Module.imports(module);
  let wasi = null;
  for (const { kind, module: module2, name } of requested) {
    const nameIdx = names.indexOf(module2);
    if (nameIdx === -1) {
      if (module2 === "wasi_snapshot_preview1" && wasi === null) {
        if (!CAPABILITIES.supportsWasiPreview1) {
          throw new Error("WASI is not supported on this platform");
        }
        if (!opts.wasiEnabled) {
          throw new Error('WASI is not enabled; see the "useWasi" plugin option');
        }
        if (wasi === null) {
          wasi = await loadWasi(opts.allowedPaths, opts.enableWasiOutput);
          wasiList.push(wasi);
          imports.wasi_snapshot_preview1 = await wasi.importObject();
        }
      }
      if (!Object.hasOwnProperty.call(imports, module2)) {
        throw new Error(
          `from module "${current.join(
            '"/"'
          )}": cannot resolve import "${module2}" "${name}": not provided by host imports nor linked manifest items`
        );
      }
      if (!Object.hasOwnProperty.call(imports[module2], name)) {
        throw new Error(
          `from module "${current.join(
            '"/"'
          )}": cannot resolve import "${module2}" "${name}" ("${module2}" is a host module, but does not contain "${name}")`
        );
      }
      if (module2 === EXTISM_ENV && name === "http_request" && promising && imports[module2][name] === context[ENV].http_request && !opts.executingInWorker) {
        const httpContext = new HttpContext(opts.fetch, opts.allowedHosts, opts.memory, opts.allowHttpResponseHeaders);
        mutableFlags.suspendsOnInvoke = true;
        const contributions = {};
        httpContext.contribute(contributions);
        for (const [key, entry] of Object.entries(contributions[EXTISM_ENV])) {
          imports[module2][key] = entry.bind(null, context);
        }
        imports[module2][name] = new Suspending(imports[module2][name]);
      }
      switch (kind) {
        case `function`: {
          instantiationImports[module2] ??= {};
          instantiationImports[module2][name] = imports[module2][name];
          break;
        }
        default:
          throw new Error(
            `from module "${current.join(
              '"/"'
            )}": in import "${module2}" "${name}", "${kind}"-typed host imports are not supported yet`
          );
      }
    } else {
      const provider = modules[nameIdx];
      const providerExports = WebAssembly.Module.exports(provider);
      const target = providerExports.find((xs) => {
        return xs.name === name && xs.kind === kind;
      });
      if (!target) {
        throw new Error(
          `from module "${current.join('"/"')}": cannot import "${module2}" "${name}"; no export matched request`
        );
      }
      const instance2 = providerExports.find((xs) => xs.name === "_start") ? await instantiateModule(
        context,
        [...current, module2],
        provider,
        imports,
        opts,
        wasiList,
        names,
        modules,
        /* @__PURE__ */ new Map(),
        mutableFlags
      ) : !linked.has(provider) ? (await instantiateModule(
        context,
        [...current, module2],
        provider,
        imports,
        opts,
        wasiList,
        names,
        modules,
        linked,
        mutableFlags
      ), linked.get(provider)) : linked.get(provider);
      if (!instance2) {
        if (kind === "function") {
          instantiationImports[module2] = {};
          let cached = null;
          instantiationImports[module2][name] = (...args) => {
            if (cached) {
              return cached(...args);
            }
            const instance3 = linked.get(modules[nameIdx]);
            if (!instance3) {
              throw new Error(
                `from module instance "${current.join('"/"')}": target module "${module2}" was never instantiated`
              );
            }
            cached = instance3.exports[name];
            return cached(...args);
          };
        } else {
          throw new Error(
            `from module "${current.join(
              '"/"'
            )}": cannot import "${module2}" "${name}"; circular imports of type="${kind}" are not supported`
          );
        }
      } else {
        instantiationImports[module2] ??= {};
        instantiationImports[module2][name] = instance2.exports[name];
      }
    }
  }
  const instance = await WebAssembly.instantiate(module, instantiationImports);
  const guestType = instance.exports.hs_init ? "haskell" : instance.exports._initialize ? "reactor" : instance.exports._start ? "command" : "none";
  if (wasi) {
    await wasi?.initialize(instance);
    if (instance.exports.hs_init) {
      instance.exports.hs_init();
    }
  } else {
    switch (guestType) {
      case "command":
        if (instance.exports._initialize) {
          instance.exports._initialize();
        }
        instance.exports._start();
        break;
      case "reactor":
        instance.exports._initialize();
        break;
      case "haskell":
        instance.exports.hs_init();
        break;
    }
  }
  linked.set(module, instance);
  return instance;
}

// src/polyfills/bun-worker-url.ts
var WORKER_URL = new URL("./worker.js", import.meta.url);

// src/background-plugin.ts
import { Worker } from "node:worker_threads";
var AtomicsWaitAsync = Atomics.waitAsync || (() => {
  const src = `onmessage = ev => {
    const [b, i, v] = ev.data
    const f = new Int32Array(b)
    postMessage(Atomics.wait(f, i, v));
  }`;
  const blob = new Blob([src], { type: "text/javascript" });
  const url = URL.createObjectURL(blob);
  const w = new Worker(url, { execArgv: [] });
  return (ia, index, value) => {
    const promise = new Promise((resolve) => {
      w.once("message", (data) => {
        resolve(data);
      });
    });
    w.postMessage([ia.buffer, index, value]);
    return { async: true, value: promise };
  };
})();
var BackgroundPlugin = class {
  constructor(worker, sharedData, names, modules, opts, context) {
    this.#request = null;
    this.sharedData = sharedData;
    this.sharedDataView = new DataView(sharedData);
    this.hostFlag = new Int32Array(sharedData);
    this.opts = opts;
    this.names = names;
    this.modules = modules;
    this.worker = worker;
    this.#context = context;
    this.hostFlag[0] = SAB_BASE_OFFSET;
    this.worker.on("message", (ev) => this.#handleMessage(ev));
  }
  #context;
  #request;
  async #handleTimeout() {
    const request = this.#request;
    this.#request = [() => {
    }, () => {
    }];
    const timedOut = {};
    const failed = {};
    const result = await Promise.race(
      [
        timeout(this.opts.timeoutMs, timedOut),
        Promise.all([terminateWorker(this.worker), createWorker(this.opts, this.names, this.modules, this.sharedData)])
      ].filter(Boolean)
    ).catch(() => failed);
    this.#context[RESET]();
    if (result === timedOut) {
      this.opts.logger.error(
        "EXTISM: Plugin timed out while handling a timeout. Plugin will hang. This Wasm module may have a non-trivial `start` section."
      );
      this.worker = null;
      return;
    }
    if (result === failed) {
      this.opts.logger.error("EXTISM: Plugin failed to restart during a timeout. Plugin will hang.");
      this.worker = null;
      return;
    }
    const [, worker] = result;
    this.worker = worker;
    if (request) {
      request.pop()(new Error("EXTISM: call canceled due to timeout"));
    }
    this.#request = null;
    this.worker.on("message", (ev) => this.#handleMessage(ev));
  }
  async reset() {
    if (this.isActive()) {
      return false;
    }
    await this.#invoke("reset");
    this.#context[RESET]();
    return true;
  }
  isActive() {
    return Boolean(this.#request);
  }
  async #handleMessage(ev) {
    switch (ev?.type) {
      case "invoke":
        return this.#handleInvoke(ev);
      case "return":
        return this.#handleReturn(ev);
      case "log":
        return this.#handleLog(ev);
    }
  }
  #handleLog(ev) {
    const fn = this.opts.logger[ev.level];
    if (typeof fn !== "function") {
      this.opts.logger?.error(`failed to find loglevel="${ev.level}" on logger: message=${ev.message}`);
    } else {
      fn.call(this.opts.logger, ev.message);
    }
  }
  #handleReturn(ev) {
    const responder = this.#request || null;
    if (responder === null) {
      throw new Error(`received "return" call with no corresponding request`);
    }
    this.#request = null;
    const [resolve, reject] = responder;
    if (!Array.isArray(ev.results) || ev.results.length !== 2) {
      return reject(new Error(`received malformed "return"`));
    }
    const [err, data] = ev.results;
    err ? reject(err) : resolve(data);
  }
  async #invoke(handler, ...args) {
    if (this.#request) {
      throw new Error("plugin is not reentrant");
    }
    let resolve, reject;
    const promise = new Promise((res, rej) => {
      resolve = res;
      reject = rej;
    });
    this.#request = [resolve, reject];
    if (!this.worker) {
      throw new Error("worker not initialized");
    }
    const timedOut = {};
    Promise.race([timeout(this.opts.timeoutMs, timedOut), promise].filter(Boolean)).then(
      async (v) => {
        if (v === timedOut) {
          await this.#handleTimeout();
        }
      },
      () => {
      }
    );
    this.worker.postMessage({
      type: "invoke",
      handler,
      args
    });
    return promise;
  }
  async functionExists(funcName) {
    return await this.#invoke("functionExists", funcName);
  }
  async call(funcName, input, hostContext) {
    const index = this.#context[STORE](input);
    this.#context[SET_HOST_CONTEXT](hostContext);
    const [errorIdx, outputIdx] = await this.callBlock(funcName, index);
    const shouldThrow = errorIdx !== null;
    const idx = errorIdx ?? outputIdx;
    if (idx === null) {
      return null;
    }
    const block = this.#context[GET_BLOCK](idx);
    if (block === null) {
      return null;
    }
    const buf = new PluginOutput(
      CAPABILITIES.allowSharedBufferCodec ? block.buffer : new Uint8Array(block.buffer).slice().buffer
    );
    if (shouldThrow) {
      const msg = new TextDecoder().decode(buf);
      throw new Error(`Plugin-originated error: ${msg}`);
    }
    return buf;
  }
  async callBlock(funcName, input) {
    const exported = this.#context[EXPORT_STATE]();
    const { results, state } = await this.#invoke("call", funcName, input, exported);
    this.#context[IMPORT_STATE](state, true);
    const [err, data] = results;
    if (err) {
      throw err;
    }
    return data;
  }
  async getExports() {
    return await this.#invoke("getExports");
  }
  async getImports() {
    return await this.#invoke("getImports");
  }
  async getInstance() {
    throw new Error("todo");
  }
  async close() {
    if (this.worker) {
      await terminateWorker(this.worker);
      this.worker = null;
    }
  }
  async #handleInvoke(ev) {
    const writer = new RingBufferWriter(this.sharedData);
    const namespace = this.opts.functions[ev.namespace];
    const func = (namespace ?? {})[ev.func];
    const timer = setInterval(() => {
    }, 0);
    try {
      if (!func) {
        throw Error(`Plugin error: host function "${ev.namespace}" "${ev.func}" does not exist`);
      }
      new Uint8Array(this.sharedData).subarray(8).fill(254);
      this.#context[IMPORT_STATE](ev.state, true);
      const data = await func(this.#context, ...ev.args);
      const { blocks } = this.#context[EXPORT_STATE]();
      let promise;
      for (const [buffer, destination] of blocks) {
        promise = writer.writeUint8(4 /* Block */);
        if (promise) {
          await promise;
        }
        promise = writer.writeUint32(destination);
        if (promise) {
          await promise;
        }
        promise = writer.writeUint32(buffer?.byteLength || 0);
        if (promise) {
          await promise;
        }
        if (buffer) {
          promise = writer.write(buffer);
          if (promise) {
            await promise;
          }
        }
      }
      if (typeof data === "bigint") {
        promise = writer.writeUint8(1 /* RetI64 */);
        if (promise) {
          await promise;
        }
        promise = writer.writeUint64(data);
        if (promise) {
          await promise;
        }
      } else if (typeof data === "number") {
        promise = writer.writeUint8(2 /* RetF64 */);
        if (promise) {
          await promise;
        }
        promise = writer.writeFloat64(data);
        if (promise) {
          await promise;
        }
      } else {
        promise = writer.writeUint8(3 /* RetVoid */);
        if (promise) {
          await promise;
        }
      }
      promise = writer.writeUint8(255 /* End */);
      if (promise) {
        await promise;
      }
      await writer.flush();
    } catch (err) {
      this.close();
      const [, reject] = this.#request;
      this.#request = null;
      return reject(err);
    } finally {
      clearInterval(timer);
    }
  }
};
var MAX_WAIT = 500;
var RingBufferWriter = class {
  constructor(output) {
    this.scratch = new ArrayBuffer(8);
    this.scratchView = new DataView(this.scratch);
    this.output = output;
    this.outputOffset = SAB_BASE_OFFSET;
    this.flag = new Int32Array(this.output);
    this.wait(0);
  }
  async wait(lastKnownValue) {
    let value = 0;
    do {
      value = Atomics.load(this.flag, 0);
      if (value === lastKnownValue) {
        const { value: result, async } = AtomicsWaitAsync(this.flag, 0, lastKnownValue, MAX_WAIT);
        if (async) {
          if (await result === "timed-out") {
            continue;
          }
        }
      }
    } while (value === lastKnownValue);
  }
  signal() {
    const old = Atomics.load(this.flag, 0);
    while (Atomics.compareExchange(this.flag, 0, old, this.outputOffset) === old) {
    }
    Atomics.notify(this.flag, 0, 1);
  }
  async flush() {
    if (this.outputOffset === SAB_BASE_OFFSET) {
      return;
    }
    const workerId = this.outputOffset;
    this.signal();
    this.outputOffset = SAB_BASE_OFFSET;
    await this.wait(workerId);
  }
  async spanningWrite(input) {
    let inputOffset = 0;
    let toWrite = this.output.byteLength - this.outputOffset;
    let flushedWriteCount = 1 + Math.floor((input.byteLength - toWrite) / (this.output.byteLength - SAB_BASE_OFFSET));
    const finalWrite = (input.byteLength - toWrite) % (this.output.byteLength - SAB_BASE_OFFSET);
    do {
      new Uint8Array(this.output).set(input.subarray(inputOffset, inputOffset + toWrite), this.outputOffset);
      this.outputOffset += toWrite;
      inputOffset += toWrite;
      await this.flush();
      toWrite = this.output.byteLength - SAB_BASE_OFFSET;
      --flushedWriteCount;
    } while (flushedWriteCount != 0);
    if (finalWrite) {
      this.write(input.subarray(inputOffset, inputOffset + finalWrite));
    }
  }
  write(bytes) {
    if (bytes.byteLength + this.outputOffset < this.output.byteLength) {
      new Uint8Array(this.output).set(new Uint8Array(bytes), this.outputOffset);
      this.outputOffset += bytes.byteLength;
      return;
    }
    return this.spanningWrite(new Uint8Array(bytes));
  }
  writeUint8(value) {
    this.scratchView.setUint8(0, value);
    return this.write(this.scratch.slice(0, 1));
  }
  writeUint32(value) {
    this.scratchView.setUint32(0, value, true);
    return this.write(this.scratch.slice(0, 4));
  }
  writeUint64(value) {
    this.scratchView.setBigUint64(0, value, true);
    return this.write(this.scratch.slice(0, 8));
  }
  writeFloat64(value) {
    this.scratchView.setFloat64(0, value, true);
    return this.write(this.scratch.slice(0, 8));
  }
};
RingBufferWriter.SAB_IDX = 0;
async function createBackgroundPlugin(opts, names, modules) {
  const context = new CallContext(SharedArrayBuffer, opts.logger, opts.logLevel, opts.config, opts.memory);
  const httpContext = new HttpContext(opts.fetch, opts.allowedHosts, opts.memory, opts.allowHttpResponseHeaders);
  httpContext.contribute(opts.functions);
  opts.functions[EXTISM_ENV] ??= {};
  opts.functions[EXTISM_ENV].var_get ??= (_, key) => {
    return context[ENV].var_get(key);
  };
  opts.functions[EXTISM_ENV].var_set ??= (_, key, val) => {
    return context[ENV].var_set(key, val);
  };
  const sharedData = new SharedArrayBuffer(opts.sharedArrayBufferSize);
  new Uint8Array(sharedData).subarray(8).fill(254);
  const timedOut = {};
  let earlyWorker;
  const onworker = (w) => {
    earlyWorker = w;
  };
  const worker = await Promise.race(
    [timeout(opts.timeoutMs, timedOut), createWorker(opts, names, modules, sharedData, onworker)].filter(Boolean)
  );
  if (worker === timedOut) {
    await terminateWorker(earlyWorker);
    throw new Error("EXTISM: timed out while waiting for plugin to instantiate");
  }
  return new BackgroundPlugin(worker, sharedData, names, modules, opts, context);
}
async function createWorker(opts, names, modules, sharedData, onworker = (_w) => {
}) {
  const worker = new Worker(WORKER_URL, opts.nodeWorkerArgs);
  onworker(worker);
  await new Promise((resolve, reject) => {
    worker.on("message", function handler(ev) {
      if (ev?.type !== "initialized") {
        reject(new Error(`received unexpected message (type=${ev?.type})`));
      }
      worker.removeListener("message", handler);
      resolve(null);
    });
  });
  const onready = new Promise((resolve, reject) => {
    worker.on("message", function handler(ev) {
      if (ev?.type !== "ready") {
        reject(new Error(`received unexpected message (type=${ev?.type})`));
      }
      worker.removeListener("message", handler);
      resolve(null);
    });
  });
  const { fetch: _, logger: __, ...rest } = opts;
  const message = {
    ...rest,
    type: "init",
    functions: Object.fromEntries(Object.entries(opts.functions || {}).map(([k, v]) => [k, Object.keys(v)])),
    names,
    modules,
    sharedData
  };
  worker.postMessage(message);
  await onready;
  return worker;
}
function timeout(ms, sentinel) {
  return ms === null ? null : new Promise((resolve) => setTimeout(() => resolve(sentinel), ms));
}
async function terminateWorker(w) {
  if (typeof globalThis.Bun !== "undefined") {
    const timer = setTimeout(() => {
    }, 10);
    await w.terminate();
    clearTimeout(timer);
  } else {
    await w.terminate();
  }
}

// src/mod.ts
async function createPlugin(manifest, opts = {}) {
  opts = { ...opts };
  opts.useWasi ??= false;
  opts.enableWasiOutput ??= opts.useWasi ? CAPABILITIES.extismStdoutEnvVarSet : false;
  opts.functions = opts.functions || {};
  opts.runInWorker ??= false;
  opts.logger ??= console;
  opts.logLevel ??= "silent";
  opts.fetch ??= fetch;
  const [manifestOpts, names, moduleData] = await toWasmModuleData(
    await Promise.resolve(manifest),
    opts.fetch ?? fetch
  );
  opts.allowedPaths = opts.allowedPaths || manifestOpts.allowedPaths || {};
  opts.allowedHosts = opts.allowedHosts || manifestOpts.allowedHosts || [];
  opts.config = opts.config || manifestOpts.config || {};
  opts.memory = opts.memory || manifestOpts.memory || {};
  opts.timeoutMs = opts.timeoutMs || manifestOpts.timeoutMs || null;
  opts.nodeWorkerArgs = Object.assign(
    {
      name: "extism plugin",
      execArgv: ["--disable-warning=ExperimentalWarning"]
    },
    opts.nodeWorkerArgs || {}
  );
  if (opts.allowedHosts.length && !opts.runInWorker) {
    if (!WebAssembly.Suspending) {
      throw new TypeError(
        '"allowedHosts" requires "runInWorker: true". HTTP functions are only available to plugins running in a worker.'
      );
    }
  }
  if (opts.timeoutMs && !opts.runInWorker) {
    throw new TypeError(
      '"timeout" requires "runInWorker: true". Call timeouts are only available to plugins running in a worker.'
    );
  }
  if (opts.runInWorker && !CAPABILITIES.hasWorkerCapability) {
    throw new Error(
      "Cannot enable off-thread wasm; current context is not `crossOriginIsolated` (see https://mdn.io/crossOriginIsolated)"
    );
  }
  for (const guest in opts.allowedPaths) {
    const host = opts.allowedPaths[guest];
    if (host.startsWith("ro:")) {
      throw new Error(`Readonly dirs are not supported: ${host}`);
    }
  }
  const ic = {
    executingInWorker: false,
    allowedHosts: opts.allowedHosts,
    allowedPaths: opts.allowedPaths,
    functions: opts.functions,
    fetch: opts.fetch || fetch,
    wasiEnabled: opts.useWasi,
    logger: opts.logger,
    logLevel: logLevelToPriority(opts.logLevel || "silent"),
    config: opts.config,
    enableWasiOutput: opts.enableWasiOutput,
    sharedArrayBufferSize: Number(opts.sharedArrayBufferSize) || 1 << 16,
    timeoutMs: opts.timeoutMs,
    memory: opts.memory,
    allowHttpResponseHeaders: !!opts.allowHttpResponseHeaders,
    nodeWorkerArgs: opts.nodeWorkerArgs || {}
  };
  return (opts.runInWorker ? createBackgroundPlugin : createForegroundPlugin)(ic, names, moduleData);
}
var mod_default = createPlugin;
export {
  CAPABILITIES,
  createPlugin,
  mod_default as default,
  createPlugin as newPlugin
};
//# sourceMappingURL=mod.js.map
