UNPKG

@huolala-tech/page-spy-lynx

Version:

An SDK of PageSpy for debugging Lynx app

8,489 lines 279 kB
function _typeof(o) {
  "@babel/helpers - typeof";

  return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
    return typeof o;
  } : function (o) {
    return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
  }, _typeof(o);
}

function toPrimitive(t, r) {
  if ("object" != _typeof(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r || "default");
    if ("object" != _typeof(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r ? String : Number)(t);
}

function toPropertyKey(t) {
  var i = toPrimitive(t, "string");
  return "symbol" == _typeof(i) ? i : i + "";
}

function _defineProperty(obj, key, value) {
  key = toPropertyKey(key);
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }
  return obj;
}

function isBrowser() {
  return typeof window === 'object' && typeof document === 'object' && Object.prototype.toString.call(document) === '[object HTMLDocument]';
}
function getRandomId() {
  return Math.random().toString(36).slice(2);
}
function getObjectKeys(obj) {
  return Object.keys(obj);
}
function toStringTag(value) {
  return Object.prototype.toString.call(value);
}
function hasOwnProperty(target, key) {
  return Object.prototype.hasOwnProperty.call(target, key);
}
function isString(value) {
  return typeof value === 'string';
}
function isNumber(value) {
  return typeof value === 'number';
}
function isBigInt(value) {
  return toStringTag(value) === '[object BigInt]';
}
function isArray(value) {
  return value instanceof Array;
}
function isArrayLike(value) {
  if (typeof NodeList === 'function' && NodeList.name === 'NodeList' && value instanceof NodeList) {
    return true;
  }
  if (typeof HTMLCollection === 'function' && HTMLCollection.name === 'HTMLCollection' && value instanceof HTMLCollection) {
    return true;
  }
  return false;
}
function isObjectLike(value) {
  return typeof value === 'object' && value !== null;
}
function isPlainObject(value) {
  if (!isObjectLike(value) || toStringTag(value) !== '[object Object]') {
    return false;
  }
  return true;
}
function isPrototype(value) {
  if (isObjectLike(value) && hasOwnProperty(value, 'constructor') && typeof value.constructor === 'function') {
    return true;
  }
  return false;
}
function isArrayBuffer(value) {
  return value instanceof ArrayBuffer;
}
function isFile(value) {
  return value instanceof File;
}
function isURL(value) {
  return value instanceof URL;
}
function isClass(obj) {
  return typeof obj === 'function' && typeof obj.prototype !== 'undefined';
}
/**
 * ES Module namespace objects (result of dynamic import()) have:
 * - Symbol.toStringTag === 'Module'
 * - null prototype (no constructor)
 */
function isModuleNamespace(value) {
  return isObjectLike(value) && toStringTag(value) === '[object Module]';
}
const CN_IDs = ['zh-CN', 'zh-HK', 'zh-TW', 'zh', 'zh-Hans-CN'];
function isCN() {
  if (isBrowser()) {
    const {
      lang
    } = document.documentElement;
    if (lang) return CN_IDs.some(i => i === lang);
    return CN_IDs.some(i => i === navigator.language);
  }
  return false;
}
function isTypedArray(value) {
  return ArrayBuffer.isView(value);
}
const stringify = value => "".concat(value);
const primitive = value => ({
  ok: true,
  value
});
function makePrimitiveValue(value) {
  if (value === undefined) {
    return primitive(stringify(value));
  }
  if (value === null) {
    return primitive(value);
  }
  if (isNumber(value)) {
    if (value === -Infinity || value === Infinity || Number.isNaN(value)) {
      return primitive(stringify(value));
    }
  }
  if (isBigInt(value)) {
    return primitive("".concat(value, "n"));
  }
  if (typeof value === 'symbol' || typeof value === 'function') {
    return primitive(stringify(value.toString()));
  }
  if (value instanceof Error) {
    return primitive(stringify(value.stack));
  }
  if (value === Object.prototype) {
    return {
      value: null,
      ok: false
    };
  }
  if (!(value instanceof Object || typeof value === 'object')) {
    return primitive(value);
  }
  return {
    value,
    ok: false
  };
}
/**
 * convert `symbol / error / undefined / function` type data to readable string content
 */
function stringifyData(data) {
  const {
    ok,
    value
  } = makePrimitiveValue(data);
  /* c8 ignore next 3 */
  if (ok) {
    return value;
  }
  return JSON.stringify(data, (key, val) => makePrimitiveValue(val).value, 2);
}
function getValueType(value) {
  if (value === undefined) return 'undefined';
  if (value === null) return 'null';
  if (isBigInt(value)) return 'bigint';
  if (value instanceof Object) {
    if (value instanceof Error) return 'error';
    // Here we do not use 'instanceof Function' because in some context
    // like mini program the Function constructor is overwritten.
    if (typeof value === 'function') return 'function';
    return 'object';
  }
  return typeof value;
}
const unproxyConsole = {
  ...console
};
const psLog = ['log', 'info', 'error', 'warn', 'debug'].reduce((result, method) => {
  result[method] = function () {
    for (var _len = arguments.length, message = new Array(_len), _key = 0; _key < _len; _key++) {
      message[_key] = arguments[_key];
    }
    console[method]("[PageSpy] [".concat(method.toLocaleUpperCase(), "] "), ...message);
  };
  result.unproxy[method] = function () {
    for (var _len2 = arguments.length, message = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
      message[_key2] = arguments[_key2];
    }
    unproxyConsole[method]("[PageSpy] [".concat(method.toLocaleUpperCase(), "] "), ...message);
  };
  return result;
}, {
  unproxy: {}
});
function getAuthSecret() {
  const secret = Math.floor(Math.random() * 1000000);
  return String(secret).padStart(6, '0');
}
const formatErrorObj = err => {
  if (typeof err !== 'object') return null;
  const {
    name,
    message,
    stack
  } = Object(err);
  if ([name, message, stack].every(Boolean) === false) {
    return null;
  }
  return {
    name,
    message,
    stack
  };
};
const blob2base64Async = blob => {
  return new Promise((resolve, reject) => {
    const fr = new FileReader();
    fr.onload = e => {
      var _e$target;
      resolve((_e$target = e.target) === null || _e$target === void 0 ? void 0 : _e$target.result);
    };
    /* c8 ignore next 3 */
    fr.onerror = () => {
      reject(new Error('blob2base64Async: can not convert'));
    };
    fr.readAsDataURL(blob);
  });
};

const CONNECT = 'connect';
const JOIN = 'join';
const LEAVE = 'leave';
const CLOSE = 'close';
const MESSAGE = 'message';
const BROADCAST = 'broadcast';
const ERROR = 'error';
const PING = 'ping';
const PONG = 'pong';
const UPDATE_ROOM_INFO = 'updateRoomInfo';

var SERVER_MESSAGE_TYPE = /*#__PURE__*/Object.freeze({
  __proto__: null,
  BROADCAST: BROADCAST,
  CLOSE: CLOSE,
  CONNECT: CONNECT,
  ERROR: ERROR,
  JOIN: JOIN,
  LEAVE: LEAVE,
  MESSAGE: MESSAGE,
  PING: PING,
  PONG: PONG,
  UPDATE_ROOM_INFO: UPDATE_ROOM_INFO
});

function makeMessage(type, data) {
  let needId = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
  const result = {
    ...(needId && {
      id: getRandomId()
    }),
    ...data
  };
  return {
    role: 'client',
    type,
    data: result
  };
}
function makeUnicastMessage(msg, from, to) {
  return {
    type: MESSAGE,
    content: {
      data: msg,
      from,
      to
    }
  };
}
function makeBroadcastMessage(msg) {
  return {
    type: BROADCAST,
    content: {
      data: msg
    }
  };
}

class RequestItem {
  constructor(id) {
    _defineProperty(this, "id", '');
    _defineProperty(this, "method", '');
    _defineProperty(this, "url", '');
    _defineProperty(this, "requestType", 'xhr');
    _defineProperty(this, "requestHeader", null);
    _defineProperty(this, "status", 0);
    _defineProperty(this, "statusText", '');
    _defineProperty(this, "readyState", 0);
    // See: https://github.com/HuolalaTech/page-spy-web/issues/390
    _defineProperty(this, "response", '__PLACEHOLDER_RESPONSE_DEFINED_BY_PAGE_SPY__');
    _defineProperty(this, "responseReason", null);
    // error response reason
    _defineProperty(this, "responseType", '');
    _defineProperty(this, "responseHeader", null);
    _defineProperty(this, "startTime", 0);
    _defineProperty(this, "endTime", 0);
    _defineProperty(this, "costTime", 0);
    /**
     * @deprecated please using `requestPayload`
     */
    _defineProperty(this, "postData", null);
    _defineProperty(this, "requestPayload", null);
    _defineProperty(this, "withCredentials", false);
    // For EventSource
    _defineProperty(this, "lastEventId", '');
    this.id = id;
  }
}

// File size is not recommended to exceed the MAX_SIZE,
// big size files would result negative performance impact distinctly in local-test.
const MAX_SIZE = 1024 * 1024 * 2;
const Reason = {
  EXCEED_SIZE: 'Exceed maximum limit'
};
const PAGE_SPY_WS_ENDPOINT = '/api/v1/ws/room/join';
// Fork XMLHttpRequest status, for usage in platforms other than browser.
var ReqReadyState;
(function (ReqReadyState) {
  ReqReadyState[ReqReadyState["UNSENT"] = 0] = "UNSENT";
  ReqReadyState[ReqReadyState["OPENED"] = 1] = "OPENED";
  ReqReadyState[ReqReadyState["HEADERS_RECEIVED"] = 2] = "HEADERS_RECEIVED";
  ReqReadyState[ReqReadyState["LOADING"] = 3] = "LOADING";
  ReqReadyState[ReqReadyState["DONE"] = 4] = "DONE";
})(ReqReadyState || (ReqReadyState = {}));
const BINARY_FILE_VARIANT = '(file)';
function formatEntries(data) {
  const result = [];
  let processor = data.next();
  while (!processor.done) {
    const [key, value] = processor.value;
    let variant;
    if (isFile(value)) {
      variant = BINARY_FILE_VARIANT;
    } else {
      variant = String(value);
    }
    result.push([key, variant]);
    processor = data.next();
  }
  return result;
}

class NetworkProxyBase {
  constructor(socketStore) {
    _defineProperty(this, "socketStore", void 0);
    _defineProperty(this, "reqMap", Object.create(null));
    this.socketStore = socketStore;
  }
  getRequestMap() {
    return this.reqMap;
  }
  getRequest(id) {
    const req = this.reqMap[id];
    return req;
  }
  removeRequest(id) {
    delete this.reqMap[id];
  }
  createRequest(id) {
    if (!id) {
      psLog.warn('The "id" is required when init request object');
      return false;
    }
    if (this.reqMap[id]) {
      psLog.warn('The request object has been in store, disallow duplicate create');
      return false;
    }
    this.reqMap[id] = new RequestItem(id);
    return true;
  }
  setRequest(id, req) {
    if (!id || !req) return false;
    this.reqMap[id] = req;
    return true;
  }
  sendRequestItem(id, req) {
    var _NetworkProxyBase$dat;
    const processedByUser = (_NetworkProxyBase$dat = NetworkProxyBase.dataProcessor) === null || _NetworkProxyBase$dat === void 0 ? void 0 : _NetworkProxyBase$dat.call(NetworkProxyBase, req);
    if (processedByUser === false) return;
    try {
      if (!this.reqMap[id]) {
        this.reqMap[id] = req;
      }
      const message = makeMessage('network', {
        ...req
      }, false);
      this.socketStore.dispatchEvent('public-data', message);
      this.socketStore.broadcastMessage(message, req.readyState !== ReqReadyState.DONE);
      this.deferDeleteRequest(id);
    } catch (e) {
      psLog.error(e instanceof Error ? e.message : String(e));
    }
  }
  deferDeleteRequest(id) {
    const req = this.getRequest(id);
    if (req && req.readyState === ReqReadyState.DONE) {
      setTimeout(() => {
        delete this.reqMap[id];
      }, 3000);
    }
  }
}
_defineProperty(NetworkProxyBase, "dataProcessor", void 0);

/** Defaults for Atom's FIFO object-reference store. */
const ATOM_CONFIG = {
  MAX_STORE_SIZE: 5000
};
/** Timings used by SocketStoreBase's heartbeat and reconnect strategy. */
const SOCKET_CONFIG = {
  // Send a ping after this period without receiving a message or pong.
  HEARTBEAT_INTERVAL_MS: 5000,
  // Delay before the first reconnect attempt.
  INITIAL_RETRY_INTERVAL_MS: 2000,
  // Exponential-backoff factor applied after each reconnect attempt.
  RETRY_INTERVAL_MULTIPLIER: 1.5,
  // Maximum exponent applied to the initial reconnect delay.
  MAX_RETRY_ATTEMPTS: 4
};

/**
 * Atom 类用于处理复杂对象的序列化
 *
 * 远程调试时无法直接序列化循环引用、getter、原型链等复杂结构。
 * Atom 采用"引用存储"方案:复杂对象存入 store,返回包含 __atomId 的引用,
 * Web 端按需通过 atom-detail 消息获取详情。
 */
class Atom {
  constructor() {
    _defineProperty(this, "store", {});
    // Store instance IDs for getter invocation: { atomId: instanceId }
    // Prototype objects inherit parent's instanceId to bind correct `this` when calling getters
    _defineProperty(this, "instanceStore", {});
    // Defaults to ATOM_CONFIG.MAX_STORE_SIZE; once exceeded, evict oldest entries (FIFO).
    _defineProperty(this, "maxStoreSize", ATOM_CONFIG.MAX_STORE_SIZE);
    // Insertion-ordered key list for efficient eviction
    _defineProperty(this, "storeKeys", []);
  }
  getStore() {
    return this.store;
  }
  resetStore() {
    this.store = {};
    this.storeKeys = [];
  }
  getInstanceStore() {
    return this.instanceStore;
  }
  resetInstanceStore() {
    this.instanceStore = {};
  }
  /**
   * Transforms any JavaScript value into an atom representation for remote inspection.
   *
   * Strategy:
   * 1. Primitives (string/number/boolean/null/undefined) → inline value
   * 2. Complex objects with serializeData=true → JSON string
   * 3. Complex objects with serializeData=false → atom reference (stored for later expansion)
   *
   * @param data - The value to transform
   * @param serializeData - If true, serialize complex objects to JSON instead
   *                        of creating references
   * @returns An atom structure with id, type, and value/reference
   */
  transformToAtom(data) {
    let serializeData = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
    const {
      value,
      ok
    } = makePrimitiveValue(data);
    const id = getRandomId();
    if (ok) {
      return {
        id,
        type: getValueType(data),
        value
      };
    }
    if (serializeData) {
      try {
        return {
          id,
          type: 'json',
          value: JSON.stringify(data)
        };
      } catch (e) {
        // Unserializable data (circular refs, functions, etc.) returns null placeholder
        return {
          id,
          type: 'json',
          value: null
        };
      }
    }
    return this.add(data);
  }
  /**
   * Retrieves a stored object by ID and expands its properties one level deep.
   *
   * Returns an object with all own properties (including non-enumerable ones),
   * plus extra metadata like [[Prototype]], [[Entries]] for Set/Map, etc.
   *
   * @param id - The atom ID to retrieve
   * @returns Expanded property descriptors, or null if not found
   */
  get(id) {
    const cacheData = this.store[id];
    const instanceId = this.instanceStore[id];
    if (!cacheData) return null;
    const result = {};
    const descriptors = Object.getOwnPropertyDescriptors(cacheData);
    Object.keys(descriptors).forEach(key => {
      const desc = descriptors[key];
      if (hasOwnProperty(desc, 'value')) {
        desc.value = this.transformToAtom(desc.value);
      }
      result[key] = Atom.getAtomOverview({
        atomId: getRandomId(),
        instanceId,
        value: desc
      });
    });
    const extraProps = this.addExtraProperty(id);
    return {
      ...result,
      ...extraProps
    };
  }
  getOrigin(id) {
    const value = this.store[id];
    if (!value) return null;
    return value;
  }
  /**
   * Stores a complex object and returns an atom reference to it.
   *
   * @param data - The object to store
   * @param insId - Instance ID for prototype objects (required when isPrototype returns true)
   *                to ensure getters are called with the correct `this` context
   * @returns An atom overview with the generated ID and semantic type name
   */
  add(data) {
    let insId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
    const id = getRandomId();
    let instanceId = id;
    // Prototype objects must use the instance ID to bind getters correctly
    if (isPrototype(data)) {
      instanceId = insId;
    }
    this.store[id] = data;
    this.instanceStore[id] = instanceId;
    this.storeKeys.push(id);
    this.evictIfNeeded();
    const name = Atom.getSemanticValue(data);
    return Atom.getAtomOverview({
      atomId: id,
      value: name,
      instanceId
    });
  }
  // FIFO 淘汰策略:当存储条目超过 maxStoreSize 时,移除最早添加的条目
  evictIfNeeded() {
    while (this.storeKeys.length > this.maxStoreSize) {
      const oldestKey = this.storeKeys.shift();
      delete this.store[oldestKey];
      delete this.instanceStore[oldestKey];
    }
  }
  static getAtomOverview(_ref) {
    let {
      instanceId = '',
      atomId,
      value
    } = _ref;
    const id = getRandomId();
    return {
      id,
      type: 'atom',
      __atomId: atomId,
      instanceId,
      value
    };
  }
  static getSemanticValue(data) {
    var _data$constructor$nam, _data$constructor;
    if (isPlainObject(data)) {
      return 'Object {...}';
    }
    if (isArray(data)) {
      return "Array (".concat(data.length, ")");
    }
    if (isModuleNamespace(data)) {
      return 'Module {...}';
    }
    return (_data$constructor$nam = data === null || data === void 0 || (_data$constructor = data.constructor) === null || _data$constructor === void 0 ? void 0 : _data$constructor.name) !== null && _data$constructor$nam !== void 0 ? _data$constructor$nam : 'Object';
  }
  // 为特殊类型添加额外属性,使其在 Web 端能够正确展示
  // - 包装对象(String/Number/Boolean):添加 [[PrimitiveValue]] 显示原始值
  // - Set/Map:添加 [[Entries]] 显示内容
  // - 原型链:添加 [[Prototype]] 支持向上追溯
  addExtraProperty(id) {
    const data = this.store[id];
    const instanceId = this.instanceStore[id];
    const result = {};
    if (data instanceof String || data instanceof Number || data instanceof Boolean) {
      result['[[PrimitiveValue]]'] = this.transformToAtom(data.valueOf());
    }
    if (data instanceof Set) {
      const entries = {};
      let index = 0;
      for (const v of data) {
        entries[index++] = v;
      }
      entries.size = data.size;
      result['[[Entries]]'] = this.transformToAtom(entries);
    }
    if (data instanceof Map) {
      const entries = {};
      let index = 0;
      for (const [k, v] of data.entries()) {
        entries[index++] = {
          key: k,
          value: v
        };
      }
      entries.size = data.size;
      result['[[Entries]]'] = this.transformToAtom(entries);
    }
    /* c8 ignore next 3 */
    if (isArray(data) || isArrayLike(data)) {
      result.length = this.transformToAtom(data.length);
    }
    if (Object.getPrototypeOf(data) !== null) {
      result['[[Prototype]]'] = this.add(Object.getPrototypeOf(data), instanceId);
    } else {
      // eslint-disable-next-line no-underscore-dangle
      result.___proto___ = this.transformToAtom(null);
    }
    return result;
  }
}
const atom = new Atom();

/**
 * Client information manager for PageSpy SDK.
 *
 * Collects and formats client environment information (OS, browser, framework, etc.)
 * to be sent to the debugging server.
 *
 * Implements the `SpyClient.Client` contract from page-spy-types so plugins
 * only need to depend on the types package.
 */
class Client {
  /**
   * Creates a new Client instance.
   *
   * @param info - Parsed client information (OS type/version, browser type/version, framework, etc.)
   * @param rawInfo - Raw system information from platform-specific APIs (e.g., wx.getSystemInfoSync).
   *                  This will be sent by the system plugin for detailed diagnostics.
   */
  constructor() {
    let info = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
      // Platform-specific packages should override browserType and framework
      osType: 'unknown',
      osVersion: 'unknown',
      browserType: 'unknown',
      browserVersion: 'unknown',
      framework: 'unknown',
      isDevTools: false,
      sdk: 'unknown',
      sdkVersion: '0.0.0'
    };
    let rawInfo = arguments.length > 1 ? arguments[1] : undefined;
    _defineProperty(this, "info", void 0);
    _defineProperty(this, "rawInfo", void 0);
    /** List of registered plugin names */
    _defineProperty(this, "plugins", []);
    /** Cached user agent string */
    _defineProperty(this, "_name", '');
    this.info = info;
    this.rawInfo = rawInfo;
  }
  /**
   * Creates a client information message to be sent to the debugging server.
   *
   * @returns Client data item containing SDK info, plugin list, and user agent string
   */
  makeClientInfoMsg() {
    const msg = {
      sdk: this.info.sdk,
      isDevTools: this.info.isDevTools,
      ua: this.getName(),
      plugins: this.plugins
    };
    return msg;
  }
  /**
   * Gets the user agent string for this client.
   *
   * Constructs a UA string in the format: "osType/osVersion browserType/browserVersion"
   * or uses the provided ua field if available. The result is cached after first call.
   *
   * @returns User agent string identifying the client environment
   *
   * @example
   * ```typescript
   * // Returns: "iOS/15.0 Safari/15.0"
   * client.getName();
   * ```
   */
  getName() {
    if (!this._name) {
      const {
        ua,
        osType,
        osVersion,
        browserType,
        browserVersion
      } = this.info;
      this._name = ua || "".concat(osType, "/").concat(osVersion, " ").concat(browserType, "/").concat(browserVersion);
    }
    return this._name;
  }
}

var util;
(function (util) {
  util.assertEqual = val => val;
  function assertIs(_arg) {}
  util.assertIs = assertIs;
  function assertNever(_x) {
    throw new Error();
  }
  util.assertNever = assertNever;
  util.arrayToEnum = items => {
    const obj = {};
    for (const item of items) {
      obj[item] = item;
    }
    return obj;
  };
  util.getValidEnumValues = obj => {
    const validKeys = util.objectKeys(obj).filter(k => typeof obj[obj[k]] !== "number");
    const filtered = {};
    for (const k of validKeys) {
      filtered[k] = obj[k];
    }
    return util.objectValues(filtered);
  };
  util.objectValues = obj => {
    return util.objectKeys(obj).map(function (e) {
      return obj[e];
    });
  };
  util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban
  ? obj => Object.keys(obj) // eslint-disable-line ban/ban
  : object => {
    const keys = [];
    for (const key in object) {
      if (Object.prototype.hasOwnProperty.call(object, key)) {
        keys.push(key);
      }
    }
    return keys;
  };
  util.find = (arr, checker) => {
    for (const item of arr) {
      if (checker(item)) return item;
    }
    return undefined;
  };
  util.isInteger = typeof Number.isInteger === "function" ? val => Number.isInteger(val) // eslint-disable-line ban/ban
  : val => typeof val === "number" && isFinite(val) && Math.floor(val) === val;
  function joinValues(array) {
    let separator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : " | ";
    return array.map(val => typeof val === "string" ? "'".concat(val, "'") : val).join(separator);
  }
  util.joinValues = joinValues;
  util.jsonStringifyReplacer = (_, value) => {
    if (typeof value === "bigint") {
      return value.toString();
    }
    return value;
  };
})(util || (util = {}));
var objectUtil;
(function (objectUtil) {
  objectUtil.mergeShapes = (first, second) => {
    return {
      ...first,
      ...second // second overwrites first
    };
  };
})(objectUtil || (objectUtil = {}));
const ZodParsedType = util.arrayToEnum(["string", "nan", "number", "integer", "float", "boolean", "date", "bigint", "symbol", "function", "undefined", "null", "array", "object", "unknown", "promise", "void", "never", "map", "set"]);
const getParsedType = data => {
  const t = typeof data;
  switch (t) {
    case "undefined":
      return ZodParsedType.undefined;
    case "string":
      return ZodParsedType.string;
    case "number":
      return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
    case "boolean":
      return ZodParsedType.boolean;
    case "function":
      return ZodParsedType.function;
    case "bigint":
      return ZodParsedType.bigint;
    case "symbol":
      return ZodParsedType.symbol;
    case "object":
      if (Array.isArray(data)) {
        return ZodParsedType.array;
      }
      if (data === null) {
        return ZodParsedType.null;
      }
      if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
        return ZodParsedType.promise;
      }
      if (typeof Map !== "undefined" && data instanceof Map) {
        return ZodParsedType.map;
      }
      if (typeof Set !== "undefined" && data instanceof Set) {
        return ZodParsedType.set;
      }
      if (typeof Date !== "undefined" && data instanceof Date) {
        return ZodParsedType.date;
      }
      return ZodParsedType.object;
    default:
      return ZodParsedType.unknown;
  }
};
const ZodIssueCode = util.arrayToEnum(["invalid_type", "invalid_literal", "custom", "invalid_union", "invalid_union_discriminator", "invalid_enum_value", "unrecognized_keys", "invalid_arguments", "invalid_return_type", "invalid_date", "invalid_string", "too_small", "too_big", "invalid_intersection_types", "not_multiple_of", "not_finite"]);
const quotelessJson = obj => {
  const json = JSON.stringify(obj, null, 2);
  return json.replace(/"([^"]+)":/g, "$1:");
};
class ZodError extends Error {
  get errors() {
    return this.issues;
  }
  constructor(issues) {
    var _this;
    super();
    _this = this;
    this.issues = [];
    this.addIssue = sub => {
      this.issues = [...this.issues, sub];
    };
    this.addIssues = function () {
      let subs = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
      _this.issues = [..._this.issues, ...subs];
    };
    const actualProto = new.target.prototype;
    if (Object.setPrototypeOf) {
      // eslint-disable-next-line ban/ban
      Object.setPrototypeOf(this, actualProto);
    } else {
      this.__proto__ = actualProto;
    }
    this.name = "ZodError";
    this.issues = issues;
  }
  format(_mapper) {
    const mapper = _mapper || function (issue) {
      return issue.message;
    };
    const fieldErrors = {
      _errors: []
    };
    const processError = error => {
      for (const issue of error.issues) {
        if (issue.code === "invalid_union") {
          issue.unionErrors.map(processError);
        } else if (issue.code === "invalid_return_type") {
          processError(issue.returnTypeError);
        } else if (issue.code === "invalid_arguments") {
          processError(issue.argumentsError);
        } else if (issue.path.length === 0) {
          fieldErrors._errors.push(mapper(issue));
        } else {
          let curr = fieldErrors;
          let i = 0;
          while (i < issue.path.length) {
            const el = issue.path[i];
            const terminal = i === issue.path.length - 1;
            if (!terminal) {
              curr[el] = curr[el] || {
                _errors: []
              };
              // if (typeof el === "string") {
              //   curr[el] = curr[el] || { _errors: [] };
              // } else if (typeof el === "number") {
              //   const errorArray: any = [];
              //   errorArray._errors = [];
              //   curr[el] = curr[el] || errorArray;
              // }
            } else {
              curr[el] = curr[el] || {
                _errors: []
              };
              curr[el]._errors.push(mapper(issue));
            }
            curr = curr[el];
            i++;
          }
        }
      }
    };
    processError(this);
    return fieldErrors;
  }
  static assert(value) {
    if (!(value instanceof ZodError)) {
      throw new Error("Not a ZodError: ".concat(value));
    }
  }
  toString() {
    return this.message;
  }
  get message() {
    return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
  }
  get isEmpty() {
    return this.issues.length === 0;
  }
  flatten() {
    let mapper = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : issue => issue.message;
    const fieldErrors = {};
    const formErrors = [];
    for (const sub of this.issues) {
      if (sub.path.length > 0) {
        fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
        fieldErrors[sub.path[0]].push(mapper(sub));
      } else {
        formErrors.push(mapper(sub));
      }
    }
    return {
      formErrors,
      fieldErrors
    };
  }
  get formErrors() {
    return this.flatten();
  }
}
ZodError.create = issues => {
  const error = new ZodError(issues);
  return error;
};
const errorMap = (issue, _ctx) => {
  let message;
  switch (issue.code) {
    case ZodIssueCode.invalid_type:
      if (issue.received === ZodParsedType.undefined) {
        message = "Required";
      } else {
        message = "Expected ".concat(issue.expected, ", received ").concat(issue.received);
      }
      break;
    case ZodIssueCode.invalid_literal:
      message = "Invalid literal value, expected ".concat(JSON.stringify(issue.expected, util.jsonStringifyReplacer));
      break;
    case ZodIssueCode.unrecognized_keys:
      message = "Unrecognized key(s) in object: ".concat(util.joinValues(issue.keys, ", "));
      break;
    case ZodIssueCode.invalid_union:
      message = "Invalid input";
      break;
    case ZodIssueCode.invalid_union_discriminator:
      message = "Invalid discriminator value. Expected ".concat(util.joinValues(issue.options));
      break;
    case ZodIssueCode.invalid_enum_value:
      message = "Invalid enum value. Expected ".concat(util.joinValues(issue.options), ", received '").concat(issue.received, "'");
      break;
    case ZodIssueCode.invalid_arguments:
      message = "Invalid function arguments";
      break;
    case ZodIssueCode.invalid_return_type:
      message = "Invalid function return type";
      break;
    case ZodIssueCode.invalid_date:
      message = "Invalid date";
      break;
    case ZodIssueCode.invalid_string:
      if (typeof issue.validation === "object") {
        if ("includes" in issue.validation) {
          message = "Invalid input: must include \"".concat(issue.validation.includes, "\"");
          if (typeof issue.validation.position === "number") {
            message = "".concat(message, " at one or more positions greater than or equal to ").concat(issue.validation.position);
          }
        } else if ("startsWith" in issue.validation) {
          message = "Invalid input: must start with \"".concat(issue.validation.startsWith, "\"");
        } else if ("endsWith" in issue.validation) {
          message = "Invalid input: must end with \"".concat(issue.validation.endsWith, "\"");
        } else {
          util.assertNever(issue.validation);
        }
      } else if (issue.validation !== "regex") {
        message = "Invalid ".concat(issue.validation);
      } else {
        message = "Invalid";
      }
      break;
    case ZodIssueCode.too_small:
      if (issue.type === "array") message = "Array must contain ".concat(issue.exact ? "exactly" : issue.inclusive ? "at least" : "more than", " ").concat(issue.minimum, " element(s)");else if (issue.type === "string") message = "String must contain ".concat(issue.exact ? "exactly" : issue.inclusive ? "at least" : "over", " ").concat(issue.minimum, " character(s)");else if (issue.type === "number") message = "Number must be ".concat(issue.exact ? "exactly equal to " : issue.inclusive ? "greater than or equal to " : "greater than ").concat(issue.minimum);else if (issue.type === "date") message = "Date must be ".concat(issue.exact ? "exactly equal to " : issue.inclusive ? "greater than or equal to " : "greater than ").concat(new Date(Number(issue.minimum)));else message = "Invalid input";
      break;
    case ZodIssueCode.too_big:
      if (issue.type === "array") message = "Array must contain ".concat(issue.exact ? "exactly" : issue.inclusive ? "at most" : "less than", " ").concat(issue.maximum, " element(s)");else if (issue.type === "string") message = "String must contain ".concat(issue.exact ? "exactly" : issue.inclusive ? "at most" : "under", " ").concat(issue.maximum, " character(s)");else if (issue.type === "number") message = "Number must be ".concat(issue.exact ? "exactly" : issue.inclusive ? "less than or equal to" : "less than", " ").concat(issue.maximum);else if (issue.type === "bigint") message = "BigInt must be ".concat(issue.exact ? "exactly" : issue.inclusive ? "less than or equal to" : "less than", " ").concat(issue.maximum);else if (issue.type === "date") message = "Date must be ".concat(issue.exact ? "exactly" : issue.inclusive ? "smaller than or equal to" : "smaller than", " ").concat(new Date(Number(issue.maximum)));else message = "Invalid input";
      break;
    case ZodIssueCode.custom:
      message = "Invalid input";
      break;
    case ZodIssueCode.invalid_intersection_types:
      message = "Intersection results could not be merged";
      break;
    case ZodIssueCode.not_multiple_of:
      message = "Number must be a multiple of ".concat(issue.multipleOf);
      break;
    case ZodIssueCode.not_finite:
      message = "Number must be finite";
      break;
    default:
      message = _ctx.defaultError;
      util.assertNever(issue);
  }
  return {
    message
  };
};
let overrideErrorMap = errorMap;
function setErrorMap(map) {
  overrideErrorMap = map;
}
function getErrorMap() {
  return overrideErrorMap;
}
const makeIssue = params => {
  const {
    data,
    path,
    errorMaps,
    issueData
  } = params;
  const fullPath = [...path, ...(issueData.path || [])];
  const fullIssue = {
    ...issueData,
    path: fullPath
  };
  if (issueData.message !== undefined) {
    return {
      ...issueData,
      path: fullPath,
      message: issueData.message
    };
  }
  let errorMessage = "";
  const maps = errorMaps.filter(m => !!m).slice().reverse();
  for (const map of maps) {
    errorMessage = map(fullIssue, {
      data,
      defaultError: errorMessage
    }).message;
  }
  return {
    ...issueData,
    path: fullPath,
    message: errorMessage
  };
};
const EMPTY_PATH = [];
function addIssueToContext(ctx, issueData) {
  const overrideMap = getErrorMap();
  const issue = makeIssue({
    issueData: issueData,
    data: ctx.data,
    path: ctx.path,
    errorMaps: [ctx.common.contextualErrorMap,
    // contextual error map is first priority
    ctx.schemaErrorMap,
    // then schema-bound map if available
    overrideMap,
    // then global override map
    overrideMap === errorMap ? undefined : errorMap // then global default map
    ].filter(x => !!x)
  });
  ctx.common.issues.push(issue);
}
class ParseStatus {
  constructor() {
    this.value = "valid";
  }
  dirty() {
    if (this.value === "valid") this.value = "dirty";
  }
  abort() {
    if (this.value !== "aborted") this.value = "aborted";
  }
  static mergeArray(status, results) {
    const arrayValue = [];
    for (const s of results) {
      if (s.status === "aborted") return INVALID;
      if (s.status === "dirty") status.dirty();
      arrayValue.push(s.value);
    }
    return {
      status: status.value,
      value: arrayValue
    };
  }
  static async mergeObjectAsync(status, pairs) {
    const syncPairs = [];
    for (const pair of pairs) {
      const key = await pair.key;
      const value = await pair.value;
      syncPairs.push({
        key,
        value
      });
    }
    return ParseStatus.mergeObjectSync(status, syncPairs);
  }
  static mergeObjectSync(status, pairs) {
    const finalObject = {};
    for (const pair of pairs) {
      const {
        key,
        value
      } = pair;
      if (key.status === "aborted") return INVALID;
      if (value.status === "aborted") return INVALID;
      if (key.status === "dirty") status.dirty();
      if (value.status === "dirty") status.dirty();
      if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
        finalObject[key.value] = value.value;
      }
    }
    return {
      status: status.value,
      value: finalObject
    };
  }
}
const INVALID = Object.freeze({
  status: "aborted"
});
const DIRTY = value => ({
  status: "dirty",
  value
});
const OK = value => ({
  status: "valid",
  value
});
const isAborted = x => x.status === "aborted";
const isDirty = x => x.status === "dirty";
const isValid = x => x.status === "valid";
const isAsync = x => typeof Promise !== "undefined" && x instanceof Promise;

/******************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */

function __classPrivateFieldGet(receiver, state, kind, f) {
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
}
function __classPrivateFieldSet(receiver, state, value, kind, f) {
  if (kind === "m") throw new TypeError("Private method is not writable");
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
}
typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
  var e = new Error(message);
  return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};
var errorUtil;
(function (errorUtil) {
  errorUtil.errToObj = message => typeof message === "string" ? {
    message
  } : message || {};
  errorUtil.toString = message => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;
})(errorUtil || (errorUtil = {}));
var _ZodEnum_cache, _ZodNativeEnum_cache;
class ParseInputLazyPath {
  constructor(parent, value, path, key) {
    this._cachedPath = [];
    this.parent = parent;
    this.data = value;
    this._path = path;
    this._key = key;
  }
  get path() {
    if (!this._cachedPath.length) {
      if (this._key instanceof Array) {
        this._cachedPath.push(...this._path, ...this._key);
      } else {
        this._cachedPath.push(...this._path, this._key);
      }
    }
    return this._cachedPath;
  }
}
const handleResult = (ctx, result) => {
  if (isValid(result)) {
    return {
      success: true,
      data: result.value
    };
  } else {
    if (!ctx.common.issues.length) {
      throw new Error("Validation failed but no issues detected.");
    }
    return {
      success: false,
      get error() {
        if (this._error) return this._error;
        const error = new ZodError(ctx.common.issues);
        this._error = error;
        return this._error;
      }
    };
  }
};
function processCreateParams(params) {
  if (!params) return {};
  const {
    errorMap,
    invalid_type_error,
    required_error,
    description
  } = params;
  if (errorMap && (invalid_type_error || required_error)) {
    throw new Error("Can't use \"invalid_type_error\" or \"required_error\" in conjunction with custom error map.");
  }
  if (errorMap) return {
    errorMap: errorMap,
    description
  };
  const customMap = (iss, ctx) => {
    var _a, _b;
    const {
      message
    } = params;
    if (iss.code === "invalid_enum_value") {
      return {
        message: message !== null && message !== void 0 ? message : ctx.defaultError
      };
    }
    if (typeof ctx.data === "undefined") {
      return {
        message: (_a = message !== null && message !== void 0 ? message : required_error) !== null && _a !== void 0 ? _a : ctx.defaultError
      };
    }
    if (iss.code !== "invalid_type") return {
      message: ctx.defaultError
    };
    return {
      message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError
    };
  };
  return {
    errorMap: customMap,
    description
  };
}
class ZodType {
  get description() {
    return this._def.description;
  }
  _getType(input) {
    return getParsedType(input.data);
  }
  _getOrReturnCtx(input, ctx) {
    return ctx || {
      common: input.parent.common,
      data: input.data,
      parsedType: getParsedType(input.data),
      schemaErrorMap: this._def.errorMap,
      path: input.path,
      parent: input.parent
    };
  }
  _processInputParams(input) {
    return {
      status: new ParseStatus(),
      ctx: {
        common: input.parent.common,
        data: input.data,
        parsedType: getParsedType(input.data),
        schemaErrorMap: this._def.errorMap,
        path: input.path,
        parent: input.parent
      }
    };
  }
  _parseSync(input) {
    const result = this._parse(input);
    if (isAsync(result)) {
      throw new Error("Synchronous parse encountered promise.");
    }
    return result;
  }
  _parseAsync(input) {
    const result = this._parse(input);
    return Promise.resolve(result);
  }
  parse(data, params) {
    const result = this.safeParse(data, params);
    if (result.success) return result.data;
    throw result.error;
  }
  safeParse(data, params) {
    var _a;
    const ctx = {
      common: {
        issues: [],
        async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false,
        contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap
      },
      path: (params === null || params === void 0 ? void 0 : params.path) || [],
      schemaErrorMap: this._def.errorMap,
      parent: null,
      data,
      parsedType: getParsedType(data)
    };
    const result = this._parseSync({
      data,
      path: ctx.path,
      parent: ctx
    });
    return handleResult(ctx, result);
  }
  "~validate"(data) {
    var _a, _b;
    const ctx = {
      common: {
        issues: [],
        async: !!this["~standard"].async
      },
      path: [],
      schemaErrorMap: this._def.errorMap,
      parent: null,
      data,
      parsedType: getParsedType(data)
    };
    if (!this["~standard"].async) {
      try {
        const result = this._parseSync({
          data,
          path: [],
          parent: ctx
        });
        return isValid(result) ? {
          value: result.value
        } : {
          issues: ctx.common.issues
        };
      } catch (err) {
        if ((_b = (_a = err === null || err === void 0 ? void 0 : err.message) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === null || _b === void 0 ? void 0 : _b.includes("encountered")) {
          this["~standard"].async = true;
        }
        ctx.common = {
          issues: [],
          async: true
        };
      }
    }
    return this._parseAsync({
      data,
      path: [],
      parent: ctx
    }).then(result => isValid(result) ? {
      value: result.value
    } : {
      issues: ctx.common.issues
    });
  }
  async parseAsync(data, params) {
    const result = await this.safeParseAsync(data, params);
    if (result.success) return result.data;
    throw result.error;
  }
  async safeParseAsync(data, params) {
    const ctx = {
      common: {
        issues: [],
        contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,
        async: true
      },
      path: (params === null || params === void 0 ? void 0 : params.path) || [],
      schemaErrorMap: this._def.errorMap,
      parent: null,
      data,
      parsedType: getParsedType(data)
    };
    const maybeAsyncResult = this._parse({
      data,
      path: ctx.path,
      parent: ctx
    });
    const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
    return handleResult(ctx, result);
  }
  refine(check, message) {
    const getIssueProperties = val => {
      if (typeof message === "string" || typeof message === "undefined") {
        return {
          message
        };
      } else if (typeof message === "function") {
        return message(val);
      } else {
        return message;
      }
    };
    return this._refinement((val, ctx) => {
      const result = check(val);
      const setError = () => ctx.addIssue({
        code: ZodIssueCode.custom,
        ...getIssueProperties(val)
      });
      if (typeof Promise !== "undefined" && result instanceof Promise) {
        return result.then(data => {
          if (!data) {
            setError();
            return false;
          } else {
            return true;
          }
        });
      }
      if (!result) {
        setError();
        return false;
      } else {
        return true;
      }
    });
  }
  refinement(check, refinementData) {
    return this._refinement((val, ctx) => {
      if (!check(val)) {
        ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
        return false;
      } else {
        return true;
      }
    });
  }
  _refinement(refinement) {
    return new ZodEffects({
      schema: this,
      typeName: ZodFirstPartyTypeKind.ZodEffects,
      effect: {
        type: "refinement",
        refinement
      }
    });
  }
  superRefine(refinement) {
    return this._refinement(refinement);
  }
  constructor(def) {
    /** Alias of safeParseAsync */
    this.spa = this.safeParseAsync;
    this._def = def;
    this.parse = this.parse.bind(this);
    this.safeParse = this.safeParse.bind(this);
    this.parseAsync = this.parseAsync.bind(this);
    this.safeParseAsync = this.safeParseAsync.bind(this);
    this.spa = this.spa.bind(this);
    this.refine = this.refine.bind(this);
    this.refinement = this.refinement.bind(this);
    this.superRefine = this.superRefine.bind(this);
    this.optional = this.optional.bind(this);
    this.nullable = this.nullable.bind(this);
    this.nullish = this.nullish.bind(this);
    this.array = this.array.bind(this);
    this.promise = this.promise.bind(this);
    this.or = this.or.bind(this);
    this.and = this.and.bind(this);
    this.transform = this.transform.bind(this);
    this.brand = this.brand.bind(this);
    this.default = this.default.bind(this);
    this.catch = this.catch.bind(this);
    this.describe = this.describe.bind(this);
    this.pipe = this.pipe.bind(this);
    this.readonly = this.readonly.bind(this);
    this.isNullable = this.isNullable.bind(this);
    this.isOptional = this.isOptional.bind(this);
    this["~standard"] = {
      version: 1,
      vendor: "zod",
      validate: data => this["~validate"](data)
    };
  }
  optional() {
    return ZodOptional.create(this, this._def);
  }
  nullable() {
    return ZodNullable.create(this, this._def);
  }
  nullish() {
    return this.nullable().optional();
  }
  array() {
    return ZodArray.create(this);
  }
  promise() {
    return ZodPromise.create(this, this._def);
  }
  or(option) {
    return ZodUnion.create([this, option], this._def);
  }
  and(incoming) {
    return ZodIntersection.create(this, incoming, this._def);
  }
  transform(transform) {
    return new ZodEffects({
      ...processCreateParams(this._def),
      schema: this,
      typeName: ZodFirstPartyTypeKind.ZodEffects,
      effect: {
        type: "transform",
        transform
      }
    });
  }
  default(def) {
    const defaultValueFunc = typeof def === "function" ? def : () => def;
    return new ZodDefault({
      ...processCreateParams(this._def),
      innerType: this,
      defaultValue: defaultValueFunc,
      typeName: ZodFirstPartyTypeKind.ZodDefault
    });
  }
  brand() {
    return new ZodBranded({
      typeName: ZodFirstPartyTypeKind.ZodBranded,
      type: this,
      ...processCreateParams(this._def)
    });
  }
  catch(def) {
    const catchValueFunc = typeof def === "function" ? def : () => def;
    return new ZodCatch({
      ...processCreateParams(this._def),
      innerType: this,
      catchValue: catchValueFunc,
      typeName: ZodFirstPartyTypeKind.ZodCatch
    });
  }
  describe(description) {
    const This = this.constructor;
    return new This({
      ...this._def,
      description
    });
  }
  pipe(target) {
    return ZodPipeline.create(this, target);
  }
  readonly() {
    return ZodReadonly.create(this);
  }
  isOptional() {
    return this.safeParse(undefined).success;
  }
  isNullable() {
    return this.safeParse(null).success;
  }
}
const cuidRegex = /^c[^\s-]{8,}$/i;
const cuid2Regex = /^[0-9a-z]+$/;
const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
// const uuidRegex =
//   /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;
const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
const nanoidRegex = /^[a-z0-9_-]{21}$/i;
const jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
const durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
// from https://stackoverflow.com/a/46181/1550155
// old version: too slow, didn't support unicode
// const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i;
//old email regex
// const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i;
// eslint-disable-next-line
// const emailRegex =
//   /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/;
// const emailRegex =
//   /^[a-zA-Z0-9\.\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
// const emailRegex =
//   /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i;
const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
// const emailRegex =
//   /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i;
// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression
const _emojiRegex = "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";
let emojiRegex;
// faster, simpler, safer
const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
const ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
// const ipv6Regex =
// /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;
const ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
const ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript
const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
// https://base64.guru/standards/base64url
const base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
// simple
// const dateRegexSource = `\\d{4}-\\d{2}-\\d{2}`;
// no leap year validation
// const dateRegexSource = `\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\d|2\\d))`;
// with leap year validation
const dateRegexSource = "((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))";
const dateRegex = new RegExp("^".concat(dateRegexSource, "$"));
function timeRegexSource(args) {
  // let regex = `\\d{2}:\\d{2}:\\d{2}`;
  let regex = "([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";
  if (args.precision) {
    regex = "".concat(regex, "\\.\\d{").concat(args.precision, "}");
  } else if (args.precision == null) {
    regex = "".concat(regex, "(\\.\\d+)?");
  }
  return regex;
}
function timeRegex(args) {
  return new RegExp("^".concat(timeRegexSource(args), "$"));
}
// Adapted from https://stackoverflow.com/a/3143231
function datetimeRegex(args) {
  let regex = "".concat(dateRegexSource, "T").concat(timeRegexSource(args));
  const opts = [];
  opts.push(args.local ? "Z?" : "Z");
  if (args.offset) opts.push("([+-]\\d{2}:?\\d{2})");
  regex = "".concat(regex, "(").concat(opts.join("|"), ")");
  return new RegExp("^".concat(regex, "$"));
}
function isValidIP(ip, version) {
  if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
    return true;
  }
  if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
    return true;
  }
  return false;
}
function isValidJWT(jwt, alg) {
  if (!jwtRegex.test(jwt)) return false;
  try {
    const [header] = jwt.split(".");
    // Convert base64url to base64
    const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
    const decoded = JSON.parse(atob(base64));
    if (typeof decoded !== "object" || decoded === null) return false;
    if (!decoded.typ || !decoded.alg) return false;
    if (alg && decoded.alg !== alg) return false;
    return true;
  } catch (_a) {
    return false;
  }
}
function isValidCidr(ip, version) {
  if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
    return true;
  }
  if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
    return true;
  }
  return false;
}
class ZodString extends ZodType {
  _parse(input) {
    if (this._def.coerce) {
      input.data = String(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.string) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.string,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const status = new ParseStatus();
    let ctx = undefined;
    for (const check of this._def.checks) {
      if (check.kind === "min") {
        if (input.data.length < check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            minimum: check.value,
            type: "string",
            inclusive: true,
            exact: false,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "max") {
        if (input.data.length > check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            maximum: check.value,
            type: "string",
            inclusive: true,
            exact: false,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "length") {
        const tooBig = input.data.length > check.value;
        const tooSmall = input.data.length < check.value;
        if (tooBig || tooSmall) {
          ctx = this._getOrReturnCtx(input, ctx);
          if (tooBig) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_big,
              maximum: check.value,
              type: "string",
              inclusive: true,
              exact: true,
              message: check.message
            });
          } else if (tooSmall) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_small,
              minimum: check.value,
              type: "string",
              inclusive: true,
              exact: true,
              message: check.message
            });
          }
          status.dirty();
        }
      } else if (check.kind === "email") {
        if (!emailRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "email",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "emoji") {
        if (!emojiRegex) {
          emojiRegex = new RegExp(_emojiRegex, "u");
        }
        if (!emojiRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "emoji",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "uuid") {
        if (!uuidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "uuid",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "nanoid") {
        if (!nanoidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "nanoid",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "cuid") {
        if (!cuidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "cuid",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "cuid2") {
        if (!cuid2Regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "cuid2",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "ulid") {
        if (!ulidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "ulid",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "url") {
        try {
          new URL(input.data);
        } catch (_a) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "url",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "regex") {
        check.regex.lastIndex = 0;
        const testResult = check.regex.test(input.data);
        if (!testResult) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "regex",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "trim") {
        input.data = input.data.trim();
      } else if (check.kind === "includes") {
        if (!input.data.includes(check.value, check.position)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: {
              includes: check.value,
              position: check.position
            },
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "toLowerCase") {
        input.data = input.data.toLowerCase();
      } else if (check.kind === "toUpperCase") {
        input.data = input.data.toUpperCase();
      } else if (check.kind === "startsWith") {
        if (!input.data.startsWith(check.value)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: {
              startsWith: check.value
            },
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "endsWith") {
        if (!input.data.endsWith(check.value)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: {
              endsWith: check.value
            },
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "datetime") {
        const regex = datetimeRegex(check);
        if (!regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: "datetime",
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "date") {
        const regex = dateRegex;
        if (!regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: "date",
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "time") {
        const regex = timeRegex(check);
        if (!regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: "time",
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "duration") {
        if (!durationRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "duration",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "ip") {
        if (!isValidIP(input.data, check.version)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "ip",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "jwt") {
        if (!isValidJWT(input.data, check.alg)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "jwt",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "cidr") {
        if (!isValidCidr(input.data, check.version)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "cidr",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "base64") {
        if (!base64Regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "base64",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "base64url") {
        if (!base64urlRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "base64url",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else {
        util.assertNever(check);
      }
    }
    return {
      status: status.value,
      value: input.data
    };
  }
  _regex(regex, validation, message) {
    return this.refinement(data => regex.test(data), {
      validation,
      code: ZodIssueCode.invalid_string,
      ...errorUtil.errToObj(message)
    });
  }
  _addCheck(check) {
    return new ZodString({
      ...this._def,
      checks: [...this._def.checks, check]
    });
  }
  email(message) {
    return this._addCheck({
      kind: "email",
      ...errorUtil.errToObj(message)
    });
  }
  url(message) {
    return this._addCheck({
      kind: "url",
      ...errorUtil.errToObj(message)
    });
  }
  emoji(message) {
    return this._addCheck({
      kind: "emoji",
      ...errorUtil.errToObj(message)
    });
  }
  uuid(message) {
    return this._addCheck({
      kind: "uuid",
      ...errorUtil.errToObj(message)
    });
  }
  nanoid(message) {
    return this._addCheck({
      kind: "nanoid",
      ...errorUtil.errToObj(message)
    });
  }
  cuid(message) {
    return this._addCheck({
      kind: "cuid",
      ...errorUtil.errToObj(message)
    });
  }
  cuid2(message) {
    return this._addCheck({
      kind: "cuid2",
      ...errorUtil.errToObj(message)
    });
  }
  ulid(message) {
    return this._addCheck({
      kind: "ulid",
      ...errorUtil.errToObj(message)
    });
  }
  base64(message) {
    return this._addCheck({
      kind: "base64",
      ...errorUtil.errToObj(message)
    });
  }
  base64url(message) {
    // base64url encoding is a modification of base64 that can safely be used in URLs and filenames
    return this._addCheck({
      kind: "base64url",
      ...errorUtil.errToObj(message)
    });
  }
  jwt(options) {
    return this._addCheck({
      kind: "jwt",
      ...errorUtil.errToObj(options)
    });
  }
  ip(options) {
    return this._addCheck({
      kind: "ip",
      ...errorUtil.errToObj(options)
    });
  }
  cidr(options) {
    return this._addCheck({
      kind: "cidr",
      ...errorUtil.errToObj(options)
    });
  }
  datetime(options) {
    var _a, _b;
    if (typeof options === "string") {
      return this._addCheck({
        kind: "datetime",
        precision: null,
        offset: false,
        local: false,
        message: options
      });
    }
    return this._addCheck({
      kind: "datetime",
      precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
      offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false,
      local: (_b = options === null || options === void 0 ? void 0 : options.local) !== null && _b !== void 0 ? _b : false,
      ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message)
    });
  }
  date(message) {
    return this._addCheck({
      kind: "date",
      message
    });
  }
  time(options) {
    if (typeof options === "string") {
      return this._addCheck({
        kind: "time",
        precision: null,
        message: options
      });
    }
    return this._addCheck({
      kind: "time",
      precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
      ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message)
    });
  }
  duration(message) {
    return this._addCheck({
      kind: "duration",
      ...errorUtil.errToObj(message)
    });
  }
  regex(regex, message) {
    return this._addCheck({
      kind: "regex",
      regex: regex,
      ...errorUtil.errToObj(message)
    });
  }
  includes(value, options) {
    return this._addCheck({
      kind: "includes",
      value: value,
      position: options === null || options === void 0 ? void 0 : options.position,
      ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message)
    });
  }
  startsWith(value, message) {
    return this._addCheck({
      kind: "startsWith",
      value: value,
      ...errorUtil.errToObj(message)
    });
  }
  endsWith(value, message) {
    return this._addCheck({
      kind: "endsWith",
      value: value,
      ...errorUtil.errToObj(message)
    });
  }
  min(minLength, message) {
    return this._addCheck({
      kind: "min",
      value: minLength,
      ...errorUtil.errToObj(message)
    });
  }
  max(maxLength, message) {
    return this._addCheck({
      kind: "max",
      value: maxLength,
      ...errorUtil.errToObj(message)
    });
  }
  length(len, message) {
    return this._addCheck({
      kind: "length",
      value: len,
      ...errorUtil.errToObj(message)
    });
  }
  /**
   * Equivalent to `.min(1)`
   */
  nonempty(message) {
    return this.min(1, errorUtil.errToObj(message));
  }
  trim() {
    return new ZodString({
      ...this._def,
      checks: [...this._def.checks, {
        kind: "trim"
      }]
    });
  }
  toLowerCase() {
    return new ZodString({
      ...this._def,
      checks: [...this._def.checks, {
        kind: "toLowerCase"
      }]
    });
  }
  toUpperCase() {
    return new ZodString({
      ...this._def,
      checks: [...this._def.checks, {
        kind: "toUpperCase"
      }]
    });
  }
  get isDatetime() {
    return !!this._def.checks.find(ch => ch.kind === "datetime");
  }
  get isDate() {
    return !!this._def.checks.find(ch => ch.kind === "date");
  }
  get isTime() {
    return !!this._def.checks.find(ch => ch.kind === "time");
  }
  get isDuration() {
    return !!this._def.checks.find(ch => ch.kind === "duration");
  }
  get isEmail() {
    return !!this._def.checks.find(ch => ch.kind === "email");
  }
  get isURL() {
    return !!this._def.checks.find(ch => ch.kind === "url");
  }
  get isEmoji() {
    return !!this._def.checks.find(ch => ch.kind === "emoji");
  }
  get isUUID() {
    return !!this._def.checks.find(ch => ch.kind === "uuid");
  }
  get isNANOID() {
    return !!this._def.checks.find(ch => ch.kind === "nanoid");
  }
  get isCUID() {
    return !!this._def.checks.find(ch => ch.kind === "cuid");
  }
  get isCUID2() {
    return !!this._def.checks.find(ch => ch.kind === "cuid2");
  }
  get isULID() {
    return !!this._def.checks.find(ch => ch.kind === "ulid");
  }
  get isIP() {
    return !!this._def.checks.find(ch => ch.kind === "ip");
  }
  get isCIDR() {
    return !!this._def.checks.find(ch => ch.kind === "cidr");
  }
  get isBase64() {
    return !!this._def.checks.find(ch => ch.kind === "base64");
  }
  get isBase64url() {
    // base64url encoding is a modification of base64 that can safely be used in URLs and filenames
    return !!this._def.checks.find(ch => ch.kind === "base64url");
  }
  get minLength() {
    let min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min === null || ch.value > min) min = ch.value;
      }
    }
    return min;
  }
  get maxLength() {
    let max = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max === null || ch.value < max) max = ch.value;
      }
    }
    return max;
  }
}
ZodString.create = params => {
  var _a;
  return new ZodString({
    checks: [],
    typeName: ZodFirstPartyTypeKind.ZodString,
    coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,
    ...processCreateParams(params)
  });
};
// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034
function floatSafeRemainder(val, step) {
  const valDecCount = (val.toString().split(".")[1] || "").length;
  const stepDecCount = (step.toString().split(".")[1] || "").length;
  const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
  const valInt = parseInt(val.toFixed(decCount).replace(".", ""));
  const stepInt = parseInt(step.toFixed(decCount).replace(".", ""));
  return valInt % stepInt / Math.pow(10, decCount);
}
class ZodNumber extends ZodType {
  constructor() {
    super(...arguments);
    this.min = this.gte;
    this.max = this.lte;
    this.step = this.multipleOf;
  }
  _parse(input) {
    if (this._def.coerce) {
      input.data = Number(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.number) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.number,
        received: ctx.parsedType
      });
      return INVALID;
    }
    let ctx = undefined;
    const status = new ParseStatus();
    for (const check of this._def.checks) {
      if (check.kind === "int") {
        if (!util.isInteger(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: "integer",
            received: "float",
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "min") {
        const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
        if (tooSmall) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            minimum: check.value,
            type: "number",
            inclusive: check.inclusive,
            exact: false,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "max") {
        const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
        if (tooBig) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            maximum: check.value,
            type: "number",
            inclusive: check.inclusive,
            exact: false,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "multipleOf") {
        if (floatSafeRemainder(input.data, check.value) !== 0) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.not_multiple_of,
            multipleOf: check.value,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "finite") {
        if (!Number.isFinite(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.not_finite,
            message: check.message
          });
          status.dirty();
        }
      } else {
        util.assertNever(check);
      }
    }
    return {
      status: status.value,
      value: input.data
    };
  }
  gte(value, message) {
    return this.setLimit("min", value, true, errorUtil.toString(message));
  }
  gt(value, message) {
    return this.setLimit("min", value, false, errorUtil.toString(message));
  }
  lte(value, message) {
    return this.setLimit("max", value, true, errorUtil.toString(message));
  }
  lt(value, message) {
    return this.setLimit("max", value, false, errorUtil.toString(message));
  }
  setLimit(kind, value, inclusive, message) {
    return new ZodNumber({
      ...this._def,
      checks: [...this._def.checks, {
        kind,
        value,
        inclusive,
        message: errorUtil.toString(message)
      }]
    });
  }
  _addCheck(check) {
    return new ZodNumber({
      ...this._def,
      checks: [...this._def.checks, check]
    });
  }
  int(message) {
    return this._addCheck({
      kind: "int",
      message: errorUtil.toString(message)
    });
  }
  positive(message) {
    return this._addCheck({
      kind: "min",
      value: 0,
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  negative(message) {
    return this._addCheck({
      kind: "max",
      value: 0,
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  nonpositive(message) {
    return this._addCheck({
      kind: "max",
      value: 0,
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  nonnegative(message) {
    return this._addCheck({
      kind: "min",
      value: 0,
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  multipleOf(value, message) {
    return this._addCheck({
      kind: "multipleOf",
      value: value,
      message: errorUtil.toString(message)
    });
  }
  finite(message) {
    return this._addCheck({
      kind: "finite",
      message: errorUtil.toString(message)
    });
  }
  safe(message) {
    return this._addCheck({
      kind: "min",
      inclusive: true,
      value: Number.MIN_SAFE_INTEGER,
      message: errorUtil.toString(message)
    })._addCheck({
      kind: "max",
      inclusive: true,
      value: Number.MAX_SAFE_INTEGER,
      message: errorUtil.toString(message)
    });
  }
  get minValue() {
    let min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min === null || ch.value > min) min = ch.value;
      }
    }
    return min;
  }
  get maxValue() {
    let max = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max === null || ch.value < max) max = ch.value;
      }
    }
    return max;
  }
  get isInt() {
    return !!this._def.checks.find(ch => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
  }
  get isFinite() {
    let max = null,
      min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
        return true;
      } else if (ch.kind === "min") {
        if (min === null || ch.value > min) min = ch.value;
      } else if (ch.kind === "max") {
        if (max === null || ch.value < max) max = ch.value;
      }
    }
    return Number.isFinite(min) && Number.isFinite(max);
  }
}
ZodNumber.create = params => {
  return new ZodNumber({
    checks: [],
    typeName: ZodFirstPartyTypeKind.ZodNumber,
    coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
    ...processCreateParams(params)
  });
};
class ZodBigInt extends ZodType {
  constructor() {
    super(...arguments);
    this.min = this.gte;
    this.max = this.lte;
  }
  _parse(input) {
    if (this._def.coerce) {
      try {
        input.data = BigInt(input.data);
      } catch (_a) {
        return this._getInvalidInput(input);
      }
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.bigint) {
      return this._getInvalidInput(input);
    }
    let ctx = undefined;
    const status = new ParseStatus();
    for (const check of this._def.checks) {
      if (check.kind === "min") {
        const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
        if (tooSmall) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            type: "bigint",
            minimum: check.value,
            inclusive: check.inclusive,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "max") {
        const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
        if (tooBig) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            type: "bigint",
            maximum: check.value,
            inclusive: check.inclusive,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "multipleOf") {
        if (input.data % check.value !== BigInt(0)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.not_multiple_of,
            multipleOf: check.value,
            message: check.message
          });
          status.dirty();
        }
      } else {
        util.assertNever(check);
      }
    }
    return {
      status: status.value,
      value: input.data
    };
  }
  _getInvalidInput(input) {
    const ctx = this._getOrReturnCtx(input);
    addIssueToContext(ctx, {
      code: ZodIssueCode.invalid_type,
      expected: ZodParsedType.bigint,
      received: ctx.parsedType
    });
    return INVALID;
  }
  gte(value, message) {
    return this.setLimit("min", value, true, errorUtil.toString(message));
  }
  gt(value, message) {
    return this.setLimit("min", value, false, errorUtil.toString(message));
  }
  lte(value, message) {
    return this.setLimit("max", value, true, errorUtil.toString(message));
  }
  lt(value, message) {
    return this.setLimit("max", value, false, errorUtil.toString(message));
  }
  setLimit(kind, value, inclusive, message) {
    return new ZodBigInt({
      ...this._def,
      checks: [...this._def.checks, {
        kind,
        value,
        inclusive,
        message: errorUtil.toString(message)
      }]
    });
  }
  _addCheck(check) {
    return new ZodBigInt({
      ...this._def,
      checks: [...this._def.checks, check]
    });
  }
  positive(message) {
    return this._addCheck({
      kind: "min",
      value: BigInt(0),
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  negative(message) {
    return this._addCheck({
      kind: "max",
      value: BigInt(0),
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  nonpositive(message) {
    return this._addCheck({
      kind: "max",
      value: BigInt(0),
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  nonnegative(message) {
    return this._addCheck({
      kind: "min",
      value: BigInt(0),
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  multipleOf(value, message) {
    return this._addCheck({
      kind: "multipleOf",
      value,
      message: errorUtil.toString(message)
    });
  }
  get minValue() {
    let min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min === null || ch.value > min) min = ch.value;
      }
    }
    return min;
  }
  get maxValue() {
    let max = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max === null || ch.value < max) max = ch.value;
      }
    }
    return max;
  }
}
ZodBigInt.create = params => {
  var _a;
  return new ZodBigInt({
    checks: [],
    typeName: ZodFirstPartyTypeKind.ZodBigInt,
    coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,
    ...processCreateParams(params)
  });
};
class ZodBoolean extends ZodType {
  _parse(input) {
    if (this._def.coerce) {
      input.data = Boolean(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.boolean) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.boolean,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
}
ZodBoolean.create = params => {
  return new ZodBoolean({
    typeName: ZodFirstPartyTypeKind.ZodBoolean,
    coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
    ...processCreateParams(params)
  });
};
class ZodDate extends ZodType {
  _parse(input) {
    if (this._def.coerce) {
      input.data = new Date(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.date) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.date,
        received: ctx.parsedType
      });
      return INVALID;
    }
    if (isNaN(input.data.getTime())) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_date
      });
      return INVALID;
    }
    const status = new ParseStatus();
    let ctx = undefined;
    for (const check of this._def.checks) {
      if (check.kind === "min") {
        if (input.data.getTime() < check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            message: check.message,
            inclusive: true,
            exact: false,
            minimum: check.value,
            type: "date"
          });
          status.dirty();
        }
      } else if (check.kind === "max") {
        if (input.data.getTime() > check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            message: check.message,
            inclusive: true,
            exact: false,
            maximum: check.value,
            type: "date"
          });
          status.dirty();
        }
      } else {
        util.assertNever(check);
      }
    }
    return {
      status: status.value,
      value: new Date(input.data.getTime())
    };
  }
  _addCheck(check) {
    return new ZodDate({
      ...this._def,
      checks: [...this._def.checks, check]
    });
  }
  min(minDate, message) {
    return this._addCheck({
      kind: "min",
      value: minDate.getTime(),
      message: errorUtil.toString(message)
    });
  }
  max(maxDate, message) {
    return this._addCheck({
      kind: "max",
      value: maxDate.getTime(),
      message: errorUtil.toString(message)
    });
  }
  get minDate() {
    let min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min === null || ch.value > min) min = ch.value;
      }
    }
    return min != null ? new Date(min) : null;
  }
  get maxDate() {
    let max = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max === null || ch.value < max) max = ch.value;
      }
    }
    return max != null ? new Date(max) : null;
  }
}
ZodDate.create = params => {
  return new ZodDate({
    checks: [],
    coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
    typeName: ZodFirstPartyTypeKind.ZodDate,
    ...processCreateParams(params)
  });
};
class ZodSymbol extends ZodType {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.symbol) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.symbol,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
}
ZodSymbol.create = params => {
  return new ZodSymbol({
    typeName: ZodFirstPartyTypeKind.ZodSymbol,
    ...processCreateParams(params)
  });
};
class ZodUndefined extends ZodType {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.undefined) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.undefined,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
}
ZodUndefined.create = params => {
  return new ZodUndefined({
    typeName: ZodFirstPartyTypeKind.ZodUndefined,
    ...processCreateParams(params)
  });
};
class ZodNull extends ZodType {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.null) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.null,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
}
ZodNull.create = params => {
  return new ZodNull({
    typeName: ZodFirstPartyTypeKind.ZodNull,
    ...processCreateParams(params)
  });
};
class ZodAny extends ZodType {
  constructor() {
    super(...arguments);
    // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.
    this._any = true;
  }
  _parse(input) {
    return OK(input.data);
  }
}
ZodAny.create = params => {
  return new ZodAny({
    typeName: ZodFirstPartyTypeKind.ZodAny,
    ...processCreateParams(params)
  });
};
class ZodUnknown extends ZodType {
  constructor() {
    super(...arguments);
    // required
    this._unknown = true;
  }
  _parse(input) {
    return OK(input.data);
  }
}
ZodUnknown.create = params => {
  return new ZodUnknown({
    typeName: ZodFirstPartyTypeKind.ZodUnknown,
    ...processCreateParams(params)
  });
};
class ZodNever extends ZodType {
  _parse(input) {
    const ctx = this._getOrReturnCtx(input);
    addIssueToContext(ctx, {
      code: ZodIssueCode.invalid_type,
      expected: ZodParsedType.never,
      received: ctx.parsedType
    });
    return INVALID;
  }
}
ZodNever.create = params => {
  return new ZodNever({
    typeName: ZodFirstPartyTypeKind.ZodNever,
    ...processCreateParams(params)
  });
};
class ZodVoid extends ZodType {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.undefined) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.void,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input.data);
  }
}
ZodVoid.create = params => {
  return new ZodVoid({
    typeName: ZodFirstPartyTypeKind.ZodVoid,
    ...processCreateParams(params)
  });
};
class ZodArray extends ZodType {
  _parse(input) {
    const {
      ctx,
      status
    } = this._processInputParams(input);
    const def = this._def;
    if (ctx.parsedType !== ZodParsedType.array) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.array,
        received: ctx.parsedType
      });
      return INVALID;
    }
    if (def.exactLength !== null) {
      const tooBig = ctx.data.length > def.exactLength.value;
      const tooSmall = ctx.data.length < def.exactLength.value;
      if (tooBig || tooSmall) {
        addIssueToContext(ctx, {
          code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
          minimum: tooSmall ? def.exactLength.value : undefined,
          maximum: tooBig ? def.exactLength.value : undefined,
          type: "array",
          inclusive: true,
          exact: true,
          message: def.exactLength.message
        });
        status.dirty();
      }
    }
    if (def.minLength !== null) {
      if (ctx.data.length < def.minLength.value) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.too_small,
          minimum: def.minLength.value,
          type: "array",
          inclusive: true,
          exact: false,
          message: def.minLength.message
        });
        status.dirty();
      }
    }
    if (def.maxLength !== null) {
      if (ctx.data.length > def.maxLength.value) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.too_big,
          maximum: def.maxLength.value,
          type: "array",
          inclusive: true,
          exact: false,
          message: def.maxLength.message
        });
        status.dirty();
      }
    }
    if (ctx.common.async) {
      return Promise.all([...ctx.data].map((item, i) => {
        return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
      })).then(result => {
        return ParseStatus.mergeArray(status, result);
      });
    }
    const result = [...ctx.data].map((item, i) => {
      return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
    });
    return ParseStatus.mergeArray(status, result);
  }
  get element() {
    return this._def.type;
  }
  min(minLength, message) {
    return new ZodArray({
      ...this._def,
      minLength: {
        value: minLength,
        message: errorUtil.toString(message)
      }
    });
  }
  max(maxLength, message) {
    return new ZodArray({
      ...this._def,
      maxLength: {
        value: maxLength,
        message: errorUtil.toString(message)
      }
    });
  }
  length(len, message) {
    return new ZodArray({
      ...this._def,
      exactLength: {
        value: len,
        message: errorUtil.toString(message)
      }
    });
  }
  nonempty(message) {
    return this.min(1, message);
  }
}
ZodArray.create = (schema, params) => {
  return new ZodArray({
    type: schema,
    minLength: null,
    maxLength: null,
    exactLength: null,
    typeName: ZodFirstPartyTypeKind.ZodArray,
    ...processCreateParams(params)
  });
};
function deepPartialify(schema) {
  if (schema instanceof ZodObject) {
    const newShape = {};
    for (const key in schema.shape) {
      const fieldSchema = schema.shape[key];
      newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
    }
    return new ZodObject({
      ...schema._def,
      shape: () => newShape
    });
  } else if (schema instanceof ZodArray) {
    return new ZodArray({
      ...schema._def,
      type: deepPartialify(schema.element)
    });
  } else if (schema instanceof ZodOptional) {
    return ZodOptional.create(deepPartialify(schema.unwrap()));
  } else if (schema instanceof ZodNullable) {
    return ZodNullable.create(deepPartialify(schema.unwrap()));
  } else if (schema instanceof ZodTuple) {
    return ZodTuple.create(schema.items.map(item => deepPartialify(item)));
  } else {
    return schema;
  }
}
class ZodObject extends ZodType {
  constructor() {
    super(...arguments);
    this._cached = null;
    /**
     * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.
     * If you want to pass through unknown properties, use `.passthrough()` instead.
     */
    this.nonstrict = this.passthrough;
    // extend<
    //   Augmentation extends ZodRawShape,
    //   NewOutput extends util.flatten<{
    //     [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
    //       ? Augmentation[k]["_output"]
    //       : k extends keyof Output
    //       ? Output[k]
    //       : never;
    //   }>,
    //   NewInput extends util.flatten<{
    //     [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
    //       ? Augmentation[k]["_input"]
    //       : k extends keyof Input
    //       ? Input[k]
    //       : never;
    //   }>
    // >(
    //   augmentation: Augmentation
    // ): ZodObject<
    //   extendShape<T, Augmentation>,
    //   UnknownKeys,
    //   Catchall,
    //   NewOutput,
    //   NewInput
    // > {
    //   return new ZodObject({
    //     ...this._def,
    //     shape: () => ({
    //       ...this._def.shape(),
    //       ...augmentation,
    //     }),
    //   }) as any;
    // }
    /**
     * @deprecated Use `.extend` instead
     *  */
    this.augment = this.extend;
  }
  _getCached() {
    if (this._cached !== null) return this._cached;
    const shape = this._def.shape();
    const keys = util.objectKeys(shape);
    return this._cached = {
      shape,
      keys
    };
  }
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.object) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.object,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const {
      status,
      ctx
    } = this._processInputParams(input);
    const {
      shape,
      keys: shapeKeys
    } = this._getCached();
    const extraKeys = [];
    if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
      for (const key in ctx.data) {
        if (!shapeKeys.includes(key)) {
          extraKeys.push(key);
        }
      }
    }
    const pairs = [];
    for (const key of shapeKeys) {
      const keyValidator = shape[key];
      const value = ctx.data[key];
      pairs.push({
        key: {
          status: "valid",
          value: key
        },
        value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
        alwaysSet: key in ctx.data
      });
    }
    if (this._def.catchall instanceof ZodNever) {
      const unknownKeys = this._def.unknownKeys;
      if (unknownKeys === "passthrough") {
        for (const key of extraKeys) {
          pairs.push({
            key: {
              status: "valid",
              value: key
            },
            value: {
              status: "valid",
              value: ctx.data[key]
            }
          });
        }
      } else if (unknownKeys === "strict") {
        if (extraKeys.length > 0) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.unrecognized_keys,
            keys: extraKeys
          });
          status.dirty();
        }
      } else if (unknownKeys === "strip") ;else {
        throw new Error("Internal ZodObject error: invalid unknownKeys value.");
      }
    } else {
      // run catchall validation
      const catchall = this._def.catchall;
      for (const key of extraKeys) {
        const value = ctx.data[key];
        pairs.push({
          key: {
            status: "valid",
            value: key
          },
          value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)
          ),
          alwaysSet: key in ctx.data
        });
      }
    }
    if (ctx.common.async) {
      return Promise.resolve().then(async () => {
        const syncPairs = [];
        for (const pair of pairs) {
          const key = await pair.key;
          const value = await pair.value;
          syncPairs.push({
            key,
            value,
            alwaysSet: pair.alwaysSet
          });
        }
        return syncPairs;
      }).then(syncPairs => {
        return ParseStatus.mergeObjectSync(status, syncPairs);
      });
    } else {
      return ParseStatus.mergeObjectSync(status, pairs);
    }
  }
  get shape() {
    return this._def.shape();
  }
  strict(message) {
    errorUtil.errToObj;
    return new ZodObject({
      ...this._def,
      unknownKeys: "strict",
      ...(message !== undefined ? {
        errorMap: (issue, ctx) => {
          var _a, _b, _c, _d;
          const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError;
          if (issue.code === "unrecognized_keys") return {
            message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError
          };
          return {
            message: defaultError
          };
        }
      } : {})
    });
  }
  strip() {
    return new ZodObject({
      ...this._def,
      unknownKeys: "strip"
    });
  }
  passthrough() {
    return new ZodObject({
      ...this._def,
      unknownKeys: "passthrough"
    });
  }
  // const AugmentFactory =
  //   <Def extends ZodObjectDef>(def: Def) =>
  //   <Augmentation extends ZodRawShape>(
  //     augmentation: Augmentation
  //   ): ZodObject<
  //     extendShape<ReturnType<Def["shape"]>, Augmentation>,
  //     Def["unknownKeys"],
  //     Def["catchall"]
  //   > => {
  //     return new ZodObject({
  //       ...def,
  //       shape: () => ({
  //         ...def.shape(),
  //         ...augmentation,
  //       }),
  //     }) as any;
  //   };
  extend(augmentation) {
    return new ZodObject({
      ...this._def,
      shape: () => ({
        ...this._def.shape(),
        ...augmentation
      })
    });
  }
  /**
   * Prior to zod@1.0.12 there was a bug in the
   * inferred type of merged objects. Please
   * upgrade if you are experiencing issues.
   */
  merge(merging) {
    const merged = new ZodObject({
      unknownKeys: merging._def.unknownKeys,
      catchall: merging._def.catchall,
      shape: () => ({
        ...this._def.shape(),
        ...merging._def.shape()
      }),
      typeName: ZodFirstPartyTypeKind.ZodObject
    });
    return merged;
  }
  // merge<
  //   Incoming extends AnyZodObject,
  //   Augmentation extends Incoming["shape"],
  //   NewOutput extends {
  //     [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
  //       ? Augmentation[k]["_output"]
  //       : k extends keyof Output
  //       ? Output[k]
  //       : never;
  //   },
  //   NewInput extends {
  //     [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
  //       ? Augmentation[k]["_input"]
  //       : k extends keyof Input
  //       ? Input[k]
  //       : never;
  //   }
  // >(
  //   merging: Incoming
  // ): ZodObject<
  //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
  //   Incoming["_def"]["unknownKeys"],
  //   Incoming["_def"]["catchall"],
  //   NewOutput,
  //   NewInput
  // > {
  //   const merged: any = new ZodObject({
  //     unknownKeys: merging._def.unknownKeys,
  //     catchall: merging._def.catchall,
  //     shape: () =>
  //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
  //     typeName: ZodFirstPartyTypeKind.ZodObject,
  //   }) as any;
  //   return merged;
  // }
  setKey(key, schema) {
    return this.augment({
      [key]: schema
    });
  }
  // merge<Incoming extends AnyZodObject>(
  //   merging: Incoming
  // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
  // ZodObject<
  //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
  //   Incoming["_def"]["unknownKeys"],
  //   Incoming["_def"]["catchall"]
  // > {
  //   // const mergedShape = objectUtil.mergeShapes(
  //   //   this._def.shape(),
  //   //   merging._def.shape()
  //   // );
  //   const merged: any = new ZodObject({
  //     unknownKeys: merging._def.unknownKeys,
  //     catchall: merging._def.catchall,
  //     shape: () =>
  //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
  //     typeName: ZodFirstPartyTypeKind.ZodObject,
  //   }) as any;
  //   return merged;
  // }
  catchall(index) {
    return new ZodObject({
      ...this._def,
      catchall: index
    });
  }
  pick(mask) {
    const shape = {};
    util.objectKeys(mask).forEach(key => {
      if (mask[key] && this.shape[key]) {
        shape[key] = this.shape[key];
      }
    });
    return new ZodObject({
      ...this._def,
      shape: () => shape
    });
  }
  omit(mask) {
    const shape = {};
    util.objectKeys(this.shape).forEach(key => {
      if (!mask[key]) {
        shape[key] = this.shape[key];
      }
    });
    return new ZodObject({
      ...this._def,
      shape: () => shape
    });
  }
  /**
   * @deprecated
   */
  deepPartial() {
    return deepPartialify(this);
  }
  partial(mask) {
    const newShape = {};
    util.objectKeys(this.shape).forEach(key => {
      const fieldSchema = this.shape[key];
      if (mask && !mask[key]) {
        newShape[key] = fieldSchema;
      } else {
        newShape[key] = fieldSchema.optional();
      }
    });
    return new ZodObject({
      ...this._def,
      shape: () => newShape
    });
  }
  required(mask) {
    const newShape = {};
    util.objectKeys(this.shape).forEach(key => {
      if (mask && !mask[key]) {
        newShape[key] = this.shape[key];
      } else {
        const fieldSchema = this.shape[key];
        let newField = fieldSchema;
        while (newField instanceof ZodOptional) {
          newField = newField._def.innerType;
        }
        newShape[key] = newField;
      }
    });
    return new ZodObject({
      ...this._def,
      shape: () => newShape
    });
  }
  keyof() {
    return createZodEnum(util.objectKeys(this.shape));
  }
}
ZodObject.create = (shape, params) => {
  return new ZodObject({
    shape: () => shape,
    unknownKeys: "strip",
    catchall: ZodNever.create(),
    typeName: ZodFirstPartyTypeKind.ZodObject,
    ...processCreateParams(params)
  });
};
ZodObject.strictCreate = (shape, params) => {
  return new ZodObject({
    shape: () => shape,
    unknownKeys: "strict",
    catchall: ZodNever.create(),
    typeName: ZodFirstPartyTypeKind.ZodObject,
    ...processCreateParams(params)
  });
};
ZodObject.lazycreate = (shape, params) => {
  return new ZodObject({
    shape,
    unknownKeys: "strip",
    catchall: ZodNever.create(),
    typeName: ZodFirstPartyTypeKind.ZodObject,
    ...processCreateParams(params)
  });
};
class ZodUnion extends ZodType {
  _parse(input) {
    const {
      ctx
    } = this._processInputParams(input);
    const options = this._def.options;
    function handleResults(results) {
      // return first issue-free validation if it exists
      for (const result of results) {
        if (result.result.status === "valid") {
          return result.result;
        }
      }
      for (const result of results) {
        if (result.result.status === "dirty") {
          // add issues from dirty option
          ctx.common.issues.push(...result.ctx.common.issues);
          return result.result;
        }
      }
      // return invalid
      const unionErrors = results.map(result => new ZodError(result.ctx.common.issues));
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_union,
        unionErrors
      });
      return INVALID;
    }
    if (ctx.common.async) {
      return Promise.all(options.map(async option => {
        const childCtx = {
          ...ctx,
          common: {
            ...ctx.common,
            issues: []
          },
          parent: null
        };
        return {
          result: await option._parseAsync({
            data: ctx.data,
            path: ctx.path,
            parent: childCtx
          }),
          ctx: childCtx
        };
      })).then(handleResults);
    } else {
      let dirty = undefined;
      const issues = [];
      for (const option of options) {
        const childCtx = {
          ...ctx,
          common: {
            ...ctx.common,
            issues: []
          },
          parent: null
        };
        const result = option._parseSync({
          data: ctx.data,
          path: ctx.path,
          parent: childCtx
        });
        if (result.status === "valid") {
          return result;
        } else if (result.status === "dirty" && !dirty) {
          dirty = {
            result,
            ctx: childCtx
          };
        }
        if (childCtx.common.issues.length) {
          issues.push(childCtx.common.issues);
        }
      }
      if (dirty) {
        ctx.common.issues.push(...dirty.ctx.common.issues);
        return dirty.result;
      }
      const unionErrors = issues.map(issues => new ZodError(issues));
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_union,
        unionErrors
      });
      return INVALID;
    }
  }
  get options() {
    return this._def.options;
  }
}
ZodUnion.create = (types, params) => {
  return new ZodUnion({
    options: types,
    typeName: ZodFirstPartyTypeKind.ZodUnion,
    ...processCreateParams(params)
  });
};
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
//////////                                 //////////
//////////      ZodDiscriminatedUnion      //////////
//////////                                 //////////
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
const getDiscriminator = type => {
  if (type instanceof ZodLazy) {
    return getDiscriminator(type.schema);
  } else if (type instanceof ZodEffects) {
    return getDiscriminator(type.innerType());
  } else if (type instanceof ZodLiteral) {
    return [type.value];
  } else if (type instanceof ZodEnum) {
    return type.options;
  } else if (type instanceof ZodNativeEnum) {
    // eslint-disable-next-line ban/ban
    return util.objectValues(type.enum);
  } else if (type instanceof ZodDefault) {
    return getDiscriminator(type._def.innerType);
  } else if (type instanceof ZodUndefined) {
    return [undefined];
  } else if (type instanceof ZodNull) {
    return [null];
  } else if (type instanceof ZodOptional) {
    return [undefined, ...getDiscriminator(type.unwrap())];
  } else if (type instanceof ZodNullable) {
    return [null, ...getDiscriminator(type.unwrap())];
  } else if (type instanceof ZodBranded) {
    return getDiscriminator(type.unwrap());
  } else if (type instanceof ZodReadonly) {
    return getDiscriminator(type.unwrap());
  } else if (type instanceof ZodCatch) {
    return getDiscriminator(type._def.innerType);
  } else {
    return [];
  }
};
class ZodDiscriminatedUnion extends ZodType {
  _parse(input) {
    const {
      ctx
    } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.object) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.object,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const discriminator = this.discriminator;
    const discriminatorValue = ctx.data[discriminator];
    const option = this.optionsMap.get(discriminatorValue);
    if (!option) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_union_discriminator,
        options: Array.from(this.optionsMap.keys()),
        path: [discriminator]
      });
      return INVALID;
    }
    if (ctx.common.async) {
      return option._parseAsync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      });
    } else {
      return option._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      });
    }
  }
  get discriminator() {
    return this._def.discriminator;
  }
  get options() {
    return this._def.options;
  }
  get optionsMap() {
    return this._def.optionsMap;
  }
  /**
   * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
   * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
   * have a different value for each object in the union.
   * @param discriminator the name of the discriminator property
   * @param types an array of object schemas
   * @param params
   */
  static create(discriminator, options, params) {
    // Get all the valid discriminator values
    const optionsMap = new Map();
    // try {
    for (const type of options) {
      const discriminatorValues = getDiscriminator(type.shape[discriminator]);
      if (!discriminatorValues.length) {
        throw new Error("A discriminator value for key `".concat(discriminator, "` could not be extracted from all schema options"));
      }
      for (const value of discriminatorValues) {
        if (optionsMap.has(value)) {
          throw new Error("Discriminator property ".concat(String(discriminator), " has duplicate value ").concat(String(value)));
        }
        optionsMap.set(value, type);
      }
    }
    return new ZodDiscriminatedUnion({
      typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
      discriminator,
      options,
      optionsMap,
      ...processCreateParams(params)
    });
  }
}
function mergeValues(a, b) {
  const aType = getParsedType(a);
  const bType = getParsedType(b);
  if (a === b) {
    return {
      valid: true,
      data: a
    };
  } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
    const bKeys = util.objectKeys(b);
    const sharedKeys = util.objectKeys(a).filter(key => bKeys.indexOf(key) !== -1);
    const newObj = {
      ...a,
      ...b
    };
    for (const key of sharedKeys) {
      const sharedValue = mergeValues(a[key], b[key]);
      if (!sharedValue.valid) {
        return {
          valid: false
        };
      }
      newObj[key] = sharedValue.data;
    }
    return {
      valid: true,
      data: newObj
    };
  } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
    if (a.length !== b.length) {
      return {
        valid: false
      };
    }
    const newArray = [];
    for (let index = 0; index < a.length; index++) {
      const itemA = a[index];
      const itemB = b[index];
      const sharedValue = mergeValues(itemA, itemB);
      if (!sharedValue.valid) {
        return {
          valid: false
        };
      }
      newArray.push(sharedValue.data);
    }
    return {
      valid: true,
      data: newArray
    };
  } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
    return {
      valid: true,
      data: a
    };
  } else {
    return {
      valid: false
    };
  }
}
class ZodIntersection extends ZodType {
  _parse(input) {
    const {
      status,
      ctx
    } = this._processInputParams(input);
    const handleParsed = (parsedLeft, parsedRight) => {
      if (isAborted(parsedLeft) || isAborted(parsedRight)) {
        return INVALID;
      }
      const merged = mergeValues(parsedLeft.value, parsedRight.value);
      if (!merged.valid) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.invalid_intersection_types
        });
        return INVALID;
      }
      if (isDirty(parsedLeft) || isDirty(parsedRight)) {
        status.dirty();
      }
      return {
        status: status.value,
        value: merged.data
      };
    };
    if (ctx.common.async) {
      return Promise.all([this._def.left._parseAsync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      }), this._def.right._parseAsync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      })]).then(_ref => {
        let [left, right] = _ref;
        return handleParsed(left, right);
      });
    } else {
      return handleParsed(this._def.left._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      }), this._def.right._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      }));
    }
  }
}
ZodIntersection.create = (left, right, params) => {
  return new ZodIntersection({
    left: left,
    right: right,
    typeName: ZodFirstPartyTypeKind.ZodIntersection,
    ...processCreateParams(params)
  });
};
class ZodTuple extends ZodType {
  _parse(input) {
    const {
      status,
      ctx
    } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.array) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.array,
        received: ctx.parsedType
      });
      return INVALID;
    }
    if (ctx.data.length < this._def.items.length) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.too_small,
        minimum: this._def.items.length,
        inclusive: true,
        exact: false,
        type: "array"
      });
      return INVALID;
    }
    const rest = this._def.rest;
    if (!rest && ctx.data.length > this._def.items.length) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.too_big,
        maximum: this._def.items.length,
        inclusive: true,
        exact: false,
        type: "array"
      });
      status.dirty();
    }
    const items = [...ctx.data].map((item, itemIndex) => {
      const schema = this._def.items[itemIndex] || this._def.rest;
      if (!schema) return null;
      return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
    }).filter(x => !!x); // filter nulls
    if (ctx.common.async) {
      return Promise.all(items).then(results => {
        return ParseStatus.mergeArray(status, results);
      });
    } else {
      return ParseStatus.mergeArray(status, items);
    }
  }
  get items() {
    return this._def.items;
  }
  rest(rest) {
    return new ZodTuple({
      ...this._def,
      rest
    });
  }
}
ZodTuple.create = (schemas, params) => {
  if (!Array.isArray(schemas)) {
    throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
  }
  return new ZodTuple({
    items: schemas,
    typeName: ZodFirstPartyTypeKind.ZodTuple,
    rest: null,
    ...processCreateParams(params)
  });
};
class ZodRecord extends ZodType {
  get keySchema() {
    return this._def.keyType;
  }
  get valueSchema() {
    return this._def.valueType;
  }
  _parse(input) {
    const {
      status,
      ctx
    } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.object) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.object,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const pairs = [];
    const keyType = this._def.keyType;
    const valueType = this._def.valueType;
    for (const key in ctx.data) {
      pairs.push({
        key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
        value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
        alwaysSet: key in ctx.data
      });
    }
    if (ctx.common.async) {
      return ParseStatus.mergeObjectAsync(status, pairs);
    } else {
      return ParseStatus.mergeObjectSync(status, pairs);
    }
  }
  get element() {
    return this._def.valueType;
  }
  static create(first, second, third) {
    if (second instanceof ZodType) {
      return new ZodRecord({
        keyType: first,
        valueType: second,
        typeName: ZodFirstPartyTypeKind.ZodRecord,
        ...processCreateParams(third)
      });
    }
    return new ZodRecord({
      keyType: ZodString.create(),
      valueType: first,
      typeName: ZodFirstPartyTypeKind.ZodRecord,
      ...processCreateParams(second)
    });
  }
}
class ZodMap extends ZodType {
  get keySchema() {
    return this._def.keyType;
  }
  get valueSchema() {
    return this._def.valueType;
  }
  _parse(input) {
    const {
      status,
      ctx
    } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.map) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.map,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const keyType = this._def.keyType;
    const valueType = this._def.valueType;
    const pairs = [...ctx.data.entries()].map((_ref2, index) => {
      let [key, value] = _ref2;
      return {
        key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
        value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
      };
    });
    if (ctx.common.async) {
      const finalMap = new Map();
      return Promise.resolve().then(async () => {
        for (const pair of pairs) {
          const key = await pair.key;
          const value = await pair.value;
          if (key.status === "aborted" || value.status === "aborted") {
            return INVALID;
          }
          if (key.status === "dirty" || value.status === "dirty") {
            status.dirty();
          }
          finalMap.set(key.value, value.value);
        }
        return {
          status: status.value,
          value: finalMap
        };
      });
    } else {
      const finalMap = new Map();
      for (const pair of pairs) {
        const key = pair.key;
        const value = pair.value;
        if (key.status === "aborted" || value.status === "aborted") {
          return INVALID;
        }
        if (key.status === "dirty" || value.status === "dirty") {
          status.dirty();
        }
        finalMap.set(key.value, value.value);
      }
      return {
        status: status.value,
        value: finalMap
      };
    }
  }
}
ZodMap.create = (keyType, valueType, params) => {
  return new ZodMap({
    valueType,
    keyType,
    typeName: ZodFirstPartyTypeKind.ZodMap,
    ...processCreateParams(params)
  });
};
class ZodSet extends ZodType {
  _parse(input) {
    const {
      status,
      ctx
    } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.set) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.set,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const def = this._def;
    if (def.minSize !== null) {
      if (ctx.data.size < def.minSize.value) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.too_small,
          minimum: def.minSize.value,
          type: "set",
          inclusive: true,
          exact: false,
          message: def.minSize.message
        });
        status.dirty();
      }
    }
    if (def.maxSize !== null) {
      if (ctx.data.size > def.maxSize.value) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.too_big,
          maximum: def.maxSize.value,
          type: "set",
          inclusive: true,
          exact: false,
          message: def.maxSize.message
        });
        status.dirty();
      }
    }
    const valueType = this._def.valueType;
    function finalizeSet(elements) {
      const parsedSet = new Set();
      for (const element of elements) {
        if (element.status === "aborted") return INVALID;
        if (element.status === "dirty") status.dirty();
        parsedSet.add(element.value);
      }
      return {
        status: status.value,
        value: parsedSet
      };
    }
    const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
    if (ctx.common.async) {
      return Promise.all(elements).then(elements => finalizeSet(elements));
    } else {
      return finalizeSet(elements);
    }
  }
  min(minSize, message) {
    return new ZodSet({
      ...this._def,
      minSize: {
        value: minSize,
        message: errorUtil.toString(message)
      }
    });
  }
  max(maxSize, message) {
    return new ZodSet({
      ...this._def,
      maxSize: {
        value: maxSize,
        message: errorUtil.toString(message)
      }
    });
  }
  size(size, message) {
    return this.min(size, message).max(size, message);
  }
  nonempty(message) {
    return this.min(1, message);
  }
}
ZodSet.create = (valueType, params) => {
  return new ZodSet({
    valueType,
    minSize: null,
    maxSize: null,
    typeName: ZodFirstPartyTypeKind.ZodSet,
    ...processCreateParams(params)
  });
};
class ZodFunction extends ZodType {
  constructor() {
    super(...arguments);
    this.validate = this.implement;
  }
  _parse(input) {
    const {
      ctx
    } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.function) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.function,
        received: ctx.parsedType
      });
      return INVALID;
    }
    function makeArgsIssue(args, error) {
      return makeIssue({
        data: args,
        path: ctx.path,
        errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), errorMap].filter(x => !!x),
        issueData: {
          code: ZodIssueCode.invalid_arguments,
          argumentsError: error
        }
      });
    }
    function makeReturnsIssue(returns, error) {
      return makeIssue({
        data: returns,
        path: ctx.path,
        errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), errorMap].filter(x => !!x),
        issueData: {
          code: ZodIssueCode.invalid_return_type,
          returnTypeError: error
        }
      });
    }
    const params = {
      errorMap: ctx.common.contextualErrorMap
    };
    const fn = ctx.data;
    if (this._def.returns instanceof ZodPromise) {
      // Would love a way to avoid disabling this rule, but we need
      // an alias (using an arrow function was what caused 2651).
      // eslint-disable-next-line @typescript-eslint/no-this-alias
      const me = this;
      return OK(async function () {
        for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
          args[_key] = arguments[_key];
        }
        const error = new ZodError([]);
        const parsedArgs = await me._def.args.parseAsync(args, params).catch(e => {
          error.addIssue(makeArgsIssue(args, e));
          throw error;
        });
        const result = await Reflect.apply(fn, this, parsedArgs);
        const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch(e => {
          error.addIssue(makeReturnsIssue(result, e));
          throw error;
        });
        return parsedReturns;
      });
    } else {
      // Would love a way to avoid disabling this rule, but we need
      // an alias (using an arrow function was what caused 2651).
      // eslint-disable-next-line @typescript-eslint/no-this-alias
      const me = this;
      return OK(function () {
        for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
          args[_key2] = arguments[_key2];
        }
        const parsedArgs = me._def.args.safeParse(args, params);
        if (!parsedArgs.success) {
          throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
        }
        const result = Reflect.apply(fn, this, parsedArgs.data);
        const parsedReturns = me._def.returns.safeParse(result, params);
        if (!parsedReturns.success) {
          throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
        }
        return parsedReturns.data;
      });
    }
  }
  parameters() {
    return this._def.args;
  }
  returnType() {
    return this._def.returns;
  }
  args() {
    for (var _len3 = arguments.length, items = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
      items[_key3] = arguments[_key3];
    }
    return new ZodFunction({
      ...this._def,
      args: ZodTuple.create(items).rest(ZodUnknown.create())
    });
  }
  returns(returnType) {
    return new ZodFunction({
      ...this._def,
      returns: returnType
    });
  }
  implement(func) {
    const validatedFunc = this.parse(func);
    return validatedFunc;
  }
  strictImplement(func) {
    const validatedFunc = this.parse(func);
    return validatedFunc;
  }
  static create(args, returns, params) {
    return new ZodFunction({
      args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
      returns: returns || ZodUnknown.create(),
      typeName: ZodFirstPartyTypeKind.ZodFunction,
      ...processCreateParams(params)
    });
  }
}
class ZodLazy extends ZodType {
  get schema() {
    return this._def.getter();
  }
  _parse(input) {
    const {
      ctx
    } = this._processInputParams(input);
    const lazySchema = this._def.getter();
    return lazySchema._parse({
      data: ctx.data,
      path: ctx.path,
      parent: ctx
    });
  }
}
ZodLazy.create = (getter, params) => {
  return new ZodLazy({
    getter: getter,
    typeName: ZodFirstPartyTypeKind.ZodLazy,
    ...processCreateParams(params)
  });
};
class ZodLiteral extends ZodType {
  _parse(input) {
    if (input.data !== this._def.value) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        received: ctx.data,
        code: ZodIssueCode.invalid_literal,
        expected: this._def.value
      });
      return INVALID;
    }
    return {
      status: "valid",
      value: input.data
    };
  }
  get value() {
    return this._def.value;
  }
}
ZodLiteral.create = (value, params) => {
  return new ZodLiteral({
    value: value,
    typeName: ZodFirstPartyTypeKind.ZodLiteral,
    ...processCreateParams(params)
  });
};
function createZodEnum(values, params) {
  return new ZodEnum({
    values,
    typeName: ZodFirstPartyTypeKind.ZodEnum,
    ...processCreateParams(params)
  });
}
class ZodEnum extends ZodType {
  constructor() {
    super(...arguments);
    _ZodEnum_cache.set(this, void 0);
  }
  _parse(input) {
    if (typeof input.data !== "string") {
      const ctx = this._getOrReturnCtx(input);
      const expectedValues = this._def.values;
      addIssueToContext(ctx, {
        expected: util.joinValues(expectedValues),
        received: ctx.parsedType,
        code: ZodIssueCode.invalid_type
      });
      return INVALID;
    }
    if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f")) {
      __classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), "f");
    }
    if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f").has(input.data)) {
      const ctx = this._getOrReturnCtx(input);
      const expectedValues = this._def.values;
      addIssueToContext(ctx, {
        received: ctx.data,
        code: ZodIssueCode.invalid_enum_value,
        options: expectedValues
      });
      return INVALID;
    }
    return OK(input.data);
  }
  get options() {
    return this._def.values;
  }
  get enum() {
    const enumValues = {};
    for (const val of this._def.values) {
      enumValues[val] = val;
    }
    return enumValues;
  }
  get Values() {
    const enumValues = {};
    for (const val of this._def.values) {
      enumValues[val] = val;
    }
    return enumValues;
  }
  get Enum() {
    const enumValues = {};
    for (const val of this._def.values) {
      enumValues[val] = val;
    }
    return enumValues;
  }
  extract(values) {
    let newDef = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this._def;
    return ZodEnum.create(values, {
      ...this._def,
      ...newDef
    });
  }
  exclude(values) {
    let newDef = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this._def;
    return ZodEnum.create(this.options.filter(opt => !values.includes(opt)), {
      ...this._def,
      ...newDef
    });
  }
}
_ZodEnum_cache = new WeakMap();
ZodEnum.create = createZodEnum;
class ZodNativeEnum extends ZodType {
  constructor() {
    super(...arguments);
    _ZodNativeEnum_cache.set(this, void 0);
  }
  _parse(input) {
    const nativeEnumValues = util.getValidEnumValues(this._def.values);
    const ctx = this._getOrReturnCtx(input);
    if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
      const expectedValues = util.objectValues(nativeEnumValues);
      addIssueToContext(ctx, {
        expected: util.joinValues(expectedValues),
        received: ctx.parsedType,
        code: ZodIssueCode.invalid_type
      });
      return INVALID;
    }
    if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f")) {
      __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util.getValidEnumValues(this._def.values)), "f");
    }
    if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f").has(input.data)) {
      const expectedValues = util.objectValues(nativeEnumValues);
      addIssueToContext(ctx, {
        received: ctx.data,
        code: ZodIssueCode.invalid_enum_value,
        options: expectedValues
      });
      return INVALID;
    }
    return OK(input.data);
  }
  get enum() {
    return this._def.values;
  }
}
_ZodNativeEnum_cache = new WeakMap();
ZodNativeEnum.create = (values, params) => {
  return new ZodNativeEnum({
    values: values,
    typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
    ...processCreateParams(params)
  });
};
class ZodPromise extends ZodType {
  unwrap() {
    return this._def.type;
  }
  _parse(input) {
    const {
      ctx
    } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.promise,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
    return OK(promisified.then(data => {
      return this._def.type.parseAsync(data, {
        path: ctx.path,
        errorMap: ctx.common.contextualErrorMap
      });
    }));
  }
}
ZodPromise.create = (schema, params) => {
  return new ZodPromise({
    type: schema,
    typeName: ZodFirstPartyTypeKind.ZodPromise,
    ...processCreateParams(params)
  });
};
class ZodEffects extends ZodType {
  innerType() {
    return this._def.schema;
  }
  sourceType() {
    return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
  }
  _parse(input) {
    const {
      status,
      ctx
    } = this._processInputParams(input);
    const effect = this._def.effect || null;
    const checkCtx = {
      addIssue: arg => {
        addIssueToContext(ctx, arg);
        if (arg.fatal) {
          status.abort();
        } else {
          status.dirty();
        }
      },
      get path() {
        return ctx.path;
      }
    };
    checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
    if (effect.type === "preprocess") {
      const processed = effect.transform(ctx.data, checkCtx);
      if (ctx.common.async) {
        return Promise.resolve(processed).then(async processed => {
          if (status.value === "aborted") return INVALID;
          const result = await this._def.schema._parseAsync({
            data: processed,
            path: ctx.path,
            parent: ctx
          });
          if (result.status === "aborted") return INVALID;
          if (result.status === "dirty") return DIRTY(result.value);
          if (status.value === "dirty") return DIRTY(result.value);
          return result;
        });
      } else {
        if (status.value === "aborted") return INVALID;
        const result = this._def.schema._parseSync({
          data: processed,
          path: ctx.path,
          parent: ctx
        });
        if (result.status === "aborted") return INVALID;
        if (result.status === "dirty") return DIRTY(result.value);
        if (status.value === "dirty") return DIRTY(result.value);
        return result;
      }
    }
    if (effect.type === "refinement") {
      const executeRefinement = acc => {
        const result = effect.refinement(acc, checkCtx);
        if (ctx.common.async) {
          return Promise.resolve(result);
        }
        if (result instanceof Promise) {
          throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
        }
        return acc;
      };
      if (ctx.common.async === false) {
        const inner = this._def.schema._parseSync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        });
        if (inner.status === "aborted") return INVALID;
        if (inner.status === "dirty") status.dirty();
        // return value is ignored
        executeRefinement(inner.value);
        return {
          status: status.value,
          value: inner.value
        };
      } else {
        return this._def.schema._parseAsync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        }).then(inner => {
          if (inner.status === "aborted") return INVALID;
          if (inner.status === "dirty") status.dirty();
          return executeRefinement(inner.value).then(() => {
            return {
              status: status.value,
              value: inner.value
            };
          });
        });
      }
    }
    if (effect.type === "transform") {
      if (ctx.common.async === false) {
        const base = this._def.schema._parseSync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        });
        if (!isValid(base)) return base;
        const result = effect.transform(base.value, checkCtx);
        if (result instanceof Promise) {
          throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");
        }
        return {
          status: status.value,
          value: result
        };
      } else {
        return this._def.schema._parseAsync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        }).then(base => {
          if (!isValid(base)) return base;
          return Promise.resolve(effect.transform(base.value, checkCtx)).then(result => ({
            status: status.value,
            value: result
          }));
        });
      }
    }
    util.assertNever(effect);
  }
}
ZodEffects.create = (schema, effect, params) => {
  return new ZodEffects({
    schema,
    typeName: ZodFirstPartyTypeKind.ZodEffects,
    effect,
    ...processCreateParams(params)
  });
};
ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
  return new ZodEffects({
    schema,
    effect: {
      type: "preprocess",
      transform: preprocess
    },
    typeName: ZodFirstPartyTypeKind.ZodEffects,
    ...processCreateParams(params)
  });
};
class ZodOptional extends ZodType {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType === ZodParsedType.undefined) {
      return OK(undefined);
    }
    return this._def.innerType._parse(input);
  }
  unwrap() {
    return this._def.innerType;
  }
}
ZodOptional.create = (type, params) => {
  return new ZodOptional({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodOptional,
    ...processCreateParams(params)
  });
};
class ZodNullable extends ZodType {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType === ZodParsedType.null) {
      return OK(null);
    }
    return this._def.innerType._parse(input);
  }
  unwrap() {
    return this._def.innerType;
  }
}
ZodNullable.create = (type, params) => {
  return new ZodNullable({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodNullable,
    ...processCreateParams(params)
  });
};
class ZodDefault extends ZodType {
  _parse(input) {
    const {
      ctx
    } = this._processInputParams(input);
    let data = ctx.data;
    if (ctx.parsedType === ZodParsedType.undefined) {
      data = this._def.defaultValue();
    }
    return this._def.innerType._parse({
      data,
      path: ctx.path,
      parent: ctx
    });
  }
  removeDefault() {
    return this._def.innerType;
  }
}
ZodDefault.create = (type, params) => {
  return new ZodDefault({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodDefault,
    defaultValue: typeof params.default === "function" ? params.default : () => params.default,
    ...processCreateParams(params)
  });
};
class ZodCatch extends ZodType {
  _parse(input) {
    const {
      ctx
    } = this._processInputParams(input);
    // newCtx is used to not collect issues from inner types in ctx
    const newCtx = {
      ...ctx,
      common: {
        ...ctx.common,
        issues: []
      }
    };
    const result = this._def.innerType._parse({
      data: newCtx.data,
      path: newCtx.path,
      parent: {
        ...newCtx
      }
    });
    if (isAsync(result)) {
      return result.then(result => {
        return {
          status: "valid",
          value: result.status === "valid" ? result.value : this._def.catchValue({
            get error() {
              return new ZodError(newCtx.common.issues);
            },
            input: newCtx.data
          })
        };
      });
    } else {
      return {
        status: "valid",
        value: result.status === "valid" ? result.value : this._def.catchValue({
          get error() {
            return new ZodError(newCtx.common.issues);
          },
          input: newCtx.data
        })
      };
    }
  }
  removeCatch() {
    return this._def.innerType;
  }
}
ZodCatch.create = (type, params) => {
  return new ZodCatch({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodCatch,
    catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
    ...processCreateParams(params)
  });
};
class ZodNaN extends ZodType {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.nan) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.nan,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return {
      status: "valid",
      value: input.data
    };
  }
}
ZodNaN.create = params => {
  return new ZodNaN({
    typeName: ZodFirstPartyTypeKind.ZodNaN,
    ...processCreateParams(params)
  });
};
const BRAND = Symbol("zod_brand");
class ZodBranded extends ZodType {
  _parse(input) {
    const {
      ctx
    } = this._processInputParams(input);
    const data = ctx.data;
    return this._def.type._parse({
      data,
      path: ctx.path,
      parent: ctx
    });
  }
  unwrap() {
    return this._def.type;
  }
}
class ZodPipeline extends ZodType {
  _parse(input) {
    const {
      status,
      ctx
    } = this._processInputParams(input);
    if (ctx.common.async) {
      const handleAsync = async () => {
        const inResult = await this._def.in._parseAsync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        });
        if (inResult.status === "aborted") return INVALID;
        if (inResult.status === "dirty") {
          status.dirty();
          return DIRTY(inResult.value);
        } else {
          return this._def.out._parseAsync({
            data: inResult.value,
            path: ctx.path,
            parent: ctx
          });
        }
      };
      return handleAsync();
    } else {
      const inResult = this._def.in._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      });
      if (inResult.status === "aborted") return INVALID;
      if (inResult.status === "dirty") {
        status.dirty();
        return {
          status: "dirty",
          value: inResult.value
        };
      } else {
        return this._def.out._parseSync({
          data: inResult.value,
          path: ctx.path,
          parent: ctx
        });
      }
    }
  }
  static create(a, b) {
    return new ZodPipeline({
      in: a,
      out: b,
      typeName: ZodFirstPartyTypeKind.ZodPipeline
    });
  }
}
class ZodReadonly extends ZodType {
  _parse(input) {
    const result = this._def.innerType._parse(input);
    const freeze = data => {
      if (isValid(data)) {
        data.value = Object.freeze(data.value);
      }
      return data;
    };
    return isAsync(result) ? result.then(data => freeze(data)) : freeze(result);
  }
  unwrap() {
    return this._def.innerType;
  }
}
ZodReadonly.create = (type, params) => {
  return new ZodReadonly({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodReadonly,
    ...processCreateParams(params)
  });
};
////////////////////////////////////////
////////////////////////////////////////
//////////                    //////////
//////////      z.custom      //////////
//////////                    //////////
////////////////////////////////////////
////////////////////////////////////////
function cleanParams(params, data) {
  const p = typeof params === "function" ? params(data) : typeof params === "string" ? {
    message: params
  } : params;
  const p2 = typeof p === "string" ? {
    message: p
  } : p;
  return p2;
}
function custom(check) {
  let _params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  let
  /**
   * @deprecated
   *
   * Pass `fatal` into the params object instead:
   *
   * ```ts
   * z.string().custom((val) => val.length > 5, { fatal: false })
   * ```
   *
   */
  fatal = arguments.length > 2 ? arguments[2] : undefined;
  if (check) return ZodAny.create().superRefine((data, ctx) => {
    var _a, _b;
    const r = check(data);
    if (r instanceof Promise) {
      return r.then(r => {
        var _a, _b;
        if (!r) {
          const params = cleanParams(_params, data);
          const _fatal = (_b = (_a = params.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true;
          ctx.addIssue({
            code: "custom",
            ...params,
            fatal: _fatal
          });
        }
      });
    }
    if (!r) {
      const params = cleanParams(_params, data);
      const _fatal = (_b = (_a = params.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true;
      ctx.addIssue({
        code: "custom",
        ...params,
        fatal: _fatal
      });
    }
    return;
  });
  return ZodAny.create();
}
const late = {
  object: ZodObject.lazycreate
};
var ZodFirstPartyTypeKind;
(function (ZodFirstPartyTypeKind) {
  ZodFirstPartyTypeKind["ZodString"] = "ZodString";
  ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber";
  ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN";
  ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt";
  ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean";
  ZodFirstPartyTypeKind["ZodDate"] = "ZodDate";
  ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol";
  ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined";
  ZodFirstPartyTypeKind["ZodNull"] = "ZodNull";
  ZodFirstPartyTypeKind["ZodAny"] = "ZodAny";
  ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown";
  ZodFirstPartyTypeKind["ZodNever"] = "ZodNever";
  ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid";
  ZodFirstPartyTypeKind["ZodArray"] = "ZodArray";
  ZodFirstPartyTypeKind["ZodObject"] = "ZodObject";
  ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion";
  ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
  ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection";
  ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple";
  ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord";
  ZodFirstPartyTypeKind["ZodMap"] = "ZodMap";
  ZodFirstPartyTypeKind["ZodSet"] = "ZodSet";
  ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction";
  ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy";
  ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral";
  ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum";
  ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects";
  ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum";
  ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional";
  ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable";
  ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault";
  ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch";
  ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise";
  ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded";
  ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline";
  ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly";
})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
const instanceOfType = function (
// const instanceOfType = <T extends new (...args: any[]) => any>(
cls) {
  let params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
    message: "Input not instance of ".concat(cls.name)
  };
  return custom(data => data instanceof cls, params);
};
const stringType = ZodString.create;
const numberType = ZodNumber.create;
const nanType = ZodNaN.create;
const bigIntType = ZodBigInt.create;
const booleanType = ZodBoolean.create;
const dateType = ZodDate.create;
const symbolType = ZodSymbol.create;
const undefinedType = ZodUndefined.create;
const nullType = ZodNull.create;
const anyType = ZodAny.create;
const unknownType = ZodUnknown.create;
const neverType = ZodNever.create;
const voidType = ZodVoid.create;
const arrayType = ZodArray.create;
const objectType = ZodObject.create;
const strictObjectType = ZodObject.strictCreate;
const unionType = ZodUnion.create;
const discriminatedUnionType = ZodDiscriminatedUnion.create;
const intersectionType = ZodIntersection.create;
const tupleType = ZodTuple.create;
const recordType = ZodRecord.create;
const mapType = ZodMap.create;
const setType = ZodSet.create;
const functionType = ZodFunction.create;
const lazyType = ZodLazy.create;
const literalType = ZodLiteral.create;
const enumType = ZodEnum.create;
const nativeEnumType = ZodNativeEnum.create;
const promiseType = ZodPromise.create;
const effectsType = ZodEffects.create;
const optionalType = ZodOptional.create;
const nullableType = ZodNullable.create;
const preprocessType = ZodEffects.createWithPreprocess;
const pipelineType = ZodPipeline.create;
const ostring = () => stringType().optional();
const onumber = () => numberType().optional();
const oboolean = () => booleanType().optional();
const coerce = {
  string: arg => ZodString.create({
    ...arg,
    coerce: true
  }),
  number: arg => ZodNumber.create({
    ...arg,
    coerce: true
  }),
  boolean: arg => ZodBoolean.create({
    ...arg,
    coerce: true
  }),
  bigint: arg => ZodBigInt.create({
    ...arg,
    coerce: true
  }),
  date: arg => ZodDate.create({
    ...arg,
    coerce: true
  })
};
const NEVER = INVALID;
var z = /*#__PURE__*/Object.freeze({
  __proto__: null,
  defaultErrorMap: errorMap,
  setErrorMap: setErrorMap,
  getErrorMap: getErrorMap,
  makeIssue: makeIssue,
  EMPTY_PATH: EMPTY_PATH,
  addIssueToContext: addIssueToContext,
  ParseStatus: ParseStatus,
  INVALID: INVALID,
  DIRTY: DIRTY,
  OK: OK,
  isAborted: isAborted,
  isDirty: isDirty,
  isValid: isValid,
  isAsync: isAsync,
  get util() {
    return util;
  },
  get objectUtil() {
    return objectUtil;
  },
  ZodParsedType: ZodParsedType,
  getParsedType: getParsedType,
  ZodType: ZodType,
  datetimeRegex: datetimeRegex,
  ZodString: ZodString,
  ZodNumber: ZodNumber,
  ZodBigInt: ZodBigInt,
  ZodBoolean: ZodBoolean,
  ZodDate: ZodDate,
  ZodSymbol: ZodSymbol,
  ZodUndefined: ZodUndefined,
  ZodNull: ZodNull,
  ZodAny: ZodAny,
  ZodUnknown: ZodUnknown,
  ZodNever: ZodNever,
  ZodVoid: ZodVoid,
  ZodArray: ZodArray,
  ZodObject: ZodObject,
  ZodUnion: ZodUnion,
  ZodDiscriminatedUnion: ZodDiscriminatedUnion,
  ZodIntersection: ZodIntersection,
  ZodTuple: ZodTuple,
  ZodRecord: ZodRecord,
  ZodMap: ZodMap,
  ZodSet: ZodSet,
  ZodFunction: ZodFunction,
  ZodLazy: ZodLazy,
  ZodLiteral: ZodLiteral,
  ZodEnum: ZodEnum,
  ZodNativeEnum: ZodNativeEnum,
  ZodPromise: ZodPromise,
  ZodEffects: ZodEffects,
  ZodTransformer: ZodEffects,
  ZodOptional: ZodOptional,
  ZodNullable: ZodNullable,
  ZodDefault: ZodDefault,
  ZodCatch: ZodCatch,
  ZodNaN: ZodNaN,
  BRAND: BRAND,
  ZodBranded: ZodBranded,
  ZodPipeline: ZodPipeline,
  ZodReadonly: ZodReadonly,
  custom: custom,
  Schema: ZodType,
  ZodSchema: ZodType,
  late: late,
  get ZodFirstPartyTypeKind() {
    return ZodFirstPartyTypeKind;
  },
  coerce: coerce,
  any: anyType,
  array: arrayType,
  bigint: bigIntType,
  boolean: booleanType,
  date: dateType,
  discriminatedUnion: discriminatedUnionType,
  effect: effectsType,
  'enum': enumType,
  'function': functionType,
  'instanceof': instanceOfType,
  intersection: intersectionType,
  lazy: lazyType,
  literal: literalType,
  map: mapType,
  nan: nanType,
  nativeEnum: nativeEnumType,
  never: neverType,
  'null': nullType,
  nullable: nullableType,
  number: numberType,
  object: objectType,
  oboolean: oboolean,
  onumber: onumber,
  optional: optionalType,
  ostring: ostring,
  pipeline: pipelineType,
  preprocess: preprocessType,
  promise: promiseType,
  record: recordType,
  set: setType,
  strictObject: strictObjectType,
  string: stringType,
  symbol: symbolType,
  transformer: effectsType,
  tuple: tupleType,
  'undefined': undefinedType,
  union: unionType,
  unknown: unknownType,
  'void': voidType,
  NEVER: NEVER,
  ZodIssueCode: ZodIssueCode,
  quotelessJson: quotelessJson,
  ZodError: ZodError
});

/**
 * Creates a Zod schema validator for data processor functions.
 *
 * Data processors are optional filters that can inspect and potentially
 * drop data items before they are sent to the server. Return false to drop the item.
 *
 * @returns Zod schema for a processor function: (data: T) => boolean | void
 */
const processorFn = () => z.function().args(z.custom()).returns(z.boolean().optional());
const baseSchema = z.object({
  /**
   * The server base url. For example, "example.com".
   * - Create room: `https://${api}/room/create`
   * - Filter room: `https://${api}/room/list`
   * - Join WebSocket room: `wss://${api}/ws/room/join`
   */
  api: z.string().refine(val => !val.startsWith('http'), {
    message: 'Just need host part in url'
  }),
  /**
   * Project name, used for group connections
   */
  project: z.string().min(1, 'Missing value'),
  /**
   * Custom title for displaying some data like user info to
   * help you to distinguish the client. The title value will
   * show in the room-list route page.
   */
  title: z.string().min(1, 'Missing value'),
  /**
   * Specify the server <scheme> manually.
   * - false: sdk will use ['http://', 'ws://'];
   * - true: sdk will use ['https://', 'wss://'];
   */
  enableSSL: z.boolean(),
  /**
   * Specify how many messages to cache.
   * The data is primarily used for define "socketStore.messageCapacity" to
   * configure the maximum number of historical data the SDK can send
   * after the debugging terminal goes online.
   */
  messageCapacity: z.number(),
  /**
   * Indicate whether authorization is required. If enabled, PageSpy generates
   * a 6-digit random number (below "secret") as a password for the debug room,
   * which is required for developers to access the debug room
   * @default false
   */
  useSecret: z.boolean(),
  secret: z.string().refine(val => !val, {
    message: 'Secret is not allowed to be set manually'
  }),
  /**
   * Indicate whether enable offline mode. Once enabled, PageSpy will not
   * make network requests and send data by server. Collected data can be
   * exported with "DataHarborPlugin" and then replayed in the debugger.
   */
  offline: z.boolean(),
  /**
   * Indicate whether serialize non-primitive data in offline log.
   */
  serializeData: z.boolean(),
  /**
   * Internal plugins is out-of-box carried with PageSpy.
   * You can disable plugin by passing the plugin name to this option.
   */
  disabledPlugins: z.array(z.string()),
  /**
   * Specify data processor for each data type.
   */
  dataProcessor: z.object({
    console: processorFn(),
    network: processorFn(),
    storage: processorFn(),
    database: processorFn(),
    page: processorFn(),
    system: processorFn()
  }).partial().strict()
}).partial().strict();
/**
 * Extends the base configuration schema with platform-specific fields.
 *
 * @param extendFn - Function that receives Zod and returns additional schema fields
 * @returns Merged schema combining base and platform-specific options
 *
 * @example
 * ```typescript
 * const browserSchema = extendConfigSchema((z) =>
 *   z.object({
 *     autoRender: z.boolean(),
 *     logo: z.string().optional(),
 *   })
 * );
 * ```
 */
const extendConfigSchema = extendFn => {
  return baseSchema.merge(extendFn(z));
};
/**
 * Custom error thrown when configuration validation fails.
 *
 * Provides detailed error messages showing which fields failed validation
 * and includes the full config object for debugging.
 */
class InvalidConfigError extends Error {
  constructor(error, config) {
    const message = error.issues.map(issue => {
      if (issue.code === 'unrecognized_keys') {
        return "- ".concat(issue.message, ";");
      }
      return "- ".concat(issue.path.join('.'), ": ").concat(issue.message, ";");
    }).join('\n');
    let output = "config values validation failed.\n\n".concat(message);
    try {
      output = "".concat(output, "\n\nCurrent config: ").concat(JSON.stringify(config, null, 2));
    } catch (e) {
      //
    }
    super(output);
    this.name = 'InvalidConfigError';
  }
}
/**
 * Abstract base class for PageSpy configuration management.
 *
 * Platform-specific packages should extend this class and provide:
 * - A Zod schema for validation (via `schema` property)
 * - Default platform-specific config values (via `platform` property)
 *
 * @template C - The configuration type (extends InitConfigBase)
 */
class ConfigBase {
  constructor() {
    /** Current merged configuration value */
    _defineProperty(this, "value", {
      ...this.base
    });
    /**
     * Merges user-provided configuration with base and platform defaults.
     *
     * Configuration priority (highest to lowest):
     * 1. User-provided config
     * 2. Platform defaults
     * 3. Base defaults
     *
     * @param userCfg - User-provided configuration object
     * @returns The fully merged and validated configuration
     * @throws {InvalidConfigError} If validation fails
     */
    _defineProperty(this, "mergeConfig", userCfg => {
      const value = {
        ...this.base,
        ...this.platform,
        ...userCfg
      };
      try {
        this.schema.parse(value);
      } catch (error) {
        throw new InvalidConfigError(error, value);
      }
      this.value = value;
      return this.value;
    });
  }
  /** Base configuration values shared across all platforms */
  get base() {
    return {
      api: '',
      project: '--',
      title: '--',
      enableSSL: true,
      messageCapacity: 1000,
      useSecret: false,
      secret: '',
      // Generated automatically when useSecret is true
      offline: false,
      serializeData: false,
      disabledPlugins: [],
      dataProcessor: {}
    };
  }
  /**
   * Gets the current configuration value.
   *
   * @returns The current merged configuration
   */
  get() {
    return this.value;
  }
  /**
   * Updates a single configuration field.
   *
   * @param key - Configuration field name
   * @param val - New value for the field
   */
  set(key, val) {
    this.value[key] = val;
  }
}

// fork WebSocket state
var SocketState;
(function (SocketState) {
  SocketState[SocketState["CONNECTING"] = 0] = "CONNECTING";
  SocketState[SocketState["OPEN"] = 1] = "OPEN";
  SocketState[SocketState["CLOSING"] = 2] = "CLOSING";
  SocketState[SocketState["CLOSED"] = 3] = "CLOSED";
})(SocketState || (SocketState = {}));
// Caps exponential backoff after SOCKET_CONFIG.MAX_RETRY_ATTEMPTS increases.
const MAX_RETRY_INTERVAL = Math.pow(SOCKET_CONFIG.RETRY_INTERVAL_MULTIPLIER, SOCKET_CONFIG.MAX_RETRY_ATTEMPTS) * SOCKET_CONFIG.INITIAL_RETRY_INTERVAL_MS;
// 封装不同平台的 socket
class SocketWrapper {
  constructor() {
    _defineProperty(this, "events", {
      open: [],
      close: [],
      error: [],
      message: []
    });
  }
  emit(event, data) {
    this.events[event].forEach(fun => {
      fun(data);
    });
    // for close and error, clear all listeners or they will be called on next socket instance.
    if (event === 'close' || event === 'error') {
      this.clearListeners();
    }
  }
  onOpen(fun) {
    this.events.open.push(fun);
  }
  onClose(fun) {
    this.events.close.push(fun);
  }
  onError(fun) {
    this.events.error.push(fun);
  }
  onMessage(fun) {
    this.events.message.push(fun);
  }
  clearListeners() {
    // clear listeners
    Object.entries(this.events).forEach(_ref => {
      let [, funs] = _ref;
      funs.splice(0);
    });
  }
}
class SocketStoreBase {
  getSocket() {
    return this.socketWrapper;
  }
  updateRoomInfo() {
    if (this.getPageSpyConfig) {
      var _this$getClient;
      const {
        project,
        title
      } = this.getPageSpyConfig();
      const name = (_this$getClient = this.getClient) === null || _this$getClient === void 0 ? void 0 : _this$getClient.call(this).getName();
      this.send({
        type: UPDATE_ROOM_INFO,
        content: {
          info: {
            name,
            group: project,
            tags: {
              title,
              name,
              group: project
            }
          }
        }
      }, true);
    }
  }
  // response message filters, to handle some wired messages

  constructor() {
    _defineProperty(this, "socketUrl", '');
    _defineProperty(this, "socketConnection", null);
    _defineProperty(this, "debuggerConnection", null);
    // ping timer used for send next ping.
    // a ping is sent after last msg (normal msg or pong) received.
    _defineProperty(this, "pingTimer", null);
    // pong timer used for waiting for pong, if pong not received, close the connection
    _defineProperty(this, "pongTimer", null);
    _defineProperty(this, "retryTimer", null);
    // Cache messages only in online mode
    _defineProperty(this, "isOffline", false);
    // Maximum message buffer size (0 = unlimited).
    // When limit is reached, oldest messages are evicted using a sliding window approach.
    _defineProperty(this, "messageCapacity", 0);
    // Message buffer implementing FIFO eviction
    _defineProperty(this, "messages", []);
    // Index of the first valid message (avoids O(n) array shifts on every eviction)
    _defineProperty(this, "messageHead", 0);
    // events center
    _defineProperty(this, "events", {
      debug: [],
      refresh: [],
      'atom-detail': [],
      'atom-getter': [],
      'debugger-online': [],
      'database-pagination': [],
      'public-data': [],
      'harbor-clear': []
    });
    // Starts at the configured delay and increases with exponential backoff.
    _defineProperty(this, "retryInterval", SOCKET_CONFIG.INITIAL_RETRY_INTERVAL_MS);
    _defineProperty(this, "connectable", true);
    _defineProperty(this, "getPageSpyConfig", null);
    _defineProperty(this, "getClient", null);
    this.addListener('atom-detail', SocketStoreBase.handleResolveAtom);
    this.addListener('atom-getter', SocketStoreBase.handleAtomPropertyGetter);
    this.addListener('debugger-online', this.handleFlushBuffer);
  }
  async init(url) {
    try {
      var _this$socketWrapper, _this$socketWrapper2, _this$socketWrapper3, _this$socketWrapper4, _this$socketWrapper5;
      if (!url) {
        throw Error('WebSocket url cannot be empty');
      }
      this.socketWrapper.clearListeners();
      // close existing connection
      if (this.socketWrapper.getState() === SocketState.OPEN) {
        // make sure the existing connection closed.
        // we need to register new handlers immediately.
        await new Promise(resolve => {
          this.socketWrapper.onClose(() => {
            this.socketWrapper.clearListeners();
            resolve();
          });
          this.socketWrapper.close();
        });
      }
      (_this$socketWrapper = this.socketWrapper) === null || _this$socketWrapper === void 0 || _this$socketWrapper.onOpen(() => {
        this.connectOnline();
      });
      // Strictly, the onMessage should be called after onOpen. But for some platform(alipay,)
      // this may cause some message losing.
      (_this$socketWrapper2 = this.socketWrapper) === null || _this$socketWrapper2 === void 0 || _this$socketWrapper2.onMessage(evt => {
        this.handleMessage(evt);
      });
      (_this$socketWrapper3 = this.socketWrapper) === null || _this$socketWrapper3 === void 0 || _this$socketWrapper3.onClose(() => {
        this.connectOffline();
      });
      (_this$socketWrapper4 = this.socketWrapper) === null || _this$socketWrapper4 === void 0 || _this$socketWrapper4.onError(() => {
        // we treat on error the same with on close.
        this.connectOffline();
      });
      this.socketUrl = url;
      (_this$socketWrapper5 = this.socketWrapper) === null || _this$socketWrapper5 === void 0 || _this$socketWrapper5.init(url);
    } catch (e) {
      psLog.error(e instanceof Error ? e.message : String(e));
    }
  }
  addListener(type, fn) {
    /* c8 ignore next 3 */
    if (!this.events[type]) {
      this.events[type] = [];
    }
    this.events[type].push(fn);
  }
  removeListener(type, fn) {
    /* c8 ignore next 3 */
    const fns = this.events[type] || [];
    const index = fns.indexOf(fn);
    if (index > -1) {
      fns.splice(index, 1);
    }
  }
  broadcastMessage(msg) {
    let noCache = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
    const message = makeBroadcastMessage(msg);
    this.send(message, noCache);
  }
  close() {
    var _this$socketWrapper6;
    this.connectable = false;
    this.clearPing();
    if (this.retryTimer) {
      clearTimeout(this.retryTimer);
      this.retryTimer = null;
    }
    (_this$socketWrapper6 = this.socketWrapper) === null || _this$socketWrapper6 === void 0 || _this$socketWrapper6.close();
    this.messages = [];
    this.messageHead = 0;
    Object.entries(this.events).forEach(_ref2 => {
      let [evt, fns] = _ref2;
      // 这三个事件的生命周期跟随 socketStore
      if (['atom-detail', 'atom-getter', 'debugger-online'].includes(evt)) {
        return;
      }
      fns.splice(0);
    });
  }
  connectOnline() {
    this.retryInterval = SOCKET_CONFIG.INITIAL_RETRY_INTERVAL_MS;
    this.updateRoomInfo();
    this.ping();
  }
  connectOffline() {
    this.socketConnection = null;
    this.debuggerConnection = null;
    this.clearPing();
    if (this.retryTimer) {
      clearTimeout(this.retryTimer);
    }
    if (!this.connectable) return;
    this.retryTimer = setTimeout(() => {
      if (this.retryInterval < MAX_RETRY_INTERVAL) {
        this.retryInterval *= SOCKET_CONFIG.RETRY_INTERVAL_MULTIPLIER;
      }
      this.retryTimer = null;
      this.tryReconnect();
    }, this.retryInterval);
  }
  tryReconnect() {
    this.init(this.socketUrl);
  }
  ping() {
    if (this.pingTimer) {
      clearTimeout(this.pingTimer);
    }
    if (this.pongTimer) {
      clearTimeout(this.pongTimer);
    }
    /* c8 ignore start */
    this.pingTimer = setTimeout(() => {
      this.send({
        type: 'ping',
        content: null
      });
      this.pingTimer = null;
      this.pongTimer = setTimeout(() => {
        // lost connection
        this.connectOffline();
        this.pongTimer = null;
      }, SOCKET_CONFIG.HEARTBEAT_INTERVAL_MS);
    }, SOCKET_CONFIG.HEARTBEAT_INTERVAL_MS);
    /* c8 ignore stop */
  }
  clearPing() {
    if (this.pingTimer) {
      clearTimeout(this.pingTimer);
      this.pingTimer = null;
    }
    if (this.pongTimer) {
      clearTimeout(this.pongTimer);
      this.pongTimer = null;
    }
  }
  handlePong() {
    if (this.pongTimer) {
      clearTimeout(this.pongTimer);
      this.pongTimer = null;
    }
    this.ping();
  }
  // get the data which we expected from nested structure of the message
  handleMessage(evt) {
    var _this$socketConnectio;
    const filteredEvent = SocketStoreBase.messageFilters.reduce((currentEvent, filter) => {
      if (!SocketStoreBase.isSocketMessageEvent(currentEvent)) {
        return currentEvent;
      }
      return filter(currentEvent);
    }, evt);
    if (!SocketStoreBase.isSocketMessageEvent(filteredEvent)) {
      psLog.warn('Failed to parse message, invalid message event received.');
      return;
    }
    const {
      data: rawData
    } = filteredEvent;
    if (typeof rawData !== 'string') {
      psLog.warn('Failed to parse message, expected string data.');
      return;
    }
    const {
      CONNECT,
      MESSAGE,
      ERROR,
      JOIN,
      PING,
      PONG,
      LEAVE,
      CLOSE,
      BROADCAST
    } = SERVER_MESSAGE_TYPE;
    let result;
    try {
      result = JSON.parse(rawData);
    } catch (e) {
      psLog.warn('Failed to parse message, malformed data received.');
      return;
    }
    const {
      type
    } = result;
    switch (type) {
      case CONNECT:
        const {
          selfConnection,
          roomConnections
        } = result.content;
        this.socketConnection = selfConnection;
        this.debuggerConnection = roomConnections.find(i => i.userId === 'Debugger') || null;
        break;
      case JOIN:
      case LEAVE:
        const {
          connection
        } = result.content;
        if (connection.userId === 'Debugger') {
          if (type === JOIN) {
            this.debuggerConnection = connection;
            // once connected, send client info
            this.sendClientInfo();
          } else {
            this.debuggerConnection = null;
          }
        }
        break;
      case MESSAGE:
        const {
          data,
          from,
          to
        } = result.content;
        if (to.address === ((_this$socketConnectio = this.socketConnection) === null || _this$socketConnectio === void 0 ? void 0 : _this$socketConnectio.address) && SocketStoreBase.isInteractiveType(data.type)) {
          this.dispatchEvent(data.type, {
            source: data,
            from,
            to
          });
        }
        break;
      case CLOSE:
      case ERROR:
        this.connectOffline();
        break;
      /* c8 ignore stop */
    }
    // whatever the type is, we should handle pong
    this.handlePong();
  }
  dispatchEvent(type, data) {
    var _this$events$type;
    if (['public-data'].includes(type)) {
      this.events['public-data'].forEach(fn => {
        fn(data);
      });
      return;
    }
    (_this$events$type = this.events[type]) === null || _this$events$type === void 0 || _this$events$type.forEach(fn => {
      fn.call(this, data, d => {
        this.unicastMessage(d, data.from);
      });
    });
  }
  unicastMessage(msg, to) {
    const message = makeUnicastMessage(msg, this.socketConnection, to);
    this.send(message);
  }
  handleFlushBuffer(message) {
    const {
      latestId
    } = message.source.data;
    const msgIndex = this.messages.findIndex((i, idx) => idx >= this.messageHead && i.content.data.data.id === latestId);
    /* c8 ignore start */
    this.messages.slice(msgIndex + 1).forEach(msg => {
      const data = {
        type: MESSAGE,
        content: {
          data: msg.content.data,
          from: this.socketConnection,
          to: message.from
        }
      };
      this.send(data, true);
    });
    /* c8 ignore stop */
  }
  static handleResolveAtom(_ref3, reply) {
    let {
      source
    } = _ref3;
    const {
      type,
      data
    } = source;
    if (type === 'atom-detail') {
      const atomData = atom.get(data) || {};
      const msg = makeMessage("atom-detail-".concat(data), atomData, false);
      reply(msg);
    }
  }
  static handleAtomPropertyGetter(_ref4, reply) {
    let {
      source
    } = _ref4;
    const {
      type,
      data
    } = source;
    if (type === 'atom-getter') {
      const {
        id,
        parentId,
        key,
        instanceId
      } = data;
      const instance = atom.getOrigin(instanceId);
      const current = atom.getOrigin(parentId);
      let value = {};
      /* c8 ignore start */
      if (instance && current) {
        var _Object$getOwnPropert;
        value = (_Object$getOwnPropert = Object.getOwnPropertyDescriptor(current, key)) === null || _Object$getOwnPropert === void 0 || (_Object$getOwnPropert = _Object$getOwnPropert.get) === null || _Object$getOwnPropert === void 0 ? void 0 : _Object$getOwnPropert.call(instance);
      } else {
        value = new Error('Getter computed failed');
      }
      /* c8 ignore stop */
      const msg = makeMessage("atom-getter-".concat(id), atom.transformToAtom(value));
      reply(msg);
    }
  }
  send(msg) {
    let noCache = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
    const sendable = this.checkIfSend(msg);
    if (sendable) {
      /* c8 ignore start */
      try {
        var _this$socketWrapper7;
        const pkMsg = msg;
        pkMsg.createdAt = Date.now();
        pkMsg.requestId = getRandomId();
        const dataString = stringifyData(pkMsg);
        (_this$socketWrapper7 = this.socketWrapper) === null || _this$socketWrapper7 === void 0 || _this$socketWrapper7.send(dataString);
      } catch (e) {
        psLog.error("Incompatible: ".concat(e instanceof Error ? e.message : String(e)));
        this.connectOffline();
      }
      /* c8 ignore stop */
    }
    const cacheable = this.checkIfCache(msg, noCache);
    if (cacheable) {
      // FIFO eviction: when buffer is full, advance the head pointer
      if (this.messageCapacity !== 0 && this.messages.length - this.messageHead >= this.messageCapacity) {
        this.messageHead += 1;
        // Compact the array periodically to prevent unbounded growth
        // Once half the array is unused, slice it off
        if (this.messageHead > this.messageCapacity) {
          this.messages = this.messages.slice(this.messageHead);
          this.messageHead = 0;
        }
      }
      this.messages.push(msg);
    }
  }
  checkIfSend(msg) {
    if (this.socketWrapper.getState() !== SocketState.OPEN) return false;
    if ([UPDATE_ROOM_INFO, PING].includes(msg.type)) {
      return true;
    }
    if (!this.debuggerConnection) return false;
    return true;
  }
  checkIfCache(msg) {
    let noCache = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
    if (this.isOffline || noCache) return false;
    if ([MESSAGE, PING].includes(msg.type)) {
      return false;
    }
    return true;
  }
  sendClientInfo() {
    var _this$getClient2;
    const clientInfo = (_this$getClient2 = this.getClient) === null || _this$getClient2 === void 0 ? void 0 : _this$getClient2.call(this).makeClientInfoMsg();
    this.broadcastMessage({
      role: 'client',
      type: 'client-info',
      data: clientInfo
    }, true);
  }
  static isSocketMessageEvent(value) {
    return typeof value === 'object' && value !== null && 'data' in value;
  }
  static isInteractiveType(type) {
    return type === 'debug' || type === 'refresh' || type === 'atom-detail' || type.startsWith('atom-detail-') || type === 'atom-getter' || type.startsWith('atom-getter-') || type === 'debugger-online' || type === 'database-pagination';
  }
}
_defineProperty(SocketStoreBase, "messageFilters", []);

isCN() ? 'zh' : 'en';

const joinQuery = args => {
  // 这里保留原始值,不额外 encode,调用方负责处理需要转义的字段。
  const arr = [];
  Object.entries(args).forEach(_ref => {
    let [k, v] = _ref;
    arr.push("".concat(k, "=").concat(v));
  });
  return arr.join('&');
};
/** 从 Lynx/JS 运行时的词法全局变量中安全读取指定能力。 */
const getLynxGlobalBinding = key => {
  try {
    if (key === 'lynx' && typeof lynx !== 'undefined') return lynx;
    if (key === 'NativeModules' && typeof NativeModules !== 'undefined') {
      return NativeModules;
    }
    if (key === 'SystemInfo' && typeof SystemInfo !== 'undefined') {
      return SystemInfo;
    }
    if (key === 'console' && typeof console !== 'undefined') return console;
    if (key === 'fetch' && typeof fetch !== 'undefined') return fetch;
    if (key === 'Request' && typeof Request !== 'undefined') return Request;
    if (key === 'Headers' && typeof Headers !== 'undefined') return Headers;
    if (key === 'Response' && typeof Response !== 'undefined') return Response;
    if (key === 'Blob' && typeof Blob !== 'undefined') return Blob;
    if (key === 'URL' && typeof URL !== 'undefined') return URL;
    if (key === 'XMLHttpRequest' && typeof XMLHttpRequest !== 'undefined') {
      return XMLHttpRequest;
    }
  } catch {
    // ignored
  }
  return undefined;
};
/** 将 Lynx 常用全局能力补齐到统一 globalObject,方便其他模块按同一入口读取。 */
const mergeLynxGlobalBindings = globalObject => {
  const keys = ['lynx', 'NativeModules', 'SystemInfo', 'console', 'fetch', 'Request', 'Headers', 'Response', 'Blob', 'URL', 'XMLHttpRequest'];
  keys.forEach(key => {
    const binding = getLynxGlobalBinding(key);
    if (binding && !globalObject[key]) {
      globalObject[key] = binding;
    }
  });
};
// 某些平台没有完整 global 对象,允许业务方手动注入运行时全局对象。
let customGlobal = {};
// 获取合并后的全局上下文,并补齐 Lynx 特有的全局能力。
const getGlobal = () => {
  let foundGlobal = {};
  if (typeof globalThis === 'object' && Object.keys(globalThis).length > 1) {
    foundGlobal = globalThis;
  } else if (typeof global === 'object' && typeof global !== 'undefined' && Object.keys(global).length > 1) {
    foundGlobal = global;
  }
  if (customGlobal) {
    Object.assign(foundGlobal, customGlobal);
  }
  mergeLynxGlobalBindings(foundGlobal);
  return foundGlobal;
};

/** 宿主侧需要注册的 Lynx 原生 WebSocket 模块名。 */
const NATIVE_MODULE_NAME = 'LynxNativeWebSocketModule';
const MISSING_NATIVE_MODULE_ERROR = 'NativeModules.LynxNativeWebSocketModule or constructable globalThis.WebSocket is required for PageSpy websocket in Lynx runtime';
let socketIdSeed = 0;
/** 为每个原生 WebSocket 连接生成唯一 ID,便于轮询事件时区分连接。 */
const createSocketId = () => {
  socketIdSeed += 1;
  return "page-spy-lynx-ws-".concat(Date.now(), "-").concat(socketIdSeed);
};
/** 获取宿主注入的原生 WebSocket 模块,并校验必要方法是否存在。 */
const getNativeWebSocketModule = () => {
  var _getGlobal$NativeModu;
  const nativeModule = (_getGlobal$NativeModu = getGlobal().NativeModules) === null || _getGlobal$NativeModu === void 0 ? void 0 : _getGlobal$NativeModu[NATIVE_MODULE_NAME];
  if (nativeModule && typeof nativeModule.connect === 'function' && typeof nativeModule.send === 'function' && typeof nativeModule.close === 'function' && typeof nativeModule.drainEvents === 'function') {
    return nativeModule;
  }
  return null;
};
/** 强制获取原生 WebSocket 模块,不存在时抛出统一错误。 */
const assertNativeWebSocketModule = () => {
  const nativeModule = getNativeWebSocketModule();
  if (!nativeModule) {
    throw Error(MISSING_NATIVE_MODULE_ERROR);
  }
  return nativeModule;
};
/** 判断 WebSocket 构造器是否可被 new,用于兼容非标准运行时对象。 */
const isConstructableWebSocket$1 = WebSocketCtor => {
  if (typeof WebSocketCtor !== 'function') {
    return false;
  }
  try {
    Reflect.construct(String, [], WebSocketCtor);
    return true;
  } catch (e) {
    return false;
  }
};
/** 判断当前运行时是否提供可直接使用的 WebSocket。 */
const hasRuntimeWebSocket = () => {
  return isConstructableWebSocket$1(getGlobal().WebSocket);
};
/** 校验当前运行时至少存在原生模块或标准 WebSocket 能力。 */
const assertRuntimeWebSocket = () => {
  if (!getNativeWebSocketModule() && !hasRuntimeWebSocket()) {
    throw Error(MISSING_NATIVE_MODULE_ERROR);
  }
};
const NATIVE_EVENT_CONNECTING_POLL_INTERVAL = 50;
const NATIVE_EVENT_OPEN_POLL_INTERVAL = 250;
const ANDROID_OPEN_TERMINAL_GRACE_PERIOD = 1000;
const ANDROID_TERMINAL_CONFIRM_DELAY = 300;
/** 根据 Lynx 系统信息判断是否为 Android,用于处理 Android 早期终止事件抖动。 */
const isAndroidRuntime = () => {
  var _globalObject$SystemI, _globalObject$lynx;
  const globalObject = getGlobal();
  const platform = String(((_globalObject$SystemI = globalObject.SystemInfo) === null || _globalObject$SystemI === void 0 ? void 0 : _globalObject$SystemI.platform) || ((_globalObject$lynx = globalObject.lynx) === null || _globalObject$lynx === void 0 || (_globalObject$lynx = _globalObject$lynx.__globalProps) === null || _globalObject$lynx === void 0 ? void 0 : _globalObject$lynx.platform) || '').toLowerCase();
  return platform.includes('android');
};
/** 校验原生侧返回的数据是否为 WebSocket 事件。 */
const isNativeWebSocketEvent = value => {
  return value && typeof value === 'object' && typeof value.type === 'string' && typeof value.socketId === 'string';
};
/** 将原生模块可能返回的数组、对象、JSON 字符串等格式统一成事件数组。 */
const normalizeNativeEvents = function (payload) {
  let extraPayloads = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  const allPayloads = [payload, ...extraPayloads];
  return allPayloads.reduce((events, item) => {
    if (typeof item === 'string') {
      try {
        events.push(...normalizeNativeEvents(JSON.parse(item)));
      } catch (e) {
        // 忽略格式错误的原生 payload,继续轮询 socket 事件。
      }
      return events;
    }
    if (Array.isArray(item)) {
      events.push(...item.filter(isNativeWebSocketEvent));
      return events;
    }
    if (item && typeof item === 'object' && 'events' in item) {
      const wrappedEvents = item.events;
      if (Array.isArray(wrappedEvents)) {
        events.push(...wrappedEvents.filter(isNativeWebSocketEvent));
      }
      return events;
    }
    if (isNativeWebSocketEvent(item)) {
      events.push(item);
    }
    return events;
  }, []);
};
/** 适配 PageSpy SocketWrapper,在 Lynx 中优先使用原生 WebSocket,必要时回退到全局 WebSocket。 */
class LynxWebSocketWrapper extends SocketWrapper {
  constructor() {
    super(...arguments);
    /** 原生连接 ID;使用标准 WebSocket 时为空。 */
    _defineProperty(this, "socketId", null);
    /** 标准 WebSocket 实例;使用原生模块时为空。 */
    _defineProperty(this, "socketInstance", null);
    _defineProperty(this, "readyState", SocketState.CLOSED);
    _defineProperty(this, "nativeEventPollTimer", null);
    _defineProperty(this, "nativeTerminalConfirmTimer", null);
    _defineProperty(this, "nativeOpenedAt", 0);
  }
  /** 初始化连接,优先走 NativeModules.LynxNativeWebSocketModule。 */
  init(url) {
    const nativeModule = getNativeWebSocketModule();
    if (!nativeModule) {
      this.initRuntimeWebSocket(url);
      return;
    }
    const socketId = createSocketId();
    this.socketId = socketId;
    this.socketInstance = null;
    this.readyState = SocketState.CONNECTING;
    nativeModule.connect(socketId, url);
    this.startNativeEventPolling();
  }
  /** 发送数据,自动区分标准 WebSocket 与原生模块通道。 */
  send(data) {
    if (this.socketInstance) {
      this.socketInstance.send(stringifyData(data));
      return;
    }
    if (!this.socketId || this.readyState !== SocketState.OPEN) return;
    assertNativeWebSocketModule().send(this.socketId, stringifyData(data));
  }
  /** 关闭当前连接,并更新内部 readyState。 */
  close() {
    if (this.socketInstance) {
      this.socketInstance.close();
      return;
    }
    if (!this.socketId || this.readyState === SocketState.CLOSED) return;
    this.readyState = SocketState.CLOSING;
    assertNativeWebSocketModule().close(this.socketId);
  }
  /** 获取当前连接状态,标准 WebSocket 直接读取实例 readyState。 */
  getState() {
    if (this.socketInstance) {
      return this.socketInstance.readyState;
    }
    return this.readyState;
  }
  /** 使用运行时自带 WebSocket 建立连接。 */
  initRuntimeWebSocket(url) {
    this.clearNativeEventPolling();
    const WebSocketCtor = getGlobal().WebSocket;
    if (!isConstructableWebSocket$1(WebSocketCtor)) {
      throw Error(MISSING_NATIVE_MODULE_ERROR);
    }
    this.socketId = null;
    this.readyState = SocketState.CONNECTING;
    this.socketInstance = new WebSocketCtor(url);
    const eventNames = ['open', 'close', 'error', 'message'];
    eventNames.forEach(eventName => {
      // 将标准 WebSocket 事件转发到 SocketWrapper 的事件队列。
      this.socketInstance.addEventListener(eventName, data => {
        if (eventName === 'open') {
          this.readyState = SocketState.OPEN;
        } else if (eventName === 'close' || eventName === 'error') {
          this.readyState = SocketState.CLOSED;
        }
        this.emit(eventName, data);
      });
    });
  }
  /** 启动原生事件轮询,连接中高频轮询,连接后降低轮询频率。 */
  startNativeEventPolling() {
    var _this = this;
    this.clearNativeEventPolling();
    const poll = () => {
      if (!this.socketId || this.socketInstance) return;
      const {
        socketId
      } = this;
      assertNativeWebSocketModule().drainEvents(socketId, function (payload) {
        for (var _len = arguments.length, rest = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
          rest[_key - 1] = arguments[_key];
        }
        const events = normalizeNativeEvents(payload, rest);
        events.forEach(event => {
          _this.handleNativeEvent(event);
        });
        if (_this.socketId === socketId && _this.readyState !== SocketState.CLOSED) {
          const interval = _this.readyState === SocketState.OPEN ? NATIVE_EVENT_OPEN_POLL_INTERVAL : NATIVE_EVENT_CONNECTING_POLL_INTERVAL;
          _this.nativeEventPollTimer = setTimeout(poll, interval);
        }
      });
    };
    poll();
  }
  /** 清理原生事件轮询定时器。 */
  clearNativeEventPolling() {
    if (this.nativeEventPollTimer) {
      clearTimeout(this.nativeEventPollTimer);
      this.nativeEventPollTimer = null;
    }
  }
  /** 清理 Android 终止事件确认定时器。 */
  clearNativeTerminalConfirm() {
    if (this.nativeTerminalConfirmTimer) {
      clearTimeout(this.nativeTerminalConfirmTimer);
      this.nativeTerminalConfirmTimer = null;
    }
  }
  /** 处理原生 WebSocket 事件,并转成 SocketWrapper 标准事件。 */
  handleNativeEvent(event) {
    if (!this.socketId || event.socketId !== this.socketId) return;
    if (event.type === 'open') {
      this.clearNativeTerminalConfirm();
      this.nativeOpenedAt = Date.now();
      this.readyState = SocketState.OPEN;
      this.emit('open', {});
      return;
    }
    if (event.type === 'message') {
      this.clearNativeTerminalConfirm();
      this.emit('message', {
        data: event.data
      });
      return;
    }
    if (event.type === 'close') {
      this.handleNativeTerminalEvent(event);
      return;
    }
    this.handleNativeTerminalEvent(event);
  }
  /** Android 刚 open 后可能立即上报误判终止事件,这里延迟确认一次。 */
  handleNativeTerminalEvent(event) {
    if (isAndroidRuntime() && this.readyState === SocketState.OPEN && (event.type === 'error' || event.code == null || event.code === 1000) && Date.now() - this.nativeOpenedAt < ANDROID_OPEN_TERMINAL_GRACE_PERIOD) {
      this.clearNativeTerminalConfirm();
      this.nativeTerminalConfirmTimer = setTimeout(() => {
        this.applyNativeTerminalEvent(event);
      }, ANDROID_TERMINAL_CONFIRM_DELAY);
      return;
    }
    this.applyNativeTerminalEvent(event);
  }
  /** 真正应用 close/error 终止事件并释放原生连接状态。 */
  applyNativeTerminalEvent(event) {
    this.readyState = SocketState.CLOSED;
    if (event.type === 'close') {
      var _event$code;
      this.emit('close', {
        code: (_event$code = event.code) !== null && _event$code !== void 0 ? _event$code : 1000,
        reason: event.reason || ''
      });
    } else {
      this.emit('error', event.message || 'Native websocket error');
    }
    this.clearNativeEventPolling();
    this.clearNativeTerminalConfirm();
    this.socketId = null;
  }
}
/** PageSpy WebSocket Store 的 Lynx 版本,使用上方 wrapper 接管连接实现。 */
class LynxWebSocketStore extends SocketStoreBase {
  // 父类抽象方法要求实例方法,这里保持空实现。
  // eslint-disable-next-line class-methods-use-this
  onOffline() {}
  // eslint-disable-next-line @typescript-eslint/no-useless-constructor
  constructor() {
    super();
    // WebSocket 连接包装实例。
    _defineProperty(this, "socketWrapper", new LynxWebSocketWrapper());
  }
  /** 初始化前先确认当前 Lynx 运行时具备 WebSocket 能力。 */
  init(url) {
    assertRuntimeWebSocket();
    return super.init(url);
  }
}
const socketStore = new LynxWebSocketStore();

/** 原生侧可直接调用的全局回调名。 */
const NATIVE_CONSOLE_GLOBAL = '__PAGE_SPY_LYNX_CONSOLE__';
const NATIVE_CONSOLE_EVENT = 'page-spy-console';
const NATIVE_CONSOLE_MODULE = 'PageSpyConsoleModule';
const NATIVE_CONSOLE_POLL_INTERVAL = 250;
/** 收集当前运行时中所有可能的 console 对象,避免只代理到其中一个宿主对象。 */
const getConsoleBindings = () => {
  var _globalObject$lynx;
  const globalObject = getGlobal();
  const bindings = [];
  const addBinding = (target, host, key) => {
    if (!target || typeof target !== 'object') return;
    if (bindings.some(item => item.target === target)) return;
    bindings.push({
      target: target,
      host,
      key
    });
  };
  addBinding(globalObject.console, globalObject, 'console');
  addBinding((_globalObject$lynx = globalObject.lynx) === null || _globalObject$lynx === void 0 ? void 0 : _globalObject$lynx.console, globalObject.lynx, 'console');
  if (typeof globalThis === 'object') {
    addBinding(globalThis.console, globalThis, 'console');
  }
  try {
    if (typeof console !== 'undefined') {
      addBinding(console);
    }
  } catch {
    // ignored
  }
  return bindings;
};
/** 尽量以 defineProperty 写入 console 方法,失败时回退到普通赋值。 */
const setConsoleMethod = (consoleTarget, method, value) => {
  try {
    Object.defineProperty(consoleTarget, method, {
      value,
      configurable: true,
      enumerable: true,
      writable: true
    });
  } catch {
    // Lynx iOS/Android 的 console 方法可能是宿主定义属性,defineProperty 可能失败。
  }
  if (consoleTarget[method] !== value) {
    try {
      consoleTarget[method] = value;
    } catch {
      // ignored
    }
  }
  return consoleTarget[method] === value;
};
/** 当宿主 console 无法直接改写时,创建一个继承原 console 的代理对象。 */
const createConsoleProxy = originConsole => {
  try {
    return Object.create(originConsole);
  } catch {
    return {};
  }
};
/** 将原生侧 console level 统一映射到 PageSpy 支持的日志类型。 */
const getNativeConsoleLevel = value => {
  const level = String(value || '').toLowerCase();
  if (level === 'error') return 'error';
  if (level === 'warn' || level === 'warning') return 'warn';
  if (level === 'info') return 'info';
  if (level === 'debug') return 'debug';
  return 'log';
};
/** 格式化原生调试协议里的参数结构,尽量还原可读值。 */
const formatNativeConsoleArg = value => {
  if (!value || typeof value !== 'object') return value;
  if ('value' in value) return value.value;
  if ('description' in value) return value.description;
  if ('unserializableValue' in value) return value.unserializableValue;
  if ('objectId' in value) {
    return "[".concat(value.subtype || value.type || 'object', "]");
  }
  if ('type' in value) return "[".concat(value.type, "]");
  return value;
};
/** 将原生侧传来的 console payload 解析为 PageSpy console 数据项。 */
const parseNativeConsolePayload = payload => {
  let data = payload;
  if (Array.isArray(data)) {
    // eslint-disable-next-line prefer-destructuring
    data = data[0];
  }
  if (data && typeof data === 'object' && 'detail' in data) {
    data = data.detail;
  }
  if (typeof data === 'string') {
    try {
      data = JSON.parse(data);
    } catch {
      return {
        logType: 'log',
        logs: [data],
        url: ''
      };
    }
  }
  if (!data || typeof data !== 'object') return null;
  const args = Array.isArray(data.args) ? data.args : [data.message || data];
  return {
    logType: getNativeConsoleLevel(data.level || data.type || data.logType || data.method),
    logs: args.map(formatNativeConsoleArg),
    url: data.url || ''
  };
};
/** 统一原生模块返回的单条、数组或包装对象消息。 */
const normalizeNativeConsoleMessages = payload => {
  if (Array.isArray(payload)) return payload;
  if (payload && typeof payload === 'object' && Array.isArray(payload.messages)) {
    return payload.messages;
  }
  if (payload == null) return [];
  return [payload];
};
/** 获取宿主注册的控制台消息原生模块。 */
const getNativeConsoleModule = () => {
  var _getGlobal$NativeModu;
  const nativeModule = (_getGlobal$NativeModu = getGlobal().NativeModules) === null || _getGlobal$NativeModu === void 0 ? void 0 : _getGlobal$NativeModu[NATIVE_CONSOLE_MODULE];
  if (typeof (nativeModule === null || nativeModule === void 0 ? void 0 : nativeModule.drainMessages) === 'function') {
    return nativeModule;
  }
  return null;
};
/** Console 插件:代理 JS console,并接收原生侧 console 日志后转发到 PageSpy。 */
class ConsolePlugin {
  constructor() {
    /** 插件名称。 */
    _defineProperty(this, "name", 'ConsolePlugin');
    /** 保存原始 console 方法,用于插件内部回显和 reset 恢复。 */
    _defineProperty(this, "console", {});
    /** 已被代理的 console 目标列表及其原始方法。 */
    _defineProperty(this, "consoleTargets", []);
    /** 原生 console 桥回调引用,reset 时用于移除。 */
    _defineProperty(this, "nativeConsoleHandler", null);
    /** 标记是否已通过 lynx.add 安装原生事件监听。 */
    _defineProperty(this, "nativeConsoleEventInstalled", false);
    /** 轮询原生 console 模块的定时器。 */
    _defineProperty(this, "nativeConsolePollTimer", null);
    /** 原生模块连续缺失次数,用于延迟打印告警。 */
    _defineProperty(this, "nativeConsoleMissingCount", 0);
    /** 避免重复打印原生模块缺失告警。 */
    _defineProperty(this, "nativeConsoleMissingWarned", false);
    /** 需要代理的 console 方法类型。 */
    _defineProperty(this, "proxyTypes", ['log', 'info', 'error', 'warn', 'debug']);
    _defineProperty(this, "$pageSpyConfig", null);
  }
  /** 插件初始化:注册远程 debug 指令并安装 console 代理。 */
  async onInit(_ref) {
    let {
      config
    } = _ref;
    if (ConsolePlugin.hasInitd) return;
    ConsolePlugin.hasInitd = true;
    socketStore.addListener('debug', ConsolePlugin.handleDebugger);
    this.$pageSpyConfig = config;
    this.init();
    this.initNativeConsoleBridge();
  }
  /** 代理所有可发现的 console 对象,并保留原始方法用于本地输出。 */
  init() {
    const printLog = this.printLog.bind(this);
    const consoleBindings = getConsoleBindings();
    this.consoleTargets = consoleBindings.map(binding => {
      const originals = {};
      this.proxyTypes.forEach(item => {
        originals[item] = binding.target[item] || binding.target.log || (() => {});
      });
      return {
        ...binding,
        originHostValue: binding.host && binding.key ? binding.host[binding.key] : undefined,
        originals
      };
    });
    this.proxyTypes.forEach(item => {
      var _this$consoleTargets$;
      const primaryConsole = (_this$consoleTargets$ = this.consoleTargets[0]) === null || _this$consoleTargets$ === void 0 ? void 0 : _this$consoleTargets$.originals;
      this.console[item] = (primaryConsole === null || primaryConsole === void 0 ? void 0 : primaryConsole[item]) || (() => {});
    });
    this.consoleTargets.forEach(binding => {
      let proxyTarget = binding.target;
      this.proxyTypes.forEach(item => {
        // 代理方法只采集日志;是否回显由 sendLog 的 shouldPrint 控制。
        const proxy = function consoleProxy() {
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          printLog({
            logType: item,
            logs: args,
            url: ''
          });
        };
        const success = setConsoleMethod(proxyTarget, item, proxy);
        if (!success && binding.host && binding.key) {
          proxyTarget = createConsoleProxy(binding.target);
          try {
            binding.host[binding.key] = proxyTarget;
            binding.target = proxyTarget;
          } catch {
            // ignored
          }
          setConsoleMethod(proxyTarget, item, proxy);
        }
      });
    });
  }
  /** 恢复被代理的 console 方法和宿主 console 对象。 */
  reset() {
    this.consoleTargets.forEach(binding => {
      this.proxyTypes.forEach(item => {
        if (binding.originals[item]) {
          setConsoleMethod(binding.target, item, binding.originals[item]);
        }
      });
      if (binding.host && binding.key && binding.originHostValue) {
        try {
          binding.host[binding.key] = binding.originHostValue;
        } catch {
          // ignored
        }
      }
    });
    this.consoleTargets = [];
    this.resetNativeConsoleBridge();
  }
  /** 插件重置入口,恢复代理并清理初始化标记。 */
  onReset() {
    this.reset();
    ConsolePlugin.hasInitd = false;
  }
  /** 安装原生 console 桥:支持全局回调、lynx 事件和 NativeModule 轮询三种路径。 */
  initNativeConsoleBridge() {
    var _this = this;
    const globalObject = getGlobal();
    const handler = function (payload) {
      for (var _len2 = arguments.length, rest = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
        rest[_key2 - 1] = arguments[_key2];
      }
      const nativePayload = rest.length > 0 ? [payload, ...rest] : payload;
      const data = parseNativeConsolePayload(nativePayload);
      if (data) {
        _this.sendLog(data, false);
      }
    };
    this.nativeConsoleHandler = handler;
    globalObject[NATIVE_CONSOLE_GLOBAL] = handler;
    if (typeof globalThis === 'object') {
      globalThis[NATIVE_CONSOLE_GLOBAL] = handler;
    }
    try {
      var _globalObject$lynx2;
      if (typeof ((_globalObject$lynx2 = globalObject.lynx) === null || _globalObject$lynx2 === void 0 ? void 0 : _globalObject$lynx2.add) === 'function') {
        globalObject.lynx.add(NATIVE_CONSOLE_EVENT, handler);
        this.nativeConsoleEventInstalled = true;
      }
    } catch {
      // ignored
    }
    this.startNativeConsolePolling();
  }
  /** 移除原生 console 桥并清理轮询状态。 */
  resetNativeConsoleBridge() {
    const globalObject = getGlobal();
    if (this.nativeConsoleEventInstalled && this.nativeConsoleHandler) {
      try {
        var _globalObject$lynx3, _globalObject$lynx3$r;
        (_globalObject$lynx3 = globalObject.lynx) === null || _globalObject$lynx3 === void 0 || (_globalObject$lynx3$r = _globalObject$lynx3.remove) === null || _globalObject$lynx3$r === void 0 || _globalObject$lynx3$r.call(_globalObject$lynx3, NATIVE_CONSOLE_EVENT, this.nativeConsoleHandler);
      } catch {
        // ignored
      }
    }
    if (globalObject[NATIVE_CONSOLE_GLOBAL] === this.nativeConsoleHandler) {
      delete globalObject[NATIVE_CONSOLE_GLOBAL];
    }
    if (typeof globalThis === 'object' && globalThis[NATIVE_CONSOLE_GLOBAL] === this.nativeConsoleHandler) {
      delete globalThis[NATIVE_CONSOLE_GLOBAL];
    }
    this.nativeConsoleHandler = null;
    this.nativeConsoleEventInstalled = false;
    this.nativeConsoleMissingCount = 0;
    this.nativeConsoleMissingWarned = false;
    if (this.nativeConsolePollTimer) {
      clearTimeout(this.nativeConsolePollTimer);
      this.nativeConsolePollTimer = null;
    }
  }
  /** 轮询原生 console 模块,读取宿主侧缓存的日志消息。 */
  startNativeConsolePolling() {
    var _this2 = this;
    if (this.nativeConsolePollTimer) return;
    const poll = () => {
      const nativeModule = getNativeConsoleModule();
      if (!nativeModule) {
        this.nativeConsoleMissingCount += 1;
        if (this.nativeConsoleMissingCount >= 4 && !this.nativeConsoleMissingWarned) {
          this.nativeConsoleMissingWarned = true;
          psLog.warn('NativeModules.PageSpyConsoleModule is not available; native iOS/Android console messages require registering PageSpyConsoleModule and LynxInspectorConsoleDelegate');
        }
        if (this.nativeConsoleHandler) {
          this.nativeConsolePollTimer = setTimeout(poll, NATIVE_CONSOLE_POLL_INTERVAL);
        } else {
          this.nativeConsolePollTimer = null;
        }
        return;
      }
      this.nativeConsoleMissingCount = 0;
      nativeModule.drainMessages(function (payload) {
        for (var _len3 = arguments.length, rest = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
          rest[_key3 - 1] = arguments[_key3];
        }
        const messages = rest.length ? normalizeNativeConsoleMessages([payload, ...rest]) : normalizeNativeConsoleMessages(payload);
        messages.forEach(message => {
          const data = parseNativeConsolePayload(message);
          if (data) {
            _this2.sendLog(data, false);
          }
        });
        if (_this2.nativeConsoleHandler) {
          _this2.nativeConsolePollTimer = setTimeout(poll, NATIVE_CONSOLE_POLL_INTERVAL);
        } else {
          _this2.nativeConsolePollTimer = null;
        }
      });
    };
    this.nativeConsolePollTimer = setTimeout(poll, 0);
  }
  // 执行远端调试面板传来的表达式,并把原始代码和执行结果回传。
  static handleDebugger(_ref2, reply) {
    let {
      source
    } = _ref2;
    const {
      type,
      data
    } = source;
    if (type === 'debug') {
      const originMsg = makeMessage('console', {
        logType: 'debug-origin',
        logs: [{
          id: getRandomId(),
          type: 'debug-origin',
          value: data
        }]
      });
      reply(originMsg);
      try {
        // eslint-disable-next-line no-new-func, @typescript-eslint/no-implied-eval
        const result = new Function("return ".concat(data))();
        const evalMsg = makeMessage('console', {
          logType: 'debug-eval',
          logs: [atom.transformToAtom(result)]
        });
        reply(evalMsg);
      } catch (err) {
        const errMsg = makeMessage('console', {
          logType: 'error',
          logs: [{
            type: 'error',
            value: err.stack
          }]
        });
        reply(errMsg);
      }
    }
  }
  printLog(data) {
    this.sendLog(data, true);
  }
  /** 发送 console 日志到 PageSpy,并按配置决定是否公开原始值或序列化值。 */
  sendLog(data, shouldPrint) {
    if (data.logs && data.logs.length) {
      var _this$$pageSpyConfig, _this$$pageSpyConfig2;
      const processor = (_this$$pageSpyConfig = this.$pageSpyConfig) === null || _this$$pageSpyConfig === void 0 || (_this$$pageSpyConfig = _this$$pageSpyConfig.dataProcessor) === null || _this$$pageSpyConfig === void 0 ? void 0 : _this$$pageSpyConfig.console;
      if (processor) {
        this.reset();
        const processedByUser = processor(data);
        this.init();
        if (processedByUser === false) return;
      }
      if (shouldPrint) {
        const print = this.console[data.logType] || this.console.log;
        print === null || print === void 0 || print(...data.logs);
      }
      const atomLog = makeMessage('console', {
        ...data,
        time: Date.now(),
        logs: data.logs.map(log => {
          return atom.transformToAtom(log, false);
        })
      });
      socketStore.broadcastMessage(atomLog);
      if (!((_this$$pageSpyConfig2 = this.$pageSpyConfig) !== null && _this$$pageSpyConfig2 !== void 0 && _this$$pageSpyConfig2.serializeData)) {
        socketStore.dispatchEvent('public-data', atomLog);
      } else {
        const serializeLog = {
          ...atomLog,
          data: {
            ...atomLog.data,
            logs: data.logs.map(log => {
              return atom.transformToAtom(log, true);
            })
          }
        };
        socketStore.dispatchEvent('public-data', serializeLog);
      }
    }
  }
}
_defineProperty(ConsolePlugin, "hasInitd", false);

/** Error 插件:捕获未处理异常和 Promise rejection,并复用 console 通道上报。 */
class ErrorPlugin {
  constructor() {
    /** 插件名称。 */
    _defineProperty(this, "name", 'ErrorPlugin');
    /** 原始全局 onerror,reset 时恢复并在捕获后继续调用。 */
    _defineProperty(this, "originOnError", null);
    /** 原始全局 onunhandledrejection,reset 时恢复并在捕获后继续调用。 */
    _defineProperty(this, "originOnUnhandledRejection", null);
    _defineProperty(this, "$pageSpyConfig", null);
    _defineProperty(this, "errorHandlerRef", null);
    _defineProperty(this, "rejectionHandlerRef", null);
  }
  /** 初始化全局错误监听。 */
  onInit(_ref) {
    let {
      config
    } = _ref;
    if (ErrorPlugin.hasInitd) return;
    ErrorPlugin.hasInitd = true;
    this.$pageSpyConfig = config;
    this.onUncaughtError();
    this.onUnhandledRejectionError();
  }
  /** 捕获运行时未处理异常,优先使用 addEventListener,兼容 onerror。 */
  onUncaughtError() {
    const g = getGlobal();
    const handler = error => {
      var _this$originOnError;
      this.errorHandler(error);
      (_this$originOnError = this.originOnError) === null || _this$originOnError === void 0 || _this$originOnError.call(this, error);
    };
    this.errorHandlerRef = handler;
    if (typeof g.addEventListener === 'function') {
      g.addEventListener('error', handler);
      return;
    }
    if ('onerror' in g) {
      this.originOnError = g.onerror || null;
      g.onerror = handler;
    }
  }
  /** 捕获未处理 Promise rejection,兼容事件监听和全局回调两种能力。 */
  onUnhandledRejectionError() {
    const g = getGlobal();
    const handler = event => {
      var _this$originOnUnhandl;
      this.errorHandler((event === null || event === void 0 ? void 0 : event.reason) || event);
      (_this$originOnUnhandl = this.originOnUnhandledRejection) === null || _this$originOnUnhandl === void 0 || _this$originOnUnhandl.call(this, event);
    };
    this.rejectionHandlerRef = handler;
    if (typeof g.addEventListener === 'function') {
      g.addEventListener('unhandledrejection', handler);
      return;
    }
    if ('onunhandledrejection' in g) {
      this.originOnUnhandledRejection = g.onunhandledrejection || null;
      g.onunhandledrejection = handler;
    }
  }
  /** 将不同形态的错误对象整理成 PageSpy console error 消息。 */
  errorHandler(error) {
    if (!ErrorPlugin.hasInitd) {
      return;
    }
    if (error !== null && error !== void 0 && error.message || error !== null && error !== void 0 && error.stack) {
      const errorDetail = formatErrorObj(error);
      this.sendMessage(error.stack || error.message, errorDetail);
    } else if (typeof error === 'string') {
      this.sendMessage(error, null);
    } else {
      const defaultMessage = '[PageSpy] An unknown error occurred and no message or stack trace available';
      this.sendMessage(defaultMessage, error);
    }
  }
  /** 移除全局监听并恢复宿主原有错误处理器。 */
  onReset() {
    if (!ErrorPlugin.hasInitd) {
      return;
    }
    const g = getGlobal();
    if (typeof g.removeEventListener === 'function') {
      if (this.errorHandlerRef) {
        g.removeEventListener('error', this.errorHandlerRef);
      }
      if (this.rejectionHandlerRef) {
        g.removeEventListener('unhandledrejection', this.rejectionHandlerRef);
      }
    }
    if ('onerror' in g) {
      g.onerror = this.originOnError;
    }
    if ('onunhandledrejection' in g) {
      g.onunhandledrejection = this.originOnUnhandledRejection;
    }
    this.errorHandlerRef = null;
    this.rejectionHandlerRef = null;
    ErrorPlugin.hasInitd = false;
  }
  /** 上报错误消息,允许用户 dataProcessor 拦截或加工。 */
  sendMessage(data, errorDetail) {
    var _this$$pageSpyConfig, _this$$pageSpyConfig$;
    const error = {
      logType: 'error',
      logs: [data],
      time: Date.now(),
      url: '',
      errorDetail
    };
    const processedByUser = (_this$$pageSpyConfig = this.$pageSpyConfig) === null || _this$$pageSpyConfig === void 0 || (_this$$pageSpyConfig = _this$$pageSpyConfig.dataProcessor) === null || _this$$pageSpyConfig === void 0 || (_this$$pageSpyConfig$ = _this$$pageSpyConfig.console) === null || _this$$pageSpyConfig$ === void 0 ? void 0 : _this$$pageSpyConfig$.call(_this$$pageSpyConfig, error);
    if (processedByUser === false) return;
    error.logs = error.logs.map(l => atom.transformToAtom(l));
    const message = makeMessage('console', error);
    socketStore.dispatchEvent('public-data', message);
    socketStore.broadcastMessage(message);
  }
}
_defineProperty(ErrorPlugin, "hasInitd", false);

/** Lynx 网络代理基类,统一注入当前包的 socketStore。 */
class LynxNetworkProxyBase extends NetworkProxyBase {
  constructor() {
    super(socketStore);
  }
}

/** 判断当前值是否为 Lynx 运行时里的 FormData。 */
const isLynxFormData = value => {
  return typeof FormData === 'function' && value instanceof FormData;
};
/** 判断当前值是否为 Lynx 运行时里的 Blob。 */
const isLynxBlob$1 = value => {
  return typeof Blob === 'function' && value instanceof Blob;
};
/** 将请求体格式化成调试面板可展示的文本/结构化值。 */
async function getFormattedBody(body) {
  if (!body) {
    return null;
  }
  if (isLynxFormData(body)) {
    return formatEntries(body.entries());
  }
  if (isLynxBlob$1(body)) {
    return '[object Blob]';
  }
  if (isTypedArray(body)) {
    return '[object TypedArray]';
  }
  if (isString(body)) {
    return body;
  }
  return toStringTag(body);
}
/** 根据请求体推断 Content-Type,用于补齐调试面板里的请求头展示。 */
function getContentType(data) {
  if (!data) return null;
  if (isLynxFormData(data)) {
    return 'multipart/form-data';
  }
  if (isLynxBlob$1(data)) {
    return data.type;
  }
  return 'text/plain;charset=UTF-8';
}
const CONTENT_TYPE_HEADER = 'Content-Type';
/** 如果调用方未设置 Content-Type,则根据 body 类型补一个展示用请求头。 */
function addContentTypeHeader(headers, body) {
  if (!body) return headers;
  const bodyContentType = getContentType(body);
  if (!bodyContentType) return headers;
  const headerTuple = [CONTENT_TYPE_HEADER, bodyContentType];
  if (!headers) {
    return [headerTuple];
  }
  for (let i = 0; i < headers.length; i++) {
    const [key] = headers[i];
    if (key.toUpperCase() === CONTENT_TYPE_HEADER.toUpperCase()) {
      return headers;
    }
  }
  return [...headers, headerTuple];
}

const isLynxBlob = value => {
  const BlobCtor = getGlobal().Blob;
  return typeof BlobCtor === 'function' && value instanceof BlobCtor;
};
/**
 * React native use whatwg-fetch to polyfill fetch API based on xhr, so it's
 * no need to proxy fetch since we already proxy xhr.
 * But there is one problem: whatwg-fetch will set responseType of xhr to 'blob',
 * which will make our response logic confused.
 *
 * The solution is: we proxy the fetch function and mark fetch-originated XHR
 * requests in memory, then still handle all proxy logic in fetch. Older SDK
 * builds used 'page-spy-is-fetch' as a request header, so XHR keeps recognizing
 * it for compatibility, but fetch must not add that header to outgoing requests
 * because it can trigger CORS preflight failures.
 */
const IS_FETCH_HEADER = 'page-spy-is-fetch';
let fetchProxyRequestDepth = 0;
/** 标记当前正在由 fetch 代理触发底层 XHR,避免重复采集。 */
const markFetchProxyRequestStart = () => {
  fetchProxyRequestDepth += 1;
};
/** 结束 fetch 触发 XHR 的标记,使用深度计数兼容嵌套调用。 */
const markFetchProxyRequestEnd = () => {
  fetchProxyRequestDepth = Math.max(0, fetchProxyRequestDepth - 1);
};
const isFetchProxyRequestInFlight = () => fetchProxyRequestDepth > 0;
/** XHR 网络代理:改写 open/send/setRequestHeader 采集请求生命周期。 */
class XhrProxy extends LynxNetworkProxyBase {
  constructor() {
    super();
    /** 原始 open 方法,reset 时恢复。 */
    _defineProperty(this, "xhrOpen", null);
    /** 原始 send 方法,reset 时恢复。 */
    _defineProperty(this, "xhrSend", null);
    /** 原始 setRequestHeader 方法,reset 时恢复。 */
    _defineProperty(this, "xhrSetRequestHeader", null);
    this.initProxyHandler();
  }
  /** 安装 XHR 原型代理,按 readyState 推送请求状态。 */
  initProxyHandler() {
    var _XHR$prototype, _XHR$prototype2, _XHR$prototype3;
    const XHR = getGlobal().XMLHttpRequest;
    if (typeof XHR !== 'function' || !((_XHR$prototype = XHR.prototype) !== null && _XHR$prototype !== void 0 && _XHR$prototype.open) || !((_XHR$prototype2 = XHR.prototype) !== null && _XHR$prototype2 !== void 0 && _XHR$prototype2.send) || !((_XHR$prototype3 = XHR.prototype) !== null && _XHR$prototype3 !== void 0 && _XHR$prototype3.setRequestHeader)) {
      return;
    }
    const that = this;
    const {
      open,
      send,
      setRequestHeader
    } = XHR.prototype;
    this.xhrOpen = open;
    this.xhrSend = send;
    this.xhrSetRequestHeader = setRequestHeader;
    XHR.prototype.open = function () {
      // open 阶段创建请求记录并缓存方法、URL,真正发送信息在 send 阶段补齐。
      const XMLReq = this;
      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }
      const method = args[0];
      const url = args[1];
      const id = getRandomId();
      that.createRequest(id);
      this.pageSpyRequestId = id;
      this.pageSpyRequestMethod = method;
      this.pageSpyRequestUrl = url;
      if (isFetchProxyRequestInFlight()) {
        // 由 fetch 代理触发的底层 XHR 只保留 fetch 侧记录。
        this.isFetch = true;
        that.removeRequest(id);
      }
      return open.apply(XMLReq, args);
    };
    XHR.prototype.setRequestHeader = function (key, value) {
      // 兼容旧版本:该 header 表示请求来自上层 fetch,不需要 XHR 代理重复采集。
      if (key === IS_FETCH_HEADER) {
        this.isFetch = true;
        that.removeRequest(this.pageSpyRequestId);
        return;
      }
      const req = that.getRequest(this.pageSpyRequestId);
      if (req) {
        if (!req.requestHeader) {
          req.requestHeader = [];
        }
        req.requestHeader.push([key, value]);
      } /* c8 ignore start */else if (!this.isFetch) {
        psLog.warn("The request object is not found on XMLHttpRequest's setRequestHeader event");
      } /* c8 ignore stop */
      setRequestHeader.apply(this, [key, value]);
    };
    XHR.prototype.send = function (body) {
      const XMLReq = this;
      const {
        pageSpyRequestId,
        pageSpyRequestMethod = 'GET',
        pageSpyRequestUrl = ''
      } = XMLReq;
      const req = that.getRequest(pageSpyRequestId);
      /** readystatechange 监听放在 send 阶段,避免 fetch 触发的 XHR 在 open 后被忽略,
       * 却已经提前触发 readystatechange,导致调试面板出现没有后续响应的空请求行。
       */
      XMLReq.addEventListener('readystatechange', async () => {
        if (req) {
          req.readyState = XMLReq.readyState;
          switch (XMLReq.readyState) {
            /* c8 ignore next */
            case XMLReq.UNSENT:
            case XMLReq.OPENED:
              req.status = XMLReq.status;
              req.statusText = 'Pending';
              if (!req.startTime) {
                req.startTime = Date.now();
              }
              break;
            // 收到响应头。
            case XMLReq.HEADERS_RECEIVED:
              req.status = XMLReq.status;
              req.statusText = 'Loading';
              const header = XMLReq.getAllResponseHeaders() || '';
              const headerArr = header.trim().split(/[\r\n]+/);
              req.responseHeader = headerArr.reduce((acc, cur) => {
                const [headerKey, ...parts] = cur.split(': ');
                acc.push([headerKey, parts.join(': ')]);
                return acc;
              }, []);
              break;
            // 响应体加载中。
            case XMLReq.LOADING:
              req.status = XMLReq.status;
              req.statusText = 'Loading';
              break;
            // 请求完成,格式化响应体并上报最终状态。
            case XMLReq.DONE:
              req.status = XMLReq.status;
              req.statusText = 'Done';
              req.endTime = Date.now();
              req.costTime = req.endTime - (req.startTime || req.endTime);
              let {
                responseType
              } = XMLReq;
              if (!responseType || XMLReq.isFetch && responseType === 'blob') {
                const contentType = XMLReq.getResponseHeader('content-type');
                if (contentType) {
                  if (contentType.includes('application/json')) {
                    responseType = 'json';
                  }
                  if (contentType.includes('text/html') || contentType.includes('text/plain')) {
                    responseType = 'text';
                  }
                }
              }
              if (!responseType) {
                responseType = 'blob';
              }
              req.responseType = responseType;
              const formatResult = await that.formatResponse(XMLReq, responseType);
              getObjectKeys(formatResult).forEach(key => {
                req[key] = formatResult[key];
              });
              break;
            /* c8 ignore next 4 */
            default:
              req.status = XMLReq.status;
              req.statusText = 'Unknown';
              break;
          }
          that.sendRequestItem(XMLReq.pageSpyRequestId, req);
        } /* c8 ignore start */else if (!this.isFetch) {
          psLog.warn("The request object is not found on XMLHttpRequest's readystatechange event");
        }
        /* c8 ignore stop */
      });
      if (req) {
        // send 阶段补齐请求信息和请求体,避免 open 阶段缺少 body。
        const URLCtor = getGlobal().URL;
        req.url = typeof URLCtor === 'function' ? new URLCtor(pageSpyRequestUrl).toString() : String(pageSpyRequestUrl);
        req.method = pageSpyRequestMethod.toUpperCase();
        req.requestType = 'xhr';
        req.withCredentials = XMLReq.withCredentials;
        if (req.method !== 'GET') {
          req.requestHeader = addContentTypeHeader(req.requestHeader, body);
          getFormattedBody(body).then(res => {
            req.requestPayload = res;
            that.sendRequestItem(XMLReq.pageSpyRequestId, req);
          });
        }
      } /* c8 ignore start */else if (!this.isFetch) {
        psLog.warn("The request object is not found on XMLHttpRequest's send event");
      } /* c8 ignore stop */
      return send.apply(XMLReq, [body]);
    };
  }
  /** 恢复 XHR 原型上的原始方法。 */
  reset() {
    const XHR = getGlobal().XMLHttpRequest;
    if (typeof XHR !== 'function' || !XHR.prototype) {
      return;
    }
    if (this.xhrOpen) {
      XHR.prototype.open = this.xhrOpen;
    }
    if (this.xhrSend) {
      XHR.prototype.send = this.xhrSend;
    }
    if (this.xhrSetRequestHeader) {
      XHR.prototype.setRequestHeader = this.xhrSetRequestHeader;
    }
  }
  // eslint-disable-next-line class-methods-use-this
  /** 按 XHR responseType 格式化响应体,供调试面板展示。 */
  async formatResponse(XMLReq, type) {
    const result = {
      response: '',
      responseReason: null
    };
    // XHR 响应格式化依赖 responseType;fetch 则主要依赖 content-type 推断。
    switch (type) {
      case '':
      case 'text':
        if (isString(XMLReq.response)) {
          try {
            result.response = JSON.parse(XMLReq.response);
          } catch (e) {
            // 非 JSON 字符串时按原文本展示。
            result.response = XMLReq.response;
          }
        } /* c8 ignore start */else if (typeof XMLReq.response !== 'undefined') {
          result.response = toStringTag(XMLReq.response);
        }
        /* c8 ignore stop */
        break;
      case 'json':
        if (typeof XMLReq.response !== 'undefined') {
          result.response = XMLReq.response;
        }
        break;
      case 'blob':
      case 'arraybuffer':
        if (XMLReq.response) {
          // ArrayBuffer 尽量转成 Blob 后复用 Blob 的体积限制和 base64 格式化逻辑。
          let blob = XMLReq.response;
          if (isArrayBuffer(blob)) {
            const contentType = XMLReq.getResponseHeader('content-type');
            const BlobCtor = getGlobal().Blob;
            if (contentType && typeof BlobCtor === 'function') {
              blob = new BlobCtor([blob], {
                type: contentType
              });
            }
          }
          if (isLynxBlob(blob)) {
            if (blob.size <= MAX_SIZE) {
              try {
                result.response = await blob2base64Async(blob);
              } /* c8 ignore start */ catch (e) {
                result.response = await blob.text();
                psLog.error(e instanceof Error ? e.message : String(e));
              } /* c8 ignore stop */
            } else {
              result.response = '[object Blob]';
              result.responseReason = Reason.EXCEED_SIZE;
            }
          }
        }
        break;
      case 'document':
      default:
        if (typeof XMLReq.response !== 'undefined') {
          result.response = Object.prototype.toString.call(XMLReq.response);
        }
        break;
    }
    return result;
  }
}

/** 判断 input 是否为当前 Lynx 运行时的 URL 实例。 */
const isLynxURL = value => {
  const URLCtor = getGlobal().URL;
  return typeof URLCtor === 'function' && value instanceof URLCtor;
};
/** 判断 headers 是否为当前 Lynx 运行时的 Headers 实例。 */
const isLynxHeaders = value => {
  const HeadersCtor = getGlobal().Headers;
  return typeof HeadersCtor === 'function' && value instanceof HeadersCtor;
};
/** 安全读取响应头 entries,兼容不完整的 Response 实现。 */
const getResponseHeaderEntries = headers => {
  return typeof (headers === null || headers === void 0 ? void 0 : headers.entries) === 'function' ? [...headers.entries()] : [];
};
/** 安全读取单个响应头,兼容不完整的 Response 实现。 */
const getResponseHeader = (headers, key) => {
  return typeof (headers === null || headers === void 0 ? void 0 : headers.get) === 'function' ? headers.get(key) : null;
};
/** 优先 clone Response,避免读取响应体影响业务代码继续消费。 */
const cloneResponse = res => {
  return typeof res.clone === 'function' ? res.clone() : res;
};
/** Android/iOS Lynx 原生环境优先代理 lynx.fetch。 */
const isNativeLynxPlatform$1 = globalObject => {
  var _globalObject$SystemI, _globalObject$lynx;
  const platform = String(((_globalObject$SystemI = globalObject.SystemInfo) === null || _globalObject$SystemI === void 0 ? void 0 : _globalObject$SystemI.platform) || ((_globalObject$lynx = globalObject.lynx) === null || _globalObject$lynx === void 0 || (_globalObject$lynx = _globalObject$lynx.__globalProps) === null || _globalObject$lynx === void 0 ? void 0 : _globalObject$lynx.platform) || '').toLowerCase();
  return platform.includes('android') || platform.includes('ios');
};
/** 找到实际需要被代理的 fetch 宿主对象和原始 fetch 方法。 */
const getFetchTarget = () => {
  var _globalObject$lynx2, _globalObject$lynx3;
  const globalObject = getGlobal();
  const globalFetchHost = typeof globalThis === 'object' ? globalThis : null;
  if (isNativeLynxPlatform$1(globalObject) && typeof ((_globalObject$lynx2 = globalObject.lynx) === null || _globalObject$lynx2 === void 0 ? void 0 : _globalObject$lynx2.fetch) === 'function') {
    return {
      host: globalObject.lynx,
      fetch: globalObject.lynx.fetch
    };
  }
  if (typeof (globalFetchHost === null || globalFetchHost === void 0 ? void 0 : globalFetchHost.fetch) === 'function') {
    return {
      host: globalFetchHost,
      fetch: globalFetchHost.fetch
    };
  }
  if (typeof ((_globalObject$lynx3 = globalObject.lynx) === null || _globalObject$lynx3 === void 0 ? void 0 : _globalObject$lynx3.fetch) === 'function') {
    return {
      host: globalObject.lynx,
      fetch: globalObject.lynx.fetch
    };
  }
  if (typeof globalObject.fetch === 'function') {
    return {
      host: globalObject,
      fetch: globalObject.fetch
    };
  }
  return null;
};
/** fetch 网络代理:替换运行时 fetch,记录请求、响应和异常状态。 */
class FetchProxy extends LynxNetworkProxyBase {
  constructor() {
    super();
    /** 原始 fetch 方法,reset 时恢复。 */
    _defineProperty(this, "fetch", null);
    /** fetch 所属宿主对象,可能是 globalThis、globalObject 或 lynx。 */
    _defineProperty(this, "fetchHost", null);
    this.initProxyHandler();
  }
  /** 恢复被代理前的 fetch 方法。 */
  reset() {
    if (this.fetch && this.fetchHost) {
      this.fetchHost.fetch = this.fetch;
    }
  }
  /** 安装 fetch 代理,保留业务调用结果,只旁路采集请求信息。 */
  initProxyHandler() {
    const createRequest = this.createRequest.bind(this);
    const getRequest = this.getRequest.bind(this);
    const sendRequestItem = this.sendRequestItem.bind(this);
    const fetchTarget = getFetchTarget();
    if (!fetchTarget) {
      return;
    }
    const {
      host,
      fetch: originFetch
    } = fetchTarget;
    this.fetch = originFetch;
    this.fetchHost = host;
    host.fetch = function (input) {
      let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
      const globalObject = getGlobal();
      markFetchProxyRequestStart();
      let fetchInstance;
      try {
        fetchInstance = originFetch.call(host, input, init);
      } finally {
        markFetchProxyRequestEnd();
      }
      const id = getRandomId();
      createRequest(id);
      const req = getRequest(id);
      if (req) {
        var _globalObject$XMLHttp;
        let method = 'GET';
        let url;
        let requestHeader = null;
        if (isString(input) || isLynxURL(input)) {
          // input 为字符串或 URL 时,请求信息来自 init。
          method = init.method || 'GET';
          url = input;
          requestHeader = init.headers || null;
        } else {
          // input 为 Request 对象时,请求信息来自对象本身。
          method = input.method;
          url = input.url;
          requestHeader = input.headers;
        }
        req.url = typeof globalObject.URL === 'function' ? new globalObject.URL(url).toString() : String(url);
        req.method = method.toUpperCase();
        req.requestType = 'fetch';
        req.status = 0;
        req.statusText = 'Pending';
        req.startTime = Date.now();
        req.readyState = ((_globalObject$XMLHttp = globalObject.XMLHttpRequest) === null || _globalObject$XMLHttp === void 0 ? void 0 : _globalObject$XMLHttp.UNSENT) || 0;
        if (init.credentials && init.credentials !== 'omit') {
          req.withCredentials = true;
        }
        if (isLynxHeaders(requestHeader)) {
          req.requestHeader = [...requestHeader.entries()];
        } else if (isObjectLike(requestHeader)) {
          req.requestHeader = Object.entries(requestHeader);
        } else {
          req.requestHeader = requestHeader;
        }
        if (req.method !== 'GET') {
          // 非 GET 请求额外采集请求体,异步格式化完成后再补发一次请求快照。
          req.requestHeader = addContentTypeHeader(req.requestHeader, init.body);
          getFormattedBody(init.body).then(res => {
            req.requestPayload = res;
            sendRequestItem(id, req);
          });
        }
        sendRequestItem(id, req);
        fetchInstance.then(res => {
          var _globalObject$XMLHttp2;
          // 收到响应头后先上报一次状态,随后再读取响应体。
          req.endTime = Date.now();
          req.costTime = req.endTime - (req.startTime || req.endTime);
          req.status = res.status || 200;
          req.statusText = res.statusText || 'Done';
          req.responseHeader = getResponseHeaderEntries(res.headers);
          req.readyState = ((_globalObject$XMLHttp2 = globalObject.XMLHttpRequest) === null || _globalObject$XMLHttp2 === void 0 ? void 0 : _globalObject$XMLHttp2.HEADERS_RECEIVED) || 2;
          sendRequestItem(id, req);
          const contentType = getResponseHeader(res.headers, 'content-type');
          if (contentType) {
            if (contentType.includes('application/json')) {
              req.responseType = 'json';
              return cloneResponse(res).text();
            }
            if (contentType.includes('text/html') || contentType.includes('text/plain')) {
              req.responseType = 'text';
              return cloneResponse(res).text();
            }
          }
          req.responseType = 'blob';
          const cloned = cloneResponse(res);
          if (typeof globalObject.Blob === 'function' && cloned.blob) {
            return cloned.blob();
          }
          return cloned.text();
        }).then(async res => {
          var _globalObject$XMLHttp3;
          switch (req.responseType) {
            case 'text':
            case 'json':
              // JSON 响应优先解析成对象,解析失败则按文本展示。
              try {
                req.response = JSON.parse(res);
              } catch {
                req.response = res;
                req.responseType = 'text';
              }
              break;
            case 'blob':
              // eslint-disable-next-line no-case-declarations
              const blob = res;
              // 小体积 Blob 转 base64 展示,大体积只标记原因避免调试链路过载。
              if (typeof globalObject.Blob !== 'function' || !(blob instanceof globalObject.Blob)) {
                req.response = res;
              } else if (blob.size <= MAX_SIZE) {
                try {
                  req.response = await blob2base64Async(blob);
                } /* c8 ignore start */ catch (e) {
                  req.response = await blob.text();
                  psLog.error(e instanceof Error ? e.message : String(e));
                } /* c8 ignore stop */
              } else {
                req.response = '[object Blob]';
                req.responseReason = Reason.EXCEED_SIZE;
              }
              break;
          }
          req.readyState = ((_globalObject$XMLHttp3 = globalObject.XMLHttpRequest) === null || _globalObject$XMLHttp3 === void 0 ? void 0 : _globalObject$XMLHttp3.DONE) || 4;
          sendRequestItem(id, req);
        }).catch(err => {
          var _globalObject$XMLHttp4;
          // fetch 本身失败时仍上报一条完整失败记录。
          req.endTime = Date.now();
          req.costTime = req.endTime - (req.startTime || req.endTime);
          req.status = 0;
          req.statusText = (err === null || err === void 0 ? void 0 : err.message) || 'Fetch Error';
          req.readyState = ((_globalObject$XMLHttp4 = globalObject.XMLHttpRequest) === null || _globalObject$XMLHttp4 === void 0 ? void 0 : _globalObject$XMLHttp4.DONE) || 4;
          sendRequestItem(id, req);
        });
      } /* c8 ignore start */else {
        psLog.warn('The request object is not found on global.fetch event');
      } /* c8 ignore stop */
      return fetchInstance;
    };
  }
}

/** 判断当前 Lynx 运行时是否有 fetch 或 lynx.fetch 能力。 */
const hasFetchCapability = () => {
  var _globalObject$lynx;
  const globalObject = getGlobal();
  return typeof globalObject.fetch === 'function' || typeof ((_globalObject$lynx = globalObject.lynx) === null || _globalObject$lynx === void 0 ? void 0 : _globalObject$lynx.fetch) === 'function';
};
/** 判断当前 Lynx 运行时是否有可代理的 XMLHttpRequest 能力。 */
const hasXhrCapability = () => {
  var _XHR$prototype, _XHR$prototype2, _XHR$prototype3;
  const XHR = getGlobal().XMLHttpRequest;
  return typeof XHR === 'function' && !!((_XHR$prototype = XHR.prototype) !== null && _XHR$prototype !== void 0 && _XHR$prototype.open) && !!((_XHR$prototype2 = XHR.prototype) !== null && _XHR$prototype2 !== void 0 && _XHR$prototype2.send) && !!((_XHR$prototype3 = XHR.prototype) !== null && _XHR$prototype3 !== void 0 && _XHR$prototype3.setRequestHeader);
};
/** Network 插件:根据运行时能力安装 fetch/XHR 代理并上报请求流水。 */
class NetworkPlugin {
  constructor() {
    /** 插件名称。 */
    _defineProperty(this, "name", 'NetworkPlugin');
    /** XHR 代理实例;运行时不支持 XHR 时为空。 */
    _defineProperty(this, "xhrProxy", null);
    /** fetch 代理实例;运行时不支持 fetch 时为空。 */
    _defineProperty(this, "fetchProxy", null);
  }
  /** 初始化网络代理,并把用户配置的数据处理器同步给基础代理类。 */
  onInit(_ref) {
    let {
      config
    } = _ref;
    if (NetworkPlugin.hasInitd) return;
    NetworkPlugin.hasInitd = true;
    NetworkProxyBase.dataProcessor = config.dataProcessor.network;
    if (hasFetchCapability()) {
      this.fetchProxy = new FetchProxy();
    }
    if (hasXhrCapability()) {
      this.xhrProxy = new XhrProxy();
    }
  }
  /** 恢复原始 fetch/XHR 并清理代理实例。 */
  onReset() {
    var _this$fetchProxy, _this$xhrProxy;
    (_this$fetchProxy = this.fetchProxy) === null || _this$fetchProxy === void 0 || _this$fetchProxy.reset();
    (_this$xhrProxy = this.xhrProxy) === null || _this$xhrProxy === void 0 || _this$xhrProxy.reset();
    this.fetchProxy = null;
    this.xhrProxy = null;
    NetworkPlugin.hasInitd = false;
  }
}
_defineProperty(NetworkPlugin, "hasInitd", false);

/** System 插件:上报 Lynx 客户端系统信息,并响应远端刷新请求。 */
class SystemPlugin {
  constructor() {
    /** 插件名称。 */
    _defineProperty(this, "name", 'SystemPlugin');
    _defineProperty(this, "$pageSpyConfig", null);
    /** PageSpy Client 中保存了格式化后的客户端信息和 rawInfo。 */
    _defineProperty(this, "client", null);
  }
  /** 初始化时立即推送一次系统信息,并监听远端 refresh 请求。 */
  onInit(_ref) {
    let {
      config,
      client
    } = _ref;
    if (SystemPlugin.hasInitd) return;
    SystemPlugin.hasInitd = true;
    this.$pageSpyConfig = config;
    this.client = client !== null && client !== void 0 ? client : null;
    this.onceInitPublicData();
    socketStore.addListener('refresh', (_ref2, reply) => {
      let {
        source
      } = _ref2;
      const {
        data
      } = source;
      if (data === 'system') {
        const info = this.getSystemInfo();
        if (info === null) return;
        reply(info);
      }
    });
  }
  /** 首次初始化后把系统信息写入 public-data,供调试面板展示。 */
  onceInitPublicData() {
    const info = this.getSystemInfo();
    if (info === null) return;
    socketStore.dispatchEvent('public-data', info);
  }
  /** 重置初始化标记,下一次初始化可重新注册监听。 */
  onReset() {
    SystemPlugin.hasInitd = false;
  }
  /** 生成系统信息消息,允许用户 dataProcessor 拦截。 */
  getSystemInfo() {
    var _this$client, _this$client2, _this$$pageSpyConfig, _this$$pageSpyConfig$;
    const info = {
      system: {
        ua: (_this$client = this.client) === null || _this$client === void 0 ? void 0 : _this$client.getName(),
        ...(((_this$client2 = this.client) === null || _this$client2 === void 0 ? void 0 : _this$client2.rawInfo) || {})
      },
      features: {}
    };
    const processedByUser = (_this$$pageSpyConfig = this.$pageSpyConfig) === null || _this$$pageSpyConfig === void 0 || (_this$$pageSpyConfig = _this$$pageSpyConfig.dataProcessor) === null || _this$$pageSpyConfig === void 0 || (_this$$pageSpyConfig$ = _this$$pageSpyConfig.system) === null || _this$$pageSpyConfig$ === void 0 ? void 0 : _this$$pageSpyConfig$.call(_this$$pageSpyConfig, info);
    if (processedByUser === false) return null;
    return makeMessage('system', info);
  }
}
_defineProperty(SystemPlugin, "hasInitd", false);

/** 内存存储,作为原生存储和 Web 存储都不可用时的降级方案 */
const memoryStorage = new Map();
/**
 * 输出存储操作失败的警告日志
 * @param action - 失败的操作类型(如 get、set、clear 等)
 * @param error - 错误对象
 */
const warnStorageFallback = (action, error) => {
  const globalConsole = getGlobal().console;
  if (typeof (globalConsole === null || globalConsole === void 0 ? void 0 : globalConsole.warn) === 'function') {
    globalConsole.warn("[page-spy-react-lynx] storage ".concat(action, " failed"), error);
  }
};
/**
 * 规范化存储值,将空字符串、undefined 等统一转为 null
 * @param value - 原始存储值
 * @returns 规范化后的值,空值返回 null
 */
const normalizeStorageValue = value => {
  return value || null;
};
/**
 * 获取原生存储模块实例
 * @returns NativeLocalStorageModule 实例,不可用时返回 null
 */
const getNativeStorage = () => {
  var _getGlobal$NativeModu;
  const nativeModule = (_getGlobal$NativeModu = getGlobal().NativeModules) === null || _getGlobal$NativeModu === void 0 ? void 0 : _getGlobal$NativeModu.NativeLocalStorageModule;
  // 校验原生模块是否具备核心方法
  if (nativeModule && typeof nativeModule.setStorageItem === 'function' && typeof nativeModule.getStorageItem === 'function' && typeof nativeModule.clearStorage === 'function') {
    return nativeModule;
  }
  return null;
};
/**
 * 获取 Web 端存储实例(localStorage)
 * @returns WebStorageLike 实例,不可用时返回 null
 */
const getWebStorage = () => {
  const globalObject = getGlobal();
  let webStorage = null;
  try {
    // 尝试从全局对象或 globalThis 获取 localStorage
    webStorage = globalObject.localStorage || (typeof globalThis === 'object' ? globalThis.localStorage : null);
  } catch (error) {
    warnStorageFallback('detect', error);
    return null;
  }
  // 校验 Web 存储是否具备核心方法
  if (webStorage && typeof webStorage.setItem === 'function' && typeof webStorage.getItem === 'function' && typeof webStorage.clear === 'function') {
    return webStorage;
  }
  return null;
};
/**
 * 从内存存储中获取指定 key 的值
 * @param key - 存储项的键名
 * @returns 存储值,不存在时返回 null
 */
const getMemoryStorageItem = key => {
  return memoryStorage.has(key) ? memoryStorage.get(key) || null : null;
};
/**
 * 获取存储项
 * 优先级:原生存储 > Web 存储 > 内存存储
 * @param key - 存储项的键名
 * @returns 存储值,不存在时返回 null
 */
const getStorageItem = async key => {
  // 优先尝试原生存储
  const nativeStorage = getNativeStorage();
  if (nativeStorage) {
    try {
      return await new Promise(resolve => {
        nativeStorage.getStorageItem(key, value => {
          const normalizedValue = normalizeStorageValue(value);
          if (normalizedValue === null) {
            memoryStorage.delete(key);
          } else {
            memoryStorage.set(key, normalizedValue);
          }
          resolve(normalizedValue);
        });
      });
    } catch (error) {
      warnStorageFallback('get', error);
      // 原生存储失败,降级到内存存储
      return getMemoryStorageItem(key);
    }
  }
  // 其次尝试 Web 存储
  const webStorage = getWebStorage();
  if (webStorage) {
    try {
      return normalizeStorageValue(webStorage.getItem(key));
    } catch (error) {
      warnStorageFallback('get', error);
      // Web 存储失败,降级到内存存储
      return getMemoryStorageItem(key);
    }
  }
  // 最终降级到内存存储
  return getMemoryStorageItem(key);
};
/**
 * 设置存储项
 * 优先级:原生存储 > Web 存储 > 内存存储
 * @param key - 存储项的键名
 * @param value - 存储项的值
 */
const setStorageItem = (key, value) => {
  // 优先尝试原生存储
  const nativeStorage = getNativeStorage();
  if (nativeStorage) {
    try {
      nativeStorage.setStorageItem(key, value);
      memoryStorage.set(key, value);
      return;
    } catch (error) {
      warnStorageFallback('set', error);
      // 原生存储失败,降级到内存存储
      memoryStorage.set(key, value);
      return;
    }
  }
  // 其次尝试 Web 存储
  const webStorage = getWebStorage();
  if (webStorage) {
    try {
      webStorage.setItem(key, value);
      memoryStorage.set(key, value);
      return;
    } catch (error) {
      warnStorageFallback('set', error);
      // Web 存储失败,降级到内存存储
      memoryStorage.set(key, value);
      return;
    }
  }
  // 最终降级到内存存储
  memoryStorage.set(key, value);
};
/**
 * 清空所有存储项
 * 同时清空持久化存储和内存存储
 */
const clearStorage = () => {
  // 优先尝试原生存储
  const nativeStorage = getNativeStorage();
  if (nativeStorage) {
    try {
      nativeStorage.clearStorage();
      memoryStorage.clear();
      return;
    } catch (error) {
      warnStorageFallback('clear', error);
      memoryStorage.clear();
      return;
    }
  }
  // 其次尝试 Web 存储
  const webStorage = getWebStorage();
  if (webStorage) {
    try {
      webStorage.clear();
      memoryStorage.clear();
      return;
    } catch (error) {
      warnStorageFallback('clear', error);
      memoryStorage.clear();
      return;
    }
  }
  // 最终降级到内存存储
  memoryStorage.clear();
};
/**
 * 删除指定存储项
 * 若原生/Web 存储不支持 removeItem,则通过设置为空字符串来模拟删除
 * @param key - 存储项的键名
 */
const removeStorageItem = key => {
  // 优先尝试原生存储
  const nativeStorage = getNativeStorage();
  if (nativeStorage) {
    try {
      if (typeof nativeStorage.removeStorageItem === 'function') {
        nativeStorage.removeStorageItem(key);
      } else {
        // 不支持 removeStorageItem 时,通过设置为空字符串模拟删除
        nativeStorage.setStorageItem(key, '');
      }
      memoryStorage.delete(key);
      return;
    } catch (error) {
      warnStorageFallback('remove', error);
      memoryStorage.delete(key);
      return;
    }
  }
  // 其次尝试 Web 存储
  const webStorage = getWebStorage();
  if (webStorage) {
    try {
      if (typeof webStorage.removeItem === 'function') {
        webStorage.removeItem(key);
      } else {
        // 不支持 removeItem 时,通过设置为空字符串模拟删除
        webStorage.setItem(key, '');
      }
      memoryStorage.delete(key);
      return;
    } catch (error) {
      warnStorageFallback('remove', error);
      memoryStorage.delete(key);
      return;
    }
  }
  // 最终降级到内存存储
  memoryStorage.delete(key);
};
/**
 * 从 DataItem 中提取存储键名
 * @param data - 存储数据项
 * @returns 键名,无法提取时返回空字符串
 */
const getStorageKey = data => {
  var _data$data$;
  if ('name' in data && data.name) {
    return data.name;
  }
  if ('data' in data && (_data$data$ = data.data[0]) !== null && _data$data$ !== void 0 && _data$data$.name) {
    return data.data[0].name;
  }
  return '';
};
/**
 * 将不同格式的存储数据统一规范化为 { name, value } 数组
 * 支持对象、数组和 JSON 字符串三种输入格式
 * @param value - 原始存储数据,可能是对象、数组或 JSON 字符串
 * @returns 规范化后的存储项数组
 */
const normalizeStorageEntries = value => {
  // 如果是字符串,先尝试 JSON 解析后递归处理
  if (typeof value === 'string') {
    try {
      return normalizeStorageEntries(JSON.parse(value));
    } catch (error) {
      warnStorageFallback('list', error);
      return [];
    }
  }
  // 如果是数组,过滤无效项并确保 value 为字符串
  if (Array.isArray(value)) {
    return value.filter(item => item && item.name).map(_ref => {
      let {
        name,
        value: val
      } = _ref;
      return {
        name,
        value: String(val)
      };
    });
  }
  // 如果是对象,转换为 { name, value } 数组
  return Object.entries(value || {}).map(_ref2 => {
    let [name, val] = _ref2;
    return {
      name,
      value: String(val)
    };
  });
};
/**
 * 获取所有存储项的值
 * 优先级:原生存储 > Web 存储 > 内存存储
 * @returns 所有存储项的 { name, value } 数组
 */
const getAllStorageValues = async () => {
  // 优先尝试原生存储
  const nativeStorage = getNativeStorage();
  if (nativeStorage && typeof nativeStorage.getAllStorageItems === 'function') {
    try {
      return await new Promise(resolve => {
        nativeStorage.getAllStorageItems(value => {
          resolve(normalizeStorageEntries(value));
        });
      });
    } catch (error) {
      warnStorageFallback('list', error);
    }
  }
  // 其次尝试 Web 存储
  const webStorage = getWebStorage();
  if (webStorage && typeof webStorage.key === 'function' && typeof webStorage.length === 'number') {
    try {
      const entries = [];
      for (let i = 0; i < webStorage.length; i += 1) {
        const name = webStorage.key(i);
        if (!name) continue;
        const value = webStorage.getItem(name);
        if (value !== null) {
          entries.push({
            name,
            value
          });
        }
      }
      return entries;
    } catch (error) {
      warnStorageFallback('list', error);
    }
  }
  // 最终降级到内存存储
  return Array.from(memoryStorage.entries()).map(_ref3 => {
    let [name, value] = _ref3;
    return {
      name,
      value
    };
  });
};
/**
 * 根据数据项获取存储值
 * 若未指定 key 则返回所有存储项,否则返回指定 key 的值
 * @param data - 存储数据项
 * @returns 存储项的 { name, value } 数组
 */
const getStorageValues = async data => {
  const key = getStorageKey(data);
  // 未指定 key 时,返回所有存储项
  if (!key) {
    return getAllStorageValues();
  }
  // 指定 key 时,返回对应存储项
  const value = await getStorageItem(key);
  return value === null ? [] : [{
    name: key,
    value
  }];
};
/** 存储操作集合,对外暴露的统一接口 */
const storage = {
  getStorageItem,
  setStorageItem,
  removeStorageItem,
  clearStorage
};
/**
 * Storage 插件
 * 实现 PageSpyPlugin 接口,通过 WebSocket 监听远程存储操作指令,
 * 并在本地执行对应的存储增删改查操作
 */
class StoragePlugin {
  constructor() {
    /** 插件名称 */
    _defineProperty(this, "name", 'StoragePlugin');
    /** 存储操作集合 */
    _defineProperty(this, "storage", storage);
    /** WebSocket 连接存储实例,用于监听和响应远程指令 */
    _defineProperty(this, "socketStore", null);
    /**
     * 处理远程存储操作事件
     * 支持 set、remove、clear、get 四种操作
     * @param event - 远程交互事件
     * @param reply - 回复函数,用于将操作结果返回给远程端
     */
    _defineProperty(this, "onStorage", async (event, reply) => {
      const {
        data
      } = event.source;
      // 设置存储项
      if (data.action === 'set') {
        setStorageItem(data.name, data.value);
        reply(makeMessage('storage', data));
        return;
      }
      // 删除存储项
      if (data.action === 'remove') {
        removeStorageItem(data.name);
        reply(makeMessage('storage', data));
        return;
      }
      // 清空所有存储项
      if (data.action === 'clear') {
        clearStorage();
        reply(makeMessage('storage', data));
        return;
      }
      // 获取存储项
      if (data.action === 'get') {
        const values = await getStorageValues(data);
        const response = {
          type: data.type,
          action: 'get',
          data: values
        };
        reply(makeMessage('storage', response));
      }
    });
  }
  /**
   * 插件初始化
   * 注册 WebSocket 监听器,监听远程存储操作指令
   * @param socketStore - WebSocket 连接存储实例
   */
  onInit(_ref4) {
    let {
      socketStore
    } = _ref4;
    if (StoragePlugin.hasInitd) return;
    StoragePlugin.hasInitd = true;
    this.socketStore = socketStore;
    socketStore.addListener('storage', this.onStorage);
  }
  /**
   * 插件重置
   * 移除 WebSocket 监听器,清理状态
   */
  onReset() {
    var _this$socketStore, _this$socketStore$rem;
    (_this$socketStore = this.socketStore) === null || _this$socketStore === void 0 || (_this$socketStore$rem = _this$socketStore.removeListener) === null || _this$socketStore$rem === void 0 || _this$socketStore$rem.call(_this$socketStore, 'storage', this.onStorage);
    this.socketStore = null;
    StoragePlugin.hasInitd = false;
  }
}
/** 标记插件是否已初始化,防止重复初始化 */
_defineProperty(StoragePlugin, "hasInitd", false);

/** 判断 WebSocket 构造器是否可继承和实例化。 */
const isConstructableWebSocket = WebSocketCtor => {
  if (typeof WebSocketCtor !== 'function') {
    return false;
  }
  try {
    Reflect.construct(String, [], WebSocketCtor);
    return true;
  } catch (e) {
    return false;
  }
};
/** WebSocket 网络代理:继承原始 WebSocket,采集连接和消息事件。 */
class WebSocketPlugin extends LynxNetworkProxyBase {
  constructor() {
    super(...arguments);
    /** 插件名称。 */
    _defineProperty(this, "name", 'WebSocketPlugin');
    /** 原始 WebSocket 构造器,reset 时恢复。 */
    _defineProperty(this, "originWebSocket", null);
  }
  /** 初始化 WebSocket 代理,并同步网络 dataProcessor。 */
  onInit(_ref) {
    let {
      config
    } = _ref;
    if (WebSocketPlugin.hasInitd) return;
    WebSocketPlugin.hasInitd = true;
    NetworkProxyBase.dataProcessor = config.dataProcessor.network;
    this.initProxyHandler();
  }
  /** 安装 WebSocket 构造器代理,PageSpy 自身连接会被跳过。 */
  initProxyHandler() {
    const OriginWebSocket = globalThis.WebSocket;
    if (!isConstructableWebSocket(OriginWebSocket)) {
      return;
    }
    this.originWebSocket = OriginWebSocket;
    const plugin = this;
    /** 代理构造器:保留原 WebSocket 行为,只旁路记录连接和消息。 */
    class PageSpyWebSocketProxy extends OriginWebSocket {
      constructor(uri) {
        for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
          args[_key - 1] = arguments[_key];
        }
        super(uri, ...args);
        // 跳过 PageSpy SDK 自己连接调试房间的 WebSocket,避免递归上报。
        _defineProperty(this, "_requestId", null);
        _defineProperty(this, "_req", null);
        _defineProperty(this, "_lastEventId", 0);
        if (uri.includes(PAGE_SPY_WS_ENDPOINT)) return;
        this._requestId = getRandomId();
        plugin.createRequest(this._requestId);
        this._req = plugin.getRequest(this._requestId);
        // 设置 WebSocket 握手的基础请求信息。
        this._req.url = uri.toString();
        this._req.method = 'GET';
        this._req.requestType = 'websocket';
        this._req.requestHeader = [['Upgrade', 'websocket'], ['Connection', 'Upgrade'], ['Sec-WebSocket-Version', '13']];
        const protocols = args[0];
        if (protocols) {
          const protocolsStr = Array.isArray(protocols) ? protocols.join(', ') : protocols;
          this._req.requestHeader.push(['Sec-WebSocket-Protocol', protocolsStr]);
        }
        this._req.readyState = ReqReadyState.UNSENT;
        this._req.startTime = Date.now();
        this._req.response = null;
        this.setupEventListeners();
      }
      /** 监听 WebSocket 生命周期和消息事件,并转成网络面板记录。 */
      setupEventListeners() {
        this.addEventListener('open', () => {
          if (!this._req || !this._requestId) return;
          this._req.readyState = ReqReadyState.OPENED;
          this._req.status = 101; // WebSocket 握手成功:Switching Protocols。
          this._req.statusText = 'Switching Protocols';
          this._req.endTime = Date.now();
          this._req.costTime = this._req.endTime - this._req.startTime;
          this._req.responseHeader = [['Upgrade', 'websocket'], ['Connection', 'Upgrade']];
          plugin.sendRequestItem(this._requestId, this._req);
        });
        // 监听消息接收事件。
        this.addEventListener('message', event => {
          if (!this._req || !this._requestId) return;
          const message = {
            type: 'receive',
            data: event.data,
            timestamp: Date.now()
          };
          this._req.readyState = ReqReadyState.DONE;
          this._req.status = 200;
          this._req.statusText = 'OK';
          this._req.response = message;
          this._req.endTime = Date.now();
          this._req.costTime = this._req.endTime - this._req.startTime;
          this._req.lastEventId = String(this._lastEventId++);
          plugin.sendRequestItem(this._requestId, this._req);
        });
        // 监听错误事件。
        this.addEventListener('error', () => {
          if (!this._req || !this._requestId) return;
          this._req.readyState = ReqReadyState.DONE;
          this._req.status = 400;
          this._req.statusText = 'WebSocket Error';
          this._req.endTime = Date.now();
          this._req.costTime = this._req.endTime - this._req.startTime;
          plugin.sendRequestItem(this._requestId, this._req);
        });
        // 监听连接关闭事件。
        this.addEventListener('close', event => {
          if (!this._req || !this._requestId) return;
          this._req.readyState = ReqReadyState.DONE;
          this._req.status = Number(event.code);
          this._req.statusText = event.reason || 'Connection Closed';
          this._req.endTime = Date.now();
          this._req.costTime = this._req.endTime - this._req.startTime;
          plugin.sendRequestItem(this._requestId, this._req);
        });
      }
      // 代理 send 方法,记录业务侧发出的 WebSocket 消息。
      send(data) {
        if (this._req && this._requestId) {
          const message = {
            type: 'send',
            data: this.formatSendData(data),
            timestamp: Date.now()
          };
          this._req.readyState = ReqReadyState.DONE;
          this._req.status = 200;
          this._req.statusText = 'OK';
          this._req.response = message;
          this._req.lastEventId = String(this._lastEventId++);
          this._req.endTime = Date.now();
          this._req.costTime = this._req.endTime - this._req.startTime;
          plugin.sendRequestItem(this._requestId, this._req);
        }
        // 调用原始 send 方法,保证业务 WebSocket 行为不变。
        super.send(data);
      }
      /** 将不同类型的发送数据转换为可展示的字符串。 */
      formatSendData(data) {
        if (typeof data === 'string') {
          return data;
        }
        if (data instanceof Blob) {
          return '[Blob data]';
        }
        if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {
          return '[Binary data]';
        }
        return String(data);
      }
    }
    globalThis.WebSocket = PageSpyWebSocketProxy;
  }
  /** 恢复原始 WebSocket 构造器。 */
  onReset() {
    if (this.originWebSocket) {
      globalThis.WebSocket = this.originWebSocket;
    }
    this.originWebSocket = null;
    WebSocketPlugin.hasInitd = false;
  }
}
_defineProperty(WebSocketPlugin, "hasInitd", false);

/** 获取带 Lynx 能力声明的全局对象。 */
const getGlobalObject = () => {
  return getGlobal();
};
/** 读取 lynx 全局对象,非 Lynx 环境返回 null。 */
const getLynxGlobal = () => {
  return getGlobalObject().lynx || null;
};
/** 读取原生模块集合,供系统信息兜底查询使用。 */
const getNativeModules = () => {
  return getGlobalObject().NativeModules;
};
/** 优先读取 Lynx 注入的 SystemInfo 全局变量,失败时回退到统一全局对象。 */
const getSystemInfoGlobal = () => {
  try {
    if (typeof SystemInfo !== 'undefined') return SystemInfo;
  } catch {
    // ignored
  }
  return getGlobalObject().SystemInfo || null;
};
/** 从多个候选值中选出第一个有效字符串,避免上报空字段。 */
const pickString = function () {
  for (var _len = arguments.length, values = new Array(_len), _key = 0; _key < _len; _key++) {
    values[_key] = arguments[_key];
  }
  const value = values.find(item => typeof item === 'string' && item);
  return value || 'unknown';
};
/** 将不同平台返回的系统名称归一化为 PageSpy 识别的 OS 枚举。 */
const normalizeOS = value => {
  const text = String(value || '').toLowerCase();
  if (text.includes('android')) return 'android';
  if (text.includes('ios') || text.includes('iphone')) return 'ios';
  if (text.includes('ipad')) return 'ipad';
  if (text.includes('mac')) return 'mac';
  if (text.includes('web')) return 'web';
  if (text.includes('windows') || text.includes('win')) return 'windows';
  if (text.includes('linux')) return 'linux';
  if (text.includes('harmony')) return 'harmony';
  return 'unknown';
};
/** 汇总 Lynx 全局属性和系统 API 信息,作为客户端识别的原始数据。 */
const getLynxSystemInfo = () => {
  const lynx = getLynxGlobal();
  const nativeModules = getNativeModules();
  const systemInfo = getSystemInfoGlobal();
  let apiInfo = {};
  try {
    var _lynx$getSystemInfoSy, _lynx$getSystemInfo, _nativeModules$System, _nativeModules$System2, _nativeModules$System3, _nativeModules$System4;
    apiInfo = systemInfo || (lynx === null || lynx === void 0 || (_lynx$getSystemInfoSy = lynx.getSystemInfoSync) === null || _lynx$getSystemInfoSy === void 0 ? void 0 : _lynx$getSystemInfoSy.call(lynx)) || (lynx === null || lynx === void 0 || (_lynx$getSystemInfo = lynx.getSystemInfo) === null || _lynx$getSystemInfo === void 0 ? void 0 : _lynx$getSystemInfo.call(lynx)) || (nativeModules === null || nativeModules === void 0 || (_nativeModules$System = nativeModules.SystemInfo) === null || _nativeModules$System === void 0 || (_nativeModules$System2 = _nativeModules$System.getSystemInfoSync) === null || _nativeModules$System2 === void 0 ? void 0 : _nativeModules$System2.call(_nativeModules$System)) || (nativeModules === null || nativeModules === void 0 || (_nativeModules$System3 = nativeModules.SystemInfo) === null || _nativeModules$System3 === void 0 || (_nativeModules$System4 = _nativeModules$System3.getSystemInfo) === null || _nativeModules$System4 === void 0 ? void 0 : _nativeModules$System4.call(_nativeModules$System3)) || {};
  } catch {
    apiInfo = {};
  }
  const globalProps = (lynx === null || lynx === void 0 ? void 0 : lynx.__globalProps) || {};
  return {
    ...globalProps,
    ...apiInfo
  };
};
/** 生成 PageSpy 客户端信息,用于房间名称、系统面板和调试端展示。 */
const getLynxClientInfo = () => {
  const rawInfo = getLynxSystemInfo();
  const osSource = rawInfo.osType || rawInfo.platform || rawInfo.os || rawInfo.system || rawInfo.devicePlatform;
  return {
    osType: normalizeOS(osSource),
    osVersion: pickString(rawInfo.osVersion, rawInfo.systemVersion, rawInfo.system, rawInfo.version),
    browserType: 'lynx',
    browserVersion: pickString(rawInfo.lynxVersion, rawInfo.engineVersion, rawInfo.lynxSdkVersion, rawInfo.sdkVersion),
    framework: 'react-lynx',
    sdk: 'react-lynx',
    sdkVersion: "2.4.0"
  };
};

/** 根据配置选择 HTTP 与 WebSocket 协议头。 */
const getScheme = enableSSL => {
  return enableSSL === false ? ['http://', 'ws://'] : ['https://', 'wss://'];
};
/** 将 HeadersInit 统一转换为普通对象,便于传给 NativeModules。 */
const headersToRecord = headers => {
  if (!headers) return {};
  if (typeof Headers === 'function' && headers instanceof Headers) {
    return [...headers.entries()].reduce((acc, _ref) => {
      let [key, value] = _ref;
      acc[key] = value;
      return acc;
    }, {});
  }
  if (Array.isArray(headers)) {
    return headers.reduce((acc, _ref2) => {
      let [key, value] = _ref2;
      acc[key] = value;
      return acc;
    }, {});
  }
  return headers;
};
/** 从 fetch 入参中提取 URL 字符串,兼容 string、URL 和 Request-like 对象。 */
const getInputUrl = input => {
  if (typeof input === 'string') return input;
  if (isURL(input)) return input.toString();
  return input.url;
};
/** 从 fetch 入参中提取请求方法,默认 GET。 */
const getInputMethod = (input, init) => {
  if (init !== null && init !== void 0 && init.method) return init.method;
  if (typeof input === 'object' && 'method' in input && input.method) {
    return input.method;
  }
  return 'GET';
};
/** 从 fetch 入参中提取请求头,优先使用 init.headers。 */
const getInputHeaders = (input, init) => {
  if (init !== null && init !== void 0 && init.headers) return headersToRecord(init.headers);
  if (typeof input === 'object' && 'headers' in input) {
    return headersToRecord(input.headers);
  }
  return {};
};
/** 将原生 FetchModule 返回值包装成近似标准 Response 的对象。 */
const createNativeModuleResponse = raw => {
  var _raw$ok, _raw$status;
  if (raw.error) {
    throw Error(raw.error);
  }
  const body = raw.body || '';
  const responseHeaders = raw.headers || {};
  return {
    ok: (_raw$ok = raw.ok) !== null && _raw$ok !== void 0 ? _raw$ok : true,
    status: (_raw$status = raw.status) !== null && _raw$status !== void 0 ? _raw$status : 200,
    statusText: raw.statusText || '',
    headers: {
      get: key => {
        var _responseHeaders$key$;
        return (_responseHeaders$key$ = responseHeaders[key.toLowerCase()]) !== null && _responseHeaders$key$ !== void 0 ? _responseHeaders$key$ : null;
      },
      entries: () => Object.entries(responseHeaders)
    },
    text: () => Promise.resolve(body),
    json: () => Promise.resolve(JSON.parse(body))
  };
};
/** 判断当前是否为需要优先走 lynx.fetch 的原生 Lynx 平台。 */
const isNativeLynxPlatform = globalObject => {
  var _globalObject$SystemI, _globalObject$lynx;
  const platform = String(((_globalObject$SystemI = globalObject.SystemInfo) === null || _globalObject$SystemI === void 0 ? void 0 : _globalObject$SystemI.platform) || ((_globalObject$lynx = globalObject.lynx) === null || _globalObject$lynx === void 0 || (_globalObject$lynx = _globalObject$lynx.__globalProps) === null || _globalObject$lynx === void 0 ? void 0 : _globalObject$lynx.platform) || '').toLowerCase();
  return ['android', 'ios', 'harmony'].includes(platform);
};
/** 包装 lynx.fetch,补齐部分平台需要 Request 实例作为入参的行为。 */
const createLynxFetch = (globalObject, lynxFetch) => {
  return (input, init) => {
    const RequestCtor = globalObject.Request || globalThis.Request;
    if (typeof RequestCtor === 'function' && !(input instanceof RequestCtor)) {
      return lynxFetch.call(globalObject.lynx, new RequestCtor(input, init));
    }
    return lynxFetch.call(globalObject.lynx, input, init);
  };
};
/** 将 NativeModules.FetchModule 适配成 fetch 风格函数。 */
const createNativeModuleFetch = nativeModule => {
  return async (input, init) => {
    const raw = await nativeModule.fetch.call(nativeModule, {
      url: getInputUrl(input),
      method: getInputMethod(input, init),
      headers: getInputHeaders(input, init),
      body: typeof (init === null || init === void 0 ? void 0 : init.body) === 'string' ? init.body : undefined
    });
    return createNativeModuleResponse(raw);
  };
};
/** 按 Lynx 原生能力、NativeModule、全局 fetch 的优先级获取可用请求函数。 */
const getRuntimeFetch = () => {
  var _globalObject$lynx2, _globalObject$NativeM;
  const globalObject = getGlobal();
  const lynxFetch = (_globalObject$lynx2 = globalObject.lynx) === null || _globalObject$lynx2 === void 0 ? void 0 : _globalObject$lynx2.fetch;
  const nativeModuleFetchModule = (_globalObject$NativeM = globalObject.NativeModules) === null || _globalObject$NativeM === void 0 ? void 0 : _globalObject$NativeM.FetchModule;
  if (isNativeLynxPlatform(globalObject) && typeof lynxFetch === 'function') {
    return createLynxFetch(globalObject, lynxFetch);
  }
  if (typeof (nativeModuleFetchModule === null || nativeModuleFetchModule === void 0 ? void 0 : nativeModuleFetchModule.fetch) === 'function') {
    return createNativeModuleFetch(nativeModuleFetchModule);
  }
  const globalFetch = globalObject.fetch;
  if (typeof globalFetch === 'function') {
    return globalFetch.bind(globalObject);
  }
  if (typeof lynxFetch === 'function') {
    return createLynxFetch(globalObject, lynxFetch);
  }
  throw Error('fetch is not available in current Lynx runtime');
};
/** PageSpy 后端 API 封装,负责创建调试房间和拼接房间 WebSocket 地址。 */
let Request$1 = class Request {
  constructor(config, client) {
    this.config = config;
    this.client = client;
    if (!config.get().api) {
      throw Error('The api base url cannot be empty');
    }
  }
  get base() {
    return this.config.get().api;
  }
  /** 当前实例使用的 HTTP/WS 协议头。 */
  getScheme() {
    return this.config.get().enableSSL ? ['https://', 'wss://'] : ['http://', 'ws://'];
  }
  /** 创建调试房间并返回房间名、房间号和 WebSocket 地址。 */
  createRoom() {
    const config = this.config.get();
    const scheme = getScheme(config.enableSSL);
    const name = this.client.getName();
    console.log('Creating room with name:', name);
    const query = joinQuery({
      name: encodeURIComponent(name),
      group: config.project,
      title: config.title
    });
    return getRuntimeFetch()("".concat(scheme[0]).concat(this.base, "/api/v1/room/create?").concat(query), {
      method: 'POST'
    }).then(res => res.json()).then(res => {
      // eslint-disable-next-line @typescript-eslint/no-shadow
      const {
        name,
        address
      } = res.data || {};
      const roomUrl = this.getRoomUrl(address);
      return {
        roomUrl,
        address,
        name
      };
    }).catch(err => {
      /* c8 ignore next */
      throw Error("Request create room failed: ".concat(err.message));
    });
  }
  /** 拼接客户端加入房间的 WebSocket URL。 */
  getRoomUrl(address) {
    const scheme = this.getScheme();
    const {
      useSecret,
      secret
    } = this.config.get();
    return "".concat(scheme[1]).concat(this.base, "/api/v1/ws/room/join?").concat(joinQuery({
      address,
      name: "client:".concat(getRandomId()),
      userId: 'Client',
      forceCreate: true,
      useSecret,
      secret
    }));
  }
};

/** Lynx 侧目前复用 PageSpy 基础配置,预留扩展 schema 入口。 */
const schema = extendConfigSchema(z => {
  return z.object({});
});
/** PageSpy ReactLynx 配置对象,封装基础配置校验和平台扩展位。 */
class Config extends ConfigBase {
  constructor() {
    super(...arguments);
    _defineProperty(this, "schema", schema);
    /** 平台专属配置扩展位,保持和基础 SDK 的配置结构一致。 */
    _defineProperty(this, "platform", {});
  }
}

/** 将单例状态挂到全局对象,避免模块重复加载时产生多个 PageSpy 实例。 */
const RUNTIME_STATE_KEY = '__PAGE_SPY_REACT_LYNX_STATE__';
/** 获取或初始化 PageSpy 在当前 Lynx 运行时中的单例状态。 */
const getPageSpyRuntimeState = () => {
  const globalObject = getGlobal();
  if (!globalObject[RUNTIME_STATE_KEY]) {
    globalObject[RUNTIME_STATE_KEY] = {
      instance: null,
      initPromise: null
    };
  }
  return globalObject[RUNTIME_STATE_KEY];
};
class PageSpy {
  /** 展开后的插件执行队列:pre -> normal -> post。 */
  static get pluginsWithOrder() {
    return [...PageSpy.plugins.pre, ...PageSpy.plugins.normal, ...PageSpy.plugins.post];
  }
  static get instance() {
    return getPageSpyRuntimeState().instance;
  }
  static set instance(value) {
    const state = getPageSpyRuntimeState();
    state.instance = value;
    if (!value) {
      state.initPromise = null;
    }
  }
  /** 根据当前 Lynx 系统信息刷新客户端标识。 */
  static refreshClient() {
    PageSpy.client = new Client(getLynxClientInfo(), getLynxSystemInfo());
  }
  /** 注册插件实例,并根据 enforce 字段放入对应执行队列。 */
  static registerPlugin(plugin) {
    if (!plugin) {
      return;
    }
    if (isClass(plugin)) {
      psLog.error('PageSpy.registerPlugin() expect to pass an instance, not a class');
      return;
    }
    if (!plugin.name) {
      psLog.error("The ".concat(plugin.constructor.name, " plugin should provide a \"name\" property"));
      return;
    }
    const isExist = PageSpy.pluginsWithOrder.some(i => i.name === plugin.name);
    if (isExist) {
      psLog.info("The ".concat(plugin.name, " has registered. Consider the following reasons:\n      - Duplicate register one same plugin;\n      - Plugin's \"name\" conflict with others, you can print all registered plugins by \"PageSpy.plugins\";"));
      return;
    }
    const currentPluginSet = PageSpy.plugins[plugin.enforce || 'normal'];
    currentPluginSet.push(plugin);
  }
  constructor(init) {
    /** 当前 SDK 版本,由构建产物注入。 */
    _defineProperty(this, "version", "2.4.0");
    /** 创建房间和生成 WebSocket 地址的请求实例。 */
    _defineProperty(this, "request", null);
    // 系统信息展示名:<os>-<browser>:<browserVersion>
    _defineProperty(this, "name", '');
    // PageSpy 房间号
    _defineProperty(this, "address", '');
    // 完整的 WebSocket 房间连接地址
    _defineProperty(this, "roomUrl", '');
    _defineProperty(this, "socketStore", socketStore);
    _defineProperty(this, "config", new Config());
    if (PageSpy.instance) {
      psLog.warn('Cannot initialize PageSpy multiple times');
      // eslint-disable-next-line no-constructor-return
      return PageSpy.instance;
    }
    const config = this.config.mergeConfig(init);
    PageSpy.refreshClient();
    // 创建请求实例时会校验 api 基础地址是否可用。
    this.request = new Request$1(this.config, PageSpy.client);
    this.updateConfiguration();
    PageSpy.instance = this;
    PageSpy.client.plugins = PageSpy.pluginsWithOrder.map(plugin => plugin.name);
    this.triggerPlugins('onInit', {
      socketStore,
      config,
      client: PageSpy.client
    });
    getPageSpyRuntimeState().initPromise = this.init();
  }
  /** 将配置同步到 socketStore,供所有插件和消息通道共享。 */
  updateConfiguration() {
    const {
      messageCapacity,
      useSecret
    } = this.config.get();
    if (useSecret === true) {
      const secret = getAuthSecret();
      this.config.set('secret', secret);
      psLog.log("Room Secret: ".concat(secret));
    }
    socketStore.connectable = true;
    socketStore.getPageSpyConfig = () => this.config.get();
    socketStore.getClient = () => PageSpy.client;
    socketStore.messageCapacity = messageCapacity;
  }
  triggerPlugins(lifecycle) {
    for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
      args[_key - 1] = arguments[_key];
    }
    const {
      disabledPlugins
    } = this.config.get();
    PageSpy.pluginsWithOrder.forEach(plugin => {
      var _plugin$lifecycle;
      if (isArray(disabledPlugins) && disabledPlugins.length && disabledPlugins.includes(plugin.name)) {
        return;
      }
      (_plugin$lifecycle = plugin[lifecycle]) === null || _plugin$lifecycle === void 0 || _plugin$lifecycle.apply(plugin, args);
    });
  }
  /** 初始化 PageSpy 房间连接,复用正在进行的初始化 Promise 防止并发建房。 */
  async init() {
    const state = getPageSpyRuntimeState();
    if (state.initPromise) {
      return state.initPromise;
    }
    state.initPromise = this.createNewConnection().then(() => {
      psLog.log('Plugins inited');
    }).catch(err => {
      state.initPromise = null;
      throw err;
    });
    return state.initPromise;
  }
  /** 重置所有插件并关闭 WebSocket 连接。 */
  abort() {
    this.triggerPlugins('onReset');
    socketStore.close();
    PageSpy.instance = null;
  }
  /** 请求服务端创建调试房间,并初始化 WebSocket 通道。 */
  async createNewConnection() {
    if (this.roomUrl) {
      return;
    }
    if (!this.request) {
      psLog.error('Cannot get the Request');
      return;
    }
    const roomInfo = await this.request.createRoom();
    this.name = roomInfo.name;
    this.address = roomInfo.address;
    this.roomUrl = roomInfo.roomUrl;
    socketStore.init(roomInfo.roomUrl);
  }
  /** 更新房间展示信息,并通知远端调试面板刷新。 */
  updateRoomInfo(obj) {
    if (!obj) return;
    const {
      project,
      title
    } = obj;
    if (project) {
      this.config.set('project', String(project));
    }
    if (title) {
      this.config.set('title', String(title));
    }
    socketStore.updateRoomInfo();
  }
  /** 获取可在浏览器中打开的 PageSpy 调试面板链接。 */
  getDebugLink() {
    const config = this.config.get();
    let link = "".concat(config.enableSSL === false ? 'http://' : 'https://').concat(config.api, "/#/devtools?address=").concat(encodeURIComponent(this.address));
    if (config.useSecret) {
      link += "&secret=".concat(config.secret);
    }
    return link;
  }
  /** Lynx 场景暂无内置面板,返回房间号供宿主侧展示。 */
  async showPanel() {
    if (this.address) {
      return Promise.reject(new Error("PageSpy \u623F\u95F4\u53F7\uFF1A".concat(this.address.slice(0, 4))));
    }
    return Promise.reject(new Error('PageSpy 房间号不存在'));
  }
}
/** 按执行顺序分组的插件注册表。 */
_defineProperty(PageSpy, "plugins", {
  pre: [],
  normal: [],
  post: []
});
PageSpy.client = new Client(getLynxClientInfo(), getLynxSystemInfo());
const INTERNAL_PLUGINS = [new ConsolePlugin(), new ErrorPlugin(), new NetworkPlugin(), new SystemPlugin(), new StoragePlugin(), new WebSocketPlugin()];
INTERNAL_PLUGINS.forEach(p => {
  PageSpy.registerPlugin(p);
});

export { clearStorage, PageSpy as default, getStorageItem, removeStorageItem, setStorageItem, storage };
//# sourceMappingURL=index.min.js.map