"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var clockSource_exports = {};
__export(clockSource_exports, {
  source: () => source
});
module.exports = __toCommonJS(clockSource_exports);
const source = '\nvar __commonJS = obj => {\n  let required = false;\n  let result;\n  return function __require() {\n    if (!required) {\n      required = true;\n      let fn;\n      for (const name in obj) { fn = obj[name]; break; }\n      const module = { exports: {} };\n      fn(module.exports, module);\n      result = module.exports;\n    }\n    return result;\n  }\n};\nvar __export = (target, all) => {for (var name in all) target[name] = all[name];};\nvar __toESM = mod => ({ ...mod, \'default\': mod });\nvar __toCommonJS = mod => ({ ...mod, __esModule: true });\n\n\n// packages/injected/src/clock.ts\nvar clock_exports = {};\n__export(clock_exports, {\n  ClockController: () => ClockController,\n  createClock: () => createClock,\n  inject: () => inject,\n  install: () => install\n});\nmodule.exports = __toCommonJS(clock_exports);\nvar ClockController = class {\n  constructor(embedder) {\n    this._duringTick = false;\n    this._uniqueTimerId = idCounterStart;\n    this.disposables = [];\n    this._log = [];\n    this._timers = /* @__PURE__ */ new Map();\n    this._now = { time: asWallTime(0), isFixedTime: false, ticks: 0, origin: asWallTime(-1) };\n    this._embedder = embedder;\n  }\n  uninstall() {\n    this.disposables.forEach((dispose) => dispose());\n    this.disposables.length = 0;\n  }\n  now() {\n    this._replayLogOnce();\n    this._syncRealTime();\n    return this._now.time;\n  }\n  install(time) {\n    this._replayLogOnce();\n    this._innerSetTime(asWallTime(time));\n  }\n  setSystemTime(time) {\n    this._replayLogOnce();\n    this._innerSetTime(asWallTime(time));\n  }\n  setFixedTime(time) {\n    this._replayLogOnce();\n    this._innerSetFixedTime(asWallTime(time));\n  }\n  performanceNow() {\n    this._replayLogOnce();\n    this._syncRealTime();\n    return this._now.ticks;\n  }\n  _syncRealTime() {\n    if (!this._realTime)\n      return;\n    const now = this._embedder.performanceNow();\n    const sinceLastSync = now - this._realTime.lastSyncTicks;\n    if (sinceLastSync > 0) {\n      this._advanceNow(shiftTicks(this._now.ticks, sinceLastSync));\n      this._realTime.lastSyncTicks = now;\n    }\n  }\n  _innerSetTime(time) {\n    this._now.time = time;\n    this._now.isFixedTime = false;\n    if (this._now.origin < 0)\n      this._now.origin = this._now.time;\n  }\n  _innerSetFixedTime(time) {\n    this._innerSetTime(time);\n    this._now.isFixedTime = true;\n  }\n  _advanceNow(to) {\n    if (this._now.ticks > to) {\n      return;\n    }\n    if (!this._now.isFixedTime)\n      this._now.time = asWallTime(this._now.time + to - this._now.ticks);\n    this._now.ticks = to;\n  }\n  async log(type, time, param) {\n    this._log.push({ type, time, param });\n  }\n  async runFor(ticks) {\n    this._replayLogOnce();\n    if (ticks < 0)\n      throw new TypeError("Negative ticks are not supported");\n    await this._runWithDisabledRealTimeSync(async () => {\n      await this._runTo(shiftTicks(this._now.ticks, ticks));\n    });\n  }\n  async _runTo(to) {\n    to = Math.ceil(to);\n    if (this._now.ticks > to)\n      return;\n    let firstException;\n    while (true) {\n      const result = await this._callFirstTimer(to);\n      if (!result.timerFound)\n        break;\n      firstException = firstException || result.error;\n    }\n    this._advanceNow(to);\n    if (firstException)\n      throw firstException;\n  }\n  async pauseAt(time) {\n    this._replayLogOnce();\n    await this._innerPause();\n    const toConsume = time - this._now.time;\n    await this._innerFastForwardTo(shiftTicks(this._now.ticks, toConsume));\n    return toConsume;\n  }\n  async _innerPause() {\n    var _a;\n    this._realTime = void 0;\n    await ((_a = this._currentRealTimeTimer) == null ? void 0 : _a.dispose());\n    this._currentRealTimeTimer = void 0;\n  }\n  resume() {\n    this._replayLogOnce();\n    this._innerResume();\n  }\n  _innerResume() {\n    const now = this._embedder.performanceNow();\n    this._realTime = { startTicks: now, lastSyncTicks: now };\n    this._updateRealTimeTimer();\n  }\n  _updateRealTimeTimer() {\n    var _a;\n    if ((_a = this._currentRealTimeTimer) == null ? void 0 : _a.promise) {\n      return;\n    }\n    const firstTimer = this._firstTimer();\n    const nextTick = Math.min(firstTimer ? firstTimer.callAt : this._now.ticks + maxTimeout, this._now.ticks + 100);\n    const callAt = this._currentRealTimeTimer ? Math.min(this._currentRealTimeTimer.callAt, nextTick) : nextTick;\n    if (this._currentRealTimeTimer) {\n      this._currentRealTimeTimer.cancel();\n      this._currentRealTimeTimer = void 0;\n    }\n    const realTimeTimer = {\n      callAt,\n      promise: void 0,\n      cancel: this._embedder.setTimeout(() => {\n        this._syncRealTime();\n        realTimeTimer.promise = this._runTo(this._now.ticks).catch((e) => console.error(e));\n        void realTimeTimer.promise.then(() => {\n          this._currentRealTimeTimer = void 0;\n          if (this._realTime)\n            this._updateRealTimeTimer();\n        });\n      }, callAt - this._now.ticks),\n      dispose: async () => {\n        realTimeTimer.cancel();\n        await realTimeTimer.promise;\n      }\n    };\n    this._currentRealTimeTimer = realTimeTimer;\n  }\n  async _runWithDisabledRealTimeSync(fn) {\n    if (!this._realTime) {\n      await fn();\n      return;\n    }\n    await this._innerPause();\n    try {\n      await fn();\n    } finally {\n      this._innerResume();\n    }\n  }\n  async fastForward(ticks) {\n    this._replayLogOnce();\n    await this._runWithDisabledRealTimeSync(async () => {\n      await this._innerFastForwardTo(shiftTicks(this._now.ticks, ticks | 0));\n    });\n  }\n  async _innerFastForwardTo(to) {\n    if (to < this._now.ticks)\n      throw new Error("Cannot fast-forward to the past");\n    for (const timer of this._timers.values()) {\n      if (to > timer.callAt)\n        timer.callAt = to;\n    }\n    await this._runTo(to);\n  }\n  addTimer(options) {\n    this._replayLogOnce();\n    if (options.type === "AnimationFrame" /* AnimationFrame */ && !options.func)\n      throw new Error("Callback must be provided to requestAnimationFrame calls");\n    if (options.type === "IdleCallback" /* IdleCallback */ && !options.func)\n      throw new Error("Callback must be provided to requestIdleCallback calls");\n    if (["Timeout" /* Timeout */, "Interval" /* Interval */].includes(options.type) && !options.func && options.delay === void 0)\n      throw new Error("Callback must be provided to timer calls");\n    let delay = options.delay ? +options.delay : 0;\n    if (!Number.isFinite(delay))\n      delay = 0;\n    delay = delay > maxTimeout ? 1 : delay;\n    delay = Math.max(0, delay);\n    const timer = {\n      type: options.type,\n      func: options.func,\n      args: options.args || [],\n      delay,\n      callAt: shiftTicks(this._now.ticks, delay || (this._duringTick ? 1 : 0)),\n      createdAt: this._now.ticks,\n      id: this._uniqueTimerId++,\n      error: new Error()\n    };\n    this._timers.set(timer.id, timer);\n    if (this._realTime)\n      this._updateRealTimeTimer();\n    return timer.id;\n  }\n  countTimers() {\n    return this._timers.size;\n  }\n  _firstTimer(beforeTick) {\n    let firstTimer = null;\n    for (const timer of this._timers.values()) {\n      const isInRange = beforeTick === void 0 || timer.callAt <= beforeTick;\n      if (isInRange && (!firstTimer || compareTimers(firstTimer, timer) === 1))\n        firstTimer = timer;\n    }\n    return firstTimer;\n  }\n  _takeFirstTimer(beforeTick) {\n    const timer = this._firstTimer(beforeTick);\n    if (!timer)\n      return null;\n    this._advanceNow(timer.callAt);\n    if (timer.type === "Interval" /* Interval */)\n      timer.callAt = shiftTicks(timer.callAt, timer.delay);\n    else\n      this._timers.delete(timer.id);\n    return timer;\n  }\n  async _callFirstTimer(beforeTick) {\n    const timer = this._takeFirstTimer(beforeTick);\n    if (!timer)\n      return { timerFound: false };\n    this._duringTick = true;\n    try {\n      if (typeof timer.func !== "function") {\n        let error2;\n        try {\n          (() => {\n            globalThis.eval(timer.func);\n          })();\n        } catch (e) {\n          error2 = e;\n        }\n        await new Promise((f) => this._embedder.setTimeout(f));\n        return { timerFound: true, error: error2 };\n      }\n      let args = timer.args;\n      if (timer.type === "AnimationFrame" /* AnimationFrame */)\n        args = [this._now.ticks];\n      else if (timer.type === "IdleCallback" /* IdleCallback */)\n        args = [{ didTimeout: false, timeRemaining: () => 0 }];\n      let error;\n      try {\n        timer.func.apply(null, args);\n      } catch (e) {\n        error = e;\n      }\n      await new Promise((f) => this._embedder.setTimeout(f));\n      return { timerFound: true, error };\n    } finally {\n      this._duringTick = false;\n    }\n  }\n  getTimeToNextFrame() {\n    this._replayLogOnce();\n    return 16 - this._now.ticks % 16;\n  }\n  clearTimer(timerId, type) {\n    this._replayLogOnce();\n    if (!timerId) {\n      return;\n    }\n    const id = Number(timerId);\n    if (Number.isNaN(id) || id < idCounterStart) {\n      const handlerName = getClearHandler(type);\n      new Error(`Clock: ${handlerName} was invoked to clear a native timer instead of one created by the clock library.`);\n    }\n    const timer = this._timers.get(id);\n    if (timer) {\n      if (timer.type === type || timer.type === "Timeout" && type === "Interval" || timer.type === "Interval" && type === "Timeout") {\n        this._timers.delete(id);\n      } else {\n        const clear = getClearHandler(type);\n        const schedule = getScheduleHandler(timer.type);\n        throw new Error(\n          `Cannot clear timer: timer created with ${schedule}() but cleared with ${clear}()`\n        );\n      }\n    }\n  }\n  _replayLogOnce() {\n    if (!this._log.length)\n      return;\n    let lastLogTime = -1;\n    let isPaused = false;\n    for (const { type, time, param } of this._log) {\n      if (!isPaused && lastLogTime !== -1)\n        this._advanceNow(shiftTicks(this._now.ticks, time - lastLogTime));\n      lastLogTime = time;\n      if (type === "install") {\n        this._innerSetTime(asWallTime(param));\n      } else if (type === "fastForward" || type === "runFor") {\n        this._advanceNow(shiftTicks(this._now.ticks, param));\n      } else if (type === "pauseAt") {\n        isPaused = true;\n        this._innerSetTime(asWallTime(param));\n      } else if (type === "resume") {\n        isPaused = false;\n      } else if (type === "setFixedTime") {\n        this._innerSetFixedTime(asWallTime(param));\n      } else if (type === "setSystemTime") {\n        this._innerSetTime(asWallTime(param));\n      }\n    }\n    if (!isPaused) {\n      if (lastLogTime > 0)\n        this._advanceNow(shiftTicks(this._now.ticks, this._embedder.dateNow() - lastLogTime));\n      this._innerResume();\n    } else {\n      this._realTime = void 0;\n    }\n    this._log.length = 0;\n  }\n};\nfunction mirrorDateProperties(target, source) {\n  for (const prop in source) {\n    if (source.hasOwnProperty(prop))\n      target[prop] = source[prop];\n  }\n  target.toString = () => source.toString();\n  target.prototype = source.prototype;\n  target.parse = source.parse;\n  target.UTC = source.UTC;\n  target.prototype.toUTCString = source.prototype.toUTCString;\n  target.isFake = true;\n  return target;\n}\nfunction createDate(clock, NativeDate) {\n  function ClockDate(year, month, date, hour, minute, second, ms) {\n    if (!(this instanceof ClockDate))\n      return new NativeDate(clock.now()).toString();\n    switch (arguments.length) {\n      case 0:\n        return new NativeDate(clock.now());\n      case 1:\n        return new NativeDate(year);\n      case 2:\n        return new NativeDate(year, month);\n      case 3:\n        return new NativeDate(year, month, date);\n      case 4:\n        return new NativeDate(year, month, date, hour);\n      case 5:\n        return new NativeDate(year, month, date, hour, minute);\n      case 6:\n        return new NativeDate(\n          year,\n          month,\n          date,\n          hour,\n          minute,\n          second\n        );\n      default:\n        return new NativeDate(\n          year,\n          month,\n          date,\n          hour,\n          minute,\n          second,\n          ms\n        );\n    }\n  }\n  ClockDate.now = () => clock.now();\n  return mirrorDateProperties(ClockDate, NativeDate);\n}\nfunction createIntl(clock, NativeIntl) {\n  const ClockIntl = {};\n  for (const key of Object.getOwnPropertyNames(NativeIntl))\n    ClockIntl[key] = NativeIntl[key];\n  ClockIntl.DateTimeFormat = function(...args) {\n    const realFormatter = new NativeIntl.DateTimeFormat(...args);\n    const formatter = {\n      formatRange: realFormatter.formatRange.bind(realFormatter),\n      formatRangeToParts: realFormatter.formatRangeToParts.bind(realFormatter),\n      resolvedOptions: realFormatter.resolvedOptions.bind(realFormatter),\n      format: (date) => realFormatter.format(date || clock.now()),\n      formatToParts: (date) => realFormatter.formatToParts(date || clock.now())\n    };\n    return formatter;\n  };\n  ClockIntl.DateTimeFormat.prototype = Object.create(\n    NativeIntl.DateTimeFormat.prototype\n  );\n  ClockIntl.DateTimeFormat.supportedLocalesOf = NativeIntl.DateTimeFormat.supportedLocalesOf;\n  return ClockIntl;\n}\nfunction compareTimers(a, b) {\n  if (a.callAt < b.callAt)\n    return -1;\n  if (a.callAt > b.callAt)\n    return 1;\n  if (a.type === "Immediate" /* Immediate */ && b.type !== "Immediate" /* Immediate */)\n    return -1;\n  if (a.type !== "Immediate" /* Immediate */ && b.type === "Immediate" /* Immediate */)\n    return 1;\n  if (a.createdAt < b.createdAt)\n    return -1;\n  if (a.createdAt > b.createdAt)\n    return 1;\n  if (a.id < b.id)\n    return -1;\n  if (a.id > b.id)\n    return 1;\n}\nvar maxTimeout = Math.pow(2, 31) - 1;\nvar idCounterStart = 1e12;\nfunction platformOriginals(globalObject) {\n  const raw = {\n    setTimeout: globalObject.setTimeout,\n    clearTimeout: globalObject.clearTimeout,\n    setInterval: globalObject.setInterval,\n    clearInterval: globalObject.clearInterval,\n    requestAnimationFrame: globalObject.requestAnimationFrame ? globalObject.requestAnimationFrame : void 0,\n    cancelAnimationFrame: globalObject.cancelAnimationFrame ? globalObject.cancelAnimationFrame : void 0,\n    requestIdleCallback: globalObject.requestIdleCallback ? globalObject.requestIdleCallback : void 0,\n    cancelIdleCallback: globalObject.cancelIdleCallback ? globalObject.cancelIdleCallback : void 0,\n    Date: globalObject.Date,\n    performance: globalObject.performance,\n    Intl: globalObject.Intl,\n    AbortSignal: globalObject.AbortSignal\n  };\n  const bound = { ...raw };\n  for (const key of Object.keys(bound)) {\n    if (key !== "Date" && key !== "AbortSignal" && typeof bound[key] === "function")\n      bound[key] = bound[key].bind(globalObject);\n  }\n  return { raw, bound };\n}\nfunction getScheduleHandler(type) {\n  if (type === "IdleCallback" || type === "AnimationFrame")\n    return `request${type}`;\n  return `set${type}`;\n}\nfunction createApi(clock, originals, browserName) {\n  return {\n    setTimeout: (func, timeout, ...args) => {\n      const delay = timeout ? +timeout : timeout;\n      return clock.addTimer({\n        type: "Timeout" /* Timeout */,\n        func,\n        args,\n        delay\n      });\n    },\n    clearTimeout: (timerId) => {\n      if (timerId)\n        clock.clearTimer(timerId, "Timeout" /* Timeout */);\n    },\n    setInterval: (func, timeout, ...args) => {\n      const delay = timeout ? +timeout : timeout;\n      return clock.addTimer({\n        type: "Interval" /* Interval */,\n        func,\n        args,\n        delay\n      });\n    },\n    clearInterval: (timerId) => {\n      if (timerId)\n        return clock.clearTimer(timerId, "Interval" /* Interval */);\n    },\n    requestAnimationFrame: (callback) => {\n      return clock.addTimer({\n        type: "AnimationFrame" /* AnimationFrame */,\n        func: callback,\n        delay: clock.getTimeToNextFrame()\n      });\n    },\n    cancelAnimationFrame: (timerId) => {\n      if (timerId)\n        return clock.clearTimer(timerId, "AnimationFrame" /* AnimationFrame */);\n    },\n    requestIdleCallback: (callback, options) => {\n      let timeToNextIdlePeriod = 0;\n      if (clock.countTimers() > 0)\n        timeToNextIdlePeriod = 50;\n      return clock.addTimer({\n        type: "IdleCallback" /* IdleCallback */,\n        func: callback,\n        delay: (options == null ? void 0 : options.timeout) ? Math.min(options == null ? void 0 : options.timeout, timeToNextIdlePeriod) : timeToNextIdlePeriod\n      });\n    },\n    cancelIdleCallback: (timerId) => {\n      if (timerId)\n        return clock.clearTimer(timerId, "IdleCallback" /* IdleCallback */);\n    },\n    Intl: originals.Intl ? createIntl(clock, originals.Intl) : void 0,\n    Date: createDate(clock, originals.Date),\n    performance: originals.performance ? fakePerformance(clock, originals.performance) : void 0,\n    AbortSignal: originals.AbortSignal ? fakeAbortSignal(clock, originals.AbortSignal, browserName) : void 0\n  };\n}\nfunction getClearHandler(type) {\n  if (type === "IdleCallback" || type === "AnimationFrame")\n    return `cancel${type}`;\n  return `clear${type}`;\n}\nvar FakePerformanceEntry = class {\n  constructor(name, entryType, startTime, duration) {\n    this.name = name;\n    this.entryType = entryType;\n    this.startTime = startTime;\n    this.duration = duration;\n  }\n  toJSON() {\n    return JSON.stringify({ ...this });\n  }\n};\nfunction fakePerformance(clock, performance) {\n  const result = {\n    now: () => clock.performanceNow()\n  };\n  result.__defineGetter__("timeOrigin", () => clock._now.origin || 0);\n  for (const key of Object.keys(performance.__proto__)) {\n    if (key === "now" || key === "timeOrigin")\n      continue;\n    if (key === "getEntries" || key === "getEntriesByName" || key === "getEntriesByType")\n      result[key] = () => [];\n    else if (key === "mark")\n      result[key] = (name) => new FakePerformanceEntry(name, "mark", 0, 0);\n    else if (key === "measure")\n      result[key] = (name) => new FakePerformanceEntry(name, "measure", 0, 50);\n    else\n      result[key] = () => {\n      };\n  }\n  return result;\n}\nfunction fakeAbortSignal(clock, abortSignal, browserName) {\n  Object.defineProperty(abortSignal, "timeout", {\n    value(ms) {\n      const controller = new AbortController();\n      clock.addTimer({\n        delay: ms,\n        type: "Timeout" /* Timeout */,\n        func: () => controller.abort(\n          new DOMException(\n            browserName === "chromium" ? "signal timed out" : "The operation timed out.",\n            "TimeoutError"\n          )\n        )\n      });\n      return controller.signal;\n    }\n  });\n  return abortSignal;\n}\nfunction createClock(globalObject, config = {}) {\n  const originals = platformOriginals(globalObject);\n  const embedder = {\n    dateNow: () => originals.raw.Date.now(),\n    performanceNow: () => Math.ceil(originals.raw.performance.now()),\n    setTimeout: (task, timeout) => {\n      const timerId = originals.bound.setTimeout(task, timeout);\n      return () => originals.bound.clearTimeout(timerId);\n    },\n    setInterval: (task, delay) => {\n      const intervalId = originals.bound.setInterval(task, delay);\n      return () => originals.bound.clearInterval(intervalId);\n    }\n  };\n  const clock = new ClockController(embedder);\n  const api = createApi(clock, originals.bound, config.browserName);\n  return { clock, api, originals: originals.raw };\n}\nfunction install(globalObject, config = {}) {\n  var _a, _b;\n  if ((_a = globalObject.Date) == null ? void 0 : _a.isFake) {\n    throw new TypeError(`Can\'t install fake timers twice on the same global object.`);\n  }\n  const { clock, api, originals } = createClock(globalObject, config);\n  const toFake = ((_b = config.toFake) == null ? void 0 : _b.length) ? config.toFake : Object.keys(originals);\n  for (const method of toFake) {\n    if (method === "Date") {\n      globalObject.Date = mirrorDateProperties(api.Date, globalObject.Date);\n    } else if (method === "Intl") {\n      globalObject.Intl = api[method];\n    } else if (method === "AbortSignal") {\n      globalObject.AbortSignal = api[method];\n    } else if (method === "performance") {\n      globalObject.performance = api[method];\n      const kEventTimeStamp = Symbol("playwrightEventTimeStamp");\n      Object.defineProperty(Event.prototype, "timeStamp", {\n        get() {\n          var _a2;\n          if (!this[kEventTimeStamp])\n            this[kEventTimeStamp] = (_a2 = api.performance) == null ? void 0 : _a2.now();\n          return this[kEventTimeStamp];\n        }\n      });\n    } else {\n      globalObject[method] = (...args) => {\n        return api[method].apply(api, args);\n      };\n    }\n    clock.disposables.push(() => {\n      globalObject[method] = originals[method];\n    });\n  }\n  return { clock, api, originals };\n}\nfunction inject(globalObject, browserName) {\n  const builtins = platformOriginals(globalObject).bound;\n  const { clock: controller } = install(globalObject, { browserName });\n  controller.resume();\n  return {\n    controller,\n    builtins\n  };\n}\nfunction asWallTime(n) {\n  return n;\n}\nfunction shiftTicks(ticks, ms) {\n  return ticks + ms;\n}\n';
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  source
});
