// @bun
// src/plugin-v2.ts
import { spawn } from "child_process";

// node_modules/superjson/dist/double-indexed-kv.js
class DoubleIndexedKV {
  constructor() {
    this.keyToValue = new Map;
    this.valueToKey = new Map;
  }
  set(key, value) {
    this.keyToValue.set(key, value);
    this.valueToKey.set(value, key);
  }
  getByKey(key) {
    return this.keyToValue.get(key);
  }
  getByValue(value) {
    return this.valueToKey.get(value);
  }
  clear() {
    this.keyToValue.clear();
    this.valueToKey.clear();
  }
}

// node_modules/superjson/dist/registry.js
class Registry {
  constructor(generateIdentifier) {
    this.generateIdentifier = generateIdentifier;
    this.kv = new DoubleIndexedKV;
  }
  register(value, identifier) {
    if (this.kv.getByValue(value)) {
      return;
    }
    if (!identifier) {
      identifier = this.generateIdentifier(value);
    }
    this.kv.set(identifier, value);
  }
  clear() {
    this.kv.clear();
  }
  getIdentifier(value) {
    return this.kv.getByValue(value);
  }
  getValue(identifier) {
    return this.kv.getByKey(identifier);
  }
}

// node_modules/superjson/dist/class-registry.js
class ClassRegistry extends Registry {
  constructor() {
    super((c) => c.name);
    this.classToAllowedProps = new Map;
  }
  register(value, options) {
    if (typeof options === "object") {
      if (options.allowProps) {
        this.classToAllowedProps.set(value, options.allowProps);
      }
      super.register(value, options.identifier);
    } else {
      super.register(value, options);
    }
  }
  getAllowedProps(value) {
    return this.classToAllowedProps.get(value);
  }
}

// node_modules/superjson/dist/util.js
function valuesOfObj(record) {
  if ("values" in Object) {
    return Object.values(record);
  }
  const values = [];
  for (const key in record) {
    if (record.hasOwnProperty(key)) {
      values.push(record[key]);
    }
  }
  return values;
}
function find(record, predicate) {
  const values = valuesOfObj(record);
  if ("find" in values) {
    return values.find(predicate);
  }
  const valuesNotNever = values;
  for (let i = 0;i < valuesNotNever.length; i++) {
    const value = valuesNotNever[i];
    if (predicate(value)) {
      return value;
    }
  }
  return;
}
function forEach(record, run) {
  Object.entries(record).forEach(([key, value]) => run(value, key));
}
function includes(arr, value) {
  return arr.indexOf(value) !== -1;
}
function findArr(record, predicate) {
  for (let i = 0;i < record.length; i++) {
    const value = record[i];
    if (predicate(value)) {
      return value;
    }
  }
  return;
}

// node_modules/superjson/dist/custom-transformer-registry.js
class CustomTransformerRegistry {
  constructor() {
    this.transfomers = {};
  }
  register(transformer) {
    this.transfomers[transformer.name] = transformer;
  }
  findApplicable(v) {
    return find(this.transfomers, (transformer) => transformer.isApplicable(v));
  }
  findByName(name) {
    return this.transfomers[name];
  }
}

// node_modules/superjson/dist/is.js
var getType = (payload) => Object.prototype.toString.call(payload).slice(8, -1);
var isUndefined = (payload) => typeof payload === "undefined";
var isNull = (payload) => payload === null;
var isPlainObject = (payload) => {
  if (typeof payload !== "object" || payload === null)
    return false;
  if (payload === Object.prototype)
    return false;
  if (Object.getPrototypeOf(payload) === null)
    return true;
  return Object.getPrototypeOf(payload) === Object.prototype;
};
var isEmptyObject = (payload) => isPlainObject(payload) && Object.keys(payload).length === 0;
var isArray = (payload) => Array.isArray(payload);
var isString = (payload) => typeof payload === "string";
var isNumber = (payload) => typeof payload === "number" && !isNaN(payload);
var isBoolean = (payload) => typeof payload === "boolean";
var isRegExp = (payload) => payload instanceof RegExp;
var isMap = (payload) => payload instanceof Map;
var isSet = (payload) => payload instanceof Set;
var isSymbol = (payload) => getType(payload) === "Symbol";
var isDate = (payload) => payload instanceof Date && !isNaN(payload.valueOf());
var isError = (payload) => payload instanceof Error;
var isNaNValue = (payload) => typeof payload === "number" && isNaN(payload);
var isPrimitive = (payload) => isBoolean(payload) || isNull(payload) || isUndefined(payload) || isNumber(payload) || isString(payload) || isSymbol(payload);
var isBigint = (payload) => typeof payload === "bigint";
var isInfinite = (payload) => payload === Infinity || payload === -Infinity;
var isTypedArray = (payload) => ArrayBuffer.isView(payload) && !(payload instanceof DataView);
var isURL = (payload) => payload instanceof URL;

// node_modules/superjson/dist/pathstringifier.js
var escapeKey = (key) => key.replace(/\./g, "\\.");
var stringifyPath = (path) => path.map(String).map(escapeKey).join(".");
var parsePath = (string) => {
  const result = [];
  let segment = "";
  for (let i = 0;i < string.length; i++) {
    let char = string.charAt(i);
    const isEscapedDot = char === "\\" && string.charAt(i + 1) === ".";
    if (isEscapedDot) {
      segment += ".";
      i++;
      continue;
    }
    const isEndOfSegment = char === ".";
    if (isEndOfSegment) {
      result.push(segment);
      segment = "";
      continue;
    }
    segment += char;
  }
  const lastSegment = segment;
  result.push(lastSegment);
  return result;
};

// node_modules/superjson/dist/transformer.js
function simpleTransformation(isApplicable, annotation, transform, untransform) {
  return {
    isApplicable,
    annotation,
    transform,
    untransform
  };
}
var simpleRules = [
  simpleTransformation(isUndefined, "undefined", () => null, () => {
    return;
  }),
  simpleTransformation(isBigint, "bigint", (v) => v.toString(), (v) => {
    if (typeof BigInt !== "undefined") {
      return BigInt(v);
    }
    console.error("Please add a BigInt polyfill.");
    return v;
  }),
  simpleTransformation(isDate, "Date", (v) => v.toISOString(), (v) => new Date(v)),
  simpleTransformation(isError, "Error", (v, superJson) => {
    const baseError = {
      name: v.name,
      message: v.message
    };
    superJson.allowedErrorProps.forEach((prop) => {
      baseError[prop] = v[prop];
    });
    return baseError;
  }, (v, superJson) => {
    const e = new Error(v.message);
    e.name = v.name;
    e.stack = v.stack;
    superJson.allowedErrorProps.forEach((prop) => {
      e[prop] = v[prop];
    });
    return e;
  }),
  simpleTransformation(isRegExp, "regexp", (v) => "" + v, (regex) => {
    const body = regex.slice(1, regex.lastIndexOf("/"));
    const flags = regex.slice(regex.lastIndexOf("/") + 1);
    return new RegExp(body, flags);
  }),
  simpleTransformation(isSet, "set", (v) => [...v.values()], (v) => new Set(v)),
  simpleTransformation(isMap, "map", (v) => [...v.entries()], (v) => new Map(v)),
  simpleTransformation((v) => isNaNValue(v) || isInfinite(v), "number", (v) => {
    if (isNaNValue(v)) {
      return "NaN";
    }
    if (v > 0) {
      return "Infinity";
    } else {
      return "-Infinity";
    }
  }, Number),
  simpleTransformation((v) => v === 0 && 1 / v === -Infinity, "number", () => {
    return "-0";
  }, Number),
  simpleTransformation(isURL, "URL", (v) => v.toString(), (v) => new URL(v))
];
function compositeTransformation(isApplicable, annotation, transform, untransform) {
  return {
    isApplicable,
    annotation,
    transform,
    untransform
  };
}
var symbolRule = compositeTransformation((s, superJson) => {
  if (isSymbol(s)) {
    const isRegistered = !!superJson.symbolRegistry.getIdentifier(s);
    return isRegistered;
  }
  return false;
}, (s, superJson) => {
  const identifier = superJson.symbolRegistry.getIdentifier(s);
  return ["symbol", identifier];
}, (v) => v.description, (_, a, superJson) => {
  const value = superJson.symbolRegistry.getValue(a[1]);
  if (!value) {
    throw new Error("Trying to deserialize unknown symbol");
  }
  return value;
});
var constructorToName = [
  Int8Array,
  Uint8Array,
  Int16Array,
  Uint16Array,
  Int32Array,
  Uint32Array,
  Float32Array,
  Float64Array,
  Uint8ClampedArray
].reduce((obj, ctor) => {
  obj[ctor.name] = ctor;
  return obj;
}, {});
var typedArrayRule = compositeTransformation(isTypedArray, (v) => ["typed-array", v.constructor.name], (v) => [...v], (v, a) => {
  const ctor = constructorToName[a[1]];
  if (!ctor) {
    throw new Error("Trying to deserialize unknown typed array");
  }
  return new ctor(v);
});
function isInstanceOfRegisteredClass(potentialClass, superJson) {
  if (potentialClass?.constructor) {
    const isRegistered = !!superJson.classRegistry.getIdentifier(potentialClass.constructor);
    return isRegistered;
  }
  return false;
}
var classRule = compositeTransformation(isInstanceOfRegisteredClass, (clazz, superJson) => {
  const identifier = superJson.classRegistry.getIdentifier(clazz.constructor);
  return ["class", identifier];
}, (clazz, superJson) => {
  const allowedProps = superJson.classRegistry.getAllowedProps(clazz.constructor);
  if (!allowedProps) {
    return { ...clazz };
  }
  const result = {};
  allowedProps.forEach((prop) => {
    result[prop] = clazz[prop];
  });
  return result;
}, (v, a, superJson) => {
  const clazz = superJson.classRegistry.getValue(a[1]);
  if (!clazz) {
    throw new Error(`Trying to deserialize unknown class '${a[1]}' - check https://github.com/blitz-js/superjson/issues/116#issuecomment-773996564`);
  }
  return Object.assign(Object.create(clazz.prototype), v);
});
var customRule = compositeTransformation((value, superJson) => {
  return !!superJson.customTransformerRegistry.findApplicable(value);
}, (value, superJson) => {
  const transformer = superJson.customTransformerRegistry.findApplicable(value);
  return ["custom", transformer.name];
}, (value, superJson) => {
  const transformer = superJson.customTransformerRegistry.findApplicable(value);
  return transformer.serialize(value);
}, (v, a, superJson) => {
  const transformer = superJson.customTransformerRegistry.findByName(a[1]);
  if (!transformer) {
    throw new Error("Trying to deserialize unknown custom value");
  }
  return transformer.deserialize(v);
});
var compositeRules = [classRule, symbolRule, customRule, typedArrayRule];
var transformValue = (value, superJson) => {
  const applicableCompositeRule = findArr(compositeRules, (rule) => rule.isApplicable(value, superJson));
  if (applicableCompositeRule) {
    return {
      value: applicableCompositeRule.transform(value, superJson),
      type: applicableCompositeRule.annotation(value, superJson)
    };
  }
  const applicableSimpleRule = findArr(simpleRules, (rule) => rule.isApplicable(value, superJson));
  if (applicableSimpleRule) {
    return {
      value: applicableSimpleRule.transform(value, superJson),
      type: applicableSimpleRule.annotation
    };
  }
  return;
};
var simpleRulesByAnnotation = {};
simpleRules.forEach((rule) => {
  simpleRulesByAnnotation[rule.annotation] = rule;
});
var untransformValue = (json, type, superJson) => {
  if (isArray(type)) {
    switch (type[0]) {
      case "symbol":
        return symbolRule.untransform(json, type, superJson);
      case "class":
        return classRule.untransform(json, type, superJson);
      case "custom":
        return customRule.untransform(json, type, superJson);
      case "typed-array":
        return typedArrayRule.untransform(json, type, superJson);
      default:
        throw new Error("Unknown transformation: " + type);
    }
  } else {
    const transformation = simpleRulesByAnnotation[type];
    if (!transformation) {
      throw new Error("Unknown transformation: " + type);
    }
    return transformation.untransform(json, superJson);
  }
};

// node_modules/superjson/dist/accessDeep.js
var getNthKey = (value, n) => {
  if (n > value.size)
    throw new Error("index out of bounds");
  const keys = value.keys();
  while (n > 0) {
    keys.next();
    n--;
  }
  return keys.next().value;
};
function validatePath(path) {
  if (includes(path, "__proto__")) {
    throw new Error("__proto__ is not allowed as a property");
  }
  if (includes(path, "prototype")) {
    throw new Error("prototype is not allowed as a property");
  }
  if (includes(path, "constructor")) {
    throw new Error("constructor is not allowed as a property");
  }
}
var getDeep = (object, path) => {
  validatePath(path);
  for (let i = 0;i < path.length; i++) {
    const key = path[i];
    if (isSet(object)) {
      object = getNthKey(object, +key);
    } else if (isMap(object)) {
      const row = +key;
      const type = +path[++i] === 0 ? "key" : "value";
      const keyOfRow = getNthKey(object, row);
      switch (type) {
        case "key":
          object = keyOfRow;
          break;
        case "value":
          object = object.get(keyOfRow);
          break;
      }
    } else {
      object = object[key];
    }
  }
  return object;
};
var setDeep = (object, path, mapper) => {
  validatePath(path);
  if (path.length === 0) {
    return mapper(object);
  }
  let parent = object;
  for (let i = 0;i < path.length - 1; i++) {
    const key = path[i];
    if (isArray(parent)) {
      const index = +key;
      parent = parent[index];
    } else if (isPlainObject(parent)) {
      parent = parent[key];
    } else if (isSet(parent)) {
      const row = +key;
      parent = getNthKey(parent, row);
    } else if (isMap(parent)) {
      const isEnd = i === path.length - 2;
      if (isEnd) {
        break;
      }
      const row = +key;
      const type = +path[++i] === 0 ? "key" : "value";
      const keyOfRow = getNthKey(parent, row);
      switch (type) {
        case "key":
          parent = keyOfRow;
          break;
        case "value":
          parent = parent.get(keyOfRow);
          break;
      }
    }
  }
  const lastKey = path[path.length - 1];
  if (isArray(parent)) {
    parent[+lastKey] = mapper(parent[+lastKey]);
  } else if (isPlainObject(parent)) {
    parent[lastKey] = mapper(parent[lastKey]);
  }
  if (isSet(parent)) {
    const oldValue = getNthKey(parent, +lastKey);
    const newValue = mapper(oldValue);
    if (oldValue !== newValue) {
      parent.delete(oldValue);
      parent.add(newValue);
    }
  }
  if (isMap(parent)) {
    const row = +path[path.length - 2];
    const keyToRow = getNthKey(parent, row);
    const type = +lastKey === 0 ? "key" : "value";
    switch (type) {
      case "key": {
        const newKey = mapper(keyToRow);
        parent.set(newKey, parent.get(keyToRow));
        if (newKey !== keyToRow) {
          parent.delete(keyToRow);
        }
        break;
      }
      case "value": {
        parent.set(keyToRow, mapper(parent.get(keyToRow)));
        break;
      }
    }
  }
  return object;
};

// node_modules/superjson/dist/plainer.js
function traverse(tree, walker, origin = []) {
  if (!tree) {
    return;
  }
  if (!isArray(tree)) {
    forEach(tree, (subtree, key) => traverse(subtree, walker, [...origin, ...parsePath(key)]));
    return;
  }
  const [nodeValue, children] = tree;
  if (children) {
    forEach(children, (child, key) => {
      traverse(child, walker, [...origin, ...parsePath(key)]);
    });
  }
  walker(nodeValue, origin);
}
function applyValueAnnotations(plain, annotations, superJson) {
  traverse(annotations, (type, path) => {
    plain = setDeep(plain, path, (v) => untransformValue(v, type, superJson));
  });
  return plain;
}
function applyReferentialEqualityAnnotations(plain, annotations) {
  function apply(identicalPaths, path) {
    const object = getDeep(plain, parsePath(path));
    identicalPaths.map(parsePath).forEach((identicalObjectPath) => {
      plain = setDeep(plain, identicalObjectPath, () => object);
    });
  }
  if (isArray(annotations)) {
    const [root, other] = annotations;
    root.forEach((identicalPath) => {
      plain = setDeep(plain, parsePath(identicalPath), () => plain);
    });
    if (other) {
      forEach(other, apply);
    }
  } else {
    forEach(annotations, apply);
  }
  return plain;
}
var isDeep = (object, superJson) => isPlainObject(object) || isArray(object) || isMap(object) || isSet(object) || isInstanceOfRegisteredClass(object, superJson);
function addIdentity(object, path, identities) {
  const existingSet = identities.get(object);
  if (existingSet) {
    existingSet.push(path);
  } else {
    identities.set(object, [path]);
  }
}
function generateReferentialEqualityAnnotations(identitites, dedupe) {
  const result = {};
  let rootEqualityPaths = undefined;
  identitites.forEach((paths) => {
    if (paths.length <= 1) {
      return;
    }
    if (!dedupe) {
      paths = paths.map((path) => path.map(String)).sort((a, b) => a.length - b.length);
    }
    const [representativePath, ...identicalPaths] = paths;
    if (representativePath.length === 0) {
      rootEqualityPaths = identicalPaths.map(stringifyPath);
    } else {
      result[stringifyPath(representativePath)] = identicalPaths.map(stringifyPath);
    }
  });
  if (rootEqualityPaths) {
    if (isEmptyObject(result)) {
      return [rootEqualityPaths];
    } else {
      return [rootEqualityPaths, result];
    }
  } else {
    return isEmptyObject(result) ? undefined : result;
  }
}
var walker = (object, identities, superJson, dedupe, path = [], objectsInThisPath = [], seenObjects = new Map) => {
  const primitive = isPrimitive(object);
  if (!primitive) {
    addIdentity(object, path, identities);
    const seen = seenObjects.get(object);
    if (seen) {
      return dedupe ? {
        transformedValue: null
      } : seen;
    }
  }
  if (!isDeep(object, superJson)) {
    const transformed2 = transformValue(object, superJson);
    const result2 = transformed2 ? {
      transformedValue: transformed2.value,
      annotations: [transformed2.type]
    } : {
      transformedValue: object
    };
    if (!primitive) {
      seenObjects.set(object, result2);
    }
    return result2;
  }
  if (includes(objectsInThisPath, object)) {
    return {
      transformedValue: null
    };
  }
  const transformationResult = transformValue(object, superJson);
  const transformed = transformationResult?.value ?? object;
  const transformedValue = isArray(transformed) ? [] : {};
  const innerAnnotations = {};
  forEach(transformed, (value, index) => {
    if (index === "__proto__" || index === "constructor" || index === "prototype") {
      throw new Error(`Detected property ${index}. This is a prototype pollution risk, please remove it from your object.`);
    }
    const recursiveResult = walker(value, identities, superJson, dedupe, [...path, index], [...objectsInThisPath, object], seenObjects);
    transformedValue[index] = recursiveResult.transformedValue;
    if (isArray(recursiveResult.annotations)) {
      innerAnnotations[index] = recursiveResult.annotations;
    } else if (isPlainObject(recursiveResult.annotations)) {
      forEach(recursiveResult.annotations, (tree, key) => {
        innerAnnotations[escapeKey(index) + "." + key] = tree;
      });
    }
  });
  const result = isEmptyObject(innerAnnotations) ? {
    transformedValue,
    annotations: transformationResult ? [transformationResult.type] : undefined
  } : {
    transformedValue,
    annotations: transformationResult ? [transformationResult.type, innerAnnotations] : innerAnnotations
  };
  if (!primitive) {
    seenObjects.set(object, result);
  }
  return result;
};

// node_modules/is-what/dist/index.js
function getType2(payload) {
  return Object.prototype.toString.call(payload).slice(8, -1);
}
function isArray2(payload) {
  return getType2(payload) === "Array";
}
function isPlainObject2(payload) {
  if (getType2(payload) !== "Object")
    return false;
  const prototype = Object.getPrototypeOf(payload);
  return !!prototype && prototype.constructor === Object && prototype === Object.prototype;
}
function isNull2(payload) {
  return getType2(payload) === "Null";
}
function isOneOf(a, b, c, d, e) {
  return (value) => a(value) || b(value) || !!c && c(value) || !!d && d(value) || !!e && e(value);
}
function isUndefined2(payload) {
  return getType2(payload) === "Undefined";
}
var isNullOrUndefined = isOneOf(isNull2, isUndefined2);

// node_modules/copy-anything/dist/index.js
function assignProp(carry, key, newVal, originalObject, includeNonenumerable) {
  const propType = {}.propertyIsEnumerable.call(originalObject, key) ? "enumerable" : "nonenumerable";
  if (propType === "enumerable")
    carry[key] = newVal;
  if (includeNonenumerable && propType === "nonenumerable") {
    Object.defineProperty(carry, key, {
      value: newVal,
      enumerable: false,
      writable: true,
      configurable: true
    });
  }
}
function copy(target, options = {}) {
  if (isArray2(target)) {
    return target.map((item) => copy(item, options));
  }
  if (!isPlainObject2(target)) {
    return target;
  }
  const props = Object.getOwnPropertyNames(target);
  const symbols = Object.getOwnPropertySymbols(target);
  return [...props, ...symbols].reduce((carry, key) => {
    if (isArray2(options.props) && !options.props.includes(key)) {
      return carry;
    }
    const val = target[key];
    const newVal = copy(val, options);
    assignProp(carry, key, newVal, target, options.nonenumerable);
    return carry;
  }, {});
}

// node_modules/superjson/dist/index.js
class SuperJSON {
  constructor({ dedupe = false } = {}) {
    this.classRegistry = new ClassRegistry;
    this.symbolRegistry = new Registry((s) => s.description ?? "");
    this.customTransformerRegistry = new CustomTransformerRegistry;
    this.allowedErrorProps = [];
    this.dedupe = dedupe;
  }
  serialize(object) {
    const identities = new Map;
    const output = walker(object, identities, this, this.dedupe);
    const res = {
      json: output.transformedValue
    };
    if (output.annotations) {
      res.meta = {
        ...res.meta,
        values: output.annotations
      };
    }
    const equalityAnnotations = generateReferentialEqualityAnnotations(identities, this.dedupe);
    if (equalityAnnotations) {
      res.meta = {
        ...res.meta,
        referentialEqualities: equalityAnnotations
      };
    }
    return res;
  }
  deserialize(payload) {
    const { json, meta } = payload;
    let result = copy(json);
    if (meta?.values) {
      result = applyValueAnnotations(result, meta.values, this);
    }
    if (meta?.referentialEqualities) {
      result = applyReferentialEqualityAnnotations(result, meta.referentialEqualities);
    }
    return result;
  }
  stringify(object) {
    return JSON.stringify(this.serialize(object));
  }
  parse(string) {
    return this.deserialize(JSON.parse(string));
  }
  registerClass(v, options) {
    this.classRegistry.register(v, options);
  }
  registerSymbol(v, identifier) {
    this.symbolRegistry.register(v, identifier);
  }
  registerCustom(transformer, name) {
    this.customTransformerRegistry.register({
      name,
      ...transformer
    });
  }
  allowErrorProps(...props) {
    this.allowedErrorProps.push(...props);
  }
}
SuperJSON.defaultInstance = new SuperJSON;
SuperJSON.serialize = SuperJSON.defaultInstance.serialize.bind(SuperJSON.defaultInstance);
SuperJSON.deserialize = SuperJSON.defaultInstance.deserialize.bind(SuperJSON.defaultInstance);
SuperJSON.stringify = SuperJSON.defaultInstance.stringify.bind(SuperJSON.defaultInstance);
SuperJSON.parse = SuperJSON.defaultInstance.parse.bind(SuperJSON.defaultInstance);
SuperJSON.registerClass = SuperJSON.defaultInstance.registerClass.bind(SuperJSON.defaultInstance);
SuperJSON.registerSymbol = SuperJSON.defaultInstance.registerSymbol.bind(SuperJSON.defaultInstance);
SuperJSON.registerCustom = SuperJSON.defaultInstance.registerCustom.bind(SuperJSON.defaultInstance);
SuperJSON.allowErrorProps = SuperJSON.defaultInstance.allowErrorProps.bind(SuperJSON.defaultInstance);
var serialize = SuperJSON.serialize;
var deserialize = SuperJSON.deserialize;
var stringify = SuperJSON.stringify;
var parse = SuperJSON.parse;
var registerClass = SuperJSON.registerClass;
var registerCustom = SuperJSON.registerCustom;
var registerSymbol = SuperJSON.registerSymbol;
var allowErrorProps = SuperJSON.allowErrorProps;

// node_modules/eventsource-parser/dist/index.js
class ParseError extends Error {
  constructor(message, options) {
    super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
  }
}
function noop(_arg) {}
function createParser(callbacks) {
  if (typeof callbacks == "function")
    throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");
  const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks;
  let incompleteLine = "", isFirstChunk = true, id, data = "", eventType = "";
  function feed(newChunk) {
    const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`);
    for (const line of complete)
      parseLine(line);
    incompleteLine = incomplete, isFirstChunk = false;
  }
  function parseLine(line) {
    if (line === "") {
      dispatchEvent();
      return;
    }
    if (line.startsWith(":")) {
      onComment && onComment(line.slice(line.startsWith(": ") ? 2 : 1));
      return;
    }
    const fieldSeparatorIndex = line.indexOf(":");
    if (fieldSeparatorIndex !== -1) {
      const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
      processField(field, value, line);
      return;
    }
    processField(line, "", line);
  }
  function processField(field, value, line) {
    switch (field) {
      case "event":
        eventType = value;
        break;
      case "data":
        data = `${data}${value}
`;
        break;
      case "id":
        id = value.includes("\x00") ? undefined : value;
        break;
      case "retry":
        /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(new ParseError(`Invalid \`retry\` value: "${value}"`, {
          type: "invalid-retry",
          value,
          line
        }));
        break;
      default:
        onError(new ParseError(`Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`, { type: "unknown-field", field, value, line }));
        break;
    }
  }
  function dispatchEvent() {
    data.length > 0 && onEvent({
      id,
      event: eventType || undefined,
      data: data.endsWith(`
`) ? data.slice(0, -1) : data
    }), id = undefined, data = "", eventType = "";
  }
  function reset(options = {}) {
    incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = true, id = undefined, data = "", eventType = "", incompleteLine = "";
  }
  return { feed, reset };
}
function splitLines(chunk) {
  const lines = [];
  let incompleteLine = "", searchIndex = 0;
  for (;searchIndex < chunk.length; ) {
    const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
`, searchIndex);
    let lineEnd = -1;
    if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) {
      incompleteLine = chunk.slice(searchIndex);
      break;
    } else {
      const line = chunk.slice(searchIndex, lineEnd);
      lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === `
` && searchIndex++;
    }
  }
  return [lines, incompleteLine];
}

// node_modules/eventsource-parser/dist/stream.js
class EventSourceParserStream extends TransformStream {
  constructor({ onError, onRetry, onComment } = {}) {
    let parser;
    super({
      start(controller) {
        parser = createParser({
          onEvent: (event) => {
            controller.enqueue(event);
          },
          onError(error) {
            onError === "terminate" ? controller.error(error) : typeof onError == "function" && onError(error);
          },
          onRetry,
          onComment
        });
      },
      transform(chunk) {
        parser.feed(chunk);
      }
    });
  }
}

// node_modules/spiceflow/dist/client/errors.js
class SpiceflowFetchError extends Error {
  status;
  passedValue;
  value;
  constructor(status, passedValue) {
    let message = String(passedValue?.message || "");
    if (!message) {
      if (typeof passedValue === "object") {
        message = JSON.stringify(passedValue);
      } else {
        message = String(passedValue || "");
      }
    }
    super(message);
    this.status = status;
    this.passedValue = passedValue;
    this.value = passedValue;
  }
}

// node_modules/spiceflow/dist/client/utils.js
function parseStringifiedValue(value) {
  try {
    return JSON.parse(value);
  } catch (error) {
    return value;
  }
}

// node_modules/spiceflow/dist/client/index.js
var method = [
  "get",
  "post",
  "put",
  "delete",
  "patch",
  "options",
  "head",
  "connect",
  "subscribe"
];
var isServer = typeof FileList === "undefined";
var isFile = (v) => {
  if (isServer)
    return v instanceof Blob;
  return v instanceof FileList || v instanceof File;
};
var hasFile = (obj) => {
  if (!obj)
    return false;
  for (const key in obj) {
    if (isFile(obj[key]))
      return true;
    if (Array.isArray(obj[key]) && obj[key].find(isFile))
      return true;
  }
  return false;
};
var createNewFile = (v) => isServer ? v : new Promise((resolve) => {
  const reader = new FileReader;
  reader.onload = () => {
    const file = new File([reader.result], v.name, {
      lastModified: v.lastModified,
      type: v.type
    });
    resolve(file);
  };
  reader.readAsArrayBuffer(v);
});
var processHeaders = (h, path, options = {}, headers = {}) => {
  if (Array.isArray(h)) {
    for (const value of h)
      if (!Array.isArray(value))
        headers = processHeaders(value, path, options, headers);
      else {
        const key = value[0];
        if (typeof key === "string")
          headers[key.toLowerCase()] = value[1];
        else
          for (const [k, value2] of key)
            headers[k.toLowerCase()] = value2;
      }
    return headers;
  }
  if (!h)
    return headers;
  switch (typeof h) {
    case "function":
      if (typeof Headers !== "undefined" && h instanceof Headers)
        return processHeaders(h, path, options, headers);
      const v = h(path, options);
      if (v)
        return processHeaders(v, path, options, headers);
      return headers;
    case "object":
      if (typeof Headers !== "undefined" && h instanceof Headers) {
        h.forEach((value, key) => {
          headers[key.toLowerCase()] = value;
        });
        return headers;
      }
      for (const [key, value] of Object.entries(h))
        headers[key.toLowerCase()] = value;
      return headers;
    default:
      return headers;
  }
};

class TextDecoderStream extends TransformStream {
  constructor() {
    const decoder = new TextDecoder("utf-8", {
      fatal: true,
      ignoreBOM: true
    });
    super({
      transform(chunk, controller) {
        const decoded = decoder.decode(chunk, { stream: true });
        if (decoded.length > 0) {
          controller.enqueue(decoded);
        }
      },
      flush(controller) {
        const output = decoder.decode();
        if (output.length > 0) {
          controller.enqueue(output);
        }
      }
    });
  }
}
function isAbortError(error) {
  return (error instanceof Error || error instanceof DOMException) && (error.name === "AbortError" || error.name === "ResponseAborted" || error.name === "TimeoutError");
}
async function* streamSSEResponse(response, map) {
  const body = response.body;
  if (!body)
    return;
  const eventStream = response.body.pipeThrough(new TextDecoderStream).pipeThrough(new EventSourceParserStream);
  let reader = eventStream.getReader();
  try {
    while (true) {
      const { done, value: event } = await reader.read();
      if (done)
        break;
      if (event?.event === "error") {
        throw new SpiceflowFetchError(500, superjsonDeserialize(event.data));
      }
      if (event) {
        yield map({ ...event, data: event.data });
      }
    }
  } catch (error) {
    if (isAbortError(error)) {
      return;
    }
    throw error;
  }
}
function tryParsingSSEJson(data) {
  try {
    return superjsonDeserialize(JSON.parse(data));
  } catch (error) {
    return data;
  }
}
var createProxy = (domain, config, paths = [], instance) => {
  if (config.state && !instance) {
    throw new Error(`State is only available when using a Spiceflow instance`);
  }
  return new Proxy(() => {}, {
    get(_, param) {
      if (!paths.length && param === "then" || param === "catch") {
        return _[param];
      }
      return createProxy(domain, config, param === "index" ? paths : [...paths, param], instance);
    },
    apply(_, __, [body, options]) {
      if (!body || options || typeof body === "object" && Object.keys(body).length !== 1 || method.includes(paths.at(-1))) {
        const methodPaths = [...paths];
        const method2 = methodPaths.pop();
        const path = "/" + methodPaths.join("/");
        let { fetch: fetcher = fetch, headers, onRequest, onResponse } = config;
        const isGetOrHead = method2 === "get" || method2 === "head" || method2 === "subscribe";
        headers = processHeaders(headers, path, options);
        const query = isGetOrHead ? body?.query : options?.query;
        let q = "";
        if (query) {
          const append = (key, value) => {
            q += (q ? "&" : "?") + `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
          };
          for (const [key, value] of Object.entries(query)) {
            if (Array.isArray(value)) {
              for (const v of value)
                append(key, v);
              continue;
            }
            if (typeof value === "object") {
              append(key, JSON.stringify(value));
              continue;
            }
            append(key, `${value}`);
          }
        }
        return Promise.resolve().then(async () => {
          let fetchInit = {
            method: method2?.toUpperCase(),
            body,
            headers
          };
          fetchInit.headers = {
            ...headers,
            ...processHeaders(isGetOrHead ? body?.headers : options?.headers, path, fetchInit)
          };
          const fetchOpts = isGetOrHead && typeof body === "object" ? body.fetch : options?.fetch;
          fetchInit = {
            ...fetchInit,
            ...fetchOpts
          };
          if (isGetOrHead)
            delete fetchInit.body;
          if (onRequest) {
            if (!Array.isArray(onRequest))
              onRequest = [onRequest];
            for (const value of onRequest) {
              const temp = await value(path, fetchInit);
              if (typeof temp === "object")
                fetchInit = {
                  ...fetchInit,
                  ...temp,
                  headers: {
                    ...fetchInit.headers,
                    ...processHeaders(temp.headers, path, fetchInit)
                  }
                };
            }
          }
          if (isGetOrHead)
            delete fetchInit.body;
          if (hasFile(body)) {
            const formData = new FormData;
            for (const [key, field] of Object.entries(fetchInit.body)) {
              if (isServer) {
                formData.append(key, field);
                continue;
              }
              if (field instanceof File) {
                formData.append(key, await createNewFile(field));
                continue;
              }
              if (field instanceof FileList) {
                for (let i = 0;i < field.length; i++)
                  formData.append(key, await createNewFile(field[i]));
                continue;
              }
              if (Array.isArray(field)) {
                for (let i = 0;i < field.length; i++) {
                  const value = field[i];
                  formData.append(key, value instanceof File ? await createNewFile(value) : value);
                }
                continue;
              }
              formData.append(key, field);
            }
            fetchInit.body = formData;
          } else if (typeof body === "object") {
            fetchInit.headers["content-type"] = "application/json";
            fetchInit.body = JSON.stringify(body);
          } else if (body !== undefined && body !== null) {
            fetchInit.headers["content-type"] = "text/plain";
          }
          if (isGetOrHead)
            delete fetchInit.body;
          fetchInit.headers["x-spiceflow-agent"] = "spiceflow-client";
          if (onRequest) {
            if (!Array.isArray(onRequest))
              onRequest = [onRequest];
            for (const value of onRequest) {
              const temp = await value(path, fetchInit);
              if (typeof temp === "object")
                fetchInit = {
                  ...fetchInit,
                  ...temp,
                  headers: {
                    ...fetchInit.headers,
                    ...processHeaders(temp.headers, path, fetchInit)
                  }
                };
            }
          }
          const url = domain + path + q;
          const response = await (instance?.handle(new Request(url, fetchInit), { state: config.state }) ?? fetcher(url, fetchInit));
          let data = null;
          let error = null;
          if (onResponse) {
            if (!Array.isArray(onResponse))
              onResponse = [onResponse];
            for (const value of onResponse) {
              const temp = await value(response.clone());
            }
          }
          if (data !== null) {
            return {
              data,
              error,
              response,
              status: response.status,
              headers: response.headers,
              url
            };
          }
          switch (response.headers.get("Content-Type")?.split(";")[0]) {
            case "text/event-stream":
              data = streamSSEResponse(response, (x) => {
                return tryParsingSSEJson(x.data);
              });
              break;
            case "application/json":
              data = await response.json();
              data = superjsonDeserialize(data);
              break;
            case "application/octet-stream":
              data = await response.arrayBuffer();
              break;
            case "multipart/form-data":
              const temp = await response.formData();
              data = {};
              temp.forEach((value, key) => {
                data[key] = value;
              });
              break;
            default:
              data = await response.text().then(parseStringifiedValue);
          }
          if (response.status >= 300 || response.status < 200) {
            error = new SpiceflowFetchError(response.status, data || "Unknown error");
            data = null;
          }
          return {
            data,
            error,
            response,
            status: response.status,
            headers: response.headers,
            url
          };
        });
      }
      if (typeof body === "object")
        return createProxy(domain, config, [...paths, Object.values(body)[0]], instance);
      return createProxy(domain, config, paths);
    }
  });
};
var createSpiceflowClient = (domain, config) => {
  if (typeof domain === "string") {
    let domainStr = String(domain);
    if (domain.endsWith("/"))
      domainStr = domain.slice(0, -1);
    return createProxy(domainStr, config || {});
  }
  if (typeof window !== "undefined")
    console.warn("Spiceflow instance server found on client side, this is not recommended for security reason. Use generic type instead.");
  return createProxy("http://e.ly", config || {}, [], domain);
};
function superjsonDeserialize(data) {
  if (data?.__superjsonMeta) {
    const { __superjsonMeta, ...rest } = data;
    return SuperJSON.deserialize({
      json: rest,
      meta: __superjsonMeta
    });
  }
  return data;
}

// src/plugin-v2.ts
var __dirname = "/Users/morse/Documents/GitHub/kimakivoice/discord/src";
var BOT_SERVER_PORT = 5645;
var BOT_SERVER_URL = `http://localhost:${BOT_SERVER_PORT}`;
async function plugin(context) {
  const { client } = context;
  let botProcess = null;
  let eventStreamAbort = null;
  async function ensureBotRunning() {
    try {
      const response = await fetch(`${BOT_SERVER_URL}/health`);
      if (response.ok) {
        console.log("\u2705 Discord bot server already running");
        return true;
      }
    } catch (error) {
      console.log("\uD83D\uDE80 Starting Discord bot server...");
      botProcess = spawn("bun", [`${__dirname}/centralBot.ts`], {
        detached: true,
        stdio: "ignore"
      });
      if (botProcess && typeof botProcess.unref === "function") {
        botProcess.unref();
      }
      for (let i = 0;i < 30; i++) {
        await new Promise((resolve) => setTimeout(resolve, 1000));
        try {
          const response = await fetch(`${BOT_SERVER_URL}/health`);
          if (response.ok) {
            console.log("\u2705 Discord bot server started successfully");
            return true;
          }
        } catch (e) {}
      }
      console.error("\u274C Failed to start Discord bot server");
      return false;
    }
  }
  async function connectToBot() {
    const botClient = createSpiceflowClient(BOT_SERVER_URL);
    eventStreamAbort = new AbortController;
    try {
      const { data: eventStream, error } = await botClient.events.get();
      if (error) {
        console.error("Failed to connect to event stream:", error);
        return;
      }
      console.log("\uD83D\uDCE1 Connected to Discord bot server event stream");
      for await (const event of eventStream) {
        if (eventStreamAbort?.signal.aborted)
          break;
        if (event.type === "connected") {
          console.log("\uD83D\uDCE1 Event stream connected");
        } else if (event.type === "opencode" && event.directory === process.cwd()) {
          handleBotEvent(event.event);
        }
      }
    } catch (error) {
      console.error("Event stream error:", error);
      if (!eventStreamAbort?.signal.aborted) {
        setTimeout(connectToBot, 5000);
      }
    }
  }
  async function handleBotEvent(event) {
    console.log(`Received bot event: ${event.type}`);
  }
  async function getBotStatus() {
    const botClient = createSpiceflowClient(BOT_SERVER_URL);
    const { data, error } = await botClient.status.get();
    if (error) {
      console.error("Failed to get bot status:", error);
      return null;
    }
    return data;
  }
  async function createSessionForThread(threadId, title) {
    const botClient = createSpiceflowClient(BOT_SERVER_URL);
    const { data, error } = await botClient["create-session"].post({
      threadId,
      directory: process.cwd(),
      title
    });
    if (error) {
      console.error("Failed to create session:", error);
      return null;
    }
    if ("sessionId" in data) {
      console.log(`Created session ${data.sessionId} for thread ${threadId}`);
      return data;
    }
    return null;
  }
  async function sendToDiscord(threadId, content) {
    const botClient = createSpiceflowClient(BOT_SERVER_URL);
    const { data, error } = await botClient.send.post({
      threadId,
      content,
      directory: process.cwd()
    });
    if (error) {
      console.error("Failed to send to Discord:", error);
      return null;
    }
    if ("messageId" in data) {
      return data.messageId;
    }
    return null;
  }
  (async () => {
    console.log("\uD83D\uDD0C Discord plugin v2 initializing...");
    console.log(`\uD83D\uDCC1 Working directory: ${process.cwd()}`);
    const botRunning = await ensureBotRunning();
    if (!botRunning) {
      console.error("\u274C Could not start Discord bot server");
      return;
    }
    await connectToBot();
    const status = await getBotStatus();
    if (status) {
      console.log(`\uD83D\uDCCA Bot status: Connected=${status.connected}, Servers=${status.servers.length}`);
    }
    try {
      const eventsResult = await client.event.subscribe();
      const events = eventsResult.stream;
      console.log(`\uD83D\uDCE1 Subscribed to OpenCode events for ${process.cwd()}`);
      for await (const event of events) {
        if (event.type === "message.updated" || event.type === "message.part.updated") {
          console.log(`OpenCode event: ${event.type}`);
        }
      }
    } catch (error) {
      console.error("Failed to subscribe to OpenCode events:", error);
    }
  })();
  process.on("exit", () => {
    if (eventStreamAbort) {
      eventStreamAbort.abort();
    }
  });
  return {};
}
export {
  plugin as default
};
