// ../../node_modules/.pnpm/@trpc+client@11.8.1_@trpc+server@11.8.1_typescript@5.9.3__typescript@5.9.3/node_modules/@trpc/client/dist/objectSpread2-BvkFp-_Y.mjs
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 __commonJS = (cb, mod) => function() {
  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 (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
    key = keys[i];
    if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
      get: ((k) => from[k]).bind(null, 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 require_typeof = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/typeof.js"(exports, module) {
  function _typeof$2(o) {
    "@babel/helpers - typeof";
    return module.exports = _typeof$2 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$1) {
      return typeof o$1;
    } : function(o$1) {
      return o$1 && "function" == typeof Symbol && o$1.constructor === Symbol && o$1 !== Symbol.prototype ? "symbol" : typeof o$1;
    }, module.exports.__esModule = true, module.exports["default"] = module.exports, _typeof$2(o);
  }
  module.exports = _typeof$2, module.exports.__esModule = true, module.exports["default"] = module.exports;
} });
var require_toPrimitive = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/toPrimitive.js"(exports, module) {
  var _typeof$1 = require_typeof()["default"];
  function toPrimitive$1(t, r) {
    if ("object" != _typeof$1(t) || !t) return t;
    var e = t[Symbol.toPrimitive];
    if (void 0 !== e) {
      var i = e.call(t, r || "default");
      if ("object" != _typeof$1(i)) return i;
      throw new TypeError("@@toPrimitive must return a primitive value.");
    }
    return ("string" === r ? String : Number)(t);
  }
  module.exports = toPrimitive$1, module.exports.__esModule = true, module.exports["default"] = module.exports;
} });
var require_toPropertyKey = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/toPropertyKey.js"(exports, module) {
  var _typeof = require_typeof()["default"];
  var toPrimitive = require_toPrimitive();
  function toPropertyKey$1(t) {
    var i = toPrimitive(t, "string");
    return "symbol" == _typeof(i) ? i : i + "";
  }
  module.exports = toPropertyKey$1, module.exports.__esModule = true, module.exports["default"] = module.exports;
} });
var require_defineProperty = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/defineProperty.js"(exports, module) {
  var toPropertyKey = require_toPropertyKey();
  function _defineProperty(e, r, t) {
    return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
      value: t,
      enumerable: true,
      configurable: true,
      writable: true
    }) : e[r] = t, e;
  }
  module.exports = _defineProperty, module.exports.__esModule = true, module.exports["default"] = module.exports;
} });
var require_objectSpread2 = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/objectSpread2.js"(exports, module) {
  var defineProperty = require_defineProperty();
  function ownKeys(e, r) {
    var t = Object.keys(e);
    if (Object.getOwnPropertySymbols) {
      var o = Object.getOwnPropertySymbols(e);
      r && (o = o.filter(function(r$1) {
        return Object.getOwnPropertyDescriptor(e, r$1).enumerable;
      })), t.push.apply(t, o);
    }
    return t;
  }
  function _objectSpread2(e) {
    for (var r = 1; r < arguments.length; r++) {
      var t = null != arguments[r] ? arguments[r] : {};
      r % 2 ? ownKeys(Object(t), true).forEach(function(r$1) {
        defineProperty(e, r$1, t[r$1]);
      }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r$1) {
        Object.defineProperty(e, r$1, Object.getOwnPropertyDescriptor(t, r$1));
      });
    }
    return e;
  }
  module.exports = _objectSpread2, module.exports.__esModule = true, module.exports["default"] = module.exports;
} });

// ../../node_modules/.pnpm/@trpc+server@11.8.1_typescript@5.9.3/node_modules/@trpc/server/dist/observable-UMO3vUa_.mjs
function observable(subscribe) {
  const self = {
    subscribe(observer) {
      let teardownRef = null;
      let isDone = false;
      let unsubscribed = false;
      let teardownImmediately = false;
      function unsubscribe() {
        if (teardownRef === null) {
          teardownImmediately = true;
          return;
        }
        if (unsubscribed) return;
        unsubscribed = true;
        if (typeof teardownRef === "function") teardownRef();
        else if (teardownRef) teardownRef.unsubscribe();
      }
      teardownRef = subscribe({
        next(value) {
          var _observer$next;
          if (isDone) return;
          (_observer$next = observer.next) === null || _observer$next === void 0 || _observer$next.call(observer, value);
        },
        error(err) {
          var _observer$error;
          if (isDone) return;
          isDone = true;
          (_observer$error = observer.error) === null || _observer$error === void 0 || _observer$error.call(observer, err);
          unsubscribe();
        },
        complete() {
          var _observer$complete;
          if (isDone) return;
          isDone = true;
          (_observer$complete = observer.complete) === null || _observer$complete === void 0 || _observer$complete.call(observer);
          unsubscribe();
        }
      });
      if (teardownImmediately) unsubscribe();
      return { unsubscribe };
    },
    pipe(...operations) {
      return operations.reduce(pipeReducer, self);
    }
  };
  return self;
}
function pipeReducer(prev, fn) {
  return fn(prev);
}
function observableToPromise(observable$1) {
  const ac = new AbortController();
  const promise = new Promise((resolve, reject) => {
    let isDone = false;
    function onDone() {
      if (isDone) return;
      isDone = true;
      obs$.unsubscribe();
    }
    ac.signal.addEventListener("abort", () => {
      reject(ac.signal.reason);
    });
    const obs$ = observable$1.subscribe({
      next(data) {
        isDone = true;
        resolve(data);
        onDone();
      },
      error(data) {
        reject(data);
      },
      complete() {
        ac.abort();
        onDone();
      }
    });
  });
  return promise;
}

// ../../node_modules/.pnpm/@trpc+server@11.8.1_typescript@5.9.3/node_modules/@trpc/server/dist/observable-CUiPknO-.mjs
function share(_opts) {
  return (source) => {
    let refCount = 0;
    let subscription = null;
    const observers = [];
    function startIfNeeded() {
      if (subscription) return;
      subscription = source.subscribe({
        next(value) {
          for (const observer of observers) {
            var _observer$next;
            (_observer$next = observer.next) === null || _observer$next === void 0 || _observer$next.call(observer, value);
          }
        },
        error(error) {
          for (const observer of observers) {
            var _observer$error;
            (_observer$error = observer.error) === null || _observer$error === void 0 || _observer$error.call(observer, error);
          }
        },
        complete() {
          for (const observer of observers) {
            var _observer$complete;
            (_observer$complete = observer.complete) === null || _observer$complete === void 0 || _observer$complete.call(observer);
          }
        }
      });
    }
    function resetIfNeeded() {
      if (refCount === 0 && subscription) {
        const _sub = subscription;
        subscription = null;
        _sub.unsubscribe();
      }
    }
    return observable((subscriber) => {
      refCount++;
      observers.push(subscriber);
      startIfNeeded();
      return { unsubscribe() {
        refCount--;
        resetIfNeeded();
        const index = observers.findIndex((v) => v === subscriber);
        if (index > -1) observers.splice(index, 1);
      } };
    });
  };
}
function tap(observer) {
  return (source) => {
    return observable((destination) => {
      return source.subscribe({
        next(value) {
          var _observer$next2;
          (_observer$next2 = observer.next) === null || _observer$next2 === void 0 || _observer$next2.call(observer, value);
          destination.next(value);
        },
        error(error) {
          var _observer$error2;
          (_observer$error2 = observer.error) === null || _observer$error2 === void 0 || _observer$error2.call(observer, error);
          destination.error(error);
        },
        complete() {
          var _observer$complete2;
          (_observer$complete2 = observer.complete) === null || _observer$complete2 === void 0 || _observer$complete2.call(observer);
          destination.complete();
        }
      });
    });
  };
}
var distinctUnsetMarker = Symbol();
function behaviorSubject(initialValue) {
  let value = initialValue;
  const observerList = [];
  const addObserver = (observer) => {
    if (value !== void 0) observer.next(value);
    observerList.push(observer);
  };
  const removeObserver = (observer) => {
    observerList.splice(observerList.indexOf(observer), 1);
  };
  const obs = observable((observer) => {
    addObserver(observer);
    return () => {
      removeObserver(observer);
    };
  });
  obs.next = (nextValue) => {
    if (value === nextValue) return;
    value = nextValue;
    for (const observer of observerList) observer.next(nextValue);
  };
  obs.get = () => value;
  return obs;
}

// ../../node_modules/.pnpm/@trpc+client@11.8.1_@trpc+server@11.8.1_typescript@5.9.3__typescript@5.9.3/node_modules/@trpc/client/dist/splitLink-B7Cuf2c_.mjs
function createChain(opts) {
  return observable((observer) => {
    function execute(index = 0, op = opts.op) {
      const next = opts.links[index];
      if (!next) throw new Error("No more links to execute - did you forget to add an ending link?");
      const subscription = next({
        op,
        next(nextOp) {
          const nextObserver = execute(index + 1, nextOp);
          return nextObserver;
        }
      });
      return subscription;
    }
    const obs$ = execute();
    return obs$.subscribe(observer);
  });
}
function asArray(value) {
  return Array.isArray(value) ? value : [value];
}
function splitLink(opts) {
  return (runtime) => {
    const yes = asArray(opts.true).map((link) => link(runtime));
    const no = asArray(opts.false).map((link) => link(runtime));
    return (props) => {
      return observable((observer) => {
        const links = opts.condition(props.op) ? yes : no;
        return createChain({
          op: props.op,
          links
        }).subscribe(observer);
      });
    };
  };
}

// ../../node_modules/.pnpm/@trpc+server@11.8.1_typescript@5.9.3/node_modules/@trpc/server/dist/codes-DagpWZLc.mjs
function mergeWithoutOverrides(obj1, ...objs) {
  const newObj = Object.assign(emptyObject(), obj1);
  for (const overrides of objs) for (const key in overrides) {
    if (key in newObj && newObj[key] !== overrides[key]) throw new Error(`Duplicate key ${key}`);
    newObj[key] = overrides[key];
  }
  return newObj;
}
function isObject(value) {
  return !!value && !Array.isArray(value) && typeof value === "object";
}
function isFunction(fn) {
  return typeof fn === "function";
}
function emptyObject() {
  return /* @__PURE__ */ Object.create(null);
}
var asyncIteratorsSupported = typeof Symbol === "function" && !!Symbol.asyncIterator;
function isAsyncIterable(value) {
  return asyncIteratorsSupported && isObject(value) && Symbol.asyncIterator in value;
}
var run = (fn) => fn();
function sleep(ms = 0) {
  return new Promise((res) => setTimeout(res, ms));
}
var TRPC_ERROR_CODES_BY_KEY = {
  PARSE_ERROR: -32700,
  BAD_REQUEST: -32600,
  INTERNAL_SERVER_ERROR: -32603,
  NOT_IMPLEMENTED: -32603,
  BAD_GATEWAY: -32603,
  SERVICE_UNAVAILABLE: -32603,
  GATEWAY_TIMEOUT: -32603,
  UNAUTHORIZED: -32001,
  PAYMENT_REQUIRED: -32002,
  FORBIDDEN: -32003,
  NOT_FOUND: -32004,
  METHOD_NOT_SUPPORTED: -32005,
  TIMEOUT: -32008,
  CONFLICT: -32009,
  PRECONDITION_FAILED: -32012,
  PAYLOAD_TOO_LARGE: -32013,
  UNSUPPORTED_MEDIA_TYPE: -32015,
  UNPROCESSABLE_CONTENT: -32022,
  PRECONDITION_REQUIRED: -32028,
  TOO_MANY_REQUESTS: -32029,
  CLIENT_CLOSED_REQUEST: -32099
};
var retryableRpcCodes = [
  TRPC_ERROR_CODES_BY_KEY.BAD_GATEWAY,
  TRPC_ERROR_CODES_BY_KEY.SERVICE_UNAVAILABLE,
  TRPC_ERROR_CODES_BY_KEY.GATEWAY_TIMEOUT,
  TRPC_ERROR_CODES_BY_KEY.INTERNAL_SERVER_ERROR
];

// ../../node_modules/.pnpm/@trpc+server@11.8.1_typescript@5.9.3/node_modules/@trpc/server/dist/getErrorShape-vC8mUXJD.mjs
var __create2 = Object.create;
var __defProp2 = Object.defineProperty;
var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
var __getOwnPropNames2 = Object.getOwnPropertyNames;
var __getProtoOf2 = Object.getPrototypeOf;
var __hasOwnProp2 = Object.prototype.hasOwnProperty;
var __commonJS2 = (cb, mod) => function() {
  return mod || (0, cb[__getOwnPropNames2(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __copyProps2 = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames2(from), i = 0, n = keys.length, key; i < n; i++) {
    key = keys[i];
    if (!__hasOwnProp2.call(to, key) && key !== except) __defProp2(to, key, {
      get: ((k) => from[k]).bind(null, key),
      enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable
    });
  }
  return to;
};
var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2(isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", {
  value: mod,
  enumerable: true
}) : target, mod));
var noop = () => {
};
var freezeIfAvailable = (obj) => {
  if (Object.freeze) Object.freeze(obj);
};
function createInnerProxy(callback, path, memo) {
  var _memo$cacheKey;
  const cacheKey = path.join(".");
  (_memo$cacheKey = memo[cacheKey]) !== null && _memo$cacheKey !== void 0 || (memo[cacheKey] = new Proxy(noop, {
    get(_obj, key) {
      if (typeof key !== "string" || key === "then") return void 0;
      return createInnerProxy(callback, [...path, key], memo);
    },
    apply(_1, _2, args) {
      const lastOfPath = path[path.length - 1];
      let opts = {
        args,
        path
      };
      if (lastOfPath === "call") opts = {
        args: args.length >= 2 ? [args[1]] : [],
        path: path.slice(0, -1)
      };
      else if (lastOfPath === "apply") opts = {
        args: args.length >= 2 ? args[1] : [],
        path: path.slice(0, -1)
      };
      freezeIfAvailable(opts.args);
      freezeIfAvailable(opts.path);
      return callback(opts);
    }
  }));
  return memo[cacheKey];
}
var createRecursiveProxy = (callback) => createInnerProxy(callback, [], emptyObject());
var createFlatProxy = (callback) => {
  return new Proxy(noop, { get(_obj, name) {
    if (name === "then") return void 0;
    return callback(name);
  } });
};
var JSONRPC2_TO_HTTP_CODE = {
  PARSE_ERROR: 400,
  BAD_REQUEST: 400,
  UNAUTHORIZED: 401,
  PAYMENT_REQUIRED: 402,
  FORBIDDEN: 403,
  NOT_FOUND: 404,
  METHOD_NOT_SUPPORTED: 405,
  TIMEOUT: 408,
  CONFLICT: 409,
  PRECONDITION_FAILED: 412,
  PAYLOAD_TOO_LARGE: 413,
  UNSUPPORTED_MEDIA_TYPE: 415,
  UNPROCESSABLE_CONTENT: 422,
  PRECONDITION_REQUIRED: 428,
  TOO_MANY_REQUESTS: 429,
  CLIENT_CLOSED_REQUEST: 499,
  INTERNAL_SERVER_ERROR: 500,
  NOT_IMPLEMENTED: 501,
  BAD_GATEWAY: 502,
  SERVICE_UNAVAILABLE: 503,
  GATEWAY_TIMEOUT: 504
};
function getStatusCodeFromKey(code) {
  var _JSONRPC2_TO_HTTP_COD;
  return (_JSONRPC2_TO_HTTP_COD = JSONRPC2_TO_HTTP_CODE[code]) !== null && _JSONRPC2_TO_HTTP_COD !== void 0 ? _JSONRPC2_TO_HTTP_COD : 500;
}
function getHTTPStatusCodeFromError(error) {
  return getStatusCodeFromKey(error.code);
}
var require_typeof2 = __commonJS2({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/typeof.js"(exports, module) {
  function _typeof$2(o) {
    "@babel/helpers - typeof";
    return module.exports = _typeof$2 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$1) {
      return typeof o$1;
    } : function(o$1) {
      return o$1 && "function" == typeof Symbol && o$1.constructor === Symbol && o$1 !== Symbol.prototype ? "symbol" : typeof o$1;
    }, module.exports.__esModule = true, module.exports["default"] = module.exports, _typeof$2(o);
  }
  module.exports = _typeof$2, module.exports.__esModule = true, module.exports["default"] = module.exports;
} });
var require_toPrimitive2 = __commonJS2({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/toPrimitive.js"(exports, module) {
  var _typeof$1 = require_typeof2()["default"];
  function toPrimitive$1(t, r) {
    if ("object" != _typeof$1(t) || !t) return t;
    var e = t[Symbol.toPrimitive];
    if (void 0 !== e) {
      var i = e.call(t, r || "default");
      if ("object" != _typeof$1(i)) return i;
      throw new TypeError("@@toPrimitive must return a primitive value.");
    }
    return ("string" === r ? String : Number)(t);
  }
  module.exports = toPrimitive$1, module.exports.__esModule = true, module.exports["default"] = module.exports;
} });
var require_toPropertyKey2 = __commonJS2({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/toPropertyKey.js"(exports, module) {
  var _typeof = require_typeof2()["default"];
  var toPrimitive = require_toPrimitive2();
  function toPropertyKey$1(t) {
    var i = toPrimitive(t, "string");
    return "symbol" == _typeof(i) ? i : i + "";
  }
  module.exports = toPropertyKey$1, module.exports.__esModule = true, module.exports["default"] = module.exports;
} });
var require_defineProperty2 = __commonJS2({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/defineProperty.js"(exports, module) {
  var toPropertyKey = require_toPropertyKey2();
  function _defineProperty(e, r, t) {
    return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
      value: t,
      enumerable: true,
      configurable: true,
      writable: true
    }) : e[r] = t, e;
  }
  module.exports = _defineProperty, module.exports.__esModule = true, module.exports["default"] = module.exports;
} });
var require_objectSpread22 = __commonJS2({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/objectSpread2.js"(exports, module) {
  var defineProperty = require_defineProperty2();
  function ownKeys(e, r) {
    var t = Object.keys(e);
    if (Object.getOwnPropertySymbols) {
      var o = Object.getOwnPropertySymbols(e);
      r && (o = o.filter(function(r$1) {
        return Object.getOwnPropertyDescriptor(e, r$1).enumerable;
      })), t.push.apply(t, o);
    }
    return t;
  }
  function _objectSpread2(e) {
    for (var r = 1; r < arguments.length; r++) {
      var t = null != arguments[r] ? arguments[r] : {};
      r % 2 ? ownKeys(Object(t), true).forEach(function(r$1) {
        defineProperty(e, r$1, t[r$1]);
      }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r$1) {
        Object.defineProperty(e, r$1, Object.getOwnPropertyDescriptor(t, r$1));
      });
    }
    return e;
  }
  module.exports = _objectSpread2, module.exports.__esModule = true, module.exports["default"] = module.exports;
} });
var import_objectSpread2 = __toESM2(require_objectSpread22(), 1);
function getErrorShape(opts) {
  const { path, error, config } = opts;
  const { code } = opts.error;
  const shape = {
    message: error.message,
    code: TRPC_ERROR_CODES_BY_KEY[code],
    data: {
      code,
      httpStatus: getHTTPStatusCodeFromError(error)
    }
  };
  if (config.isDev && typeof opts.error.stack === "string") shape.data.stack = opts.error.stack;
  if (typeof path === "string") shape.data.path = path;
  return config.errorFormatter((0, import_objectSpread2.default)((0, import_objectSpread2.default)({}, opts), {}, { shape }));
}

// ../../node_modules/.pnpm/@trpc+server@11.8.1_typescript@5.9.3/node_modules/@trpc/server/dist/tracked-D4V22yc5.mjs
var defaultFormatter = ({ shape }) => {
  return shape;
};
var import_defineProperty = __toESM2(require_defineProperty2(), 1);
var UnknownCauseError = class extends Error {
};
function getCauseFromUnknown(cause) {
  if (cause instanceof Error) return cause;
  const type = typeof cause;
  if (type === "undefined" || type === "function" || cause === null) return void 0;
  if (type !== "object") return new Error(String(cause));
  if (isObject(cause)) return Object.assign(new UnknownCauseError(), cause);
  return void 0;
}
function getTRPCErrorFromUnknown(cause) {
  if (cause instanceof TRPCError) return cause;
  if (cause instanceof Error && cause.name === "TRPCError") return cause;
  const trpcError = new TRPCError({
    code: "INTERNAL_SERVER_ERROR",
    cause
  });
  if (cause instanceof Error && cause.stack) trpcError.stack = cause.stack;
  return trpcError;
}
var TRPCError = class extends Error {
  constructor(opts) {
    var _ref, _opts$message, _this$cause;
    const cause = getCauseFromUnknown(opts.cause);
    const message = (_ref = (_opts$message = opts.message) !== null && _opts$message !== void 0 ? _opts$message : cause === null || cause === void 0 ? void 0 : cause.message) !== null && _ref !== void 0 ? _ref : opts.code;
    super(message, { cause });
    (0, import_defineProperty.default)(this, "cause", void 0);
    (0, import_defineProperty.default)(this, "code", void 0);
    this.code = opts.code;
    this.name = "TRPCError";
    (_this$cause = this.cause) !== null && _this$cause !== void 0 || (this.cause = cause);
  }
};
var import_objectSpread2$1 = __toESM2(require_objectSpread22(), 1);
function getDataTransformer(transformer) {
  if ("input" in transformer) return transformer;
  return {
    input: transformer,
    output: transformer
  };
}
var defaultTransformer = {
  input: {
    serialize: (obj) => obj,
    deserialize: (obj) => obj
  },
  output: {
    serialize: (obj) => obj,
    deserialize: (obj) => obj
  }
};
function transformResultInner(response, transformer) {
  if ("error" in response) {
    const error = transformer.deserialize(response.error);
    return {
      ok: false,
      error: (0, import_objectSpread2$1.default)((0, import_objectSpread2$1.default)({}, response), {}, { error })
    };
  }
  const result = (0, import_objectSpread2$1.default)((0, import_objectSpread2$1.default)({}, response.result), (!response.result.type || response.result.type === "data") && {
    type: "data",
    data: transformer.deserialize(response.result.data)
  });
  return {
    ok: true,
    result
  };
}
var TransformResultError = class extends Error {
  constructor() {
    super("Unable to transform response from server");
  }
};
function transformResult(response, transformer) {
  let result;
  try {
    result = transformResultInner(response, transformer);
  } catch (_unused) {
    throw new TransformResultError();
  }
  if (!result.ok && (!isObject(result.error.error) || typeof result.error.error["code"] !== "number")) throw new TransformResultError();
  if (result.ok && !isObject(result.result)) throw new TransformResultError();
  return result;
}
var import_objectSpread22 = __toESM2(require_objectSpread22(), 1);
var lazyMarker = "lazyMarker";
function once(fn) {
  const uncalled = Symbol();
  let result = uncalled;
  return () => {
    if (result === uncalled) result = fn();
    return result;
  };
}
function isLazy(input) {
  return typeof input === "function" && lazyMarker in input;
}
function isRouter(value) {
  return isObject(value) && isObject(value["_def"]) && "router" in value["_def"];
}
var emptyRouter = {
  _ctx: null,
  _errorShape: null,
  _meta: null,
  queries: {},
  mutations: {},
  subscriptions: {},
  errorFormatter: defaultFormatter,
  transformer: defaultTransformer
};
var reservedWords = [
  "then",
  "call",
  "apply"
];
function createRouterFactory(config) {
  function createRouterInner(input) {
    const reservedWordsUsed = new Set(Object.keys(input).filter((v) => reservedWords.includes(v)));
    if (reservedWordsUsed.size > 0) throw new Error("Reserved words used in `router({})` call: " + Array.from(reservedWordsUsed).join(", "));
    const procedures = emptyObject();
    const lazy$1 = emptyObject();
    function createLazyLoader(opts) {
      return {
        ref: opts.ref,
        load: once(async () => {
          const router$1 = await opts.ref();
          const lazyPath = [...opts.path, opts.key];
          const lazyKey = lazyPath.join(".");
          opts.aggregate[opts.key] = step(router$1._def.record, lazyPath);
          delete lazy$1[lazyKey];
          for (const [nestedKey, nestedItem] of Object.entries(router$1._def.lazy)) {
            const nestedRouterKey = [...lazyPath, nestedKey].join(".");
            lazy$1[nestedRouterKey] = createLazyLoader({
              ref: nestedItem.ref,
              path: lazyPath,
              key: nestedKey,
              aggregate: opts.aggregate[opts.key]
            });
          }
        })
      };
    }
    function step(from, path = []) {
      const aggregate = emptyObject();
      for (const [key, item] of Object.entries(from !== null && from !== void 0 ? from : {})) {
        if (isLazy(item)) {
          lazy$1[[...path, key].join(".")] = createLazyLoader({
            path,
            ref: item,
            key,
            aggregate
          });
          continue;
        }
        if (isRouter(item)) {
          aggregate[key] = step(item._def.record, [...path, key]);
          continue;
        }
        if (!isProcedure(item)) {
          aggregate[key] = step(item, [...path, key]);
          continue;
        }
        const newPath = [...path, key].join(".");
        if (procedures[newPath]) throw new Error(`Duplicate key: ${newPath}`);
        procedures[newPath] = item;
        aggregate[key] = item;
      }
      return aggregate;
    }
    const record = step(input);
    const _def = (0, import_objectSpread22.default)((0, import_objectSpread22.default)({
      _config: config,
      router: true,
      procedures,
      lazy: lazy$1
    }, emptyRouter), {}, { record });
    const router = (0, import_objectSpread22.default)((0, import_objectSpread22.default)({}, record), {}, {
      _def,
      createCaller: createCallerFactory()({ _def })
    });
    return router;
  }
  return createRouterInner;
}
function isProcedure(procedureOrRouter) {
  return typeof procedureOrRouter === "function";
}
async function getProcedureAtPath(router, path) {
  const { _def } = router;
  let procedure = _def.procedures[path];
  while (!procedure) {
    const key = Object.keys(_def.lazy).find((key$1) => path.startsWith(key$1));
    if (!key) return null;
    const lazyRouter = _def.lazy[key];
    await lazyRouter.load();
    procedure = _def.procedures[path];
  }
  return procedure;
}
async function callProcedure(opts) {
  const { type, path } = opts;
  const proc = await getProcedureAtPath(opts.router, path);
  if (!proc || !isProcedure(proc) || proc._def.type !== type && !opts.allowMethodOverride) throw new TRPCError({
    code: "NOT_FOUND",
    message: `No "${type}"-procedure on path "${path}"`
  });
  if (proc._def.type !== type && opts.allowMethodOverride && proc._def.type === "subscription") throw new TRPCError({
    code: "METHOD_NOT_SUPPORTED",
    message: `Method override is not supported for subscriptions`
  });
  return proc(opts);
}
function createCallerFactory() {
  return function createCallerInner(router) {
    const { _def } = router;
    return function createCaller(ctxOrCallback, opts) {
      return createRecursiveProxy(async (innerOpts) => {
        const { path, args } = innerOpts;
        const fullPath = path.join(".");
        if (path.length === 1 && path[0] === "_def") return _def;
        const procedure = await getProcedureAtPath(router, fullPath);
        let ctx = void 0;
        try {
          if (!procedure) throw new TRPCError({
            code: "NOT_FOUND",
            message: `No procedure found on path "${path}"`
          });
          ctx = isFunction(ctxOrCallback) ? await Promise.resolve(ctxOrCallback()) : ctxOrCallback;
          return await procedure({
            path: fullPath,
            getRawInput: async () => args[0],
            ctx,
            type: procedure._def.type,
            signal: opts === null || opts === void 0 ? void 0 : opts.signal
          });
        } catch (cause) {
          var _opts$onError, _procedure$_def$type;
          opts === null || opts === void 0 || (_opts$onError = opts.onError) === null || _opts$onError === void 0 || _opts$onError.call(opts, {
            ctx,
            error: getTRPCErrorFromUnknown(cause),
            input: args[0],
            path: fullPath,
            type: (_procedure$_def$type = procedure === null || procedure === void 0 ? void 0 : procedure._def.type) !== null && _procedure$_def$type !== void 0 ? _procedure$_def$type : "unknown"
          });
          throw cause;
        }
      });
    };
  };
}
function mergeRouters(...routerList) {
  var _routerList$, _routerList$2;
  const record = mergeWithoutOverrides({}, ...routerList.map((r) => r._def.record));
  const errorFormatter = routerList.reduce((currentErrorFormatter, nextRouter) => {
    if (nextRouter._def._config.errorFormatter && nextRouter._def._config.errorFormatter !== defaultFormatter) {
      if (currentErrorFormatter !== defaultFormatter && currentErrorFormatter !== nextRouter._def._config.errorFormatter) throw new Error("You seem to have several error formatters");
      return nextRouter._def._config.errorFormatter;
    }
    return currentErrorFormatter;
  }, defaultFormatter);
  const transformer = routerList.reduce((prev, current) => {
    if (current._def._config.transformer && current._def._config.transformer !== defaultTransformer) {
      if (prev !== defaultTransformer && prev !== current._def._config.transformer) throw new Error("You seem to have several transformers");
      return current._def._config.transformer;
    }
    return prev;
  }, defaultTransformer);
  const router = createRouterFactory({
    errorFormatter,
    transformer,
    isDev: routerList.every((r) => r._def._config.isDev),
    allowOutsideOfServer: routerList.every((r) => r._def._config.allowOutsideOfServer),
    isServer: routerList.every((r) => r._def._config.isServer),
    $types: (_routerList$ = routerList[0]) === null || _routerList$ === void 0 ? void 0 : _routerList$._def._config.$types,
    sse: (_routerList$2 = routerList[0]) === null || _routerList$2 === void 0 ? void 0 : _routerList$2._def._config.sse
  })(record);
  return router;
}
var trackedSymbol = Symbol();
function isTrackedEnvelope(value) {
  return Array.isArray(value) && value[2] === trackedSymbol;
}

// ../../node_modules/.pnpm/@trpc+server@11.8.1_typescript@5.9.3/node_modules/@trpc/server/dist/resolveResponse-C7AcnFLN.mjs
var import_objectSpread2$12 = __toESM2(require_objectSpread22(), 1);
function isAbortError(error) {
  return isObject(error) && error["name"] === "AbortError";
}
var import_defineProperty2 = __toESM2(require_defineProperty2(), 1);
var _Symbol$toStringTag;
var subscribableCache = /* @__PURE__ */ new WeakMap();
var NOOP = () => {
};
_Symbol$toStringTag = Symbol.toStringTag;
var Unpromise = class Unpromise2 {
  constructor(arg) {
    (0, import_defineProperty2.default)(this, "promise", void 0);
    (0, import_defineProperty2.default)(this, "subscribers", []);
    (0, import_defineProperty2.default)(this, "settlement", null);
    (0, import_defineProperty2.default)(this, _Symbol$toStringTag, "Unpromise");
    if (typeof arg === "function") this.promise = new Promise(arg);
    else this.promise = arg;
    const thenReturn = this.promise.then((value) => {
      const { subscribers } = this;
      this.subscribers = null;
      this.settlement = {
        status: "fulfilled",
        value
      };
      subscribers === null || subscribers === void 0 || subscribers.forEach(({ resolve }) => {
        resolve(value);
      });
    });
    if ("catch" in thenReturn) thenReturn.catch((reason) => {
      const { subscribers } = this;
      this.subscribers = null;
      this.settlement = {
        status: "rejected",
        reason
      };
      subscribers === null || subscribers === void 0 || subscribers.forEach(({ reject }) => {
        reject(reason);
      });
    });
  }
  /** Create a promise that mitigates uncontrolled subscription to a long-lived
  * Promise via .then() and .catch() - otherwise a source of memory leaks.
  *
  * The returned promise has an `unsubscribe()` method which can be called when
  * the Promise is no longer being tracked by application logic, and which
  * ensures that there is no reference chain from the original promise to the
  * new one, and therefore no memory leak.
  *
  * If original promise has not yet settled, this adds a new unique promise
  * that listens to then/catch events, along with an `unsubscribe()` method to
  * detach it.
  *
  * If original promise has settled, then creates a new Promise.resolve() or
  * Promise.reject() and provided unsubscribe is a noop.
  *
  * If you call `unsubscribe()` before the returned Promise has settled, it
  * will never settle.
  */
  subscribe() {
    let promise;
    let unsubscribe;
    const { settlement } = this;
    if (settlement === null) {
      if (this.subscribers === null) throw new Error("Unpromise settled but still has subscribers");
      const subscriber = withResolvers();
      this.subscribers = listWithMember(this.subscribers, subscriber);
      promise = subscriber.promise;
      unsubscribe = () => {
        if (this.subscribers !== null) this.subscribers = listWithoutMember(this.subscribers, subscriber);
      };
    } else {
      const { status } = settlement;
      if (status === "fulfilled") promise = Promise.resolve(settlement.value);
      else promise = Promise.reject(settlement.reason);
      unsubscribe = NOOP;
    }
    return Object.assign(promise, { unsubscribe });
  }
  /** STANDARD PROMISE METHODS (but returning a SubscribedPromise) */
  then(onfulfilled, onrejected) {
    const subscribed = this.subscribe();
    const { unsubscribe } = subscribed;
    return Object.assign(subscribed.then(onfulfilled, onrejected), { unsubscribe });
  }
  catch(onrejected) {
    const subscribed = this.subscribe();
    const { unsubscribe } = subscribed;
    return Object.assign(subscribed.catch(onrejected), { unsubscribe });
  }
  finally(onfinally) {
    const subscribed = this.subscribe();
    const { unsubscribe } = subscribed;
    return Object.assign(subscribed.finally(onfinally), { unsubscribe });
  }
  /** Unpromise STATIC METHODS */
  /** Create or Retrieve the proxy Unpromise (a re-used Unpromise for the VM lifetime
  * of the provided Promise reference) */
  static proxy(promise) {
    const cached = Unpromise2.getSubscribablePromise(promise);
    return typeof cached !== "undefined" ? cached : Unpromise2.createSubscribablePromise(promise);
  }
  /** Create and store an Unpromise keyed by an original Promise. */
  static createSubscribablePromise(promise) {
    const created = new Unpromise2(promise);
    subscribableCache.set(promise, created);
    subscribableCache.set(created, created);
    return created;
  }
  /** Retrieve a previously-created Unpromise keyed by an original Promise. */
  static getSubscribablePromise(promise) {
    return subscribableCache.get(promise);
  }
  /** Promise STATIC METHODS */
  /** Lookup the Unpromise for this promise, and derive a SubscribedPromise from
  * it (that can be later unsubscribed to eliminate Memory leaks) */
  static resolve(value) {
    const promise = typeof value === "object" && value !== null && "then" in value && typeof value.then === "function" ? value : Promise.resolve(value);
    return Unpromise2.proxy(promise).subscribe();
  }
  static async any(values) {
    const valuesArray = Array.isArray(values) ? values : [...values];
    const subscribedPromises = valuesArray.map(Unpromise2.resolve);
    try {
      return await Promise.any(subscribedPromises);
    } finally {
      subscribedPromises.forEach(({ unsubscribe }) => {
        unsubscribe();
      });
    }
  }
  static async race(values) {
    const valuesArray = Array.isArray(values) ? values : [...values];
    const subscribedPromises = valuesArray.map(Unpromise2.resolve);
    try {
      return await Promise.race(subscribedPromises);
    } finally {
      subscribedPromises.forEach(({ unsubscribe }) => {
        unsubscribe();
      });
    }
  }
  /** Create a race of SubscribedPromises that will fulfil to a single winning
  * Promise (in a 1-Tuple). Eliminates memory leaks from long-lived promises
  * accumulating .then() and .catch() subscribers. Allows simple logic to
  * consume the result, like...
  * ```ts
  * const [ winner ] = await Unpromise.race([ promiseA, promiseB ]);
  * if(winner === promiseB){
  *   const result = await promiseB;
  *   // do the thing
  * }
  * ```
  * */
  static async raceReferences(promises) {
    const selfPromises = promises.map(resolveSelfTuple);
    try {
      return await Promise.race(selfPromises);
    } finally {
      for (const promise of selfPromises) promise.unsubscribe();
    }
  }
};
function resolveSelfTuple(promise) {
  return Unpromise.proxy(promise).then(() => [promise]);
}
function withResolvers() {
  let resolve;
  let reject;
  const promise = new Promise((_resolve, _reject) => {
    resolve = _resolve;
    reject = _reject;
  });
  return {
    promise,
    resolve,
    reject
  };
}
function listWithMember(arr, member) {
  return [...arr, member];
}
function listWithoutIndex(arr, index) {
  return [...arr.slice(0, index), ...arr.slice(index + 1)];
}
function listWithoutMember(arr, member) {
  const index = arr.indexOf(member);
  if (index !== -1) return listWithoutIndex(arr, index);
  return arr;
}
var _Symbol;
var _Symbol$dispose;
var _Symbol2;
var _Symbol2$asyncDispose;
(_Symbol$dispose = (_Symbol = Symbol).dispose) !== null && _Symbol$dispose !== void 0 || (_Symbol.dispose = Symbol());
(_Symbol2$asyncDispose = (_Symbol2 = Symbol).asyncDispose) !== null && _Symbol2$asyncDispose !== void 0 || (_Symbol2.asyncDispose = Symbol());
function makeResource(thing, dispose) {
  const it = thing;
  const existing = it[Symbol.dispose];
  it[Symbol.dispose] = () => {
    dispose();
    existing === null || existing === void 0 || existing();
  };
  return it;
}
function makeAsyncResource(thing, dispose) {
  const it = thing;
  const existing = it[Symbol.asyncDispose];
  it[Symbol.asyncDispose] = async () => {
    await dispose();
    await (existing === null || existing === void 0 ? void 0 : existing());
  };
  return it;
}
var disposablePromiseTimerResult = Symbol();
function timerResource(ms) {
  let timer = null;
  return makeResource({ start() {
    if (timer) throw new Error("Timer already started");
    const promise = new Promise((resolve) => {
      timer = setTimeout(() => resolve(disposablePromiseTimerResult), ms);
    });
    return promise;
  } }, () => {
    if (timer) clearTimeout(timer);
  });
}
var require_usingCtx = __commonJS2({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/usingCtx.js"(exports, module) {
  function _usingCtx() {
    var r = "function" == typeof SuppressedError ? SuppressedError : function(r$1, e$1) {
      var n$1 = Error();
      return n$1.name = "SuppressedError", n$1.error = r$1, n$1.suppressed = e$1, n$1;
    }, e = {}, n = [];
    function using(r$1, e$1) {
      if (null != e$1) {
        if (Object(e$1) !== e$1) throw new TypeError("using declarations can only be used with objects, functions, null, or undefined.");
        if (r$1) var o = e$1[Symbol.asyncDispose || Symbol["for"]("Symbol.asyncDispose")];
        if (void 0 === o && (o = e$1[Symbol.dispose || Symbol["for"]("Symbol.dispose")], r$1)) var t = o;
        if ("function" != typeof o) throw new TypeError("Object is not disposable.");
        t && (o = function o$1() {
          try {
            t.call(e$1);
          } catch (r$2) {
            return Promise.reject(r$2);
          }
        }), n.push({
          v: e$1,
          d: o,
          a: r$1
        });
      } else r$1 && n.push({
        d: e$1,
        a: r$1
      });
      return e$1;
    }
    return {
      e,
      u: using.bind(null, false),
      a: using.bind(null, true),
      d: function d() {
        var o, t = this.e, s = 0;
        function next() {
          for (; o = n.pop(); ) try {
            if (!o.a && 1 === s) return s = 0, n.push(o), Promise.resolve().then(next);
            if (o.d) {
              var r$1 = o.d.call(o.v);
              if (o.a) return s |= 2, Promise.resolve(r$1).then(next, err);
            } else s |= 1;
          } catch (r$2) {
            return err(r$2);
          }
          if (1 === s) return t !== e ? Promise.reject(t) : Promise.resolve();
          if (t !== e) throw t;
        }
        function err(n$1) {
          return t = t !== e ? new r(n$1, t) : n$1, next();
        }
        return next();
      }
    };
  }
  module.exports = _usingCtx, module.exports.__esModule = true, module.exports["default"] = module.exports;
} });
var require_OverloadYield = __commonJS2({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/OverloadYield.js"(exports, module) {
  function _OverloadYield(e, d) {
    this.v = e, this.k = d;
  }
  module.exports = _OverloadYield, module.exports.__esModule = true, module.exports["default"] = module.exports;
} });
var require_awaitAsyncGenerator = __commonJS2({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/awaitAsyncGenerator.js"(exports, module) {
  var OverloadYield$2 = require_OverloadYield();
  function _awaitAsyncGenerator$5(e) {
    return new OverloadYield$2(e, 0);
  }
  module.exports = _awaitAsyncGenerator$5, module.exports.__esModule = true, module.exports["default"] = module.exports;
} });
var require_wrapAsyncGenerator = __commonJS2({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/wrapAsyncGenerator.js"(exports, module) {
  var OverloadYield$1 = require_OverloadYield();
  function _wrapAsyncGenerator$6(e) {
    return function() {
      return new AsyncGenerator(e.apply(this, arguments));
    };
  }
  function AsyncGenerator(e) {
    var r, t;
    function resume(r$1, t$1) {
      try {
        var n = e[r$1](t$1), o = n.value, u = o instanceof OverloadYield$1;
        Promise.resolve(u ? o.v : o).then(function(t$2) {
          if (u) {
            var i = "return" === r$1 ? "return" : "next";
            if (!o.k || t$2.done) return resume(i, t$2);
            t$2 = e[i](t$2).value;
          }
          settle(n.done ? "return" : "normal", t$2);
        }, function(e$1) {
          resume("throw", e$1);
        });
      } catch (e$1) {
        settle("throw", e$1);
      }
    }
    function settle(e$1, n) {
      switch (e$1) {
        case "return":
          r.resolve({
            value: n,
            done: true
          });
          break;
        case "throw":
          r.reject(n);
          break;
        default:
          r.resolve({
            value: n,
            done: false
          });
      }
      (r = r.next) ? resume(r.key, r.arg) : t = null;
    }
    this._invoke = function(e$1, n) {
      return new Promise(function(o, u) {
        var i = {
          key: e$1,
          arg: n,
          resolve: o,
          reject: u,
          next: null
        };
        t ? t = t.next = i : (r = t = i, resume(e$1, n));
      });
    }, "function" != typeof e["return"] && (this["return"] = void 0);
  }
  AsyncGenerator.prototype["function" == typeof Symbol && Symbol.asyncIterator || "@@asyncIterator"] = function() {
    return this;
  }, AsyncGenerator.prototype.next = function(e) {
    return this._invoke("next", e);
  }, AsyncGenerator.prototype["throw"] = function(e) {
    return this._invoke("throw", e);
  }, AsyncGenerator.prototype["return"] = function(e) {
    return this._invoke("return", e);
  };
  module.exports = _wrapAsyncGenerator$6, module.exports.__esModule = true, module.exports["default"] = module.exports;
} });
var import_usingCtx$4 = __toESM2(require_usingCtx(), 1);
var import_awaitAsyncGenerator$4 = __toESM2(require_awaitAsyncGenerator(), 1);
var import_wrapAsyncGenerator$5 = __toESM2(require_wrapAsyncGenerator(), 1);
function iteratorResource(iterable) {
  const iterator = iterable[Symbol.asyncIterator]();
  if (iterator[Symbol.asyncDispose]) return iterator;
  return makeAsyncResource(iterator, async () => {
    var _iterator$return;
    await ((_iterator$return = iterator.return) === null || _iterator$return === void 0 ? void 0 : _iterator$return.call(iterator));
  });
}
function createDeferred() {
  let resolve;
  let reject;
  const promise = new Promise((res, rej) => {
    resolve = res;
    reject = rej;
  });
  return {
    promise,
    resolve,
    reject
  };
}
var import_usingCtx$3 = __toESM2(require_usingCtx(), 1);
var import_awaitAsyncGenerator$3 = __toESM2(require_awaitAsyncGenerator(), 1);
var import_wrapAsyncGenerator$4 = __toESM2(require_wrapAsyncGenerator(), 1);
var import_usingCtx$2 = __toESM2(require_usingCtx(), 1);
var import_awaitAsyncGenerator$2 = __toESM2(require_awaitAsyncGenerator(), 1);
var import_wrapAsyncGenerator$3 = __toESM2(require_wrapAsyncGenerator(), 1);
var PING_SYM = Symbol("ping");
var require_asyncIterator = __commonJS2({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/asyncIterator.js"(exports, module) {
  function _asyncIterator$2(r) {
    var n, t, o, e = 2;
    for ("undefined" != typeof Symbol && (t = Symbol.asyncIterator, o = Symbol.iterator); e--; ) {
      if (t && null != (n = r[t])) return n.call(r);
      if (o && null != (n = r[o])) return new AsyncFromSyncIterator(n.call(r));
      t = "@@asyncIterator", o = "@@iterator";
    }
    throw new TypeError("Object is not async iterable");
  }
  function AsyncFromSyncIterator(r) {
    function AsyncFromSyncIteratorContinuation(r$1) {
      if (Object(r$1) !== r$1) return Promise.reject(new TypeError(r$1 + " is not an object."));
      var n = r$1.done;
      return Promise.resolve(r$1.value).then(function(r$2) {
        return {
          value: r$2,
          done: n
        };
      });
    }
    return AsyncFromSyncIterator = function AsyncFromSyncIterator$1(r$1) {
      this.s = r$1, this.n = r$1.next;
    }, AsyncFromSyncIterator.prototype = {
      s: null,
      n: null,
      next: function next() {
        return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments));
      },
      "return": function _return(r$1) {
        var n = this.s["return"];
        return void 0 === n ? Promise.resolve({
          value: r$1,
          done: true
        }) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments));
      },
      "throw": function _throw(r$1) {
        var n = this.s["return"];
        return void 0 === n ? Promise.reject(r$1) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments));
      }
    }, new AsyncFromSyncIterator(r);
  }
  module.exports = _asyncIterator$2, module.exports.__esModule = true, module.exports["default"] = module.exports;
} });
var import_awaitAsyncGenerator$1 = __toESM2(require_awaitAsyncGenerator(), 1);
var import_wrapAsyncGenerator$2 = __toESM2(require_wrapAsyncGenerator(), 1);
var import_usingCtx$1 = __toESM2(require_usingCtx(), 1);
var import_asyncIterator$1 = __toESM2(require_asyncIterator(), 1);
var CHUNK_VALUE_TYPE_PROMISE = 0;
var CHUNK_VALUE_TYPE_ASYNC_ITERABLE = 1;
var PROMISE_STATUS_FULFILLED = 0;
var PROMISE_STATUS_REJECTED = 1;
var ASYNC_ITERABLE_STATUS_RETURN = 0;
var ASYNC_ITERABLE_STATUS_YIELD = 1;
var ASYNC_ITERABLE_STATUS_ERROR = 2;
var AsyncError = class extends Error {
  constructor(data) {
    super("Received error from server");
    this.data = data;
  }
};
var nodeJsStreamToReaderEsque = (source) => {
  return { getReader() {
    const stream = new ReadableStream({ start(controller) {
      source.on("data", (chunk) => {
        controller.enqueue(chunk);
      });
      source.on("end", () => {
        controller.close();
      });
      source.on("error", (error) => {
        controller.error(error);
      });
    } });
    return stream.getReader();
  } };
};
function createLineAccumulator(from) {
  const reader = "getReader" in from ? from.getReader() : nodeJsStreamToReaderEsque(from).getReader();
  let lineAggregate = "";
  return new ReadableStream({
    async pull(controller) {
      const { done, value } = await reader.read();
      if (done) controller.close();
      else controller.enqueue(value);
    },
    cancel() {
      return reader.cancel();
    }
  }).pipeThrough(new TextDecoderStream()).pipeThrough(new TransformStream({ transform(chunk, controller) {
    var _parts$pop;
    lineAggregate += chunk;
    const parts = lineAggregate.split("\n");
    lineAggregate = (_parts$pop = parts.pop()) !== null && _parts$pop !== void 0 ? _parts$pop : "";
    for (const part of parts) controller.enqueue(part);
  } }));
}
function createConsumerStream(from) {
  const stream = createLineAccumulator(from);
  let sentHead = false;
  return stream.pipeThrough(new TransformStream({ transform(line, controller) {
    if (!sentHead) {
      const head = JSON.parse(line);
      controller.enqueue(head);
      sentHead = true;
    } else {
      const chunk = JSON.parse(line);
      controller.enqueue(chunk);
    }
  } }));
}
function createStreamsManager(abortController) {
  const controllerMap = /* @__PURE__ */ new Map();
  function isEmpty() {
    return Array.from(controllerMap.values()).every((c) => c.closed);
  }
  function createStreamController() {
    let originalController;
    const stream = new ReadableStream({ start(controller) {
      originalController = controller;
    } });
    const streamController = {
      enqueue: (v) => originalController.enqueue(v),
      close: () => {
        originalController.close();
        clear();
        if (isEmpty()) abortController.abort();
      },
      closed: false,
      getReaderResource: () => {
        const reader = stream.getReader();
        return makeResource(reader, () => {
          streamController.close();
          reader.releaseLock();
        });
      },
      error: (reason) => {
        originalController.error(reason);
        clear();
      }
    };
    function clear() {
      Object.assign(streamController, {
        closed: true,
        close: () => {
        },
        enqueue: () => {
        },
        getReaderResource: null,
        error: () => {
        }
      });
    }
    return streamController;
  }
  function getOrCreate(chunkId) {
    let c = controllerMap.get(chunkId);
    if (!c) {
      c = createStreamController();
      controllerMap.set(chunkId, c);
    }
    return c;
  }
  function cancelAll(reason) {
    for (const controller of controllerMap.values()) controller.error(reason);
  }
  return {
    getOrCreate,
    cancelAll
  };
}
async function jsonlStreamConsumer(opts) {
  const { deserialize = (v) => v } = opts;
  let source = createConsumerStream(opts.from);
  if (deserialize) source = source.pipeThrough(new TransformStream({ transform(chunk, controller) {
    controller.enqueue(deserialize(chunk));
  } }));
  let headDeferred = createDeferred();
  const streamManager = createStreamsManager(opts.abortController);
  function decodeChunkDefinition(value) {
    const [_path, type, chunkId] = value;
    const controller = streamManager.getOrCreate(chunkId);
    switch (type) {
      case CHUNK_VALUE_TYPE_PROMISE:
        return run(async () => {
          try {
            var _usingCtx3 = (0, import_usingCtx$1.default)();
            const reader = _usingCtx3.u(controller.getReaderResource());
            const { value: value$1 } = await reader.read();
            const [_chunkId, status, data] = value$1;
            switch (status) {
              case PROMISE_STATUS_FULFILLED:
                return decode(data);
              case PROMISE_STATUS_REJECTED:
                var _opts$formatError3, _opts$formatError4;
                throw (_opts$formatError3 = (_opts$formatError4 = opts.formatError) === null || _opts$formatError4 === void 0 ? void 0 : _opts$formatError4.call(opts, { error: data })) !== null && _opts$formatError3 !== void 0 ? _opts$formatError3 : new AsyncError(data);
            }
          } catch (_) {
            _usingCtx3.e = _;
          } finally {
            _usingCtx3.d();
          }
        });
      case CHUNK_VALUE_TYPE_ASYNC_ITERABLE:
        return run((0, import_wrapAsyncGenerator$2.default)(function* () {
          try {
            var _usingCtx4 = (0, import_usingCtx$1.default)();
            const reader = _usingCtx4.u(controller.getReaderResource());
            while (true) {
              const { value: value$1 } = yield (0, import_awaitAsyncGenerator$1.default)(reader.read());
              const [_chunkId, status, data] = value$1;
              switch (status) {
                case ASYNC_ITERABLE_STATUS_YIELD:
                  yield decode(data);
                  break;
                case ASYNC_ITERABLE_STATUS_RETURN:
                  return decode(data);
                case ASYNC_ITERABLE_STATUS_ERROR:
                  var _opts$formatError5, _opts$formatError6;
                  throw (_opts$formatError5 = (_opts$formatError6 = opts.formatError) === null || _opts$formatError6 === void 0 ? void 0 : _opts$formatError6.call(opts, { error: data })) !== null && _opts$formatError5 !== void 0 ? _opts$formatError5 : new AsyncError(data);
              }
            }
          } catch (_) {
            _usingCtx4.e = _;
          } finally {
            _usingCtx4.d();
          }
        }));
    }
  }
  function decode(value) {
    const [[data], ...asyncProps] = value;
    for (const value$1 of asyncProps) {
      const [key] = value$1;
      const decoded = decodeChunkDefinition(value$1);
      if (key === null) return decoded;
      data[key] = decoded;
    }
    return data;
  }
  const closeOrAbort = (reason) => {
    headDeferred === null || headDeferred === void 0 || headDeferred.reject(reason);
    streamManager.cancelAll(reason);
  };
  source.pipeTo(new WritableStream({
    write(chunkOrHead) {
      if (headDeferred) {
        const head = chunkOrHead;
        for (const [key, value] of Object.entries(chunkOrHead)) {
          const parsed = decode(value);
          head[key] = parsed;
        }
        headDeferred.resolve(head);
        headDeferred = null;
        return;
      }
      const chunk = chunkOrHead;
      const [idx] = chunk;
      const controller = streamManager.getOrCreate(idx);
      controller.enqueue(chunk);
    },
    close: closeOrAbort,
    abort: closeOrAbort
  })).catch((error) => {
    var _opts$onError4;
    (_opts$onError4 = opts.onError) === null || _opts$onError4 === void 0 || _opts$onError4.call(opts, { error });
    closeOrAbort(error);
  });
  return [await headDeferred.promise];
}
var require_asyncGeneratorDelegate = __commonJS2({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/asyncGeneratorDelegate.js"(exports, module) {
  var OverloadYield = require_OverloadYield();
  function _asyncGeneratorDelegate$1(t) {
    var e = {}, n = false;
    function pump(e$1, r) {
      return n = true, r = new Promise(function(n$1) {
        n$1(t[e$1](r));
      }), {
        done: false,
        value: new OverloadYield(r, 1)
      };
    }
    return e["undefined" != typeof Symbol && Symbol.iterator || "@@iterator"] = function() {
      return this;
    }, e.next = function(t$1) {
      return n ? (n = false, t$1) : pump("next", t$1);
    }, "function" == typeof t["throw"] && (e["throw"] = function(t$1) {
      if (n) throw n = false, t$1;
      return pump("throw", t$1);
    }), "function" == typeof t["return"] && (e["return"] = function(t$1) {
      return n ? (n = false, t$1) : pump("return", t$1);
    }), e;
  }
  module.exports = _asyncGeneratorDelegate$1, module.exports.__esModule = true, module.exports["default"] = module.exports;
} });
var import_asyncIterator = __toESM2(require_asyncIterator(), 1);
var import_awaitAsyncGenerator = __toESM2(require_awaitAsyncGenerator(), 1);
var import_wrapAsyncGenerator$1 = __toESM2(require_wrapAsyncGenerator(), 1);
var import_asyncGeneratorDelegate = __toESM2(require_asyncGeneratorDelegate(), 1);
var import_usingCtx = __toESM2(require_usingCtx(), 1);
var PING_EVENT = "ping";
var SERIALIZED_ERROR_EVENT = "serialized-error";
var CONNECTED_EVENT = "connected";
var RETURN_EVENT = "return";
async function withTimeout(opts) {
  try {
    var _usingCtx$1 = (0, import_usingCtx.default)();
    const timeoutPromise = _usingCtx$1.u(timerResource(opts.timeoutMs));
    const res = await Unpromise.race([opts.promise, timeoutPromise.start()]);
    if (res === disposablePromiseTimerResult) return await opts.onTimeout();
    return res;
  } catch (_) {
    _usingCtx$1.e = _;
  } finally {
    _usingCtx$1.d();
  }
}
function sseStreamConsumer(opts) {
  const { deserialize = (v) => v } = opts;
  let clientOptions = emptyObject();
  const signal = opts.signal;
  let _es = null;
  const createStream = () => new ReadableStream({
    async start(controller) {
      const [url, init] = await Promise.all([opts.url(), opts.init()]);
      const eventSource = _es = new opts.EventSource(url, init);
      controller.enqueue({
        type: "connecting",
        eventSource: _es,
        event: null
      });
      eventSource.addEventListener(CONNECTED_EVENT, (_msg) => {
        const msg = _msg;
        const options = JSON.parse(msg.data);
        clientOptions = options;
        controller.enqueue({
          type: "connected",
          options,
          eventSource
        });
      });
      eventSource.addEventListener(SERIALIZED_ERROR_EVENT, (_msg) => {
        const msg = _msg;
        controller.enqueue({
          type: "serialized-error",
          error: deserialize(JSON.parse(msg.data)),
          eventSource
        });
      });
      eventSource.addEventListener(PING_EVENT, () => {
        controller.enqueue({
          type: "ping",
          eventSource
        });
      });
      eventSource.addEventListener(RETURN_EVENT, () => {
        eventSource.close();
        controller.close();
        _es = null;
      });
      eventSource.addEventListener("error", (event) => {
        if (eventSource.readyState === eventSource.CLOSED) controller.error(event);
        else controller.enqueue({
          type: "connecting",
          eventSource,
          event
        });
      });
      eventSource.addEventListener("message", (_msg) => {
        const msg = _msg;
        const chunk = deserialize(JSON.parse(msg.data));
        const def = { data: chunk };
        if (msg.lastEventId) def.id = msg.lastEventId;
        controller.enqueue({
          type: "data",
          data: def,
          eventSource
        });
      });
      const onAbort = () => {
        try {
          eventSource.close();
          controller.close();
        } catch (_unused) {
        }
      };
      if (signal.aborted) onAbort();
      else signal.addEventListener("abort", onAbort);
    },
    cancel() {
      _es === null || _es === void 0 || _es.close();
    }
  });
  const getStreamResource = () => {
    let stream = createStream();
    let reader = stream.getReader();
    async function dispose() {
      await reader.cancel();
      _es = null;
    }
    return makeAsyncResource({
      read() {
        return reader.read();
      },
      async recreate() {
        await dispose();
        stream = createStream();
        reader = stream.getReader();
      }
    }, dispose);
  };
  return run((0, import_wrapAsyncGenerator$1.default)(function* () {
    try {
      var _usingCtx3 = (0, import_usingCtx.default)();
      const stream = _usingCtx3.a(getStreamResource());
      while (true) {
        let promise = stream.read();
        const timeoutMs = clientOptions.reconnectAfterInactivityMs;
        if (timeoutMs) promise = withTimeout({
          promise,
          timeoutMs,
          onTimeout: async () => {
            const res = {
              value: {
                type: "timeout",
                ms: timeoutMs,
                eventSource: _es
              },
              done: false
            };
            await stream.recreate();
            return res;
          }
        });
        const result = yield (0, import_awaitAsyncGenerator.default)(promise);
        if (result.done) return result.value;
        yield result.value;
      }
    } catch (_) {
      _usingCtx3.e = _;
    } finally {
      yield (0, import_awaitAsyncGenerator.default)(_usingCtx3.d());
    }
  }));
}
var import_wrapAsyncGenerator = __toESM2(require_wrapAsyncGenerator(), 1);
var import_objectSpread23 = __toESM2(require_objectSpread22(), 1);

// ../../node_modules/.pnpm/@trpc+server@11.8.1_typescript@5.9.3/node_modules/@trpc/server/dist/initTRPC-T5bbc89W.mjs
var import_objectSpread2$2 = __toESM2(require_objectSpread22(), 1);
var middlewareMarker = "middlewareMarker";
function createMiddlewareFactory() {
  function createMiddlewareInner(middlewares) {
    return {
      _middlewares: middlewares,
      unstable_pipe(middlewareBuilderOrFn) {
        const pipedMiddleware = "_middlewares" in middlewareBuilderOrFn ? middlewareBuilderOrFn._middlewares : [middlewareBuilderOrFn];
        return createMiddlewareInner([...middlewares, ...pipedMiddleware]);
      }
    };
  }
  function createMiddleware(fn) {
    return createMiddlewareInner([fn]);
  }
  return createMiddleware;
}
function createInputMiddleware(parse) {
  const inputMiddleware = async function inputValidatorMiddleware(opts) {
    let parsedInput;
    const rawInput = await opts.getRawInput();
    try {
      parsedInput = await parse(rawInput);
    } catch (cause) {
      throw new TRPCError({
        code: "BAD_REQUEST",
        cause
      });
    }
    const combinedInput = isObject(opts.input) && isObject(parsedInput) ? (0, import_objectSpread2$2.default)((0, import_objectSpread2$2.default)({}, opts.input), parsedInput) : parsedInput;
    return opts.next({ input: combinedInput });
  };
  inputMiddleware._type = "input";
  return inputMiddleware;
}
function createOutputMiddleware(parse) {
  const outputMiddleware = async function outputValidatorMiddleware({ next }) {
    const result = await next();
    if (!result.ok) return result;
    try {
      const data = await parse(result.data);
      return (0, import_objectSpread2$2.default)((0, import_objectSpread2$2.default)({}, result), {}, { data });
    } catch (cause) {
      throw new TRPCError({
        message: "Output validation failed",
        code: "INTERNAL_SERVER_ERROR",
        cause
      });
    }
  };
  outputMiddleware._type = "output";
  return outputMiddleware;
}
var import_defineProperty3 = __toESM2(require_defineProperty2(), 1);
var StandardSchemaV1Error = class extends Error {
  /**
  * Creates a schema error with useful information.
  *
  * @param issues The schema issues.
  */
  constructor(issues) {
    var _issues$;
    super((_issues$ = issues[0]) === null || _issues$ === void 0 ? void 0 : _issues$.message);
    (0, import_defineProperty3.default)(this, "issues", void 0);
    this.name = "SchemaError";
    this.issues = issues;
  }
};
function getParseFn(procedureParser) {
  const parser = procedureParser;
  const isStandardSchema = "~standard" in parser;
  if (typeof parser === "function" && typeof parser.assert === "function") return parser.assert.bind(parser);
  if (typeof parser === "function" && !isStandardSchema) return parser;
  if (typeof parser.parseAsync === "function") return parser.parseAsync.bind(parser);
  if (typeof parser.parse === "function") return parser.parse.bind(parser);
  if (typeof parser.validateSync === "function") return parser.validateSync.bind(parser);
  if (typeof parser.create === "function") return parser.create.bind(parser);
  if (typeof parser.assert === "function") return (value) => {
    parser.assert(value);
    return value;
  };
  if (isStandardSchema) return async (value) => {
    const result = await parser["~standard"].validate(value);
    if (result.issues) throw new StandardSchemaV1Error(result.issues);
    return result.value;
  };
  throw new Error("Could not find a validator fn");
}
var require_objectWithoutPropertiesLoose = __commonJS2({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/objectWithoutPropertiesLoose.js"(exports, module) {
  function _objectWithoutPropertiesLoose(r, e) {
    if (null == r) return {};
    var t = {};
    for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
      if (e.includes(n)) continue;
      t[n] = r[n];
    }
    return t;
  }
  module.exports = _objectWithoutPropertiesLoose, module.exports.__esModule = true, module.exports["default"] = module.exports;
} });
var require_objectWithoutProperties = __commonJS2({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/objectWithoutProperties.js"(exports, module) {
  var objectWithoutPropertiesLoose = require_objectWithoutPropertiesLoose();
  function _objectWithoutProperties$1(e, t) {
    if (null == e) return {};
    var o, r, i = objectWithoutPropertiesLoose(e, t);
    if (Object.getOwnPropertySymbols) {
      var s = Object.getOwnPropertySymbols(e);
      for (r = 0; r < s.length; r++) o = s[r], t.includes(o) || {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]);
    }
    return i;
  }
  module.exports = _objectWithoutProperties$1, module.exports.__esModule = true, module.exports["default"] = module.exports;
} });
var import_objectWithoutProperties = __toESM2(require_objectWithoutProperties(), 1);
var import_objectSpread2$13 = __toESM2(require_objectSpread22(), 1);
var _excluded = [
  "middlewares",
  "inputs",
  "meta"
];
function createNewBuilder(def1, def2) {
  const { middlewares = [], inputs, meta } = def2, rest = (0, import_objectWithoutProperties.default)(def2, _excluded);
  return createBuilder((0, import_objectSpread2$13.default)((0, import_objectSpread2$13.default)({}, mergeWithoutOverrides(def1, rest)), {}, {
    inputs: [...def1.inputs, ...inputs !== null && inputs !== void 0 ? inputs : []],
    middlewares: [...def1.middlewares, ...middlewares],
    meta: def1.meta && meta ? (0, import_objectSpread2$13.default)((0, import_objectSpread2$13.default)({}, def1.meta), meta) : meta !== null && meta !== void 0 ? meta : def1.meta
  }));
}
function createBuilder(initDef = {}) {
  const _def = (0, import_objectSpread2$13.default)({
    procedure: true,
    inputs: [],
    middlewares: []
  }, initDef);
  const builder = {
    _def,
    input(input) {
      const parser = getParseFn(input);
      return createNewBuilder(_def, {
        inputs: [input],
        middlewares: [createInputMiddleware(parser)]
      });
    },
    output(output) {
      const parser = getParseFn(output);
      return createNewBuilder(_def, {
        output,
        middlewares: [createOutputMiddleware(parser)]
      });
    },
    meta(meta) {
      return createNewBuilder(_def, { meta });
    },
    use(middlewareBuilderOrFn) {
      const middlewares = "_middlewares" in middlewareBuilderOrFn ? middlewareBuilderOrFn._middlewares : [middlewareBuilderOrFn];
      return createNewBuilder(_def, { middlewares });
    },
    unstable_concat(builder$1) {
      return createNewBuilder(_def, builder$1._def);
    },
    concat(builder$1) {
      return createNewBuilder(_def, builder$1._def);
    },
    query(resolver) {
      return createResolver((0, import_objectSpread2$13.default)((0, import_objectSpread2$13.default)({}, _def), {}, { type: "query" }), resolver);
    },
    mutation(resolver) {
      return createResolver((0, import_objectSpread2$13.default)((0, import_objectSpread2$13.default)({}, _def), {}, { type: "mutation" }), resolver);
    },
    subscription(resolver) {
      return createResolver((0, import_objectSpread2$13.default)((0, import_objectSpread2$13.default)({}, _def), {}, { type: "subscription" }), resolver);
    },
    experimental_caller(caller) {
      return createNewBuilder(_def, { caller });
    }
  };
  return builder;
}
function createResolver(_defIn, resolver) {
  const finalBuilder = createNewBuilder(_defIn, {
    resolver,
    middlewares: [async function resolveMiddleware(opts) {
      const data = await resolver(opts);
      return {
        marker: middlewareMarker,
        ok: true,
        data,
        ctx: opts.ctx
      };
    }]
  });
  const _def = (0, import_objectSpread2$13.default)((0, import_objectSpread2$13.default)({}, finalBuilder._def), {}, {
    type: _defIn.type,
    experimental_caller: Boolean(finalBuilder._def.caller),
    meta: finalBuilder._def.meta,
    $types: null
  });
  const invoke = createProcedureCaller(finalBuilder._def);
  const callerOverride = finalBuilder._def.caller;
  if (!callerOverride) return invoke;
  const callerWrapper = async (...args) => {
    return await callerOverride({
      args,
      invoke,
      _def
    });
  };
  callerWrapper._def = _def;
  return callerWrapper;
}
var codeblock = `
This is a client-only function.
If you want to call this function on the server, see https://trpc.io/docs/v11/server/server-side-calls
`.trim();
async function callRecursive(index, _def, opts) {
  try {
    const middleware = _def.middlewares[index];
    const result = await middleware((0, import_objectSpread2$13.default)((0, import_objectSpread2$13.default)({}, opts), {}, {
      meta: _def.meta,
      input: opts.input,
      next(_nextOpts) {
        var _nextOpts$getRawInput;
        const nextOpts = _nextOpts;
        return callRecursive(index + 1, _def, (0, import_objectSpread2$13.default)((0, import_objectSpread2$13.default)({}, opts), {}, {
          ctx: (nextOpts === null || nextOpts === void 0 ? void 0 : nextOpts.ctx) ? (0, import_objectSpread2$13.default)((0, import_objectSpread2$13.default)({}, opts.ctx), nextOpts.ctx) : opts.ctx,
          input: nextOpts && "input" in nextOpts ? nextOpts.input : opts.input,
          getRawInput: (_nextOpts$getRawInput = nextOpts === null || nextOpts === void 0 ? void 0 : nextOpts.getRawInput) !== null && _nextOpts$getRawInput !== void 0 ? _nextOpts$getRawInput : opts.getRawInput
        }));
      }
    }));
    return result;
  } catch (cause) {
    return {
      ok: false,
      error: getTRPCErrorFromUnknown(cause),
      marker: middlewareMarker
    };
  }
}
function createProcedureCaller(_def) {
  async function procedure(opts) {
    if (!opts || !("getRawInput" in opts)) throw new Error(codeblock);
    const result = await callRecursive(0, _def, opts);
    if (!result) throw new TRPCError({
      code: "INTERNAL_SERVER_ERROR",
      message: "No result from middlewares - did you forget to `return next()`?"
    });
    if (!result.ok) throw result.error;
    return result.data;
  }
  procedure._def = _def;
  procedure.procedure = true;
  procedure.meta = _def.meta;
  return procedure;
}
var _globalThis$process;
var _globalThis$process2;
var _globalThis$process3;
var isServerDefault = typeof window === "undefined" || "Deno" in window || ((_globalThis$process = globalThis.process) === null || _globalThis$process === void 0 || (_globalThis$process = _globalThis$process.env) === null || _globalThis$process === void 0 ? void 0 : _globalThis$process["NODE_ENV"]) === "test" || !!((_globalThis$process2 = globalThis.process) === null || _globalThis$process2 === void 0 || (_globalThis$process2 = _globalThis$process2.env) === null || _globalThis$process2 === void 0 ? void 0 : _globalThis$process2["JEST_WORKER_ID"]) || !!((_globalThis$process3 = globalThis.process) === null || _globalThis$process3 === void 0 || (_globalThis$process3 = _globalThis$process3.env) === null || _globalThis$process3 === void 0 ? void 0 : _globalThis$process3["VITEST_WORKER_ID"]);
var import_objectSpread24 = __toESM2(require_objectSpread22(), 1);
var TRPCBuilder = class TRPCBuilder2 {
  /**
  * Add a context shape as a generic to the root object
  * @see https://trpc.io/docs/v11/server/context
  */
  context() {
    return new TRPCBuilder2();
  }
  /**
  * Add a meta shape as a generic to the root object
  * @see https://trpc.io/docs/v11/quickstart
  */
  meta() {
    return new TRPCBuilder2();
  }
  /**
  * Create the root object
  * @see https://trpc.io/docs/v11/server/routers#initialize-trpc
  */
  create(opts) {
    var _opts$transformer, _opts$isDev, _globalThis$process$1, _opts$allowOutsideOfS, _opts$errorFormatter, _opts$isServer;
    const config = (0, import_objectSpread24.default)((0, import_objectSpread24.default)({}, opts), {}, {
      transformer: getDataTransformer((_opts$transformer = opts === null || opts === void 0 ? void 0 : opts.transformer) !== null && _opts$transformer !== void 0 ? _opts$transformer : defaultTransformer),
      isDev: (_opts$isDev = opts === null || opts === void 0 ? void 0 : opts.isDev) !== null && _opts$isDev !== void 0 ? _opts$isDev : ((_globalThis$process$1 = globalThis.process) === null || _globalThis$process$1 === void 0 ? void 0 : _globalThis$process$1.env["NODE_ENV"]) !== "production",
      allowOutsideOfServer: (_opts$allowOutsideOfS = opts === null || opts === void 0 ? void 0 : opts.allowOutsideOfServer) !== null && _opts$allowOutsideOfS !== void 0 ? _opts$allowOutsideOfS : false,
      errorFormatter: (_opts$errorFormatter = opts === null || opts === void 0 ? void 0 : opts.errorFormatter) !== null && _opts$errorFormatter !== void 0 ? _opts$errorFormatter : defaultFormatter,
      isServer: (_opts$isServer = opts === null || opts === void 0 ? void 0 : opts.isServer) !== null && _opts$isServer !== void 0 ? _opts$isServer : isServerDefault,
      $types: null
    });
    {
      var _opts$isServer2;
      const isServer = (_opts$isServer2 = opts === null || opts === void 0 ? void 0 : opts.isServer) !== null && _opts$isServer2 !== void 0 ? _opts$isServer2 : isServerDefault;
      if (!isServer && (opts === null || opts === void 0 ? void 0 : opts.allowOutsideOfServer) !== true) throw new Error(`You're trying to use @trpc/server in a non-server environment. This is not supported by default.`);
    }
    return {
      _config: config,
      procedure: createBuilder({ meta: opts === null || opts === void 0 ? void 0 : opts.defaultMeta }),
      middleware: createMiddlewareFactory(),
      router: createRouterFactory(config),
      mergeRouters,
      createCallerFactory: createCallerFactory()
    };
  }
};
var initTRPC = new TRPCBuilder();

// ../../node_modules/.pnpm/@trpc+client@11.8.1_@trpc+server@11.8.1_typescript@5.9.3__typescript@5.9.3/node_modules/@trpc/client/dist/TRPCClientError-CjKyS10w.mjs
var import_defineProperty4 = __toESM(require_defineProperty(), 1);
var import_objectSpread25 = __toESM(require_objectSpread2(), 1);
function isTRPCClientError(cause) {
  return cause instanceof TRPCClientError;
}
function isTRPCErrorResponse(obj) {
  return isObject(obj) && isObject(obj["error"]) && typeof obj["error"]["code"] === "number" && typeof obj["error"]["message"] === "string";
}
function getMessageFromUnknownError(err, fallback) {
  if (typeof err === "string") return err;
  if (isObject(err) && typeof err["message"] === "string") return err["message"];
  return fallback;
}
var TRPCClientError = class TRPCClientError2 extends Error {
  constructor(message, opts) {
    var _opts$result, _opts$result2;
    const cause = opts === null || opts === void 0 ? void 0 : opts.cause;
    super(message, { cause });
    (0, import_defineProperty4.default)(this, "cause", void 0);
    (0, import_defineProperty4.default)(this, "shape", void 0);
    (0, import_defineProperty4.default)(this, "data", void 0);
    (0, import_defineProperty4.default)(this, "meta", void 0);
    this.meta = opts === null || opts === void 0 ? void 0 : opts.meta;
    this.cause = cause;
    this.shape = opts === null || opts === void 0 || (_opts$result = opts.result) === null || _opts$result === void 0 ? void 0 : _opts$result.error;
    this.data = opts === null || opts === void 0 || (_opts$result2 = opts.result) === null || _opts$result2 === void 0 ? void 0 : _opts$result2.error.data;
    this.name = "TRPCClientError";
    Object.setPrototypeOf(this, TRPCClientError2.prototype);
  }
  static from(_cause, opts = {}) {
    const cause = _cause;
    if (isTRPCClientError(cause)) {
      if (opts.meta) cause.meta = (0, import_objectSpread25.default)((0, import_objectSpread25.default)({}, cause.meta), opts.meta);
      return cause;
    }
    if (isTRPCErrorResponse(cause)) return new TRPCClientError2(cause.error.message, (0, import_objectSpread25.default)((0, import_objectSpread25.default)({}, opts), {}, { result: cause }));
    return new TRPCClientError2(getMessageFromUnknownError(cause, "Unknown error"), (0, import_objectSpread25.default)((0, import_objectSpread25.default)({}, opts), {}, { cause }));
  }
};

// ../../node_modules/.pnpm/@trpc+client@11.8.1_@trpc+server@11.8.1_typescript@5.9.3__typescript@5.9.3/node_modules/@trpc/client/dist/unstable-internals-Bg7n9BBj.mjs
function getTransformer(transformer) {
  const _transformer = transformer;
  if (!_transformer) return {
    input: {
      serialize: (data) => data,
      deserialize: (data) => data
    },
    output: {
      serialize: (data) => data,
      deserialize: (data) => data
    }
  };
  if ("input" in _transformer) return _transformer;
  return {
    input: _transformer,
    output: _transformer
  };
}

// ../../node_modules/.pnpm/@trpc+client@11.8.1_@trpc+server@11.8.1_typescript@5.9.3__typescript@5.9.3/node_modules/@trpc/client/dist/httpUtils-Dv57hbOd.mjs
var isFunction2 = (fn) => typeof fn === "function";
function getFetch(customFetchImpl) {
  if (customFetchImpl) return customFetchImpl;
  if (typeof window !== "undefined" && isFunction2(window.fetch)) return window.fetch;
  if (typeof globalThis !== "undefined" && isFunction2(globalThis.fetch)) return globalThis.fetch;
  throw new Error("No fetch implementation found");
}
var import_objectSpread26 = __toESM(require_objectSpread2(), 1);
function resolveHTTPLinkOptions(opts) {
  return {
    url: opts.url.toString(),
    fetch: opts.fetch,
    transformer: getTransformer(opts.transformer),
    methodOverride: opts.methodOverride
  };
}
function arrayToDict(array) {
  const dict = {};
  for (let index = 0; index < array.length; index++) {
    const element = array[index];
    dict[index] = element;
  }
  return dict;
}
var METHOD = {
  query: "GET",
  mutation: "POST",
  subscription: "PATCH"
};
function getInput(opts) {
  return "input" in opts ? opts.transformer.input.serialize(opts.input) : arrayToDict(opts.inputs.map((_input) => opts.transformer.input.serialize(_input)));
}
var getUrl = (opts) => {
  const parts = opts.url.split("?");
  const base = parts[0].replace(/\/$/, "");
  let url = base + "/" + opts.path;
  const queryParts = [];
  if (parts[1]) queryParts.push(parts[1]);
  if ("inputs" in opts) queryParts.push("batch=1");
  if (opts.type === "query" || opts.type === "subscription") {
    const input = getInput(opts);
    if (input !== void 0 && opts.methodOverride !== "POST") queryParts.push(`input=${encodeURIComponent(JSON.stringify(input))}`);
  }
  if (queryParts.length) url += "?" + queryParts.join("&");
  return url;
};
var getBody = (opts) => {
  if (opts.type === "query" && opts.methodOverride !== "POST") return void 0;
  const input = getInput(opts);
  return input !== void 0 ? JSON.stringify(input) : void 0;
};
var jsonHttpRequester = (opts) => {
  return httpRequest((0, import_objectSpread26.default)((0, import_objectSpread26.default)({}, opts), {}, {
    contentTypeHeader: "application/json",
    getUrl,
    getBody
  }));
};
var AbortError = class extends Error {
  constructor() {
    const name = "AbortError";
    super(name);
    this.name = name;
    this.message = name;
  }
};
var throwIfAborted = (signal) => {
  var _signal$throwIfAborte;
  if (!(signal === null || signal === void 0 ? void 0 : signal.aborted)) return;
  (_signal$throwIfAborte = signal.throwIfAborted) === null || _signal$throwIfAborte === void 0 || _signal$throwIfAborte.call(signal);
  if (typeof DOMException !== "undefined") throw new DOMException("AbortError", "AbortError");
  throw new AbortError();
};
async function fetchHTTPResponse(opts) {
  var _opts$methodOverride;
  throwIfAborted(opts.signal);
  const url = opts.getUrl(opts);
  const body = opts.getBody(opts);
  const method = (_opts$methodOverride = opts.methodOverride) !== null && _opts$methodOverride !== void 0 ? _opts$methodOverride : METHOD[opts.type];
  const resolvedHeaders = await (async () => {
    const heads = await opts.headers();
    if (Symbol.iterator in heads) return Object.fromEntries(heads);
    return heads;
  })();
  const headers = (0, import_objectSpread26.default)((0, import_objectSpread26.default)((0, import_objectSpread26.default)({}, opts.contentTypeHeader && method !== "GET" ? { "content-type": opts.contentTypeHeader } : {}), opts.trpcAcceptHeader ? { "trpc-accept": opts.trpcAcceptHeader } : void 0), resolvedHeaders);
  return getFetch(opts.fetch)(url, {
    method,
    signal: opts.signal,
    body,
    headers
  });
}
async function httpRequest(opts) {
  const meta = {};
  const res = await fetchHTTPResponse(opts);
  meta.response = res;
  const json = await res.json();
  meta.responseJSON = json;
  return {
    json,
    meta
  };
}

// ../../node_modules/.pnpm/@trpc+client@11.8.1_@trpc+server@11.8.1_typescript@5.9.3__typescript@5.9.3/node_modules/@trpc/client/dist/httpLink-DCFpUmZF.mjs
function isOctetType(input) {
  return input instanceof Uint8Array || input instanceof Blob;
}
function isFormData(input) {
  return input instanceof FormData;
}
function isNonJsonSerializable(input) {
  return isOctetType(input) || isFormData(input);
}
var import_objectSpread27 = __toESM(require_objectSpread2(), 1);
var universalRequester = (opts) => {
  if ("input" in opts) {
    const { input } = opts;
    if (isFormData(input)) {
      if (opts.type !== "mutation" && opts.methodOverride !== "POST") throw new Error("FormData is only supported for mutations");
      return httpRequest((0, import_objectSpread27.default)((0, import_objectSpread27.default)({}, opts), {}, {
        contentTypeHeader: void 0,
        getUrl,
        getBody: () => input
      }));
    }
    if (isOctetType(input)) {
      if (opts.type !== "mutation" && opts.methodOverride !== "POST") throw new Error("Octet type input is only supported for mutations");
      return httpRequest((0, import_objectSpread27.default)((0, import_objectSpread27.default)({}, opts), {}, {
        contentTypeHeader: "application/octet-stream",
        getUrl,
        getBody: () => input
      }));
    }
  }
  return jsonHttpRequester(opts);
};
function httpLink(opts) {
  const resolvedOpts = resolveHTTPLinkOptions(opts);
  return () => {
    return (operationOpts) => {
      const { op } = operationOpts;
      return observable((observer) => {
        const { path, input, type } = op;
        if (type === "subscription") throw new Error("Subscriptions are unsupported by `httpLink` - use `httpSubscriptionLink` or `wsLink`");
        const request = universalRequester((0, import_objectSpread27.default)((0, import_objectSpread27.default)({}, resolvedOpts), {}, {
          type,
          path,
          input,
          signal: op.signal,
          headers() {
            if (!opts.headers) return {};
            if (typeof opts.headers === "function") return opts.headers({ op });
            return opts.headers;
          }
        }));
        let meta = void 0;
        request.then((res) => {
          meta = res.meta;
          const transformed = transformResult(res.json, resolvedOpts.transformer.output);
          if (!transformed.ok) {
            observer.error(TRPCClientError.from(transformed.error, { meta }));
            return;
          }
          observer.next({
            context: res.meta,
            result: transformed.result
          });
          observer.complete();
        }).catch((cause) => {
          observer.error(TRPCClientError.from(cause, { meta }));
        });
        return () => {
        };
      });
    };
  };
}

// ../../node_modules/.pnpm/@trpc+client@11.8.1_@trpc+server@11.8.1_typescript@5.9.3__typescript@5.9.3/node_modules/@trpc/client/dist/httpBatchLink-BOe5aCcR.mjs
var throwFatalError = () => {
  throw new Error("Something went wrong. Please submit an issue at https://github.com/trpc/trpc/issues/new");
};
function dataLoader(batchLoader) {
  let pendingItems = null;
  let dispatchTimer = null;
  const destroyTimerAndPendingItems = () => {
    clearTimeout(dispatchTimer);
    dispatchTimer = null;
    pendingItems = null;
  };
  function groupItems(items) {
    const groupedItems = [[]];
    let index = 0;
    while (true) {
      const item = items[index];
      if (!item) break;
      const lastGroup = groupedItems[groupedItems.length - 1];
      if (item.aborted) {
        var _item$reject;
        (_item$reject = item.reject) === null || _item$reject === void 0 || _item$reject.call(item, new Error("Aborted"));
        index++;
        continue;
      }
      const isValid = batchLoader.validate(lastGroup.concat(item).map((it) => it.key));
      if (isValid) {
        lastGroup.push(item);
        index++;
        continue;
      }
      if (lastGroup.length === 0) {
        var _item$reject2;
        (_item$reject2 = item.reject) === null || _item$reject2 === void 0 || _item$reject2.call(item, new Error("Input is too big for a single dispatch"));
        index++;
        continue;
      }
      groupedItems.push([]);
    }
    return groupedItems;
  }
  function dispatch() {
    const groupedItems = groupItems(pendingItems);
    destroyTimerAndPendingItems();
    for (const items of groupedItems) {
      if (!items.length) continue;
      const batch = { items };
      for (const item of items) item.batch = batch;
      const promise = batchLoader.fetch(batch.items.map((_item) => _item.key));
      promise.then(async (result) => {
        await Promise.all(result.map(async (valueOrPromise, index) => {
          const item = batch.items[index];
          try {
            var _item$resolve;
            const value = await Promise.resolve(valueOrPromise);
            (_item$resolve = item.resolve) === null || _item$resolve === void 0 || _item$resolve.call(item, value);
          } catch (cause) {
            var _item$reject3;
            (_item$reject3 = item.reject) === null || _item$reject3 === void 0 || _item$reject3.call(item, cause);
          }
          item.batch = null;
          item.reject = null;
          item.resolve = null;
        }));
        for (const item of batch.items) {
          var _item$reject4;
          (_item$reject4 = item.reject) === null || _item$reject4 === void 0 || _item$reject4.call(item, new Error("Missing result"));
          item.batch = null;
        }
      }).catch((cause) => {
        for (const item of batch.items) {
          var _item$reject5;
          (_item$reject5 = item.reject) === null || _item$reject5 === void 0 || _item$reject5.call(item, cause);
          item.batch = null;
        }
      });
    }
  }
  function load(key) {
    var _dispatchTimer;
    const item = {
      aborted: false,
      key,
      batch: null,
      resolve: throwFatalError,
      reject: throwFatalError
    };
    const promise = new Promise((resolve, reject) => {
      var _pendingItems;
      item.reject = reject;
      item.resolve = resolve;
      (_pendingItems = pendingItems) !== null && _pendingItems !== void 0 || (pendingItems = []);
      pendingItems.push(item);
    });
    (_dispatchTimer = dispatchTimer) !== null && _dispatchTimer !== void 0 || (dispatchTimer = setTimeout(dispatch));
    return promise;
  }
  return { load };
}
function allAbortSignals(...signals) {
  const ac = new AbortController();
  const count = signals.length;
  let abortedCount = 0;
  const onAbort = () => {
    if (++abortedCount === count) ac.abort();
  };
  for (const signal of signals) if (signal === null || signal === void 0 ? void 0 : signal.aborted) onAbort();
  else signal === null || signal === void 0 || signal.addEventListener("abort", onAbort, { once: true });
  return ac.signal;
}
function raceAbortSignals(...signals) {
  const ac = new AbortController();
  for (const signal of signals) if (signal === null || signal === void 0 ? void 0 : signal.aborted) ac.abort();
  else signal === null || signal === void 0 || signal.addEventListener("abort", () => ac.abort(), { once: true });
  return ac.signal;
}
function abortSignalToPromise(signal) {
  return new Promise((_, reject) => {
    if (signal.aborted) {
      reject(signal.reason);
      return;
    }
    signal.addEventListener("abort", () => {
      reject(signal.reason);
    }, { once: true });
  });
}
var import_objectSpread28 = __toESM(require_objectSpread2(), 1);
function httpBatchLink(opts) {
  var _opts$maxURLLength, _opts$maxItems;
  const resolvedOpts = resolveHTTPLinkOptions(opts);
  const maxURLLength = (_opts$maxURLLength = opts.maxURLLength) !== null && _opts$maxURLLength !== void 0 ? _opts$maxURLLength : Infinity;
  const maxItems = (_opts$maxItems = opts.maxItems) !== null && _opts$maxItems !== void 0 ? _opts$maxItems : Infinity;
  return () => {
    const batchLoader = (type) => {
      return {
        validate(batchOps) {
          if (maxURLLength === Infinity && maxItems === Infinity) return true;
          if (batchOps.length > maxItems) return false;
          const path = batchOps.map((op) => op.path).join(",");
          const inputs = batchOps.map((op) => op.input);
          const url = getUrl((0, import_objectSpread28.default)((0, import_objectSpread28.default)({}, resolvedOpts), {}, {
            type,
            path,
            inputs,
            signal: null
          }));
          return url.length <= maxURLLength;
        },
        async fetch(batchOps) {
          const path = batchOps.map((op) => op.path).join(",");
          const inputs = batchOps.map((op) => op.input);
          const signal = allAbortSignals(...batchOps.map((op) => op.signal));
          const res = await jsonHttpRequester((0, import_objectSpread28.default)((0, import_objectSpread28.default)({}, resolvedOpts), {}, {
            path,
            inputs,
            type,
            headers() {
              if (!opts.headers) return {};
              if (typeof opts.headers === "function") return opts.headers({ opList: batchOps });
              return opts.headers;
            },
            signal
          }));
          const resJSON = Array.isArray(res.json) ? res.json : batchOps.map(() => res.json);
          const result = resJSON.map((item) => ({
            meta: res.meta,
            json: item
          }));
          return result;
        }
      };
    };
    const query = dataLoader(batchLoader("query"));
    const mutation = dataLoader(batchLoader("mutation"));
    const loaders = {
      query,
      mutation
    };
    return ({ op }) => {
      return observable((observer) => {
        if (op.type === "subscription") throw new Error("Subscriptions are unsupported by `httpLink` - use `httpSubscriptionLink` or `wsLink`");
        const loader = loaders[op.type];
        const promise = loader.load(op);
        let _res = void 0;
        promise.then((res) => {
          _res = res;
          const transformed = transformResult(res.json, resolvedOpts.transformer.output);
          if (!transformed.ok) {
            observer.error(TRPCClientError.from(transformed.error, { meta: res.meta }));
            return;
          }
          observer.next({
            context: res.meta,
            result: transformed.result
          });
          observer.complete();
        }).catch((err) => {
          observer.error(TRPCClientError.from(err, { meta: _res === null || _res === void 0 ? void 0 : _res.meta }));
        });
        return () => {
        };
      });
    };
  };
}

// ../../node_modules/.pnpm/@trpc+client@11.8.1_@trpc+server@11.8.1_typescript@5.9.3__typescript@5.9.3/node_modules/@trpc/client/dist/loggerLink-ineCN1PO.mjs
var import_objectSpread29 = __toESM(require_objectSpread2(), 1);
function isFormData2(value) {
  if (typeof FormData === "undefined") return false;
  return value instanceof FormData;
}
var palettes = {
  css: {
    query: ["72e3ff", "3fb0d8"],
    mutation: ["c5a3fc", "904dfc"],
    subscription: ["ff49e1", "d83fbe"]
  },
  ansi: {
    regular: {
      query: ["\x1B[30;46m", "\x1B[97;46m"],
      mutation: ["\x1B[30;45m", "\x1B[97;45m"],
      subscription: ["\x1B[30;42m", "\x1B[97;42m"]
    },
    bold: {
      query: ["\x1B[1;30;46m", "\x1B[1;97;46m"],
      mutation: ["\x1B[1;30;45m", "\x1B[1;97;45m"],
      subscription: ["\x1B[1;30;42m", "\x1B[1;97;42m"]
    }
  }
};
function constructPartsAndArgs(opts) {
  const { direction, type, withContext, path, id, input } = opts;
  const parts = [];
  const args = [];
  if (opts.colorMode === "none") parts.push(direction === "up" ? ">>" : "<<", type, `#${id}`, path);
  else if (opts.colorMode === "ansi") {
    const [lightRegular, darkRegular] = palettes.ansi.regular[type];
    const [lightBold, darkBold] = palettes.ansi.bold[type];
    const reset = "\x1B[0m";
    parts.push(direction === "up" ? lightRegular : darkRegular, direction === "up" ? ">>" : "<<", type, direction === "up" ? lightBold : darkBold, `#${id}`, path, reset);
  } else {
    const [light, dark] = palettes.css[type];
    const css = `
    background-color: #${direction === "up" ? light : dark};
    color: ${direction === "up" ? "black" : "white"};
    padding: 2px;
  `;
    parts.push("%c", direction === "up" ? ">>" : "<<", type, `#${id}`, `%c${path}%c`, "%O");
    args.push(css, `${css}; font-weight: bold;`, `${css}; font-weight: normal;`);
  }
  if (direction === "up") args.push(withContext ? {
    input,
    context: opts.context
  } : { input });
  else args.push((0, import_objectSpread29.default)({
    input,
    result: opts.result,
    elapsedMs: opts.elapsedMs
  }, withContext && { context: opts.context }));
  return {
    parts,
    args
  };
}
var defaultLogger = ({ c = console, colorMode = "css", withContext }) => (props) => {
  const rawInput = props.input;
  const input = isFormData2(rawInput) ? Object.fromEntries(rawInput) : rawInput;
  const { parts, args } = constructPartsAndArgs((0, import_objectSpread29.default)((0, import_objectSpread29.default)({}, props), {}, {
    colorMode,
    input,
    withContext
  }));
  const fn = props.direction === "down" && props.result && (props.result instanceof Error || "error" in props.result.result && props.result.result.error) ? "error" : "log";
  c[fn].apply(null, [parts.join(" ")].concat(args));
};
function loggerLink(opts = {}) {
  var _opts$colorMode, _opts$withContext;
  const { enabled = () => true } = opts;
  const colorMode = (_opts$colorMode = opts.colorMode) !== null && _opts$colorMode !== void 0 ? _opts$colorMode : typeof window === "undefined" ? "ansi" : "css";
  const withContext = (_opts$withContext = opts.withContext) !== null && _opts$withContext !== void 0 ? _opts$withContext : colorMode === "css";
  const { logger = defaultLogger({
    c: opts.console,
    colorMode,
    withContext
  }) } = opts;
  return () => {
    return ({ op, next }) => {
      return observable((observer) => {
        if (enabled((0, import_objectSpread29.default)((0, import_objectSpread29.default)({}, op), {}, { direction: "up" }))) logger((0, import_objectSpread29.default)((0, import_objectSpread29.default)({}, op), {}, { direction: "up" }));
        const requestStartTime = Date.now();
        function logResult(result) {
          const elapsedMs = Date.now() - requestStartTime;
          if (enabled((0, import_objectSpread29.default)((0, import_objectSpread29.default)({}, op), {}, {
            direction: "down",
            result
          }))) logger((0, import_objectSpread29.default)((0, import_objectSpread29.default)({}, op), {}, {
            direction: "down",
            elapsedMs,
            result
          }));
        }
        return next(op).pipe(tap({
          next(result) {
            logResult(result);
          },
          error(result) {
            logResult(result);
          }
        })).subscribe(observer);
      });
    };
  };
}

// ../../node_modules/.pnpm/@trpc+client@11.8.1_@trpc+server@11.8.1_typescript@5.9.3__typescript@5.9.3/node_modules/@trpc/client/dist/wsLink-CatceK3c.mjs
var lazyDefaults = {
  enabled: false,
  closeMs: 0
};
var keepAliveDefaults = {
  enabled: false,
  pongTimeoutMs: 1e3,
  intervalMs: 5e3
};
var exponentialBackoff = (attemptIndex) => {
  return attemptIndex === 0 ? 0 : Math.min(1e3 * 2 ** attemptIndex, 3e4);
};
var resultOf = (value, ...args) => {
  return typeof value === "function" ? value(...args) : value;
};
var import_defineProperty$3 = __toESM(require_defineProperty(), 1);
var TRPCWebSocketClosedError = class TRPCWebSocketClosedError2 extends Error {
  constructor(opts) {
    super(opts.message, { cause: opts.cause });
    this.name = "TRPCWebSocketClosedError";
    Object.setPrototypeOf(this, TRPCWebSocketClosedError2.prototype);
  }
};
var ResettableTimeout = class {
  constructor(onTimeout, timeoutMs) {
    this.onTimeout = onTimeout;
    this.timeoutMs = timeoutMs;
    (0, import_defineProperty$3.default)(this, "timeout", void 0);
  }
  /**
  * Resets the current timeout, restarting it with the same duration.
  * Does nothing if no timeout is active.
  */
  reset() {
    if (!this.timeout) return;
    clearTimeout(this.timeout);
    this.timeout = setTimeout(this.onTimeout, this.timeoutMs);
  }
  start() {
    clearTimeout(this.timeout);
    this.timeout = setTimeout(this.onTimeout, this.timeoutMs);
  }
  stop() {
    clearTimeout(this.timeout);
    this.timeout = void 0;
  }
};
function withResolvers2() {
  let resolve;
  let reject;
  const promise = new Promise((res, rej) => {
    resolve = res;
    reject = rej;
  });
  return {
    promise,
    resolve,
    reject
  };
}
async function prepareUrl(urlOptions) {
  const url = await resultOf(urlOptions.url);
  if (!urlOptions.connectionParams) return url;
  const prefix = url.includes("?") ? "&" : "?";
  const connectionParams = `${prefix}connectionParams=1`;
  return url + connectionParams;
}
async function buildConnectionMessage(connectionParams) {
  const message = {
    method: "connectionParams",
    data: await resultOf(connectionParams)
  };
  return JSON.stringify(message);
}
var import_defineProperty$2 = __toESM(require_defineProperty(), 1);
var RequestManager = class {
  constructor() {
    (0, import_defineProperty$2.default)(this, "outgoingRequests", new Array());
    (0, import_defineProperty$2.default)(this, "pendingRequests", {});
  }
  /**
  * Registers a new request by adding it to the outgoing queue and setting up
  * callbacks for lifecycle events such as completion or error.
  *
  * @param message - The outgoing message to be sent.
  * @param callbacks - Callback functions to observe the request's state.
  * @returns A cleanup function to manually remove the request.
  */
  register(message, callbacks) {
    const { promise: end, resolve } = withResolvers2();
    this.outgoingRequests.push({
      id: String(message.id),
      message,
      end,
      callbacks: {
        next: callbacks.next,
        complete: () => {
          callbacks.complete();
          resolve();
        },
        error: (e) => {
          callbacks.error(e);
          resolve();
        }
      }
    });
    return () => {
      this.delete(message.id);
      callbacks.complete();
      resolve();
    };
  }
  /**
  * Deletes a request from both the outgoing and pending collections, if it exists.
  */
  delete(messageId) {
    if (messageId === null) return;
    this.outgoingRequests = this.outgoingRequests.filter(({ id }) => id !== String(messageId));
    delete this.pendingRequests[String(messageId)];
  }
  /**
  * Moves all outgoing requests to the pending state and clears the outgoing queue.
  *
  * The caller is expected to handle the actual sending of the requests
  * (e.g., sending them over the network) after this method is called.
  *
  * @returns The list of requests that were transitioned to the pending state.
  */
  flush() {
    const requests = this.outgoingRequests;
    this.outgoingRequests = [];
    for (const request of requests) this.pendingRequests[request.id] = request;
    return requests;
  }
  /**
  * Retrieves all currently pending requests, which are in flight awaiting responses
  * or handling ongoing subscriptions.
  */
  getPendingRequests() {
    return Object.values(this.pendingRequests);
  }
  /**
  * Retrieves a specific pending request by its message ID.
  */
  getPendingRequest(messageId) {
    if (messageId === null) return null;
    return this.pendingRequests[String(messageId)];
  }
  /**
  * Retrieves all outgoing requests, which are waiting to be sent.
  */
  getOutgoingRequests() {
    return this.outgoingRequests;
  }
  /**
  * Retrieves all requests, both outgoing and pending, with their respective states.
  *
  * @returns An array of all requests with their state ("outgoing" or "pending").
  */
  getRequests() {
    return [...this.getOutgoingRequests().map((request) => ({
      state: "outgoing",
      message: request.message,
      end: request.end,
      callbacks: request.callbacks
    })), ...this.getPendingRequests().map((request) => ({
      state: "pending",
      message: request.message,
      end: request.end,
      callbacks: request.callbacks
    }))];
  }
  /**
  * Checks if there are any pending requests, including ongoing subscriptions.
  */
  hasPendingRequests() {
    return this.getPendingRequests().length > 0;
  }
  /**
  * Checks if there are any pending subscriptions
  */
  hasPendingSubscriptions() {
    return this.getPendingRequests().some((request) => request.message.method === "subscription");
  }
  /**
  * Checks if there are any outgoing requests waiting to be sent.
  */
  hasOutgoingRequests() {
    return this.outgoingRequests.length > 0;
  }
};
var import_defineProperty$1 = __toESM(require_defineProperty(), 1);
function asyncWsOpen(ws) {
  const { promise, resolve, reject } = withResolvers2();
  ws.addEventListener("open", () => {
    ws.removeEventListener("error", reject);
    resolve();
  });
  ws.addEventListener("error", reject);
  return promise;
}
function setupPingInterval(ws, { intervalMs, pongTimeoutMs }) {
  let pingTimeout;
  let pongTimeout;
  function start() {
    pingTimeout = setTimeout(() => {
      ws.send("PING");
      pongTimeout = setTimeout(() => {
        ws.close();
      }, pongTimeoutMs);
    }, intervalMs);
  }
  function reset() {
    clearTimeout(pingTimeout);
    start();
  }
  function pong() {
    clearTimeout(pongTimeout);
    reset();
  }
  ws.addEventListener("open", start);
  ws.addEventListener("message", ({ data }) => {
    clearTimeout(pingTimeout);
    start();
    if (data === "PONG") pong();
  });
  ws.addEventListener("close", () => {
    clearTimeout(pingTimeout);
    clearTimeout(pongTimeout);
  });
}
var WsConnection = class WsConnection2 {
  constructor(opts) {
    var _opts$WebSocketPonyfi;
    (0, import_defineProperty$1.default)(this, "id", ++WsConnection2.connectCount);
    (0, import_defineProperty$1.default)(this, "WebSocketPonyfill", void 0);
    (0, import_defineProperty$1.default)(this, "urlOptions", void 0);
    (0, import_defineProperty$1.default)(this, "keepAliveOpts", void 0);
    (0, import_defineProperty$1.default)(this, "wsObservable", behaviorSubject(null));
    (0, import_defineProperty$1.default)(this, "openPromise", null);
    this.WebSocketPonyfill = (_opts$WebSocketPonyfi = opts.WebSocketPonyfill) !== null && _opts$WebSocketPonyfi !== void 0 ? _opts$WebSocketPonyfi : WebSocket;
    if (!this.WebSocketPonyfill) throw new Error("No WebSocket implementation found - you probably don't want to use this on the server, but if you do you need to pass a `WebSocket`-ponyfill");
    this.urlOptions = opts.urlOptions;
    this.keepAliveOpts = opts.keepAlive;
  }
  get ws() {
    return this.wsObservable.get();
  }
  set ws(ws) {
    this.wsObservable.next(ws);
  }
  /**
  * Checks if the WebSocket connection is open and ready to communicate.
  */
  isOpen() {
    return !!this.ws && this.ws.readyState === this.WebSocketPonyfill.OPEN && !this.openPromise;
  }
  /**
  * Checks if the WebSocket connection is closed or in the process of closing.
  */
  isClosed() {
    return !!this.ws && (this.ws.readyState === this.WebSocketPonyfill.CLOSING || this.ws.readyState === this.WebSocketPonyfill.CLOSED);
  }
  async open() {
    var _this = this;
    if (_this.openPromise) return _this.openPromise;
    _this.id = ++WsConnection2.connectCount;
    const wsPromise = prepareUrl(_this.urlOptions).then((url) => new _this.WebSocketPonyfill(url));
    _this.openPromise = wsPromise.then(async (ws) => {
      _this.ws = ws;
      ws.addEventListener("message", function({ data }) {
        if (data === "PING") this.send("PONG");
      });
      if (_this.keepAliveOpts.enabled) setupPingInterval(ws, _this.keepAliveOpts);
      ws.addEventListener("close", () => {
        if (_this.ws === ws) _this.ws = null;
      });
      await asyncWsOpen(ws);
      if (_this.urlOptions.connectionParams) ws.send(await buildConnectionMessage(_this.urlOptions.connectionParams));
    });
    try {
      await _this.openPromise;
    } finally {
      _this.openPromise = null;
    }
  }
  /**
  * Closes the WebSocket connection gracefully.
  * Waits for any ongoing open operation to complete before closing.
  */
  async close() {
    var _this2 = this;
    try {
      await _this2.openPromise;
    } finally {
      var _this$ws;
      (_this$ws = _this2.ws) === null || _this$ws === void 0 || _this$ws.close();
    }
  }
};
(0, import_defineProperty$1.default)(WsConnection, "connectCount", 0);
function backwardCompatibility(connection) {
  if (connection.isOpen()) return {
    id: connection.id,
    state: "open",
    ws: connection.ws
  };
  if (connection.isClosed()) return {
    id: connection.id,
    state: "closed",
    ws: connection.ws
  };
  if (!connection.ws) return null;
  return {
    id: connection.id,
    state: "connecting",
    ws: connection.ws
  };
}
var import_defineProperty5 = __toESM(require_defineProperty(), 1);
var import_objectSpread210 = __toESM(require_objectSpread2(), 1);
var WsClient = class {
  constructor(opts) {
    var _opts$retryDelayMs;
    (0, import_defineProperty5.default)(this, "connectionState", void 0);
    (0, import_defineProperty5.default)(this, "allowReconnect", false);
    (0, import_defineProperty5.default)(this, "requestManager", new RequestManager());
    (0, import_defineProperty5.default)(this, "activeConnection", void 0);
    (0, import_defineProperty5.default)(this, "reconnectRetryDelay", void 0);
    (0, import_defineProperty5.default)(this, "inactivityTimeout", void 0);
    (0, import_defineProperty5.default)(this, "callbacks", void 0);
    (0, import_defineProperty5.default)(this, "lazyMode", void 0);
    (0, import_defineProperty5.default)(this, "reconnecting", null);
    this.callbacks = {
      onOpen: opts.onOpen,
      onClose: opts.onClose,
      onError: opts.onError
    };
    const lazyOptions = (0, import_objectSpread210.default)((0, import_objectSpread210.default)({}, lazyDefaults), opts.lazy);
    this.inactivityTimeout = new ResettableTimeout(() => {
      if (this.requestManager.hasOutgoingRequests() || this.requestManager.hasPendingRequests()) {
        this.inactivityTimeout.reset();
        return;
      }
      this.close().catch(() => null);
    }, lazyOptions.closeMs);
    this.activeConnection = new WsConnection({
      WebSocketPonyfill: opts.WebSocket,
      urlOptions: opts,
      keepAlive: (0, import_objectSpread210.default)((0, import_objectSpread210.default)({}, keepAliveDefaults), opts.keepAlive)
    });
    this.activeConnection.wsObservable.subscribe({ next: (ws) => {
      if (!ws) return;
      this.setupWebSocketListeners(ws);
    } });
    this.reconnectRetryDelay = (_opts$retryDelayMs = opts.retryDelayMs) !== null && _opts$retryDelayMs !== void 0 ? _opts$retryDelayMs : exponentialBackoff;
    this.lazyMode = lazyOptions.enabled;
    this.connectionState = behaviorSubject({
      type: "state",
      state: lazyOptions.enabled ? "idle" : "connecting",
      error: null
    });
    if (!this.lazyMode) this.open().catch(() => null);
  }
  /**
  * Opens the WebSocket connection. Handles reconnection attempts and updates
  * the connection state accordingly.
  */
  async open() {
    var _this = this;
    _this.allowReconnect = true;
    if (_this.connectionState.get().state === "idle") _this.connectionState.next({
      type: "state",
      state: "connecting",
      error: null
    });
    try {
      await _this.activeConnection.open();
    } catch (error) {
      _this.reconnect(new TRPCWebSocketClosedError({
        message: "Initialization error",
        cause: error
      }));
      return _this.reconnecting;
    }
  }
  /**
  * Closes the WebSocket connection and stops managing requests.
  * Ensures all outgoing and pending requests are properly finalized.
  */
  async close() {
    var _this2 = this;
    _this2.allowReconnect = false;
    _this2.inactivityTimeout.stop();
    const requestsToAwait = [];
    for (const request of _this2.requestManager.getRequests()) if (request.message.method === "subscription") request.callbacks.complete();
    else if (request.state === "outgoing") request.callbacks.error(TRPCClientError.from(new TRPCWebSocketClosedError({ message: "Closed before connection was established" })));
    else requestsToAwait.push(request.end);
    await Promise.all(requestsToAwait).catch(() => null);
    await _this2.activeConnection.close().catch(() => null);
    _this2.connectionState.next({
      type: "state",
      state: "idle",
      error: null
    });
  }
  /**
  * Method to request the server.
  * Handles data transformation, batching of requests, and subscription lifecycle.
  *
  * @param op - The operation details including id, type, path, input and signal
  * @param transformer - Data transformer for serializing requests and deserializing responses
  * @param lastEventId - Optional ID of the last received event for subscriptions
  *
  * @returns An observable that emits operation results and handles cleanup
  */
  request({ op: { id, type, path, input, signal }, transformer, lastEventId }) {
    return observable((observer) => {
      const abort = this.batchSend({
        id,
        method: type,
        params: {
          input: transformer.input.serialize(input),
          path,
          lastEventId
        }
      }, (0, import_objectSpread210.default)((0, import_objectSpread210.default)({}, observer), {}, { next(event) {
        const transformed = transformResult(event, transformer.output);
        if (!transformed.ok) {
          observer.error(TRPCClientError.from(transformed.error));
          return;
        }
        observer.next({ result: transformed.result });
      } }));
      return () => {
        abort();
        if (type === "subscription" && this.activeConnection.isOpen()) this.send({
          id,
          method: "subscription.stop"
        });
        signal === null || signal === void 0 || signal.removeEventListener("abort", abort);
      };
    });
  }
  get connection() {
    return backwardCompatibility(this.activeConnection);
  }
  reconnect(closedError) {
    var _this3 = this;
    this.connectionState.next({
      type: "state",
      state: "connecting",
      error: TRPCClientError.from(closedError)
    });
    if (this.reconnecting) return;
    const tryReconnect = async (attemptIndex) => {
      try {
        await sleep(_this3.reconnectRetryDelay(attemptIndex));
        if (_this3.allowReconnect) {
          await _this3.activeConnection.close();
          await _this3.activeConnection.open();
          if (_this3.requestManager.hasPendingRequests()) _this3.send(_this3.requestManager.getPendingRequests().map(({ message }) => message));
        }
        _this3.reconnecting = null;
      } catch (_unused) {
        await tryReconnect(attemptIndex + 1);
      }
    };
    this.reconnecting = tryReconnect(0);
  }
  setupWebSocketListeners(ws) {
    var _this4 = this;
    const handleCloseOrError = (cause) => {
      const reqs = this.requestManager.getPendingRequests();
      for (const { message, callbacks } of reqs) {
        if (message.method === "subscription") continue;
        callbacks.error(TRPCClientError.from(cause !== null && cause !== void 0 ? cause : new TRPCWebSocketClosedError({
          message: "WebSocket closed",
          cause
        })));
        this.requestManager.delete(message.id);
      }
    };
    ws.addEventListener("open", () => {
      run(async () => {
        var _this$callbacks$onOpe, _this$callbacks;
        if (_this4.lazyMode) _this4.inactivityTimeout.start();
        (_this$callbacks$onOpe = (_this$callbacks = _this4.callbacks).onOpen) === null || _this$callbacks$onOpe === void 0 || _this$callbacks$onOpe.call(_this$callbacks);
        _this4.connectionState.next({
          type: "state",
          state: "pending",
          error: null
        });
      }).catch((error) => {
        ws.close(3e3);
        handleCloseOrError(error);
      });
    });
    ws.addEventListener("message", ({ data }) => {
      this.inactivityTimeout.reset();
      if (typeof data !== "string" || ["PING", "PONG"].includes(data)) return;
      const incomingMessage = JSON.parse(data);
      if ("method" in incomingMessage) {
        this.handleIncomingRequest(incomingMessage);
        return;
      }
      this.handleResponseMessage(incomingMessage);
    });
    ws.addEventListener("close", (event) => {
      var _this$callbacks$onClo, _this$callbacks2;
      handleCloseOrError(event);
      (_this$callbacks$onClo = (_this$callbacks2 = this.callbacks).onClose) === null || _this$callbacks$onClo === void 0 || _this$callbacks$onClo.call(_this$callbacks2, event);
      if (!this.lazyMode || this.requestManager.hasPendingSubscriptions()) this.reconnect(new TRPCWebSocketClosedError({
        message: "WebSocket closed",
        cause: event
      }));
    });
    ws.addEventListener("error", (event) => {
      var _this$callbacks$onErr, _this$callbacks3;
      handleCloseOrError(event);
      (_this$callbacks$onErr = (_this$callbacks3 = this.callbacks).onError) === null || _this$callbacks$onErr === void 0 || _this$callbacks$onErr.call(_this$callbacks3, event);
      this.reconnect(new TRPCWebSocketClosedError({
        message: "WebSocket closed",
        cause: event
      }));
    });
  }
  handleResponseMessage(message) {
    const request = this.requestManager.getPendingRequest(message.id);
    if (!request) return;
    request.callbacks.next(message);
    let completed = true;
    if ("result" in message && request.message.method === "subscription") {
      if (message.result.type === "data") request.message.params.lastEventId = message.result.id;
      if (message.result.type !== "stopped") completed = false;
    }
    if (completed) {
      request.callbacks.complete();
      this.requestManager.delete(message.id);
    }
  }
  handleIncomingRequest(message) {
    if (message.method === "reconnect") this.reconnect(new TRPCWebSocketClosedError({ message: "Server requested reconnect" }));
  }
  /**
  * Sends a message or batch of messages directly to the server.
  */
  send(messageOrMessages) {
    if (!this.activeConnection.isOpen()) throw new Error("Active connection is not open");
    const messages = messageOrMessages instanceof Array ? messageOrMessages : [messageOrMessages];
    this.activeConnection.ws.send(JSON.stringify(messages.length === 1 ? messages[0] : messages));
  }
  /**
  * Groups requests for batch sending.
  *
  * @returns A function to abort the batched request.
  */
  batchSend(message, callbacks) {
    var _this5 = this;
    this.inactivityTimeout.reset();
    run(async () => {
      if (!_this5.activeConnection.isOpen()) await _this5.open();
      await sleep(0);
      if (!_this5.requestManager.hasOutgoingRequests()) return;
      _this5.send(_this5.requestManager.flush().map(({ message: message$1 }) => message$1));
    }).catch((err) => {
      this.requestManager.delete(message.id);
      callbacks.error(TRPCClientError.from(err));
    });
    return this.requestManager.register(message, callbacks);
  }
};
function createWSClient(opts) {
  return new WsClient(opts);
}
function wsLink(opts) {
  const { client } = opts;
  const transformer = getTransformer(opts.transformer);
  return () => {
    return ({ op }) => {
      return observable((observer) => {
        const connStateSubscription = op.type === "subscription" ? client.connectionState.subscribe({ next(result) {
          observer.next({
            result,
            context: op.context
          });
        } }) : null;
        const requestSubscription = client.request({
          op,
          transformer
        }).subscribe(observer);
        return () => {
          requestSubscription.unsubscribe();
          connStateSubscription === null || connStateSubscription === void 0 || connStateSubscription.unsubscribe();
        };
      });
    };
  };
}

// ../../node_modules/.pnpm/@trpc+client@11.8.1_@trpc+server@11.8.1_typescript@5.9.3__typescript@5.9.3/node_modules/@trpc/client/dist/index.mjs
var import_defineProperty6 = __toESM(require_defineProperty(), 1);
var import_objectSpread2$4 = __toESM(require_objectSpread2(), 1);
var TRPCUntypedClient = class {
  constructor(opts) {
    (0, import_defineProperty6.default)(this, "links", void 0);
    (0, import_defineProperty6.default)(this, "runtime", void 0);
    (0, import_defineProperty6.default)(this, "requestId", void 0);
    this.requestId = 0;
    this.runtime = {};
    this.links = opts.links.map((link) => link(this.runtime));
  }
  $request(opts) {
    var _opts$context;
    const chain$ = createChain({
      links: this.links,
      op: (0, import_objectSpread2$4.default)((0, import_objectSpread2$4.default)({}, opts), {}, {
        context: (_opts$context = opts.context) !== null && _opts$context !== void 0 ? _opts$context : {},
        id: ++this.requestId
      })
    });
    return chain$.pipe(share());
  }
  async requestAsPromise(opts) {
    var _this = this;
    try {
      const req$ = _this.$request(opts);
      const envelope = await observableToPromise(req$);
      const data = envelope.result.data;
      return data;
    } catch (err) {
      throw TRPCClientError.from(err);
    }
  }
  query(path, input, opts) {
    return this.requestAsPromise({
      type: "query",
      path,
      input,
      context: opts === null || opts === void 0 ? void 0 : opts.context,
      signal: opts === null || opts === void 0 ? void 0 : opts.signal
    });
  }
  mutation(path, input, opts) {
    return this.requestAsPromise({
      type: "mutation",
      path,
      input,
      context: opts === null || opts === void 0 ? void 0 : opts.context,
      signal: opts === null || opts === void 0 ? void 0 : opts.signal
    });
  }
  subscription(path, input, opts) {
    const observable$ = this.$request({
      type: "subscription",
      path,
      input,
      context: opts.context,
      signal: opts.signal
    });
    return observable$.subscribe({
      next(envelope) {
        switch (envelope.result.type) {
          case "state": {
            var _opts$onConnectionSta;
            (_opts$onConnectionSta = opts.onConnectionStateChange) === null || _opts$onConnectionSta === void 0 || _opts$onConnectionSta.call(opts, envelope.result);
            break;
          }
          case "started": {
            var _opts$onStarted;
            (_opts$onStarted = opts.onStarted) === null || _opts$onStarted === void 0 || _opts$onStarted.call(opts, { context: envelope.context });
            break;
          }
          case "stopped": {
            var _opts$onStopped;
            (_opts$onStopped = opts.onStopped) === null || _opts$onStopped === void 0 || _opts$onStopped.call(opts);
            break;
          }
          case "data":
          case void 0: {
            var _opts$onData;
            (_opts$onData = opts.onData) === null || _opts$onData === void 0 || _opts$onData.call(opts, envelope.result.data);
            break;
          }
        }
      },
      error(err) {
        var _opts$onError;
        (_opts$onError = opts.onError) === null || _opts$onError === void 0 || _opts$onError.call(opts, err);
      },
      complete() {
        var _opts$onComplete;
        (_opts$onComplete = opts.onComplete) === null || _opts$onComplete === void 0 || _opts$onComplete.call(opts);
      }
    });
  }
};
function createTRPCUntypedClient(opts) {
  return new TRPCUntypedClient(opts);
}
var untypedClientSymbol = Symbol.for("trpc_untypedClient");
var clientCallTypeMap = {
  query: "query",
  mutate: "mutation",
  subscribe: "subscription"
};
var clientCallTypeToProcedureType = (clientCallType) => {
  return clientCallTypeMap[clientCallType];
};
function createTRPCClientProxy(client) {
  const proxy = createRecursiveProxy(({ path, args }) => {
    const pathCopy = [...path];
    const procedureType = clientCallTypeToProcedureType(pathCopy.pop());
    const fullPath = pathCopy.join(".");
    return client[procedureType](fullPath, ...args);
  });
  return createFlatProxy((key) => {
    if (key === untypedClientSymbol) return client;
    return proxy[key];
  });
}
function createTRPCClient(opts) {
  const client = new TRPCUntypedClient(opts);
  const proxy = createTRPCClientProxy(client);
  return proxy;
}
function getUntypedClient(client) {
  return client[untypedClientSymbol];
}
var import_objectSpread2$3 = __toESM(require_objectSpread2(), 1);
function httpBatchStreamLink(opts) {
  var _opts$maxURLLength, _opts$maxItems;
  const resolvedOpts = resolveHTTPLinkOptions(opts);
  const maxURLLength = (_opts$maxURLLength = opts.maxURLLength) !== null && _opts$maxURLLength !== void 0 ? _opts$maxURLLength : Infinity;
  const maxItems = (_opts$maxItems = opts.maxItems) !== null && _opts$maxItems !== void 0 ? _opts$maxItems : Infinity;
  return () => {
    const batchLoader = (type) => {
      return {
        validate(batchOps) {
          if (maxURLLength === Infinity && maxItems === Infinity) return true;
          if (batchOps.length > maxItems) return false;
          const path = batchOps.map((op) => op.path).join(",");
          const inputs = batchOps.map((op) => op.input);
          const url = getUrl((0, import_objectSpread2$3.default)((0, import_objectSpread2$3.default)({}, resolvedOpts), {}, {
            type,
            path,
            inputs,
            signal: null
          }));
          return url.length <= maxURLLength;
        },
        async fetch(batchOps) {
          const path = batchOps.map((op) => op.path).join(",");
          const inputs = batchOps.map((op) => op.input);
          const batchSignals = allAbortSignals(...batchOps.map((op) => op.signal));
          const abortController = new AbortController();
          const responsePromise = fetchHTTPResponse((0, import_objectSpread2$3.default)((0, import_objectSpread2$3.default)({}, resolvedOpts), {}, {
            signal: raceAbortSignals(batchSignals, abortController.signal),
            type,
            contentTypeHeader: "application/json",
            trpcAcceptHeader: "application/jsonl",
            getUrl,
            getBody,
            inputs,
            path,
            headers() {
              if (!opts.headers) return {};
              if (typeof opts.headers === "function") return opts.headers({ opList: batchOps });
              return opts.headers;
            }
          }));
          const res = await responsePromise;
          const [head] = await jsonlStreamConsumer({
            from: res.body,
            deserialize: (data) => resolvedOpts.transformer.output.deserialize(data),
            formatError(opts$1) {
              const error = opts$1.error;
              return TRPCClientError.from({ error });
            },
            abortController
          });
          const promises = Object.keys(batchOps).map(async (key) => {
            let json = await Promise.resolve(head[key]);
            if ("result" in json) {
              const result = await Promise.resolve(json.result);
              json = { result: { data: await Promise.resolve(result.data) } };
            }
            return {
              json,
              meta: { response: res }
            };
          });
          return promises;
        }
      };
    };
    const query = dataLoader(batchLoader("query"));
    const mutation = dataLoader(batchLoader("mutation"));
    const loaders = {
      query,
      mutation
    };
    return ({ op }) => {
      return observable((observer) => {
        if (op.type === "subscription") throw new Error("Subscriptions are unsupported by `httpBatchStreamLink` - use `httpSubscriptionLink` or `wsLink`");
        const loader = loaders[op.type];
        const promise = loader.load(op);
        let _res = void 0;
        promise.then((res) => {
          _res = res;
          if ("error" in res.json) {
            observer.error(TRPCClientError.from(res.json, { meta: res.meta }));
            return;
          } else if ("result" in res.json) {
            observer.next({
              context: res.meta,
              result: res.json.result
            });
            observer.complete();
            return;
          }
          observer.complete();
        }).catch((err) => {
          observer.error(TRPCClientError.from(err, { meta: _res === null || _res === void 0 ? void 0 : _res.meta }));
        });
        return () => {
        };
      });
    };
  };
}
var unstable_httpBatchStreamLink = httpBatchStreamLink;
var import_objectSpread2$22 = __toESM(require_objectSpread2(), 1);
function inputWithTrackedEventId(input, lastEventId) {
  if (!lastEventId) return input;
  if (input != null && typeof input !== "object") return input;
  return (0, import_objectSpread2$22.default)((0, import_objectSpread2$22.default)({}, input !== null && input !== void 0 ? input : {}), {}, { lastEventId });
}
var require_asyncIterator2 = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/asyncIterator.js"(exports, module) {
  function _asyncIterator$1(r) {
    var n, t, o, e = 2;
    for ("undefined" != typeof Symbol && (t = Symbol.asyncIterator, o = Symbol.iterator); e--; ) {
      if (t && null != (n = r[t])) return n.call(r);
      if (o && null != (n = r[o])) return new AsyncFromSyncIterator(n.call(r));
      t = "@@asyncIterator", o = "@@iterator";
    }
    throw new TypeError("Object is not async iterable");
  }
  function AsyncFromSyncIterator(r) {
    function AsyncFromSyncIteratorContinuation(r$1) {
      if (Object(r$1) !== r$1) return Promise.reject(new TypeError(r$1 + " is not an object."));
      var n = r$1.done;
      return Promise.resolve(r$1.value).then(function(r$2) {
        return {
          value: r$2,
          done: n
        };
      });
    }
    return AsyncFromSyncIterator = function AsyncFromSyncIterator$1(r$1) {
      this.s = r$1, this.n = r$1.next;
    }, AsyncFromSyncIterator.prototype = {
      s: null,
      n: null,
      next: function next() {
        return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments));
      },
      "return": function _return(r$1) {
        var n = this.s["return"];
        return void 0 === n ? Promise.resolve({
          value: r$1,
          done: true
        }) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments));
      },
      "throw": function _throw(r$1) {
        var n = this.s["return"];
        return void 0 === n ? Promise.reject(r$1) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments));
      }
    }, new AsyncFromSyncIterator(r);
  }
  module.exports = _asyncIterator$1, module.exports.__esModule = true, module.exports["default"] = module.exports;
} });
var import_asyncIterator2 = __toESM(require_asyncIterator2(), 1);
async function urlWithConnectionParams(opts) {
  let url = await resultOf(opts.url);
  if (opts.connectionParams) {
    const params = await resultOf(opts.connectionParams);
    const prefix = url.includes("?") ? "&" : "?";
    url += prefix + "connectionParams=" + encodeURIComponent(JSON.stringify(params));
  }
  return url;
}
function httpSubscriptionLink(opts) {
  const transformer = getTransformer(opts.transformer);
  return () => {
    return ({ op }) => {
      return observable((observer) => {
        var _opts$EventSource;
        const { type, path, input } = op;
        if (type !== "subscription") throw new Error("httpSubscriptionLink only supports subscriptions");
        let lastEventId = void 0;
        const ac = new AbortController();
        const signal = raceAbortSignals(op.signal, ac.signal);
        const eventSourceStream = sseStreamConsumer({
          url: async () => getUrl({
            transformer,
            url: await urlWithConnectionParams(opts),
            input: inputWithTrackedEventId(input, lastEventId),
            path,
            type,
            signal: null
          }),
          init: () => resultOf(opts.eventSourceOptions, { op }),
          signal,
          deserialize: (data) => transformer.output.deserialize(data),
          EventSource: (_opts$EventSource = opts.EventSource) !== null && _opts$EventSource !== void 0 ? _opts$EventSource : globalThis.EventSource
        });
        const connectionState = behaviorSubject({
          type: "state",
          state: "connecting",
          error: null
        });
        const connectionSub = connectionState.subscribe({ next(state) {
          observer.next({ result: state });
        } });
        run(async () => {
          var _iteratorAbruptCompletion = false;
          var _didIteratorError = false;
          var _iteratorError;
          try {
            for (var _iterator = (0, import_asyncIterator2.default)(eventSourceStream), _step; _iteratorAbruptCompletion = !(_step = await _iterator.next()).done; _iteratorAbruptCompletion = false) {
              const chunk = _step.value;
              switch (chunk.type) {
                case "ping":
                  break;
                case "data":
                  const chunkData = chunk.data;
                  let result;
                  if (chunkData.id) {
                    lastEventId = chunkData.id;
                    result = {
                      id: chunkData.id,
                      data: chunkData
                    };
                  } else result = { data: chunkData.data };
                  observer.next({
                    result,
                    context: { eventSource: chunk.eventSource }
                  });
                  break;
                case "connected": {
                  observer.next({
                    result: { type: "started" },
                    context: { eventSource: chunk.eventSource }
                  });
                  connectionState.next({
                    type: "state",
                    state: "pending",
                    error: null
                  });
                  break;
                }
                case "serialized-error": {
                  const error = TRPCClientError.from({ error: chunk.error });
                  if (retryableRpcCodes.includes(chunk.error.code)) {
                    connectionState.next({
                      type: "state",
                      state: "connecting",
                      error
                    });
                    break;
                  }
                  throw error;
                }
                case "connecting": {
                  const lastState = connectionState.get();
                  const error = chunk.event && TRPCClientError.from(chunk.event);
                  if (!error && lastState.state === "connecting") break;
                  connectionState.next({
                    type: "state",
                    state: "connecting",
                    error
                  });
                  break;
                }
                case "timeout":
                  connectionState.next({
                    type: "state",
                    state: "connecting",
                    error: new TRPCClientError(`Timeout of ${chunk.ms}ms reached while waiting for a response`)
                  });
              }
            }
          } catch (err) {
            _didIteratorError = true;
            _iteratorError = err;
          } finally {
            try {
              if (_iteratorAbruptCompletion && _iterator.return != null) await _iterator.return();
            } finally {
              if (_didIteratorError) throw _iteratorError;
            }
          }
          observer.next({ result: { type: "stopped" } });
          connectionState.next({
            type: "state",
            state: "idle",
            error: null
          });
          observer.complete();
        }).catch((error) => {
          observer.error(TRPCClientError.from(error));
        });
        return () => {
          observer.complete();
          ac.abort();
          connectionSub.unsubscribe();
        };
      });
    };
  };
}
var unstable_httpSubscriptionLink = httpSubscriptionLink;
var import_objectSpread2$14 = __toESM(require_objectSpread2(), 1);
function retryLink(opts) {
  return () => {
    return (callOpts) => {
      return observable((observer) => {
        let next$;
        let callNextTimeout = void 0;
        let lastEventId = void 0;
        attempt(1);
        function opWithLastEventId() {
          const op = callOpts.op;
          if (!lastEventId) return op;
          return (0, import_objectSpread2$14.default)((0, import_objectSpread2$14.default)({}, op), {}, { input: inputWithTrackedEventId(op.input, lastEventId) });
        }
        function attempt(attempts) {
          const op = opWithLastEventId();
          next$ = callOpts.next(op).subscribe({
            error(error) {
              var _opts$retryDelayMs, _opts$retryDelayMs2;
              const shouldRetry = opts.retry({
                op,
                attempts,
                error
              });
              if (!shouldRetry) {
                observer.error(error);
                return;
              }
              const delayMs = (_opts$retryDelayMs = (_opts$retryDelayMs2 = opts.retryDelayMs) === null || _opts$retryDelayMs2 === void 0 ? void 0 : _opts$retryDelayMs2.call(opts, attempts)) !== null && _opts$retryDelayMs !== void 0 ? _opts$retryDelayMs : 0;
              if (delayMs <= 0) {
                attempt(attempts + 1);
                return;
              }
              callNextTimeout = setTimeout(() => attempt(attempts + 1), delayMs);
            },
            next(envelope) {
              if ((!envelope.result.type || envelope.result.type === "data") && envelope.result.id) lastEventId = envelope.result.id;
              observer.next(envelope);
            },
            complete() {
              observer.complete();
            }
          });
        }
        return () => {
          next$.unsubscribe();
          clearTimeout(callNextTimeout);
        };
      });
    };
  };
}
var require_usingCtx2 = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/usingCtx.js"(exports, module) {
  function _usingCtx() {
    var r = "function" == typeof SuppressedError ? SuppressedError : function(r$1, e$1) {
      var n$1 = Error();
      return n$1.name = "SuppressedError", n$1.error = r$1, n$1.suppressed = e$1, n$1;
    }, e = {}, n = [];
    function using(r$1, e$1) {
      if (null != e$1) {
        if (Object(e$1) !== e$1) throw new TypeError("using declarations can only be used with objects, functions, null, or undefined.");
        if (r$1) var o = e$1[Symbol.asyncDispose || Symbol["for"]("Symbol.asyncDispose")];
        if (void 0 === o && (o = e$1[Symbol.dispose || Symbol["for"]("Symbol.dispose")], r$1)) var t = o;
        if ("function" != typeof o) throw new TypeError("Object is not disposable.");
        t && (o = function o$1() {
          try {
            t.call(e$1);
          } catch (r$2) {
            return Promise.reject(r$2);
          }
        }), n.push({
          v: e$1,
          d: o,
          a: r$1
        });
      } else r$1 && n.push({
        d: e$1,
        a: r$1
      });
      return e$1;
    }
    return {
      e,
      u: using.bind(null, false),
      a: using.bind(null, true),
      d: function d() {
        var o, t = this.e, s = 0;
        function next() {
          for (; o = n.pop(); ) try {
            if (!o.a && 1 === s) return s = 0, n.push(o), Promise.resolve().then(next);
            if (o.d) {
              var r$1 = o.d.call(o.v);
              if (o.a) return s |= 2, Promise.resolve(r$1).then(next, err);
            } else s |= 1;
          } catch (r$2) {
            return err(r$2);
          }
          if (1 === s) return t !== e ? Promise.reject(t) : Promise.resolve();
          if (t !== e) throw t;
        }
        function err(n$1) {
          return t = t !== e ? new r(n$1, t) : n$1, next();
        }
        return next();
      }
    };
  }
  module.exports = _usingCtx, module.exports.__esModule = true, module.exports["default"] = module.exports;
} });
var require_OverloadYield2 = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/OverloadYield.js"(exports, module) {
  function _OverloadYield(e, d) {
    this.v = e, this.k = d;
  }
  module.exports = _OverloadYield, module.exports.__esModule = true, module.exports["default"] = module.exports;
} });
var require_awaitAsyncGenerator2 = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/awaitAsyncGenerator.js"(exports, module) {
  var OverloadYield$1 = require_OverloadYield2();
  function _awaitAsyncGenerator$1(e) {
    return new OverloadYield$1(e, 0);
  }
  module.exports = _awaitAsyncGenerator$1, module.exports.__esModule = true, module.exports["default"] = module.exports;
} });
var require_wrapAsyncGenerator2 = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/wrapAsyncGenerator.js"(exports, module) {
  var OverloadYield = require_OverloadYield2();
  function _wrapAsyncGenerator$1(e) {
    return function() {
      return new AsyncGenerator(e.apply(this, arguments));
    };
  }
  function AsyncGenerator(e) {
    var r, t;
    function resume(r$1, t$1) {
      try {
        var n = e[r$1](t$1), o = n.value, u = o instanceof OverloadYield;
        Promise.resolve(u ? o.v : o).then(function(t$2) {
          if (u) {
            var i = "return" === r$1 ? "return" : "next";
            if (!o.k || t$2.done) return resume(i, t$2);
            t$2 = e[i](t$2).value;
          }
          settle(n.done ? "return" : "normal", t$2);
        }, function(e$1) {
          resume("throw", e$1);
        });
      } catch (e$1) {
        settle("throw", e$1);
      }
    }
    function settle(e$1, n) {
      switch (e$1) {
        case "return":
          r.resolve({
            value: n,
            done: true
          });
          break;
        case "throw":
          r.reject(n);
          break;
        default:
          r.resolve({
            value: n,
            done: false
          });
      }
      (r = r.next) ? resume(r.key, r.arg) : t = null;
    }
    this._invoke = function(e$1, n) {
      return new Promise(function(o, u) {
        var i = {
          key: e$1,
          arg: n,
          resolve: o,
          reject: u,
          next: null
        };
        t ? t = t.next = i : (r = t = i, resume(e$1, n));
      });
    }, "function" != typeof e["return"] && (this["return"] = void 0);
  }
  AsyncGenerator.prototype["function" == typeof Symbol && Symbol.asyncIterator || "@@asyncIterator"] = function() {
    return this;
  }, AsyncGenerator.prototype.next = function(e) {
    return this._invoke("next", e);
  }, AsyncGenerator.prototype["throw"] = function(e) {
    return this._invoke("throw", e);
  }, AsyncGenerator.prototype["return"] = function(e) {
    return this._invoke("return", e);
  };
  module.exports = _wrapAsyncGenerator$1, module.exports.__esModule = true, module.exports["default"] = module.exports;
} });
var import_usingCtx2 = __toESM(require_usingCtx2(), 1);
var import_awaitAsyncGenerator2 = __toESM(require_awaitAsyncGenerator2(), 1);
var import_wrapAsyncGenerator2 = __toESM(require_wrapAsyncGenerator2(), 1);
var import_objectSpread211 = __toESM(require_objectSpread2(), 1);
function unstable_localLink(opts) {
  const transformer = getTransformer(opts.transformer);
  const transformChunk = (chunk) => {
    if (opts.transformer) return chunk;
    if (chunk === void 0) return chunk;
    const serialized = JSON.stringify(transformer.input.serialize(chunk));
    const deserialized = JSON.parse(transformer.output.deserialize(serialized));
    return deserialized;
  };
  return () => ({ op }) => observable((observer) => {
    let ctx = void 0;
    const ac = new AbortController();
    const signal = raceAbortSignals(op.signal, ac.signal);
    const signalPromise = abortSignalToPromise(signal);
    signalPromise.catch(() => {
    });
    let input = op.input;
    async function runProcedure(newInput) {
      input = newInput;
      ctx = await opts.createContext();
      return callProcedure({
        router: opts.router,
        path: op.path,
        getRawInput: async () => newInput,
        ctx,
        type: op.type,
        signal
      });
    }
    function onErrorCallback(cause) {
      var _opts$onError;
      if (isAbortError(cause)) return;
      (_opts$onError = opts.onError) === null || _opts$onError === void 0 || _opts$onError.call(opts, {
        error: getTRPCErrorFromUnknown(cause),
        type: op.type,
        path: op.path,
        input,
        ctx
      });
    }
    function coerceToTRPCClientError(cause) {
      if (isTRPCClientError(cause)) return cause;
      const error = getTRPCErrorFromUnknown(cause);
      const shape = getErrorShape({
        config: opts.router._def._config,
        ctx,
        error,
        input,
        path: op.path,
        type: op.type
      });
      return TRPCClientError.from({ error: transformChunk(shape) });
    }
    run(async () => {
      switch (op.type) {
        case "query":
        case "mutation": {
          const result = await runProcedure(op.input);
          if (!isAsyncIterable(result)) {
            observer.next({ result: { data: transformChunk(result) } });
            observer.complete();
            break;
          }
          observer.next({ result: { data: (0, import_wrapAsyncGenerator2.default)(function* () {
            try {
              var _usingCtx$1 = (0, import_usingCtx2.default)();
              const iterator = _usingCtx$1.a(iteratorResource(result));
              const _finally = _usingCtx$1.u(makeResource({}, () => {
                observer.complete();
              }));
              try {
                while (true) {
                  const res = yield (0, import_awaitAsyncGenerator2.default)(Promise.race([iterator.next(), signalPromise]));
                  if (res.done) return transformChunk(res.value);
                  yield transformChunk(res.value);
                }
              } catch (cause) {
                onErrorCallback(cause);
                throw coerceToTRPCClientError(cause);
              }
            } catch (_) {
              _usingCtx$1.e = _;
            } finally {
              yield (0, import_awaitAsyncGenerator2.default)(_usingCtx$1.d());
            }
          })() } });
          break;
        }
        case "subscription":
          try {
            var _usingCtx3 = (0, import_usingCtx2.default)();
            const connectionState = behaviorSubject({
              type: "state",
              state: "connecting",
              error: null
            });
            const connectionSub = connectionState.subscribe({ next(state) {
              observer.next({ result: state });
            } });
            let lastEventId = void 0;
            const _finally = _usingCtx3.u(makeResource({}, async () => {
              observer.complete();
              connectionState.next({
                type: "state",
                state: "idle",
                error: null
              });
              connectionSub.unsubscribe();
            }));
            while (true) try {
              var _usingCtx4 = (0, import_usingCtx2.default)();
              const result = await runProcedure(inputWithTrackedEventId(op.input, lastEventId));
              if (!isAsyncIterable(result)) throw new Error("Expected an async iterable");
              const iterator = _usingCtx4.a(iteratorResource(result));
              observer.next({ result: { type: "started" } });
              connectionState.next({
                type: "state",
                state: "pending",
                error: null
              });
              while (true) {
                let res;
                try {
                  res = await Promise.race([iterator.next(), signalPromise]);
                } catch (cause) {
                  if (isAbortError(cause)) return;
                  const error = getTRPCErrorFromUnknown(cause);
                  if (!retryableRpcCodes.includes(TRPC_ERROR_CODES_BY_KEY[error.code])) throw coerceToTRPCClientError(error);
                  onErrorCallback(error);
                  connectionState.next({
                    type: "state",
                    state: "connecting",
                    error: coerceToTRPCClientError(error)
                  });
                  break;
                }
                if (res.done) return;
                let chunk;
                if (isTrackedEnvelope(res.value)) {
                  lastEventId = res.value[0];
                  chunk = {
                    id: res.value[0],
                    data: {
                      id: res.value[0],
                      data: res.value[1]
                    }
                  };
                } else chunk = { data: res.value };
                observer.next({ result: (0, import_objectSpread211.default)((0, import_objectSpread211.default)({}, chunk), {}, { data: transformChunk(chunk.data) }) });
              }
            } catch (_) {
              _usingCtx4.e = _;
            } finally {
              await _usingCtx4.d();
            }
            break;
          } catch (_) {
            _usingCtx3.e = _;
          } finally {
            _usingCtx3.d();
          }
      }
    }).catch((cause) => {
      onErrorCallback(cause);
      observer.error(coerceToTRPCClientError(cause));
    });
    return () => {
      ac.abort();
    };
  });
}
var experimental_localLink = unstable_localLink;

export {
  isObject,
  isAsyncIterable,
  createRecursiveProxy,
  createFlatProxy,
  splitLink,
  isTRPCClientError,
  TRPCClientError,
  getFetch,
  isOctetType,
  isFormData,
  isNonJsonSerializable,
  httpLink,
  httpBatchLink,
  loggerLink,
  createWSClient,
  wsLink,
  TRPCUntypedClient,
  createTRPCUntypedClient,
  clientCallTypeToProcedureType,
  createTRPCClientProxy,
  createTRPCClient,
  getUntypedClient,
  httpBatchStreamLink,
  unstable_httpBatchStreamLink,
  httpSubscriptionLink,
  unstable_httpSubscriptionLink,
  retryLink,
  unstable_localLink,
  experimental_localLink
};
//# sourceMappingURL=chunk-FHGAEALY.js.map
