var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __export = (target, all2) => {
  for (var name in all2)
    __defProp(target, name, { get: all2[name], enumerable: true });
};
var __publicField = (obj, key, value) => {
  __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
  return value;
};

// node_modules/.pnpm/unenv@2.0.0-rc.14/node_modules/unenv/dist/runtime/_internal/utils.mjs
function createNotImplementedError(name) {
  return new Error(`[unenv] ${name} is not implemented yet!`);
}
__name(createNotImplementedError, "createNotImplementedError");
function notImplemented(name) {
  const fn = /* @__PURE__ */ __name(() => {
    throw createNotImplementedError(name);
  }, "fn");
  return Object.assign(fn, { __unenv__: true });
}
__name(notImplemented, "notImplemented");
function notImplementedClass(name) {
  return class {
    __unenv__ = true;
    constructor() {
      throw new Error(`[unenv] ${name} is not implemented yet!`);
    }
  };
}
__name(notImplementedClass, "notImplementedClass");

// node_modules/.pnpm/unenv@2.0.0-rc.14/node_modules/unenv/dist/runtime/node/internal/perf_hooks/performance.mjs
var _timeOrigin = globalThis.performance?.timeOrigin ?? Date.now();
var _performanceNow = globalThis.performance?.now ? globalThis.performance.now.bind(globalThis.performance) : () => Date.now() - _timeOrigin;
var nodeTiming = {
  name: "node",
  entryType: "node",
  startTime: 0,
  duration: 0,
  nodeStart: 0,
  v8Start: 0,
  bootstrapComplete: 0,
  environment: 0,
  loopStart: 0,
  loopExit: 0,
  idleTime: 0,
  uvMetricsInfo: {
    loopCount: 0,
    events: 0,
    eventsWaiting: 0
  },
  detail: void 0,
  toJSON() {
    return this;
  }
};
var PerformanceEntry = class {
  __unenv__ = true;
  detail;
  entryType = "event";
  name;
  startTime;
  constructor(name, options) {
    this.name = name;
    this.startTime = options?.startTime || _performanceNow();
    this.detail = options?.detail;
  }
  get duration() {
    return _performanceNow() - this.startTime;
  }
  toJSON() {
    return {
      name: this.name,
      entryType: this.entryType,
      startTime: this.startTime,
      duration: this.duration,
      detail: this.detail
    };
  }
};
__name(PerformanceEntry, "PerformanceEntry");
var PerformanceMark = /* @__PURE__ */ __name(class PerformanceMark2 extends PerformanceEntry {
  entryType = "mark";
  constructor() {
    super(...arguments);
  }
  get duration() {
    return 0;
  }
}, "PerformanceMark");
var PerformanceMeasure = class extends PerformanceEntry {
  entryType = "measure";
};
__name(PerformanceMeasure, "PerformanceMeasure");
var PerformanceResourceTiming = class extends PerformanceEntry {
  entryType = "resource";
  serverTiming = [];
  connectEnd = 0;
  connectStart = 0;
  decodedBodySize = 0;
  domainLookupEnd = 0;
  domainLookupStart = 0;
  encodedBodySize = 0;
  fetchStart = 0;
  initiatorType = "";
  name = "";
  nextHopProtocol = "";
  redirectEnd = 0;
  redirectStart = 0;
  requestStart = 0;
  responseEnd = 0;
  responseStart = 0;
  secureConnectionStart = 0;
  startTime = 0;
  transferSize = 0;
  workerStart = 0;
  responseStatus = 0;
};
__name(PerformanceResourceTiming, "PerformanceResourceTiming");
var PerformanceObserverEntryList = class {
  __unenv__ = true;
  getEntries() {
    return [];
  }
  getEntriesByName(_name, _type) {
    return [];
  }
  getEntriesByType(type) {
    return [];
  }
};
__name(PerformanceObserverEntryList, "PerformanceObserverEntryList");
var Performance = class {
  __unenv__ = true;
  timeOrigin = _timeOrigin;
  eventCounts = /* @__PURE__ */ new Map();
  _entries = [];
  _resourceTimingBufferSize = 0;
  navigation = void 0;
  timing = void 0;
  timerify(_fn, _options) {
    throw createNotImplementedError("Performance.timerify");
  }
  get nodeTiming() {
    return nodeTiming;
  }
  eventLoopUtilization() {
    return {};
  }
  markResourceTiming() {
    return new PerformanceResourceTiming("");
  }
  onresourcetimingbufferfull = null;
  now() {
    if (this.timeOrigin === _timeOrigin) {
      return _performanceNow();
    }
    return Date.now() - this.timeOrigin;
  }
  clearMarks(markName) {
    this._entries = markName ? this._entries.filter((e) => e.name !== markName) : this._entries.filter((e) => e.entryType !== "mark");
  }
  clearMeasures(measureName) {
    this._entries = measureName ? this._entries.filter((e) => e.name !== measureName) : this._entries.filter((e) => e.entryType !== "measure");
  }
  clearResourceTimings() {
    this._entries = this._entries.filter((e) => e.entryType !== "resource" || e.entryType !== "navigation");
  }
  getEntries() {
    return this._entries;
  }
  getEntriesByName(name, type) {
    return this._entries.filter((e) => e.name === name && (!type || e.entryType === type));
  }
  getEntriesByType(type) {
    return this._entries.filter((e) => e.entryType === type);
  }
  mark(name, options) {
    const entry = new PerformanceMark(name, options);
    this._entries.push(entry);
    return entry;
  }
  measure(measureName, startOrMeasureOptions, endMark) {
    let start;
    let end;
    if (typeof startOrMeasureOptions === "string") {
      start = this.getEntriesByName(startOrMeasureOptions, "mark")[0]?.startTime;
      end = this.getEntriesByName(endMark, "mark")[0]?.startTime;
    } else {
      start = Number.parseFloat(startOrMeasureOptions?.start) || this.now();
      end = Number.parseFloat(startOrMeasureOptions?.end) || this.now();
    }
    const entry = new PerformanceMeasure(measureName, {
      startTime: start,
      detail: {
        start,
        end
      }
    });
    this._entries.push(entry);
    return entry;
  }
  setResourceTimingBufferSize(maxSize) {
    this._resourceTimingBufferSize = maxSize;
  }
  addEventListener(type, listener, options) {
    throw createNotImplementedError("Performance.addEventListener");
  }
  removeEventListener(type, listener, options) {
    throw createNotImplementedError("Performance.removeEventListener");
  }
  dispatchEvent(event) {
    throw createNotImplementedError("Performance.dispatchEvent");
  }
  toJSON() {
    return this;
  }
};
__name(Performance, "Performance");
var PerformanceObserver = class {
  __unenv__ = true;
  _callback = null;
  constructor(callback) {
    this._callback = callback;
  }
  takeRecords() {
    return [];
  }
  disconnect() {
    throw createNotImplementedError("PerformanceObserver.disconnect");
  }
  observe(options) {
    throw createNotImplementedError("PerformanceObserver.observe");
  }
  bind(fn) {
    return fn;
  }
  runInAsyncScope(fn, thisArg, ...args) {
    return fn.call(thisArg, ...args);
  }
  asyncId() {
    return 0;
  }
  triggerAsyncId() {
    return 0;
  }
  emitDestroy() {
    return this;
  }
};
__name(PerformanceObserver, "PerformanceObserver");
__publicField(PerformanceObserver, "supportedEntryTypes", []);
var performance = globalThis.performance && "addEventListener" in globalThis.performance ? globalThis.performance : new Performance();

// node_modules/.pnpm/@cloudflare+unenv-preset@2.0.2_unenv@2.0.0-rc.14_workerd@1.20250718.0/node_modules/@cloudflare/unenv-preset/dist/runtime/polyfill/performance.mjs
globalThis.performance = performance;
globalThis.Performance = Performance;
globalThis.PerformanceEntry = PerformanceEntry;
globalThis.PerformanceMark = PerformanceMark;
globalThis.PerformanceMeasure = PerformanceMeasure;
globalThis.PerformanceObserver = PerformanceObserver;
globalThis.PerformanceObserverEntryList = PerformanceObserverEntryList;
globalThis.PerformanceResourceTiming = PerformanceResourceTiming;

// node_modules/.pnpm/unenv@2.0.0-rc.14/node_modules/unenv/dist/runtime/node/console.mjs
import { Writable } from "node:stream";

// node_modules/.pnpm/unenv@2.0.0-rc.14/node_modules/unenv/dist/runtime/mock/noop.mjs
var noop_default = Object.assign(() => {
}, { __unenv__: true });

// node_modules/.pnpm/unenv@2.0.0-rc.14/node_modules/unenv/dist/runtime/node/console.mjs
var _console = globalThis.console;
var _ignoreErrors = true;
var _stderr = new Writable();
var _stdout = new Writable();
var log = _console?.log ?? noop_default;
var info = _console?.info ?? log;
var trace = _console?.trace ?? info;
var debug = _console?.debug ?? log;
var table = _console?.table ?? log;
var error = _console?.error ?? log;
var warn = _console?.warn ?? error;
var createTask = _console?.createTask ?? /* @__PURE__ */ notImplemented("console.createTask");
var clear = _console?.clear ?? noop_default;
var count = _console?.count ?? noop_default;
var countReset = _console?.countReset ?? noop_default;
var dir = _console?.dir ?? noop_default;
var dirxml = _console?.dirxml ?? noop_default;
var group = _console?.group ?? noop_default;
var groupEnd = _console?.groupEnd ?? noop_default;
var groupCollapsed = _console?.groupCollapsed ?? noop_default;
var profile = _console?.profile ?? noop_default;
var profileEnd = _console?.profileEnd ?? noop_default;
var time = _console?.time ?? noop_default;
var timeEnd = _console?.timeEnd ?? noop_default;
var timeLog = _console?.timeLog ?? noop_default;
var timeStamp = _console?.timeStamp ?? noop_default;
var Console = _console?.Console ?? /* @__PURE__ */ notImplementedClass("console.Console");
var _times = /* @__PURE__ */ new Map();
var _stdoutErrorHandler = noop_default;
var _stderrErrorHandler = noop_default;

// node_modules/.pnpm/@cloudflare+unenv-preset@2.0.2_unenv@2.0.0-rc.14_workerd@1.20250718.0/node_modules/@cloudflare/unenv-preset/dist/runtime/node/console.mjs
var workerdConsole = globalThis["console"];
var {
  assert,
  clear: clear2,
  // @ts-expect-error undocumented public API
  context,
  count: count2,
  countReset: countReset2,
  // @ts-expect-error undocumented public API
  createTask: createTask2,
  debug: debug2,
  dir: dir2,
  dirxml: dirxml2,
  error: error2,
  group: group2,
  groupCollapsed: groupCollapsed2,
  groupEnd: groupEnd2,
  info: info2,
  log: log2,
  profile: profile2,
  profileEnd: profileEnd2,
  table: table2,
  time: time2,
  timeEnd: timeEnd2,
  timeLog: timeLog2,
  timeStamp: timeStamp2,
  trace: trace2,
  warn: warn2
} = workerdConsole;
Object.assign(workerdConsole, {
  Console,
  _ignoreErrors,
  _stderr,
  _stderrErrorHandler,
  _stdout,
  _stdoutErrorHandler,
  _times
});
var console_default = workerdConsole;

// node_modules/.pnpm/wrangler@3.114.17_@cloudflare+workers-types@4.20260526.1/node_modules/wrangler/_virtual_unenv_global_polyfill-@cloudflare-unenv-preset-node-console
globalThis.console = console_default;

// node_modules/.pnpm/unenv@2.0.0-rc.14/node_modules/unenv/dist/runtime/node/internal/process/hrtime.mjs
var hrtime = /* @__PURE__ */ Object.assign(/* @__PURE__ */ __name(function hrtime2(startTime) {
  const now = Date.now();
  const seconds = Math.trunc(now / 1e3);
  const nanos = now % 1e3 * 1e6;
  if (startTime) {
    let diffSeconds = seconds - startTime[0];
    let diffNanos = nanos - startTime[0];
    if (diffNanos < 0) {
      diffSeconds = diffSeconds - 1;
      diffNanos = 1e9 + diffNanos;
    }
    return [diffSeconds, diffNanos];
  }
  return [seconds, nanos];
}, "hrtime"), { bigint: /* @__PURE__ */ __name(function bigint() {
  return BigInt(Date.now() * 1e6);
}, "bigint") });

// node_modules/.pnpm/unenv@2.0.0-rc.14/node_modules/unenv/dist/runtime/node/internal/process/process.mjs
import { EventEmitter } from "node:events";

// node_modules/.pnpm/unenv@2.0.0-rc.14/node_modules/unenv/dist/runtime/node/internal/tty/read-stream.mjs
import { Socket } from "node:net";
var ReadStream = class extends Socket {
  fd;
  constructor(fd) {
    super();
    this.fd = fd;
  }
  isRaw = false;
  setRawMode(mode) {
    this.isRaw = mode;
    return this;
  }
  isTTY = false;
};
__name(ReadStream, "ReadStream");

// node_modules/.pnpm/unenv@2.0.0-rc.14/node_modules/unenv/dist/runtime/node/internal/tty/write-stream.mjs
import { Socket as Socket2 } from "node:net";
var WriteStream = class extends Socket2 {
  fd;
  constructor(fd) {
    super();
    this.fd = fd;
  }
  clearLine(dir3, callback) {
    callback && callback();
    return false;
  }
  clearScreenDown(callback) {
    callback && callback();
    return false;
  }
  cursorTo(x, y, callback) {
    callback && typeof callback === "function" && callback();
    return false;
  }
  moveCursor(dx, dy, callback) {
    callback && callback();
    return false;
  }
  getColorDepth(env2) {
    return 1;
  }
  hasColors(count3, env2) {
    return false;
  }
  getWindowSize() {
    return [this.columns, this.rows];
  }
  columns = 80;
  rows = 24;
  isTTY = false;
};
__name(WriteStream, "WriteStream");

// node_modules/.pnpm/unenv@2.0.0-rc.14/node_modules/unenv/dist/runtime/node/internal/process/process.mjs
var Process = class extends EventEmitter {
  env;
  hrtime;
  nextTick;
  constructor(impl) {
    super();
    this.env = impl.env;
    this.hrtime = impl.hrtime;
    this.nextTick = impl.nextTick;
    for (const prop of [...Object.getOwnPropertyNames(Process.prototype), ...Object.getOwnPropertyNames(EventEmitter.prototype)]) {
      const value = this[prop];
      if (typeof value === "function") {
        this[prop] = value.bind(this);
      }
    }
  }
  emitWarning(warning, type, code) {
    console.warn(`${code ? `[${code}] ` : ""}${type ? `${type}: ` : ""}${warning}`);
  }
  emit(...args) {
    return super.emit(...args);
  }
  listeners(eventName) {
    return super.listeners(eventName);
  }
  #stdin;
  #stdout;
  #stderr;
  get stdin() {
    return this.#stdin ??= new ReadStream(0);
  }
  get stdout() {
    return this.#stdout ??= new WriteStream(1);
  }
  get stderr() {
    return this.#stderr ??= new WriteStream(2);
  }
  #cwd = "/";
  chdir(cwd2) {
    this.#cwd = cwd2;
  }
  cwd() {
    return this.#cwd;
  }
  arch = "";
  platform = "";
  argv = [];
  argv0 = "";
  execArgv = [];
  execPath = "";
  title = "";
  pid = 200;
  ppid = 100;
  get version() {
    return "";
  }
  get versions() {
    return {};
  }
  get allowedNodeEnvironmentFlags() {
    return /* @__PURE__ */ new Set();
  }
  get sourceMapsEnabled() {
    return false;
  }
  get debugPort() {
    return 0;
  }
  get throwDeprecation() {
    return false;
  }
  get traceDeprecation() {
    return false;
  }
  get features() {
    return {};
  }
  get release() {
    return {};
  }
  get connected() {
    return false;
  }
  get config() {
    return {};
  }
  get moduleLoadList() {
    return [];
  }
  constrainedMemory() {
    return 0;
  }
  availableMemory() {
    return 0;
  }
  uptime() {
    return 0;
  }
  resourceUsage() {
    return {};
  }
  ref() {
  }
  unref() {
  }
  umask() {
    throw createNotImplementedError("process.umask");
  }
  getBuiltinModule() {
    return void 0;
  }
  getActiveResourcesInfo() {
    throw createNotImplementedError("process.getActiveResourcesInfo");
  }
  exit() {
    throw createNotImplementedError("process.exit");
  }
  reallyExit() {
    throw createNotImplementedError("process.reallyExit");
  }
  kill() {
    throw createNotImplementedError("process.kill");
  }
  abort() {
    throw createNotImplementedError("process.abort");
  }
  dlopen() {
    throw createNotImplementedError("process.dlopen");
  }
  setSourceMapsEnabled() {
    throw createNotImplementedError("process.setSourceMapsEnabled");
  }
  loadEnvFile() {
    throw createNotImplementedError("process.loadEnvFile");
  }
  disconnect() {
    throw createNotImplementedError("process.disconnect");
  }
  cpuUsage() {
    throw createNotImplementedError("process.cpuUsage");
  }
  setUncaughtExceptionCaptureCallback() {
    throw createNotImplementedError("process.setUncaughtExceptionCaptureCallback");
  }
  hasUncaughtExceptionCaptureCallback() {
    throw createNotImplementedError("process.hasUncaughtExceptionCaptureCallback");
  }
  initgroups() {
    throw createNotImplementedError("process.initgroups");
  }
  openStdin() {
    throw createNotImplementedError("process.openStdin");
  }
  assert() {
    throw createNotImplementedError("process.assert");
  }
  binding() {
    throw createNotImplementedError("process.binding");
  }
  permission = { has: /* @__PURE__ */ notImplemented("process.permission.has") };
  report = {
    directory: "",
    filename: "",
    signal: "SIGUSR2",
    compact: false,
    reportOnFatalError: false,
    reportOnSignal: false,
    reportOnUncaughtException: false,
    getReport: /* @__PURE__ */ notImplemented("process.report.getReport"),
    writeReport: /* @__PURE__ */ notImplemented("process.report.writeReport")
  };
  finalization = {
    register: /* @__PURE__ */ notImplemented("process.finalization.register"),
    unregister: /* @__PURE__ */ notImplemented("process.finalization.unregister"),
    registerBeforeExit: /* @__PURE__ */ notImplemented("process.finalization.registerBeforeExit")
  };
  memoryUsage = Object.assign(() => ({
    arrayBuffers: 0,
    rss: 0,
    external: 0,
    heapTotal: 0,
    heapUsed: 0
  }), { rss: () => 0 });
  mainModule = void 0;
  domain = void 0;
  send = void 0;
  exitCode = void 0;
  channel = void 0;
  getegid = void 0;
  geteuid = void 0;
  getgid = void 0;
  getgroups = void 0;
  getuid = void 0;
  setegid = void 0;
  seteuid = void 0;
  setgid = void 0;
  setgroups = void 0;
  setuid = void 0;
  _events = void 0;
  _eventsCount = void 0;
  _exiting = void 0;
  _maxListeners = void 0;
  _debugEnd = void 0;
  _debugProcess = void 0;
  _fatalException = void 0;
  _getActiveHandles = void 0;
  _getActiveRequests = void 0;
  _kill = void 0;
  _preload_modules = void 0;
  _rawDebug = void 0;
  _startProfilerIdleNotifier = void 0;
  _stopProfilerIdleNotifier = void 0;
  _tickCallback = void 0;
  _disconnect = void 0;
  _handleQueue = void 0;
  _pendingMessage = void 0;
  _channel = void 0;
  _send = void 0;
  _linkedBinding = void 0;
};
__name(Process, "Process");

// node_modules/.pnpm/@cloudflare+unenv-preset@2.0.2_unenv@2.0.0-rc.14_workerd@1.20250718.0/node_modules/@cloudflare/unenv-preset/dist/runtime/node/process.mjs
var globalProcess = globalThis["process"];
var getBuiltinModule = globalProcess.getBuiltinModule;
var { exit, platform, nextTick } = getBuiltinModule(
  "node:process"
);
var unenvProcess = new Process({
  env: globalProcess.env,
  hrtime,
  nextTick
});
var {
  abort,
  addListener,
  allowedNodeEnvironmentFlags,
  hasUncaughtExceptionCaptureCallback,
  setUncaughtExceptionCaptureCallback,
  loadEnvFile,
  sourceMapsEnabled,
  arch,
  argv,
  argv0,
  chdir,
  config,
  connected,
  constrainedMemory,
  availableMemory,
  cpuUsage,
  cwd,
  debugPort,
  dlopen,
  disconnect,
  emit,
  emitWarning,
  env,
  eventNames,
  execArgv,
  execPath,
  finalization,
  features,
  getActiveResourcesInfo,
  getMaxListeners,
  hrtime: hrtime3,
  kill,
  listeners,
  listenerCount,
  memoryUsage,
  on,
  off,
  once,
  pid,
  ppid,
  prependListener,
  prependOnceListener,
  rawListeners,
  release,
  removeAllListeners,
  removeListener,
  report,
  resourceUsage,
  setMaxListeners,
  setSourceMapsEnabled,
  stderr,
  stdin,
  stdout,
  title,
  throwDeprecation,
  traceDeprecation,
  umask,
  uptime,
  version,
  versions,
  domain,
  initgroups,
  moduleLoadList,
  reallyExit,
  openStdin,
  assert: assert2,
  binding,
  send,
  exitCode,
  channel,
  getegid,
  geteuid,
  getgid,
  getgroups,
  getuid,
  setegid,
  seteuid,
  setgid,
  setgroups,
  setuid,
  permission,
  mainModule,
  _events,
  _eventsCount,
  _exiting,
  _maxListeners,
  _debugEnd,
  _debugProcess,
  _fatalException,
  _getActiveHandles,
  _getActiveRequests,
  _kill,
  _preload_modules,
  _rawDebug,
  _startProfilerIdleNotifier,
  _stopProfilerIdleNotifier,
  _tickCallback,
  _disconnect,
  _handleQueue,
  _pendingMessage,
  _channel,
  _send,
  _linkedBinding
} = unenvProcess;
var _process = {
  abort,
  addListener,
  allowedNodeEnvironmentFlags,
  hasUncaughtExceptionCaptureCallback,
  setUncaughtExceptionCaptureCallback,
  loadEnvFile,
  sourceMapsEnabled,
  arch,
  argv,
  argv0,
  chdir,
  config,
  connected,
  constrainedMemory,
  availableMemory,
  cpuUsage,
  cwd,
  debugPort,
  dlopen,
  disconnect,
  emit,
  emitWarning,
  env,
  eventNames,
  execArgv,
  execPath,
  exit,
  finalization,
  features,
  getBuiltinModule,
  getActiveResourcesInfo,
  getMaxListeners,
  hrtime: hrtime3,
  kill,
  listeners,
  listenerCount,
  memoryUsage,
  nextTick,
  on,
  off,
  once,
  pid,
  platform,
  ppid,
  prependListener,
  prependOnceListener,
  rawListeners,
  release,
  removeAllListeners,
  removeListener,
  report,
  resourceUsage,
  setMaxListeners,
  setSourceMapsEnabled,
  stderr,
  stdin,
  stdout,
  title,
  throwDeprecation,
  traceDeprecation,
  umask,
  uptime,
  version,
  versions,
  // @ts-expect-error old API
  domain,
  initgroups,
  moduleLoadList,
  reallyExit,
  openStdin,
  assert: assert2,
  binding,
  send,
  exitCode,
  channel,
  getegid,
  geteuid,
  getgid,
  getgroups,
  getuid,
  setegid,
  seteuid,
  setgid,
  setgroups,
  setuid,
  permission,
  mainModule,
  _events,
  _eventsCount,
  _exiting,
  _maxListeners,
  _debugEnd,
  _debugProcess,
  _fatalException,
  _getActiveHandles,
  _getActiveRequests,
  _kill,
  _preload_modules,
  _rawDebug,
  _startProfilerIdleNotifier,
  _stopProfilerIdleNotifier,
  _tickCallback,
  _disconnect,
  _handleQueue,
  _pendingMessage,
  _channel,
  _send,
  _linkedBinding
};
var process_default = _process;

// node_modules/.pnpm/wrangler@3.114.17_@cloudflare+workers-types@4.20260526.1/node_modules/wrangler/_virtual_unenv_global_polyfill-@cloudflare-unenv-preset-node-process
globalThis.process = process_default;

// node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/compose.js
var compose = /* @__PURE__ */ __name((middleware, onError, onNotFound) => {
  return (context2, next) => {
    let index = -1;
    return dispatch(0);
    async function dispatch(i) {
      if (i <= index) {
        throw new Error("next() called multiple times");
      }
      index = i;
      let res;
      let isError = false;
      let handler;
      if (middleware[i]) {
        handler = middleware[i][0][0];
        context2.req.routeIndex = i;
      } else {
        handler = i === middleware.length && next || void 0;
      }
      if (handler) {
        try {
          res = await handler(context2, () => dispatch(i + 1));
        } catch (err) {
          if (err instanceof Error && onError) {
            context2.error = err;
            res = await onError(err, context2);
            isError = true;
          } else {
            throw err;
          }
        }
      } else {
        if (context2.finalized === false && onNotFound) {
          res = await onNotFound(context2);
        }
      }
      if (res && (context2.finalized === false || isError)) {
        context2.res = res;
      }
      return context2;
    }
    __name(dispatch, "dispatch");
  };
}, "compose");

// node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/request/constants.js
var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();

// node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/utils/body.js
var parseBody = /* @__PURE__ */ __name(async (request, options = /* @__PURE__ */ Object.create(null)) => {
  const { all: all2 = false, dot = false } = options;
  const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
  const contentType = headers.get("Content-Type");
  if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
    return parseFormData(request, { all: all2, dot });
  }
  return {};
}, "parseBody");
async function parseFormData(request, options) {
  const formData = await request.formData();
  if (formData) {
    return convertFormDataToBodyData(formData, options);
  }
  return {};
}
__name(parseFormData, "parseFormData");
function convertFormDataToBodyData(formData, options) {
  const form2 = /* @__PURE__ */ Object.create(null);
  formData.forEach((value, key) => {
    const shouldParseAllValues = options.all || key.endsWith("[]");
    if (!shouldParseAllValues) {
      form2[key] = value;
    } else {
      handleParsingAllValues(form2, key, value);
    }
  });
  if (options.dot) {
    Object.entries(form2).forEach(([key, value]) => {
      const shouldParseDotValues = key.includes(".");
      if (shouldParseDotValues) {
        handleParsingNestedValues(form2, key, value);
        delete form2[key];
      }
    });
  }
  return form2;
}
__name(convertFormDataToBodyData, "convertFormDataToBodyData");
var handleParsingAllValues = /* @__PURE__ */ __name((form2, key, value) => {
  if (form2[key] !== void 0) {
    if (Array.isArray(form2[key])) {
      ;
      form2[key].push(value);
    } else {
      form2[key] = [form2[key], value];
    }
  } else {
    if (!key.endsWith("[]")) {
      form2[key] = value;
    } else {
      form2[key] = [value];
    }
  }
}, "handleParsingAllValues");
var handleParsingNestedValues = /* @__PURE__ */ __name((form2, key, value) => {
  if (/(?:^|\.)__proto__\./.test(key)) {
    return;
  }
  let nestedForm = form2;
  const keys = key.split(".");
  keys.forEach((key2, index) => {
    if (index === keys.length - 1) {
      nestedForm[key2] = value;
    } else {
      if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
        nestedForm[key2] = /* @__PURE__ */ Object.create(null);
      }
      nestedForm = nestedForm[key2];
    }
  });
}, "handleParsingNestedValues");

// node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/utils/url.js
var splitPath = /* @__PURE__ */ __name((path) => {
  const paths = path.split("/");
  if (paths[0] === "") {
    paths.shift();
  }
  return paths;
}, "splitPath");
var splitRoutingPath = /* @__PURE__ */ __name((routePath) => {
  const { groups, path } = extractGroupsFromPath(routePath);
  const paths = splitPath(path);
  return replaceGroupMarks(paths, groups);
}, "splitRoutingPath");
var extractGroupsFromPath = /* @__PURE__ */ __name((path) => {
  const groups = [];
  path = path.replace(/\{[^}]+\}/g, (match2, index) => {
    const mark = `@${index}`;
    groups.push([mark, match2]);
    return mark;
  });
  return { groups, path };
}, "extractGroupsFromPath");
var replaceGroupMarks = /* @__PURE__ */ __name((paths, groups) => {
  for (let i = groups.length - 1; i >= 0; i--) {
    const [mark] = groups[i];
    for (let j = paths.length - 1; j >= 0; j--) {
      if (paths[j].includes(mark)) {
        paths[j] = paths[j].replace(mark, groups[i][1]);
        break;
      }
    }
  }
  return paths;
}, "replaceGroupMarks");
var patternCache = {};
var getPattern = /* @__PURE__ */ __name((label, next) => {
  if (label === "*") {
    return "*";
  }
  const match2 = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
  if (match2) {
    const cacheKey = `${label}#${next}`;
    if (!patternCache[cacheKey]) {
      if (match2[2]) {
        patternCache[cacheKey] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey, match2[1], new RegExp(`^${match2[2]}(?=/${next})`)] : [label, match2[1], new RegExp(`^${match2[2]}$`)];
      } else {
        patternCache[cacheKey] = [label, match2[1], true];
      }
    }
    return patternCache[cacheKey];
  }
  return null;
}, "getPattern");
var tryDecode = /* @__PURE__ */ __name((str, decoder) => {
  try {
    return decoder(str);
  } catch {
    return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match2) => {
      try {
        return decoder(match2);
      } catch {
        return match2;
      }
    });
  }
}, "tryDecode");
var tryDecodeURI = /* @__PURE__ */ __name((str) => tryDecode(str, decodeURI), "tryDecodeURI");
var getPath = /* @__PURE__ */ __name((request) => {
  const url = request.url;
  const start = url.indexOf("/", url.indexOf(":") + 4);
  let i = start;
  for (; i < url.length; i++) {
    const charCode = url.charCodeAt(i);
    if (charCode === 37) {
      const queryIndex = url.indexOf("?", i);
      const hashIndex = url.indexOf("#", i);
      const end = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);
      const path = url.slice(start, end);
      return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
    } else if (charCode === 63 || charCode === 35) {
      break;
    }
  }
  return url.slice(start, i);
}, "getPath");
var getPathNoStrict = /* @__PURE__ */ __name((request) => {
  const result = getPath(request);
  return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
}, "getPathNoStrict");
var mergePath = /* @__PURE__ */ __name((base, sub, ...rest) => {
  if (rest.length) {
    sub = mergePath(sub, ...rest);
  }
  return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
}, "mergePath");
var checkOptionalParameter = /* @__PURE__ */ __name((path) => {
  if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) {
    return null;
  }
  const segments = path.split("/");
  const results = [];
  let basePath = "";
  segments.forEach((segment) => {
    if (segment !== "" && !/\:/.test(segment)) {
      basePath += "/" + segment;
    } else if (/\:/.test(segment)) {
      if (/\?/.test(segment)) {
        if (results.length === 0 && basePath === "") {
          results.push("/");
        } else {
          results.push(basePath);
        }
        const optionalSegment = segment.replace("?", "");
        basePath += "/" + optionalSegment;
        results.push(basePath);
      } else {
        basePath += "/" + segment;
      }
    }
  });
  return results.filter((v, i, a) => a.indexOf(v) === i);
}, "checkOptionalParameter");
var _decodeURI = /* @__PURE__ */ __name((value) => {
  if (!/[%+]/.test(value)) {
    return value;
  }
  if (value.indexOf("+") !== -1) {
    value = value.replace(/\+/g, " ");
  }
  return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value;
}, "_decodeURI");
var _getQueryParam = /* @__PURE__ */ __name((url, key, multiple) => {
  let encoded;
  if (!multiple && key && !/[%+]/.test(key)) {
    let keyIndex2 = url.indexOf("?", 8);
    if (keyIndex2 === -1) {
      return void 0;
    }
    if (!url.startsWith(key, keyIndex2 + 1)) {
      keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
    }
    while (keyIndex2 !== -1) {
      const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
      if (trailingKeyCode === 61) {
        const valueIndex = keyIndex2 + key.length + 2;
        const endIndex = url.indexOf("&", valueIndex);
        return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));
      } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
        return "";
      }
      keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
    }
    encoded = /[%+]/.test(url);
    if (!encoded) {
      return void 0;
    }
  }
  const results = {};
  encoded ??= /[%+]/.test(url);
  let keyIndex = url.indexOf("?", 8);
  while (keyIndex !== -1) {
    const nextKeyIndex = url.indexOf("&", keyIndex + 1);
    let valueIndex = url.indexOf("=", keyIndex);
    if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
      valueIndex = -1;
    }
    let name = url.slice(
      keyIndex + 1,
      valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex
    );
    if (encoded) {
      name = _decodeURI(name);
    }
    keyIndex = nextKeyIndex;
    if (name === "") {
      continue;
    }
    let value;
    if (valueIndex === -1) {
      value = "";
    } else {
      value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);
      if (encoded) {
        value = _decodeURI(value);
      }
    }
    if (multiple) {
      if (!(results[name] && Array.isArray(results[name]))) {
        results[name] = [];
      }
      ;
      results[name].push(value);
    } else {
      results[name] ??= value;
    }
  }
  return key ? results[key] : results;
}, "_getQueryParam");
var getQueryParam = _getQueryParam;
var getQueryParams = /* @__PURE__ */ __name((url, key) => {
  return _getQueryParam(url, key, true);
}, "getQueryParams");
var decodeURIComponent_ = decodeURIComponent;

// node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/request.js
var tryDecodeURIComponent = /* @__PURE__ */ __name((str) => tryDecode(str, decodeURIComponent_), "tryDecodeURIComponent");
var HonoRequest = /* @__PURE__ */ __name(class {
  /**
   * `.raw` can get the raw Request object.
   *
   * @see {@link https://hono.dev/docs/api/request#raw}
   *
   * @example
   * ```ts
   * // For Cloudflare Workers
   * app.post('/', async (c) => {
   *   const metadata = c.req.raw.cf?.hostMetadata?
   *   ...
   * })
   * ```
   */
  raw;
  #validatedData;
  // Short name of validatedData
  #matchResult;
  routeIndex = 0;
  /**
   * `.path` can get the pathname of the request.
   *
   * @see {@link https://hono.dev/docs/api/request#path}
   *
   * @example
   * ```ts
   * app.get('/about/me', (c) => {
   *   const pathname = c.req.path // `/about/me`
   * })
   * ```
   */
  path;
  bodyCache = {};
  constructor(request, path = "/", matchResult = [[]]) {
    this.raw = request;
    this.path = path;
    this.#matchResult = matchResult;
    this.#validatedData = {};
  }
  param(key) {
    return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
  }
  #getDecodedParam(key) {
    const paramKey = this.#matchResult[0][this.routeIndex][1][key];
    const param = this.#getParamValue(paramKey);
    return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param;
  }
  #getAllDecodedParams() {
    const decoded = {};
    const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
    for (const key of keys) {
      const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
      if (value !== void 0) {
        decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
      }
    }
    return decoded;
  }
  #getParamValue(paramKey) {
    return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
  }
  query(key) {
    return getQueryParam(this.url, key);
  }
  queries(key) {
    return getQueryParams(this.url, key);
  }
  header(name) {
    if (name) {
      return this.raw.headers.get(name) ?? void 0;
    }
    const headerData = {};
    this.raw.headers.forEach((value, key) => {
      headerData[key] = value;
    });
    return headerData;
  }
  async parseBody(options) {
    return parseBody(this, options);
  }
  #cachedBody = (key) => {
    const { bodyCache, raw: raw2 } = this;
    const cachedBody = bodyCache[key];
    if (cachedBody) {
      return cachedBody;
    }
    const anyCachedKey = Object.keys(bodyCache)[0];
    if (anyCachedKey) {
      return bodyCache[anyCachedKey].then((body) => {
        if (anyCachedKey === "json") {
          body = JSON.stringify(body);
        }
        return new Response(body)[key]();
      });
    }
    return bodyCache[key] = raw2[key]();
  };
  /**
   * `.json()` can parse Request body of type `application/json`
   *
   * @see {@link https://hono.dev/docs/api/request#json}
   *
   * @example
   * ```ts
   * app.post('/entry', async (c) => {
   *   const body = await c.req.json()
   * })
   * ```
   */
  json() {
    return this.#cachedBody("text").then((text) => JSON.parse(text));
  }
  /**
   * `.text()` can parse Request body of type `text/plain`
   *
   * @see {@link https://hono.dev/docs/api/request#text}
   *
   * @example
   * ```ts
   * app.post('/entry', async (c) => {
   *   const body = await c.req.text()
   * })
   * ```
   */
  text() {
    return this.#cachedBody("text");
  }
  /**
   * `.arrayBuffer()` parse Request body as an `ArrayBuffer`
   *
   * @see {@link https://hono.dev/docs/api/request#arraybuffer}
   *
   * @example
   * ```ts
   * app.post('/entry', async (c) => {
   *   const body = await c.req.arrayBuffer()
   * })
   * ```
   */
  arrayBuffer() {
    return this.#cachedBody("arrayBuffer");
  }
  /**
   * `.bytes()` parses the request body as a `Uint8Array`.
   *
   * @see {@link https://hono.dev/docs/api/request#bytes}
   *
   * @example
   * ```ts
   * app.post('/entry', async (c) => {
   *   const body = await c.req.bytes()
   * })
   * ```
   */
  bytes() {
    return this.#cachedBody("arrayBuffer").then((buffer) => new Uint8Array(buffer));
  }
  /**
   * Parses the request body as a `Blob`.
   * @example
   * ```ts
   * app.post('/entry', async (c) => {
   *   const body = await c.req.blob();
   * });
   * ```
   * @see https://hono.dev/docs/api/request#blob
   */
  blob() {
    return this.#cachedBody("blob");
  }
  /**
   * Parses the request body as `FormData`.
   * @example
   * ```ts
   * app.post('/entry', async (c) => {
   *   const body = await c.req.formData();
   * });
   * ```
   * @see https://hono.dev/docs/api/request#formdata
   */
  formData() {
    return this.#cachedBody("formData");
  }
  /**
   * Adds validated data to the request.
   *
   * @param target - The target of the validation.
   * @param data - The validated data to add.
   */
  addValidatedData(target, data) {
    this.#validatedData[target] = data;
  }
  valid(target) {
    return this.#validatedData[target];
  }
  /**
   * `.url()` can get the request url strings.
   *
   * @see {@link https://hono.dev/docs/api/request#url}
   *
   * @example
   * ```ts
   * app.get('/about/me', (c) => {
   *   const url = c.req.url // `http://localhost:8787/about/me`
   *   ...
   * })
   * ```
   */
  get url() {
    return this.raw.url;
  }
  /**
   * `.method()` can get the method name of the request.
   *
   * @see {@link https://hono.dev/docs/api/request#method}
   *
   * @example
   * ```ts
   * app.get('/about/me', (c) => {
   *   const method = c.req.method // `GET`
   * })
   * ```
   */
  get method() {
    return this.raw.method;
  }
  get [GET_MATCH_RESULT]() {
    return this.#matchResult;
  }
  /**
   * `.matchedRoutes()` can return a matched route in the handler
   *
   * @deprecated
   *
   * Use matchedRoutes helper defined in "hono/route" instead.
   *
   * @see {@link https://hono.dev/docs/api/request#matchedroutes}
   *
   * @example
   * ```ts
   * app.use('*', async function logger(c, next) {
   *   await next()
   *   c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {
   *     const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')
   *     console.log(
   *       method,
   *       ' ',
   *       path,
   *       ' '.repeat(Math.max(10 - path.length, 0)),
   *       name,
   *       i === c.req.routeIndex ? '<- respond from here' : ''
   *     )
   *   })
   * })
   * ```
   */
  get matchedRoutes() {
    return this.#matchResult[0].map(([[, route]]) => route);
  }
  /**
   * `routePath()` can retrieve the path registered within the handler
   *
   * @deprecated
   *
   * Use routePath helper defined in "hono/route" instead.
   *
   * @see {@link https://hono.dev/docs/api/request#routepath}
   *
   * @example
   * ```ts
   * app.get('/posts/:id', (c) => {
   *   return c.json({ path: c.req.routePath })
   * })
   * ```
   */
  get routePath() {
    return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
  }
}, "HonoRequest");

// node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/utils/html.js
var HtmlEscapedCallbackPhase = {
  Stringify: 1,
  BeforeStream: 2,
  Stream: 3
};
var raw = /* @__PURE__ */ __name((value, callbacks) => {
  const escapedString = new String(value);
  escapedString.isEscaped = true;
  escapedString.callbacks = callbacks;
  return escapedString;
}, "raw");
var escapeRe = /[&<>'"]/;
var stringBufferToString = /* @__PURE__ */ __name(async (buffer, callbacks) => {
  let str = "";
  callbacks ||= [];
  const resolvedBuffer = await Promise.all(buffer);
  for (let i = resolvedBuffer.length - 1; ; i--) {
    str += resolvedBuffer[i];
    i--;
    if (i < 0) {
      break;
    }
    let r = resolvedBuffer[i];
    if (typeof r === "object") {
      callbacks.push(...r.callbacks || []);
    }
    const isEscaped = r.isEscaped;
    r = await (typeof r === "object" ? r.toString() : r);
    if (typeof r === "object") {
      callbacks.push(...r.callbacks || []);
    }
    if (r.isEscaped ?? isEscaped) {
      str += r;
    } else {
      const buf = [str];
      escapeToBuffer(r, buf);
      str = buf[0];
    }
  }
  return raw(str, callbacks);
}, "stringBufferToString");
var escapeToBuffer = /* @__PURE__ */ __name((str, buffer) => {
  const match2 = str.search(escapeRe);
  if (match2 === -1) {
    buffer[0] += str;
    return;
  }
  let escape;
  let index;
  let lastIndex = 0;
  for (index = match2; index < str.length; index++) {
    switch (str.charCodeAt(index)) {
      case 34:
        escape = "&quot;";
        break;
      case 39:
        escape = "&#39;";
        break;
      case 38:
        escape = "&amp;";
        break;
      case 60:
        escape = "&lt;";
        break;
      case 62:
        escape = "&gt;";
        break;
      default:
        continue;
    }
    buffer[0] += str.substring(lastIndex, index) + escape;
    lastIndex = index + 1;
  }
  buffer[0] += str.substring(lastIndex, index);
}, "escapeToBuffer");
var resolveCallbackSync = /* @__PURE__ */ __name((str) => {
  const callbacks = str.callbacks;
  if (!callbacks?.length) {
    return str;
  }
  const buffer = [str];
  const context2 = {};
  callbacks.forEach((c) => c({ phase: HtmlEscapedCallbackPhase.Stringify, buffer, context: context2 }));
  return buffer[0];
}, "resolveCallbackSync");
var resolveCallback = /* @__PURE__ */ __name(async (str, phase, preserveCallbacks, context2, buffer) => {
  if (typeof str === "object" && !(str instanceof String)) {
    if (!(str instanceof Promise)) {
      str = str.toString();
    }
    if (str instanceof Promise) {
      str = await str;
    }
  }
  const callbacks = str.callbacks;
  if (!callbacks?.length) {
    return Promise.resolve(str);
  }
  if (buffer) {
    buffer[0] += str;
  } else {
    buffer = [str];
  }
  const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context: context2 }))).then(
    (res) => Promise.all(
      res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context2, buffer))
    ).then(() => buffer[0])
  );
  if (preserveCallbacks) {
    return raw(await resStr, callbacks);
  } else {
    return resStr;
  }
}, "resolveCallback");

// node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/context.js
var TEXT_PLAIN = "text/plain; charset=UTF-8";
var setDefaultContentType = /* @__PURE__ */ __name((contentType, headers) => {
  return {
    "Content-Type": contentType,
    ...headers
  };
}, "setDefaultContentType");
var createResponseInstance = /* @__PURE__ */ __name((body, init) => new Response(body, init), "createResponseInstance");
var Context = /* @__PURE__ */ __name(class {
  #rawRequest;
  #req;
  /**
   * `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.
   *
   * @see {@link https://hono.dev/docs/api/context#env}
   *
   * @example
   * ```ts
   * // Environment object for Cloudflare Workers
   * app.get('*', async c => {
   *   const counter = c.env.COUNTER
   * })
   * ```
   */
  env = {};
  #var;
  finalized = false;
  /**
   * `.error` can get the error object from the middleware if the Handler throws an error.
   *
   * @see {@link https://hono.dev/docs/api/context#error}
   *
   * @example
   * ```ts
   * app.use('*', async (c, next) => {
   *   await next()
   *   if (c.error) {
   *     // do something...
   *   }
   * })
   * ```
   */
  error;
  #status;
  #executionCtx;
  #res;
  #layout;
  #renderer;
  #notFoundHandler;
  #preparedHeaders;
  #matchResult;
  #path;
  /**
   * Creates an instance of the Context class.
   *
   * @param req - The Request object.
   * @param options - Optional configuration options for the context.
   */
  constructor(req, options) {
    this.#rawRequest = req;
    if (options) {
      this.#executionCtx = options.executionCtx;
      this.env = options.env;
      this.#notFoundHandler = options.notFoundHandler;
      this.#path = options.path;
      this.#matchResult = options.matchResult;
    }
  }
  /**
   * `.req` is the instance of {@link HonoRequest}.
   */
  get req() {
    this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
    return this.#req;
  }
  /**
   * @see {@link https://hono.dev/docs/api/context#event}
   * The FetchEvent associated with the current request.
   *
   * @throws Will throw an error if the context does not have a FetchEvent.
   */
  get event() {
    if (this.#executionCtx && "respondWith" in this.#executionCtx) {
      return this.#executionCtx;
    } else {
      throw Error("This context has no FetchEvent");
    }
  }
  /**
   * @see {@link https://hono.dev/docs/api/context#executionctx}
   * The ExecutionContext associated with the current request.
   *
   * @throws Will throw an error if the context does not have an ExecutionContext.
   */
  get executionCtx() {
    if (this.#executionCtx) {
      return this.#executionCtx;
    } else {
      throw Error("This context has no ExecutionContext");
    }
  }
  /**
   * @see {@link https://hono.dev/docs/api/context#res}
   * The Response object for the current request.
   */
  get res() {
    return this.#res ||= createResponseInstance(null, {
      headers: this.#preparedHeaders ??= new Headers()
    });
  }
  /**
   * Sets the Response object for the current request.
   *
   * @param _res - The Response object to set.
   */
  set res(_res) {
    if (this.#res && _res) {
      _res = createResponseInstance(_res.body, _res);
      for (const [k, v] of this.#res.headers.entries()) {
        if (k === "content-type") {
          continue;
        }
        if (k === "set-cookie") {
          const cookies = this.#res.headers.getSetCookie();
          _res.headers.delete("set-cookie");
          for (const cookie of cookies) {
            _res.headers.append("set-cookie", cookie);
          }
        } else {
          _res.headers.set(k, v);
        }
      }
    }
    this.#res = _res;
    this.finalized = true;
  }
  /**
   * `.render()` can create a response within a layout.
   *
   * @see {@link https://hono.dev/docs/api/context#render-setrenderer}
   *
   * @example
   * ```ts
   * app.get('/', (c) => {
   *   return c.render('Hello!')
   * })
   * ```
   */
  render = (...args) => {
    this.#renderer ??= (content) => this.html(content);
    return this.#renderer(...args);
  };
  /**
   * Sets the layout for the response.
   *
   * @param layout - The layout to set.
   * @returns The layout function.
   */
  setLayout = (layout) => this.#layout = layout;
  /**
   * Gets the current layout for the response.
   *
   * @returns The current layout function.
   */
  getLayout = () => this.#layout;
  /**
   * `.setRenderer()` can set the layout in the custom middleware.
   *
   * @see {@link https://hono.dev/docs/api/context#render-setrenderer}
   *
   * @example
   * ```tsx
   * app.use('*', async (c, next) => {
   *   c.setRenderer((content) => {
   *     return c.html(
   *       <html>
   *         <body>
   *           <p>{content}</p>
   *         </body>
   *       </html>
   *     )
   *   })
   *   await next()
   * })
   * ```
   */
  setRenderer = (renderer) => {
    this.#renderer = renderer;
  };
  /**
   * `.header()` can set headers.
   *
   * @see {@link https://hono.dev/docs/api/context#header}
   *
   * @example
   * ```ts
   * app.get('/welcome', (c) => {
   *   // Set headers
   *   c.header('X-Message', 'Hello!')
   *   c.header('Content-Type', 'text/plain')
   *
   *   return c.body('Thank you for coming')
   * })
   * ```
   */
  header = (name, value, options) => {
    if (this.finalized) {
      this.#res = createResponseInstance(this.#res.body, this.#res);
    }
    const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();
    if (value === void 0) {
      headers.delete(name);
    } else if (options?.append) {
      headers.append(name, value);
    } else {
      headers.set(name, value);
    }
  };
  status = (status) => {
    this.#status = status;
  };
  /**
   * `.set()` can set the value specified by the key.
   *
   * @see {@link https://hono.dev/docs/api/context#set-get}
   *
   * @example
   * ```ts
   * app.use('*', async (c, next) => {
   *   c.set('message', 'Hono is hot!!')
   *   await next()
   * })
   * ```
   */
  set = (key, value) => {
    this.#var ??= /* @__PURE__ */ new Map();
    this.#var.set(key, value);
  };
  /**
   * `.get()` can use the value specified by the key.
   *
   * @see {@link https://hono.dev/docs/api/context#set-get}
   *
   * @example
   * ```ts
   * app.get('/', (c) => {
   *   const message = c.get('message')
   *   return c.text(`The message is "${message}"`)
   * })
   * ```
   */
  get = (key) => {
    return this.#var ? this.#var.get(key) : void 0;
  };
  /**
   * `.var` can access the value of a variable.
   *
   * @see {@link https://hono.dev/docs/api/context#var}
   *
   * @example
   * ```ts
   * const result = c.var.client.oneMethod()
   * ```
   */
  // c.var.propName is a read-only
  get var() {
    if (!this.#var) {
      return {};
    }
    return Object.fromEntries(this.#var);
  }
  #newResponse(data, arg, headers) {
    const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers();
    if (typeof arg === "object" && "headers" in arg) {
      const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);
      for (const [key, value] of argHeaders) {
        if (key.toLowerCase() === "set-cookie") {
          responseHeaders.append(key, value);
        } else {
          responseHeaders.set(key, value);
        }
      }
    }
    if (headers) {
      for (const [k, v] of Object.entries(headers)) {
        if (typeof v === "string") {
          responseHeaders.set(k, v);
        } else {
          responseHeaders.delete(k);
          for (const v2 of v) {
            responseHeaders.append(k, v2);
          }
        }
      }
    }
    const status = typeof arg === "number" ? arg : arg?.status ?? this.#status;
    return createResponseInstance(data, { status, headers: responseHeaders });
  }
  newResponse = (...args) => this.#newResponse(...args);
  /**
   * `.body()` can return the HTTP response.
   * You can set headers with `.header()` and set HTTP status code with `.status`.
   * This can also be set in `.text()`, `.json()` and so on.
   *
   * @see {@link https://hono.dev/docs/api/context#body}
   *
   * @example
   * ```ts
   * app.get('/welcome', (c) => {
   *   // Set headers
   *   c.header('X-Message', 'Hello!')
   *   c.header('Content-Type', 'text/plain')
   *   // Set HTTP status code
   *   c.status(201)
   *
   *   // Return the response body
   *   return c.body('Thank you for coming')
   * })
   * ```
   */
  body = (data, arg, headers) => this.#newResponse(data, arg, headers);
  /**
   * `.text()` can render text as `Content-Type:text/plain`.
   *
   * @see {@link https://hono.dev/docs/api/context#text}
   *
   * @example
   * ```ts
   * app.get('/say', (c) => {
   *   return c.text('Hello!')
   * })
   * ```
   */
  text = (text, arg, headers) => {
    return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(
      text,
      arg,
      setDefaultContentType(TEXT_PLAIN, headers)
    );
  };
  /**
   * `.json()` can render JSON as `Content-Type:application/json`.
   *
   * @see {@link https://hono.dev/docs/api/context#json}
   *
   * @example
   * ```ts
   * app.get('/api', (c) => {
   *   return c.json({ message: 'Hello!' })
   * })
   * ```
   */
  json = (object, arg, headers) => {
    return this.#newResponse(
      JSON.stringify(object),
      arg,
      setDefaultContentType("application/json", headers)
    );
  };
  html = (html2, arg, headers) => {
    const res = /* @__PURE__ */ __name((html22) => this.#newResponse(html22, arg, setDefaultContentType("text/html; charset=UTF-8", headers)), "res");
    return typeof html2 === "object" ? resolveCallback(html2, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html2);
  };
  /**
   * `.redirect()` can Redirect, default status code is 302.
   *
   * @see {@link https://hono.dev/docs/api/context#redirect}
   *
   * @example
   * ```ts
   * app.get('/redirect', (c) => {
   *   return c.redirect('/')
   * })
   * app.get('/redirect-permanently', (c) => {
   *   return c.redirect('/', 301)
   * })
   * ```
   */
  redirect = (location, status) => {
    const locationString = String(location);
    this.header(
      "Location",
      // Multibyes should be encoded
      // eslint-disable-next-line no-control-regex
      !/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString)
    );
    return this.newResponse(null, status ?? 302);
  };
  /**
   * `.notFound()` can return the Not Found Response.
   *
   * @see {@link https://hono.dev/docs/api/context#notfound}
   *
   * @example
   * ```ts
   * app.get('/notfound', (c) => {
   *   return c.notFound()
   * })
   * ```
   */
  notFound = () => {
    this.#notFoundHandler ??= () => createResponseInstance();
    return this.#notFoundHandler(this);
  };
}, "Context");

// node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/router.js
var METHOD_NAME_ALL = "ALL";
var METHOD_NAME_ALL_LOWERCASE = "all";
var METHODS = ["get", "post", "put", "delete", "options", "patch"];
var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
var UnsupportedPathError = /* @__PURE__ */ __name(class extends Error {
}, "UnsupportedPathError");

// node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/utils/constants.js
var COMPOSED_HANDLER = "__COMPOSED_HANDLER";

// node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/hono-base.js
var notFoundHandler = /* @__PURE__ */ __name((c) => {
  return c.text("404 Not Found", 404);
}, "notFoundHandler");
var errorHandler = /* @__PURE__ */ __name((err, c) => {
  if ("getResponse" in err) {
    const res = err.getResponse();
    return c.newResponse(res.body, res);
  }
  console.error(err);
  return c.text("Internal Server Error", 500);
}, "errorHandler");
var Hono = /* @__PURE__ */ __name(class _Hono {
  get;
  post;
  put;
  delete;
  options;
  patch;
  all;
  on;
  use;
  /*
    This class is like an abstract class and does not have a router.
    To use it, inherit the class and implement router in the constructor.
  */
  router;
  getPath;
  // Cannot use `#` because it requires visibility at JavaScript runtime.
  _basePath = "/";
  #path = "/";
  routes = [];
  constructor(options = {}) {
    const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
    allMethods.forEach((method) => {
      this[method] = (args1, ...args) => {
        if (typeof args1 === "string") {
          this.#path = args1;
        } else {
          this.#addRoute(method, this.#path, args1);
        }
        args.forEach((handler) => {
          this.#addRoute(method, this.#path, handler);
        });
        return this;
      };
    });
    this.on = (method, path, ...handlers) => {
      for (const p of [path].flat()) {
        this.#path = p;
        for (const m of [method].flat()) {
          handlers.map((handler) => {
            this.#addRoute(m.toUpperCase(), this.#path, handler);
          });
        }
      }
      return this;
    };
    this.use = (arg1, ...handlers) => {
      if (typeof arg1 === "string") {
        this.#path = arg1;
      } else {
        this.#path = "*";
        handlers.unshift(arg1);
      }
      handlers.forEach((handler) => {
        this.#addRoute(METHOD_NAME_ALL, this.#path, handler);
      });
      return this;
    };
    const { strict, ...optionsWithoutStrict } = options;
    Object.assign(this, optionsWithoutStrict);
    this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
  }
  #clone() {
    const clone = new _Hono({
      router: this.router,
      getPath: this.getPath
    });
    clone.errorHandler = this.errorHandler;
    clone.#notFoundHandler = this.#notFoundHandler;
    clone.routes = this.routes;
    return clone;
  }
  #notFoundHandler = notFoundHandler;
  // Cannot use `#` because it requires visibility at JavaScript runtime.
  errorHandler = errorHandler;
  /**
   * `.route()` allows grouping other Hono instance in routes.
   *
   * @see {@link https://hono.dev/docs/api/routing#grouping}
   *
   * @param {string} path - base Path
   * @param {Hono} app - other Hono instance
   * @returns {Hono} routed Hono instance
   *
   * @example
   * ```ts
   * const app = new Hono()
   * const app2 = new Hono()
   *
   * app2.get("/user", (c) => c.text("user"))
   * app.route("/api", app2) // GET /api/user
   * ```
   */
  route(path, app2) {
    const subApp = this.basePath(path);
    app2.routes.map((r) => {
      let handler;
      if (app2.errorHandler === errorHandler) {
        handler = r.handler;
      } else {
        handler = /* @__PURE__ */ __name(async (c, next) => (await compose([], app2.errorHandler)(c, () => r.handler(c, next))).res, "handler");
        handler[COMPOSED_HANDLER] = r.handler;
      }
      subApp.#addRoute(r.method, r.path, handler, r.basePath);
    });
    return this;
  }
  /**
   * `.basePath()` allows base paths to be specified.
   *
   * @see {@link https://hono.dev/docs/api/routing#base-path}
   *
   * @param {string} path - base Path
   * @returns {Hono} changed Hono instance
   *
   * @example
   * ```ts
   * const api = new Hono().basePath('/api')
   * ```
   */
  basePath(path) {
    const subApp = this.#clone();
    subApp._basePath = mergePath(this._basePath, path);
    return subApp;
  }
  /**
   * `.onError()` handles an error and returns a customized Response.
   *
   * @see {@link https://hono.dev/docs/api/hono#error-handling}
   *
   * @param {ErrorHandler} handler - request Handler for error
   * @returns {Hono} changed Hono instance
   *
   * @example
   * ```ts
   * app.onError((err, c) => {
   *   console.error(`${err}`)
   *   return c.text('Custom Error Message', 500)
   * })
   * ```
   */
  onError = (handler) => {
    this.errorHandler = handler;
    return this;
  };
  /**
   * `.notFound()` allows you to customize a Not Found Response.
   *
   * @see {@link https://hono.dev/docs/api/hono#not-found}
   *
   * @param {NotFoundHandler} handler - request handler for not-found
   * @returns {Hono} changed Hono instance
   *
   * @example
   * ```ts
   * app.notFound((c) => {
   *   return c.text('Custom 404 Message', 404)
   * })
   * ```
   */
  notFound = (handler) => {
    this.#notFoundHandler = handler;
    return this;
  };
  /**
   * `.mount()` allows you to mount applications built with other frameworks into your Hono application.
   *
   * @see {@link https://hono.dev/docs/api/hono#mount}
   *
   * @param {string} path - base Path
   * @param {Function} applicationHandler - other Request Handler
   * @param {MountOptions} [options] - options of `.mount()`
   * @returns {Hono} mounted Hono instance
   *
   * @example
   * ```ts
   * import { Router as IttyRouter } from 'itty-router'
   * import { Hono } from 'hono'
   * // Create itty-router application
   * const ittyRouter = IttyRouter()
   * // GET /itty-router/hello
   * ittyRouter.get('/hello', () => new Response('Hello from itty-router'))
   *
   * const app = new Hono()
   * app.mount('/itty-router', ittyRouter.handle)
   * ```
   *
   * @example
   * ```ts
   * const app = new Hono()
   * // Send the request to another application without modification.
   * app.mount('/app', anotherApp, {
   *   replaceRequest: (req) => req,
   * })
   * ```
   */
  mount(path, applicationHandler, options) {
    let replaceRequest;
    let optionHandler;
    if (options) {
      if (typeof options === "function") {
        optionHandler = options;
      } else {
        optionHandler = options.optionHandler;
        if (options.replaceRequest === false) {
          replaceRequest = /* @__PURE__ */ __name((request) => request, "replaceRequest");
        } else {
          replaceRequest = options.replaceRequest;
        }
      }
    }
    const getOptions = optionHandler ? (c) => {
      const options2 = optionHandler(c);
      return Array.isArray(options2) ? options2 : [options2];
    } : (c) => {
      let executionContext = void 0;
      try {
        executionContext = c.executionCtx;
      } catch {
      }
      return [c.env, executionContext];
    };
    replaceRequest ||= (() => {
      const mergedPath = mergePath(this._basePath, path);
      const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
      return (request) => {
        const url = new URL(request.url);
        url.pathname = this.getPath(request).slice(pathPrefixLength) || "/";
        return new Request(url, request);
      };
    })();
    const handler = /* @__PURE__ */ __name(async (c, next) => {
      const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
      if (res) {
        return res;
      }
      await next();
    }, "handler");
    this.#addRoute(METHOD_NAME_ALL, mergePath(path, "*"), handler);
    return this;
  }
  #addRoute(method, path, handler, baseRoutePath) {
    method = method.toUpperCase();
    path = mergePath(this._basePath, path);
    const r = {
      basePath: baseRoutePath !== void 0 ? mergePath(this._basePath, baseRoutePath) : this._basePath,
      path,
      method,
      handler
    };
    this.router.add(method, path, [handler, r]);
    this.routes.push(r);
  }
  #handleError(err, c) {
    if (err instanceof Error) {
      return this.errorHandler(err, c);
    }
    throw err;
  }
  #dispatch(request, executionCtx, env2, method) {
    if (method === "HEAD") {
      return (async () => new Response(null, await this.#dispatch(request, executionCtx, env2, "GET")))();
    }
    const path = this.getPath(request, { env: env2 });
    const matchResult = this.router.match(method, path);
    const c = new Context(request, {
      path,
      matchResult,
      env: env2,
      executionCtx,
      notFoundHandler: this.#notFoundHandler
    });
    if (matchResult[0].length === 1) {
      let res;
      try {
        res = matchResult[0][0][0][0](c, async () => {
          c.res = await this.#notFoundHandler(c);
        });
      } catch (err) {
        return this.#handleError(err, c);
      }
      return res instanceof Promise ? res.then(
        (resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))
      ).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);
    }
    const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
    return (async () => {
      try {
        const context2 = await composed(c);
        if (!context2.finalized) {
          throw new Error(
            "Context is not finalized. Did you forget to return a Response object or `await next()`?"
          );
        }
        return context2.res;
      } catch (err) {
        return this.#handleError(err, c);
      }
    })();
  }
  /**
   * `.fetch()` will be entry point of your app.
   *
   * @see {@link https://hono.dev/docs/api/hono#fetch}
   *
   * @param {Request} request - request Object of request
   * @param {Env} Env - env Object
   * @param {ExecutionContext} - context of execution
   * @returns {Response | Promise<Response>} response of request
   *
   */
  fetch = (request, ...rest) => {
    return this.#dispatch(request, rest[1], rest[0], request.method);
  };
  /**
   * `.request()` is a useful method for testing.
   * You can pass a URL or pathname to send a GET request.
   * app will return a Response object.
   * ```ts
   * test('GET /hello is ok', async () => {
   *   const res = await app.request('/hello')
   *   expect(res.status).toBe(200)
   * })
   * ```
   * @see https://hono.dev/docs/api/hono#request
   */
  request = (input2, requestInit, Env, executionCtx) => {
    if (input2 instanceof Request) {
      return this.fetch(requestInit ? new Request(input2, requestInit) : input2, Env, executionCtx);
    }
    input2 = input2.toString();
    return this.fetch(
      new Request(
        /^https?:\/\//.test(input2) ? input2 : `http://localhost${mergePath("/", input2)}`,
        requestInit
      ),
      Env,
      executionCtx
    );
  };
  /**
   * `.fire()` automatically adds a global fetch event listener.
   * This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers.
   * @deprecated
   * Use `fire` from `hono/service-worker` instead.
   * ```ts
   * import { Hono } from 'hono'
   * import { fire } from 'hono/service-worker'
   *
   * const app = new Hono()
   * // ...
   * fire(app)
   * ```
   * @see https://hono.dev/docs/api/hono#fire
   * @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API
   * @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/
   */
  fire = () => {
    addEventListener("fetch", (event) => {
      event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method));
    });
  };
}, "_Hono");

// node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/router/reg-exp-router/matcher.js
var emptyParam = [];
function match(method, path) {
  const matchers = this.buildAllMatchers();
  const match2 = /* @__PURE__ */ __name((method2, path2) => {
    const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
    const staticMatch = matcher[2][path2];
    if (staticMatch) {
      return staticMatch;
    }
    const match3 = path2.match(matcher[0]);
    if (!match3) {
      return [[], emptyParam];
    }
    const index = match3.indexOf("", 1);
    return [matcher[1][index], match3];
  }, "match2");
  this.match = match2;
  return match2(method, path);
}
__name(match, "match");

// node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/router/reg-exp-router/node.js
var LABEL_REG_EXP_STR = "[^/]+";
var ONLY_WILDCARD_REG_EXP_STR = ".*";
var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
var PATH_ERROR = /* @__PURE__ */ Symbol();
var regExpMetaChars = new Set(".\\+*[^]$()");
function compareKey(a, b) {
  if (a.length === 1) {
    return b.length === 1 ? a < b ? -1 : 1 : -1;
  }
  if (b.length === 1) {
    return 1;
  }
  if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
    return 1;
  } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
    return -1;
  }
  if (a === LABEL_REG_EXP_STR) {
    return 1;
  } else if (b === LABEL_REG_EXP_STR) {
    return -1;
  }
  return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
}
__name(compareKey, "compareKey");
var Node = /* @__PURE__ */ __name(class _Node {
  #index;
  #varIndex;
  #children = /* @__PURE__ */ Object.create(null);
  insert(tokens, index, paramMap, context2, pathErrorCheckOnly) {
    if (tokens.length === 0) {
      if (this.#index !== void 0) {
        throw PATH_ERROR;
      }
      if (pathErrorCheckOnly) {
        return;
      }
      this.#index = index;
      return;
    }
    const [token, ...restTokens] = tokens;
    const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
    let node;
    if (pattern) {
      const name = pattern[1];
      let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
      if (name && pattern[2]) {
        if (regexpStr === ".*") {
          throw PATH_ERROR;
        }
        regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
        if (/\((?!\?:)/.test(regexpStr)) {
          throw PATH_ERROR;
        }
      }
      node = this.#children[regexpStr];
      if (!node) {
        if (Object.keys(this.#children).some(
          (k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
        )) {
          throw PATH_ERROR;
        }
        if (pathErrorCheckOnly) {
          return;
        }
        node = this.#children[regexpStr] = new _Node();
        if (name !== "") {
          node.#varIndex = context2.varIndex++;
        }
      }
      if (!pathErrorCheckOnly && name !== "") {
        paramMap.push([name, node.#varIndex]);
      }
    } else {
      node = this.#children[token];
      if (!node) {
        if (Object.keys(this.#children).some(
          (k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
        )) {
          throw PATH_ERROR;
        }
        if (pathErrorCheckOnly) {
          return;
        }
        node = this.#children[token] = new _Node();
      }
    }
    node.insert(restTokens, index, paramMap, context2, pathErrorCheckOnly);
  }
  buildRegExpStr() {
    const childKeys = Object.keys(this.#children).sort(compareKey);
    const strList = childKeys.map((k) => {
      const c = this.#children[k];
      return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
    });
    if (typeof this.#index === "number") {
      strList.unshift(`#${this.#index}`);
    }
    if (strList.length === 0) {
      return "";
    }
    if (strList.length === 1) {
      return strList[0];
    }
    return "(?:" + strList.join("|") + ")";
  }
}, "_Node");

// node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/router/reg-exp-router/trie.js
var Trie = /* @__PURE__ */ __name(class {
  #context = { varIndex: 0 };
  #root = new Node();
  insert(path, index, pathErrorCheckOnly) {
    const paramAssoc = [];
    const groups = [];
    for (let i = 0; ; ) {
      let replaced = false;
      path = path.replace(/\{[^}]+\}/g, (m) => {
        const mark = `@\\${i}`;
        groups[i] = [mark, m];
        i++;
        replaced = true;
        return mark;
      });
      if (!replaced) {
        break;
      }
    }
    const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
    for (let i = groups.length - 1; i >= 0; i--) {
      const [mark] = groups[i];
      for (let j = tokens.length - 1; j >= 0; j--) {
        if (tokens[j].indexOf(mark) !== -1) {
          tokens[j] = tokens[j].replace(mark, groups[i][1]);
          break;
        }
      }
    }
    this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);
    return paramAssoc;
  }
  buildRegExp() {
    let regexp = this.#root.buildRegExpStr();
    if (regexp === "") {
      return [/^$/, [], []];
    }
    let captureIndex = 0;
    const indexReplacementMap = [];
    const paramReplacementMap = [];
    regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
      if (handlerIndex !== void 0) {
        indexReplacementMap[++captureIndex] = Number(handlerIndex);
        return "$()";
      }
      if (paramIndex !== void 0) {
        paramReplacementMap[Number(paramIndex)] = ++captureIndex;
        return "";
      }
      return "";
    });
    return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
  }
}, "Trie");

// node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/router/reg-exp-router/router.js
var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
function buildWildcardRegExp(path) {
  return wildcardRegExpCache[path] ??= new RegExp(
    path === "*" ? "" : `^${path.replace(
      /\/\*$|([.\\+*[^\]$()])/g,
      (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)"
    )}$`
  );
}
__name(buildWildcardRegExp, "buildWildcardRegExp");
function clearWildcardRegExpCache() {
  wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
}
__name(clearWildcardRegExpCache, "clearWildcardRegExpCache");
function buildMatcherFromPreprocessedRoutes(routes) {
  const trie = new Trie();
  const handlerData = [];
  if (routes.length === 0) {
    return nullMatcher;
  }
  const routesWithStaticPathFlag = routes.map(
    (route) => [!/\*|\/:/.test(route[0]), ...route]
  ).sort(
    ([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length
  );
  const staticMap = /* @__PURE__ */ Object.create(null);
  for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) {
    const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];
    if (pathErrorCheckOnly) {
      staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
    } else {
      j++;
    }
    let paramAssoc;
    try {
      paramAssoc = trie.insert(path, j, pathErrorCheckOnly);
    } catch (e) {
      throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;
    }
    if (pathErrorCheckOnly) {
      continue;
    }
    handlerData[j] = handlers.map(([h, paramCount]) => {
      const paramIndexMap = /* @__PURE__ */ Object.create(null);
      paramCount -= 1;
      for (; paramCount >= 0; paramCount--) {
        const [key, value] = paramAssoc[paramCount];
        paramIndexMap[key] = value;
      }
      return [h, paramIndexMap];
    });
  }
  const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
  for (let i = 0, len = handlerData.length; i < len; i++) {
    for (let j = 0, len2 = handlerData[i].length; j < len2; j++) {
      const map = handlerData[i][j]?.[1];
      if (!map) {
        continue;
      }
      const keys = Object.keys(map);
      for (let k = 0, len3 = keys.length; k < len3; k++) {
        map[keys[k]] = paramReplacementMap[map[keys[k]]];
      }
    }
  }
  const handlerMap = [];
  for (const i in indexReplacementMap) {
    handlerMap[i] = handlerData[indexReplacementMap[i]];
  }
  return [regexp, handlerMap, staticMap];
}
__name(buildMatcherFromPreprocessedRoutes, "buildMatcherFromPreprocessedRoutes");
function findMiddleware(middleware, path) {
  if (!middleware) {
    return void 0;
  }
  for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
    if (buildWildcardRegExp(k).test(path)) {
      return [...middleware[k]];
    }
  }
  return void 0;
}
__name(findMiddleware, "findMiddleware");
var RegExpRouter = /* @__PURE__ */ __name(class {
  name = "RegExpRouter";
  #middleware;
  #routes;
  constructor() {
    this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
    this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
  }
  add(method, path, handler) {
    const middleware = this.#middleware;
    const routes = this.#routes;
    if (!middleware || !routes) {
      throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
    }
    if (!middleware[method]) {
      ;
      [middleware, routes].forEach((handlerMap) => {
        handlerMap[method] = /* @__PURE__ */ Object.create(null);
        Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {
          handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
        });
      });
    }
    if (path === "/*") {
      path = "*";
    }
    const paramCount = (path.match(/\/:/g) || []).length;
    if (/\*$/.test(path)) {
      const re = buildWildcardRegExp(path);
      if (method === METHOD_NAME_ALL) {
        Object.keys(middleware).forEach((m) => {
          middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
        });
      } else {
        middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
      }
      Object.keys(middleware).forEach((m) => {
        if (method === METHOD_NAME_ALL || method === m) {
          Object.keys(middleware[m]).forEach((p) => {
            re.test(p) && middleware[m][p].push([handler, paramCount]);
          });
        }
      });
      Object.keys(routes).forEach((m) => {
        if (method === METHOD_NAME_ALL || method === m) {
          Object.keys(routes[m]).forEach(
            (p) => re.test(p) && routes[m][p].push([handler, paramCount])
          );
        }
      });
      return;
    }
    const paths = checkOptionalParameter(path) || [path];
    for (let i = 0, len = paths.length; i < len; i++) {
      const path2 = paths[i];
      Object.keys(routes).forEach((m) => {
        if (method === METHOD_NAME_ALL || method === m) {
          routes[m][path2] ||= [
            ...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []
          ];
          routes[m][path2].push([handler, paramCount - len + i + 1]);
        }
      });
    }
  }
  match = match;
  buildAllMatchers() {
    const matchers = /* @__PURE__ */ Object.create(null);
    Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
      matchers[method] ||= this.#buildMatcher(method);
    });
    this.#middleware = this.#routes = void 0;
    clearWildcardRegExpCache();
    return matchers;
  }
  #buildMatcher(method) {
    const routes = [];
    let hasOwnRoute = method === METHOD_NAME_ALL;
    [this.#middleware, this.#routes].forEach((r) => {
      const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];
      if (ownRoute.length !== 0) {
        hasOwnRoute ||= true;
        routes.push(...ownRoute);
      } else if (method !== METHOD_NAME_ALL) {
        routes.push(
          ...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]])
        );
      }
    });
    if (!hasOwnRoute) {
      return null;
    } else {
      return buildMatcherFromPreprocessedRoutes(routes);
    }
  }
}, "RegExpRouter");

// node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/router/smart-router/router.js
var SmartRouter = /* @__PURE__ */ __name(class {
  name = "SmartRouter";
  #routers = [];
  #routes = [];
  constructor(init) {
    this.#routers = init.routers;
  }
  add(method, path, handler) {
    if (!this.#routes) {
      throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
    }
    this.#routes.push([method, path, handler]);
  }
  match(method, path) {
    if (!this.#routes) {
      throw new Error("Fatal error");
    }
    const routers = this.#routers;
    const routes = this.#routes;
    const len = routers.length;
    let i = 0;
    let res;
    for (; i < len; i++) {
      const router = routers[i];
      try {
        for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) {
          router.add(...routes[i2]);
        }
        res = router.match(method, path);
      } catch (e) {
        if (e instanceof UnsupportedPathError) {
          continue;
        }
        throw e;
      }
      this.match = router.match.bind(router);
      this.#routers = [router];
      this.#routes = void 0;
      break;
    }
    if (i === len) {
      throw new Error("Fatal error");
    }
    this.name = `SmartRouter + ${this.activeRouter.name}`;
    return res;
  }
  get activeRouter() {
    if (this.#routes || this.#routers.length !== 1) {
      throw new Error("No active router has been determined yet.");
    }
    return this.#routers[0];
  }
}, "SmartRouter");

// node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/router/trie-router/node.js
var emptyParams = /* @__PURE__ */ Object.create(null);
var hasChildren = /* @__PURE__ */ __name((children) => {
  for (const _ in children) {
    return true;
  }
  return false;
}, "hasChildren");
var Node2 = /* @__PURE__ */ __name(class _Node2 {
  #methods;
  #children;
  #patterns;
  #order = 0;
  #params = emptyParams;
  constructor(method, handler, children) {
    this.#children = children || /* @__PURE__ */ Object.create(null);
    this.#methods = [];
    if (method && handler) {
      const m = /* @__PURE__ */ Object.create(null);
      m[method] = { handler, possibleKeys: [], score: 0 };
      this.#methods = [m];
    }
    this.#patterns = [];
  }
  insert(method, path, handler) {
    this.#order = ++this.#order;
    let curNode = this;
    const parts = splitRoutingPath(path);
    const possibleKeys = [];
    for (let i = 0, len = parts.length; i < len; i++) {
      const p = parts[i];
      const nextP = parts[i + 1];
      const pattern = getPattern(p, nextP);
      const key = Array.isArray(pattern) ? pattern[0] : p;
      if (key in curNode.#children) {
        curNode = curNode.#children[key];
        if (pattern) {
          possibleKeys.push(pattern[1]);
        }
        continue;
      }
      curNode.#children[key] = new _Node2();
      if (pattern) {
        curNode.#patterns.push(pattern);
        possibleKeys.push(pattern[1]);
      }
      curNode = curNode.#children[key];
    }
    curNode.#methods.push({
      [method]: {
        handler,
        possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
        score: this.#order
      }
    });
    return curNode;
  }
  #pushHandlerSets(handlerSets, node, method, nodeParams, params) {
    for (let i = 0, len = node.#methods.length; i < len; i++) {
      const m = node.#methods[i];
      const handlerSet = m[method] || m[METHOD_NAME_ALL];
      const processedSet = {};
      if (handlerSet !== void 0) {
        handlerSet.params = /* @__PURE__ */ Object.create(null);
        handlerSets.push(handlerSet);
        if (nodeParams !== emptyParams || params && params !== emptyParams) {
          for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) {
            const key = handlerSet.possibleKeys[i2];
            const processed = processedSet[handlerSet.score];
            handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
            processedSet[handlerSet.score] = true;
          }
        }
      }
    }
  }
  search(method, path) {
    const handlerSets = [];
    this.#params = emptyParams;
    const curNode = this;
    let curNodes = [curNode];
    const parts = splitPath(path);
    const curNodesQueue = [];
    const len = parts.length;
    let partOffsets = null;
    for (let i = 0; i < len; i++) {
      const part = parts[i];
      const isLast = i === len - 1;
      const tempNodes = [];
      for (let j = 0, len2 = curNodes.length; j < len2; j++) {
        const node = curNodes[j];
        const nextNode = node.#children[part];
        if (nextNode) {
          nextNode.#params = node.#params;
          if (isLast) {
            if (nextNode.#children["*"]) {
              this.#pushHandlerSets(handlerSets, nextNode.#children["*"], method, node.#params);
            }
            this.#pushHandlerSets(handlerSets, nextNode, method, node.#params);
          } else {
            tempNodes.push(nextNode);
          }
        }
        for (let k = 0, len3 = node.#patterns.length; k < len3; k++) {
          const pattern = node.#patterns[k];
          const params = node.#params === emptyParams ? {} : { ...node.#params };
          if (pattern === "*") {
            const astNode = node.#children["*"];
            if (astNode) {
              this.#pushHandlerSets(handlerSets, astNode, method, node.#params);
              astNode.#params = params;
              tempNodes.push(astNode);
            }
            continue;
          }
          const [key, name, matcher] = pattern;
          if (!part && !(matcher instanceof RegExp)) {
            continue;
          }
          const child = node.#children[key];
          if (matcher instanceof RegExp) {
            if (partOffsets === null) {
              partOffsets = new Array(len);
              let offset = path[0] === "/" ? 1 : 0;
              for (let p = 0; p < len; p++) {
                partOffsets[p] = offset;
                offset += parts[p].length + 1;
              }
            }
            const restPathString = path.substring(partOffsets[i]);
            const m = matcher.exec(restPathString);
            if (m) {
              params[name] = m[0];
              this.#pushHandlerSets(handlerSets, child, method, node.#params, params);
              if (hasChildren(child.#children)) {
                child.#params = params;
                const componentCount = m[0].match(/\//)?.length ?? 0;
                const targetCurNodes = curNodesQueue[componentCount] ||= [];
                targetCurNodes.push(child);
              }
              continue;
            }
          }
          if (matcher === true || matcher.test(part)) {
            params[name] = part;
            if (isLast) {
              this.#pushHandlerSets(handlerSets, child, method, params, node.#params);
              if (child.#children["*"]) {
                this.#pushHandlerSets(
                  handlerSets,
                  child.#children["*"],
                  method,
                  params,
                  node.#params
                );
              }
            } else {
              child.#params = params;
              tempNodes.push(child);
            }
          }
        }
      }
      const shifted = curNodesQueue.shift();
      curNodes = shifted ? tempNodes.concat(shifted) : tempNodes;
    }
    if (handlerSets.length > 1) {
      handlerSets.sort((a, b) => {
        return a.score - b.score;
      });
    }
    return [handlerSets.map(({ handler, params }) => [handler, params])];
  }
}, "_Node");

// node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/router/trie-router/router.js
var TrieRouter = /* @__PURE__ */ __name(class {
  name = "TrieRouter";
  #node;
  constructor() {
    this.#node = new Node2();
  }
  add(method, path, handler) {
    const results = checkOptionalParameter(path);
    if (results) {
      for (let i = 0, len = results.length; i < len; i++) {
        this.#node.insert(method, results[i], handler);
      }
      return;
    }
    this.#node.insert(method, path, handler);
  }
  match(method, path) {
    return this.#node.search(method, path);
  }
}, "TrieRouter");

// node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/hono.js
var Hono2 = /* @__PURE__ */ __name(class extends Hono {
  /**
   * Creates an instance of the Hono class.
   *
   * @param options - Optional configuration options for the Hono instance.
   */
  constructor(options = {}) {
    super(options);
    this.router = options.router ?? new SmartRouter({
      routers: [new RegExpRouter(), new TrieRouter()]
    });
  }
}, "Hono");

// src/utils/id.ts
var ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
function encodeTime(now, len) {
  let mod = now;
  let str = "";
  for (let i = len; i > 0; i -= 1) {
    str = ENCODING[mod % 32] + str;
    mod = Math.floor(mod / 32);
  }
  return str;
}
__name(encodeTime, "encodeTime");
function encodeRandom(len) {
  const bytes = new Uint8Array(len);
  crypto.getRandomValues(bytes);
  let str = "";
  for (let i = 0; i < len; i += 1) {
    str += ENCODING[bytes[i] & 31];
  }
  return str;
}
__name(encodeRandom, "encodeRandom");
function ulid(now = Date.now()) {
  return encodeTime(now, 10) + encodeRandom(16);
}
__name(ulid, "ulid");
function randomToken(byteLength = 32) {
  const bytes = new Uint8Array(byteLength);
  crypto.getRandomValues(bytes);
  return bytesToBase64Url(bytes);
}
__name(randomToken, "randomToken");
function bytesToHex(bytes) {
  const view = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
  return Array.from(view).map((b) => b.toString(16).padStart(2, "0")).join("");
}
__name(bytesToHex, "bytesToHex");
function bytesToBase64(bytes) {
  let raw2 = "";
  for (const byte of bytes)
    raw2 += String.fromCharCode(byte);
  return btoa(raw2);
}
__name(bytesToBase64, "bytesToBase64");
function base64ToBytes(value) {
  const raw2 = atob(value);
  const out = new Uint8Array(raw2.length);
  for (let i = 0; i < raw2.length; i += 1)
    out[i] = raw2.charCodeAt(i);
  return out;
}
__name(base64ToBytes, "base64ToBytes");
function bytesToBase64Url(bytes) {
  return bytesToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
}
__name(bytesToBase64Url, "bytesToBase64Url");
async function sha256Hex(input2) {
  const data = new TextEncoder().encode(input2);
  return bytesToHex(await crypto.subtle.digest("SHA-256", data));
}
__name(sha256Hex, "sha256Hex");

// src/middleware/logger.ts
var requestLogger = /* @__PURE__ */ __name(async (c, next) => {
  const requestId = ulid();
  c.set("requestId", requestId);
  const start = Date.now();
  await next();
  c.header("X-Request-Id", requestId);
  const duration = Date.now() - start;
  if (duration > 1500 || c.res.status >= 500) {
    console.log(JSON.stringify({ requestId, method: c.req.method, path: c.req.path, status: c.res.status, duration }));
  }
}, "requestLogger");

// node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/utils/cookie.js
var validCookieNameRegEx = /^[\w!#$%&'*.^`|~+-]+$/;
var validCookieValueRegEx = /^[ !#-:<-[\]-~]*$/;
var trimCookieWhitespace = /* @__PURE__ */ __name((value) => {
  let start = 0;
  let end = value.length;
  while (start < end) {
    const charCode = value.charCodeAt(start);
    if (charCode !== 32 && charCode !== 9) {
      break;
    }
    start++;
  }
  while (end > start) {
    const charCode = value.charCodeAt(end - 1);
    if (charCode !== 32 && charCode !== 9) {
      break;
    }
    end--;
  }
  return start === 0 && end === value.length ? value : value.slice(start, end);
}, "trimCookieWhitespace");
var parse = /* @__PURE__ */ __name((cookie, name) => {
  if (name && cookie.indexOf(name) === -1) {
    return {};
  }
  const pairs = cookie.split(";");
  const parsedCookie = /* @__PURE__ */ Object.create(null);
  for (const pairStr of pairs) {
    const valueStartPos = pairStr.indexOf("=");
    if (valueStartPos === -1) {
      continue;
    }
    const cookieName = trimCookieWhitespace(pairStr.substring(0, valueStartPos));
    if (name && name !== cookieName || !validCookieNameRegEx.test(cookieName) || cookieName in parsedCookie) {
      continue;
    }
    let cookieValue = trimCookieWhitespace(pairStr.substring(valueStartPos + 1));
    if (cookieValue.startsWith('"') && cookieValue.endsWith('"')) {
      cookieValue = cookieValue.slice(1, -1);
    }
    if (validCookieValueRegEx.test(cookieValue)) {
      parsedCookie[cookieName] = cookieValue.indexOf("%") !== -1 ? tryDecode(cookieValue, decodeURIComponent_) : cookieValue;
      if (name) {
        break;
      }
    }
  }
  return parsedCookie;
}, "parse");
var _serialize = /* @__PURE__ */ __name((name, value, opt = {}) => {
  if (!validCookieNameRegEx.test(name)) {
    throw new Error("Invalid cookie name");
  }
  let cookie = `${name}=${value}`;
  if (name.startsWith("__Secure-") && !opt.secure) {
    throw new Error("__Secure- Cookie must have Secure attributes");
  }
  if (name.startsWith("__Host-")) {
    if (!opt.secure) {
      throw new Error("__Host- Cookie must have Secure attributes");
    }
    if (opt.path !== "/") {
      throw new Error('__Host- Cookie must have Path attributes with "/"');
    }
    if (opt.domain) {
      throw new Error("__Host- Cookie must not have Domain attributes");
    }
  }
  for (const key of ["domain", "path", "sameSite", "priority"]) {
    if (opt[key] && /[;\r\n]/.test(opt[key])) {
      throw new Error(`${key} must not contain ";", "\\r", or "\\n"`);
    }
  }
  if (opt && typeof opt.maxAge === "number" && opt.maxAge >= 0) {
    if (opt.maxAge > 3456e4) {
      throw new Error(
        "Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration."
      );
    }
    cookie += `; Max-Age=${opt.maxAge | 0}`;
  }
  if (opt.domain && opt.prefix !== "host") {
    cookie += `; Domain=${opt.domain}`;
  }
  if (opt.path) {
    cookie += `; Path=${opt.path}`;
  }
  if (opt.expires) {
    if (opt.expires.getTime() - Date.now() > 3456e7) {
      throw new Error(
        "Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future."
      );
    }
    cookie += `; Expires=${opt.expires.toUTCString()}`;
  }
  if (opt.httpOnly) {
    cookie += "; HttpOnly";
  }
  if (opt.secure) {
    cookie += "; Secure";
  }
  if (opt.sameSite) {
    cookie += `; SameSite=${opt.sameSite.charAt(0).toUpperCase() + opt.sameSite.slice(1)}`;
  }
  if (opt.priority) {
    cookie += `; Priority=${opt.priority.charAt(0).toUpperCase() + opt.priority.slice(1)}`;
  }
  if (opt.partitioned) {
    if (!opt.secure) {
      throw new Error("Partitioned Cookie must have Secure attributes");
    }
    cookie += "; Partitioned";
  }
  return cookie;
}, "_serialize");
var serialize = /* @__PURE__ */ __name((name, value, opt) => {
  value = encodeURIComponent(value);
  return _serialize(name, value, opt);
}, "serialize");

// node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/helper/cookie/index.js
var getCookie = /* @__PURE__ */ __name((c, key, prefix) => {
  const cookie = c.req.raw.headers.get("Cookie");
  if (typeof key === "string") {
    if (!cookie) {
      return void 0;
    }
    let finalKey = key;
    if (prefix === "secure") {
      finalKey = "__Secure-" + key;
    } else if (prefix === "host") {
      finalKey = "__Host-" + key;
    }
    const obj2 = parse(cookie, finalKey);
    return obj2[finalKey];
  }
  if (!cookie) {
    return {};
  }
  const obj = parse(cookie);
  return obj;
}, "getCookie");
var generateCookie = /* @__PURE__ */ __name((name, value, opt) => {
  let cookie;
  if (opt?.prefix === "secure") {
    cookie = serialize("__Secure-" + name, value, { path: "/", ...opt, secure: true });
  } else if (opt?.prefix === "host") {
    cookie = serialize("__Host-" + name, value, {
      ...opt,
      path: "/",
      secure: true,
      domain: void 0
    });
  } else {
    cookie = serialize(name, value, { path: "/", ...opt });
  }
  return cookie;
}, "generateCookie");
var setCookie = /* @__PURE__ */ __name((c, name, value, opt) => {
  const cookie = generateCookie(name, value, opt);
  c.header("Set-Cookie", cookie, { append: true });
}, "setCookie");
var deleteCookie = /* @__PURE__ */ __name((c, name, opt) => {
  const deletedCookie = getCookie(c, name, opt?.prefix);
  setCookie(c, name, "", { ...opt, maxAge: 0 });
  return deletedCookie;
}, "deleteCookie");

// node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/utils.js
function isBytes(a) {
  return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
}
__name(isBytes, "isBytes");
function anumber(n) {
  if (!Number.isSafeInteger(n) || n < 0)
    throw new Error("positive integer expected, got " + n);
}
__name(anumber, "anumber");
function abytes(b, ...lengths) {
  if (!isBytes(b))
    throw new Error("Uint8Array expected");
  if (lengths.length > 0 && !lengths.includes(b.length))
    throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
}
__name(abytes, "abytes");
function ahash(h) {
  if (typeof h !== "function" || typeof h.create !== "function")
    throw new Error("Hash should be wrapped by utils.createHasher");
  anumber(h.outputLen);
  anumber(h.blockLen);
}
__name(ahash, "ahash");
function aexists(instance, checkFinished = true) {
  if (instance.destroyed)
    throw new Error("Hash instance has been destroyed");
  if (checkFinished && instance.finished)
    throw new Error("Hash#digest() has already been called");
}
__name(aexists, "aexists");
function aoutput(out, instance) {
  abytes(out);
  const min = instance.outputLen;
  if (out.length < min) {
    throw new Error("digestInto() expects output buffer of length at least " + min);
  }
}
__name(aoutput, "aoutput");
function u32(arr) {
  return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
}
__name(u32, "u32");
function clean(...arrays) {
  for (let i = 0; i < arrays.length; i++) {
    arrays[i].fill(0);
  }
}
__name(clean, "clean");
function createView(arr) {
  return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
}
__name(createView, "createView");
function rotr(word, shift) {
  return word << 32 - shift | word >>> shift;
}
__name(rotr, "rotr");
function rotl(word, shift) {
  return word << shift | word >>> 32 - shift >>> 0;
}
__name(rotl, "rotl");
var isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
function byteSwap(word) {
  return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
}
__name(byteSwap, "byteSwap");
function byteSwap32(arr) {
  for (let i = 0; i < arr.length; i++) {
    arr[i] = byteSwap(arr[i]);
  }
  return arr;
}
__name(byteSwap32, "byteSwap32");
var swap32IfBE = isLE ? (u) => u : byteSwap32;
function utf8ToBytes(str) {
  if (typeof str !== "string")
    throw new Error("string expected");
  return new Uint8Array(new TextEncoder().encode(str));
}
__name(utf8ToBytes, "utf8ToBytes");
function toBytes(data) {
  if (typeof data === "string")
    data = utf8ToBytes(data);
  abytes(data);
  return data;
}
__name(toBytes, "toBytes");
function kdfInputToBytes(data) {
  if (typeof data === "string")
    data = utf8ToBytes(data);
  abytes(data);
  return data;
}
__name(kdfInputToBytes, "kdfInputToBytes");
function checkOpts(defaults, opts) {
  if (opts !== void 0 && {}.toString.call(opts) !== "[object Object]")
    throw new Error("options should be object or undefined");
  const merged = Object.assign(defaults, opts);
  return merged;
}
__name(checkOpts, "checkOpts");
var Hash = class {
};
__name(Hash, "Hash");
function createHasher(hashCons) {
  const hashC = /* @__PURE__ */ __name((msg) => hashCons().update(toBytes(msg)).digest(), "hashC");
  const tmp = hashCons();
  hashC.outputLen = tmp.outputLen;
  hashC.blockLen = tmp.blockLen;
  hashC.create = () => hashCons();
  return hashC;
}
__name(createHasher, "createHasher");

// node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/hmac.js
var HMAC = class extends Hash {
  constructor(hash, _key) {
    super();
    this.finished = false;
    this.destroyed = false;
    ahash(hash);
    const key = toBytes(_key);
    this.iHash = hash.create();
    if (typeof this.iHash.update !== "function")
      throw new Error("Expected instance of class which extends utils.Hash");
    this.blockLen = this.iHash.blockLen;
    this.outputLen = this.iHash.outputLen;
    const blockLen = this.blockLen;
    const pad2 = new Uint8Array(blockLen);
    pad2.set(key.length > blockLen ? hash.create().update(key).digest() : key);
    for (let i = 0; i < pad2.length; i++)
      pad2[i] ^= 54;
    this.iHash.update(pad2);
    this.oHash = hash.create();
    for (let i = 0; i < pad2.length; i++)
      pad2[i] ^= 54 ^ 92;
    this.oHash.update(pad2);
    clean(pad2);
  }
  update(buf) {
    aexists(this);
    this.iHash.update(buf);
    return this;
  }
  digestInto(out) {
    aexists(this);
    abytes(out, this.outputLen);
    this.finished = true;
    this.iHash.digestInto(out);
    this.oHash.update(out);
    this.oHash.digestInto(out);
    this.destroy();
  }
  digest() {
    const out = new Uint8Array(this.oHash.outputLen);
    this.digestInto(out);
    return out;
  }
  _cloneInto(to) {
    to || (to = Object.create(Object.getPrototypeOf(this), {}));
    const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
    to = to;
    to.finished = finished;
    to.destroyed = destroyed;
    to.blockLen = blockLen;
    to.outputLen = outputLen;
    to.oHash = oHash._cloneInto(to.oHash);
    to.iHash = iHash._cloneInto(to.iHash);
    return to;
  }
  clone() {
    return this._cloneInto();
  }
  destroy() {
    this.destroyed = true;
    this.oHash.destroy();
    this.iHash.destroy();
  }
};
__name(HMAC, "HMAC");
var hmac = /* @__PURE__ */ __name((hash, key, message) => new HMAC(hash, key).update(message).digest(), "hmac");
hmac.create = (hash, key) => new HMAC(hash, key);

// node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/pbkdf2.js
function pbkdf2Init(hash, _password, _salt, _opts) {
  ahash(hash);
  const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);
  const { c, dkLen, asyncTick } = opts;
  anumber(c);
  anumber(dkLen);
  anumber(asyncTick);
  if (c < 1)
    throw new Error("iterations (c) should be >= 1");
  const password = kdfInputToBytes(_password);
  const salt = kdfInputToBytes(_salt);
  const DK = new Uint8Array(dkLen);
  const PRF = hmac.create(hash, password);
  const PRFSalt = PRF._cloneInto().update(salt);
  return { c, dkLen, asyncTick, DK, PRF, PRFSalt };
}
__name(pbkdf2Init, "pbkdf2Init");
function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) {
  PRF.destroy();
  PRFSalt.destroy();
  if (prfW)
    prfW.destroy();
  clean(u);
  return DK;
}
__name(pbkdf2Output, "pbkdf2Output");
function pbkdf2(hash, password, salt, opts) {
  const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);
  let prfW;
  const arr = new Uint8Array(4);
  const view = createView(arr);
  const u = new Uint8Array(PRF.outputLen);
  for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {
    const Ti = DK.subarray(pos, pos + PRF.outputLen);
    view.setInt32(0, ti, false);
    (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);
    Ti.set(u.subarray(0, Ti.length));
    for (let ui = 1; ui < c; ui++) {
      PRF._cloneInto(prfW).update(u).digestInto(u);
      for (let i = 0; i < Ti.length; i++)
        Ti[i] ^= u[i];
    }
  }
  return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);
}
__name(pbkdf2, "pbkdf2");

// node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_md.js
function setBigUint64(view, byteOffset, value, isLE2) {
  if (typeof view.setBigUint64 === "function")
    return view.setBigUint64(byteOffset, value, isLE2);
  const _32n = BigInt(32);
  const _u32_max = BigInt(4294967295);
  const wh = Number(value >> _32n & _u32_max);
  const wl = Number(value & _u32_max);
  const h = isLE2 ? 4 : 0;
  const l = isLE2 ? 0 : 4;
  view.setUint32(byteOffset + h, wh, isLE2);
  view.setUint32(byteOffset + l, wl, isLE2);
}
__name(setBigUint64, "setBigUint64");
function Chi(a, b, c) {
  return a & b ^ ~a & c;
}
__name(Chi, "Chi");
function Maj(a, b, c) {
  return a & b ^ a & c ^ b & c;
}
__name(Maj, "Maj");
var HashMD = class extends Hash {
  constructor(blockLen, outputLen, padOffset, isLE2) {
    super();
    this.finished = false;
    this.length = 0;
    this.pos = 0;
    this.destroyed = false;
    this.blockLen = blockLen;
    this.outputLen = outputLen;
    this.padOffset = padOffset;
    this.isLE = isLE2;
    this.buffer = new Uint8Array(blockLen);
    this.view = createView(this.buffer);
  }
  update(data) {
    aexists(this);
    data = toBytes(data);
    abytes(data);
    const { view, buffer, blockLen } = this;
    const len = data.length;
    for (let pos = 0; pos < len; ) {
      const take = Math.min(blockLen - this.pos, len - pos);
      if (take === blockLen) {
        const dataView = createView(data);
        for (; blockLen <= len - pos; pos += blockLen)
          this.process(dataView, pos);
        continue;
      }
      buffer.set(data.subarray(pos, pos + take), this.pos);
      this.pos += take;
      pos += take;
      if (this.pos === blockLen) {
        this.process(view, 0);
        this.pos = 0;
      }
    }
    this.length += data.length;
    this.roundClean();
    return this;
  }
  digestInto(out) {
    aexists(this);
    aoutput(out, this);
    this.finished = true;
    const { buffer, view, blockLen, isLE: isLE2 } = this;
    let { pos } = this;
    buffer[pos++] = 128;
    clean(this.buffer.subarray(pos));
    if (this.padOffset > blockLen - pos) {
      this.process(view, 0);
      pos = 0;
    }
    for (let i = pos; i < blockLen; i++)
      buffer[i] = 0;
    setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE2);
    this.process(view, 0);
    const oview = createView(out);
    const len = this.outputLen;
    if (len % 4)
      throw new Error("_sha2: outputLen should be aligned to 32bit");
    const outLen = len / 4;
    const state = this.get();
    if (outLen > state.length)
      throw new Error("_sha2: outputLen bigger than state");
    for (let i = 0; i < outLen; i++)
      oview.setUint32(4 * i, state[i], isLE2);
  }
  digest() {
    const { buffer, outputLen } = this;
    this.digestInto(buffer);
    const res = buffer.slice(0, outputLen);
    this.destroy();
    return res;
  }
  _cloneInto(to) {
    to || (to = new this.constructor());
    to.set(...this.get());
    const { blockLen, buffer, length, finished, destroyed, pos } = this;
    to.destroyed = destroyed;
    to.finished = finished;
    to.length = length;
    to.pos = pos;
    if (length % blockLen)
      to.buffer.set(buffer);
    return to;
  }
  clone() {
    return this._cloneInto();
  }
};
__name(HashMD, "HashMD");
var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
  1779033703,
  3144134277,
  1013904242,
  2773480762,
  1359893119,
  2600822924,
  528734635,
  1541459225
]);

// node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha2.js
var SHA256_K = /* @__PURE__ */ Uint32Array.from([
  1116352408,
  1899447441,
  3049323471,
  3921009573,
  961987163,
  1508970993,
  2453635748,
  2870763221,
  3624381080,
  310598401,
  607225278,
  1426881987,
  1925078388,
  2162078206,
  2614888103,
  3248222580,
  3835390401,
  4022224774,
  264347078,
  604807628,
  770255983,
  1249150122,
  1555081692,
  1996064986,
  2554220882,
  2821834349,
  2952996808,
  3210313671,
  3336571891,
  3584528711,
  113926993,
  338241895,
  666307205,
  773529912,
  1294757372,
  1396182291,
  1695183700,
  1986661051,
  2177026350,
  2456956037,
  2730485921,
  2820302411,
  3259730800,
  3345764771,
  3516065817,
  3600352804,
  4094571909,
  275423344,
  430227734,
  506948616,
  659060556,
  883997877,
  958139571,
  1322822218,
  1537002063,
  1747873779,
  1955562222,
  2024104815,
  2227730452,
  2361852424,
  2428436474,
  2756734187,
  3204031479,
  3329325298
]);
var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
var SHA256 = class extends HashMD {
  constructor(outputLen = 32) {
    super(64, outputLen, 8, false);
    this.A = SHA256_IV[0] | 0;
    this.B = SHA256_IV[1] | 0;
    this.C = SHA256_IV[2] | 0;
    this.D = SHA256_IV[3] | 0;
    this.E = SHA256_IV[4] | 0;
    this.F = SHA256_IV[5] | 0;
    this.G = SHA256_IV[6] | 0;
    this.H = SHA256_IV[7] | 0;
  }
  get() {
    const { A, B, C, D, E, F, G, H } = this;
    return [A, B, C, D, E, F, G, H];
  }
  // prettier-ignore
  set(A, B, C, D, E, F, G, H) {
    this.A = A | 0;
    this.B = B | 0;
    this.C = C | 0;
    this.D = D | 0;
    this.E = E | 0;
    this.F = F | 0;
    this.G = G | 0;
    this.H = H | 0;
  }
  process(view, offset) {
    for (let i = 0; i < 16; i++, offset += 4)
      SHA256_W[i] = view.getUint32(offset, false);
    for (let i = 16; i < 64; i++) {
      const W15 = SHA256_W[i - 15];
      const W2 = SHA256_W[i - 2];
      const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
      const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
      SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
    }
    let { A, B, C, D, E, F, G, H } = this;
    for (let i = 0; i < 64; i++) {
      const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
      const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
      const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
      const T2 = sigma0 + Maj(A, B, C) | 0;
      H = G;
      G = F;
      F = E;
      E = D + T1 | 0;
      D = C;
      C = B;
      B = A;
      A = T1 + T2 | 0;
    }
    A = A + this.A | 0;
    B = B + this.B | 0;
    C = C + this.C | 0;
    D = D + this.D | 0;
    E = E + this.E | 0;
    F = F + this.F | 0;
    G = G + this.G | 0;
    H = H + this.H | 0;
    this.set(A, B, C, D, E, F, G, H);
  }
  roundClean() {
    clean(SHA256_W);
  }
  destroy() {
    this.set(0, 0, 0, 0, 0, 0, 0, 0);
    clean(this.buffer);
  }
};
__name(SHA256, "SHA256");
var sha256 = /* @__PURE__ */ createHasher(() => new SHA256());

// node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/scrypt.js
function XorAndSalsa(prev, pi, input2, ii, out, oi) {
  let y00 = prev[pi++] ^ input2[ii++], y01 = prev[pi++] ^ input2[ii++];
  let y02 = prev[pi++] ^ input2[ii++], y03 = prev[pi++] ^ input2[ii++];
  let y04 = prev[pi++] ^ input2[ii++], y05 = prev[pi++] ^ input2[ii++];
  let y06 = prev[pi++] ^ input2[ii++], y07 = prev[pi++] ^ input2[ii++];
  let y08 = prev[pi++] ^ input2[ii++], y09 = prev[pi++] ^ input2[ii++];
  let y10 = prev[pi++] ^ input2[ii++], y11 = prev[pi++] ^ input2[ii++];
  let y12 = prev[pi++] ^ input2[ii++], y13 = prev[pi++] ^ input2[ii++];
  let y14 = prev[pi++] ^ input2[ii++], y15 = prev[pi++] ^ input2[ii++];
  let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;
  for (let i = 0; i < 8; i += 2) {
    x04 ^= rotl(x00 + x12 | 0, 7);
    x08 ^= rotl(x04 + x00 | 0, 9);
    x12 ^= rotl(x08 + x04 | 0, 13);
    x00 ^= rotl(x12 + x08 | 0, 18);
    x09 ^= rotl(x05 + x01 | 0, 7);
    x13 ^= rotl(x09 + x05 | 0, 9);
    x01 ^= rotl(x13 + x09 | 0, 13);
    x05 ^= rotl(x01 + x13 | 0, 18);
    x14 ^= rotl(x10 + x06 | 0, 7);
    x02 ^= rotl(x14 + x10 | 0, 9);
    x06 ^= rotl(x02 + x14 | 0, 13);
    x10 ^= rotl(x06 + x02 | 0, 18);
    x03 ^= rotl(x15 + x11 | 0, 7);
    x07 ^= rotl(x03 + x15 | 0, 9);
    x11 ^= rotl(x07 + x03 | 0, 13);
    x15 ^= rotl(x11 + x07 | 0, 18);
    x01 ^= rotl(x00 + x03 | 0, 7);
    x02 ^= rotl(x01 + x00 | 0, 9);
    x03 ^= rotl(x02 + x01 | 0, 13);
    x00 ^= rotl(x03 + x02 | 0, 18);
    x06 ^= rotl(x05 + x04 | 0, 7);
    x07 ^= rotl(x06 + x05 | 0, 9);
    x04 ^= rotl(x07 + x06 | 0, 13);
    x05 ^= rotl(x04 + x07 | 0, 18);
    x11 ^= rotl(x10 + x09 | 0, 7);
    x08 ^= rotl(x11 + x10 | 0, 9);
    x09 ^= rotl(x08 + x11 | 0, 13);
    x10 ^= rotl(x09 + x08 | 0, 18);
    x12 ^= rotl(x15 + x14 | 0, 7);
    x13 ^= rotl(x12 + x15 | 0, 9);
    x14 ^= rotl(x13 + x12 | 0, 13);
    x15 ^= rotl(x14 + x13 | 0, 18);
  }
  out[oi++] = y00 + x00 | 0;
  out[oi++] = y01 + x01 | 0;
  out[oi++] = y02 + x02 | 0;
  out[oi++] = y03 + x03 | 0;
  out[oi++] = y04 + x04 | 0;
  out[oi++] = y05 + x05 | 0;
  out[oi++] = y06 + x06 | 0;
  out[oi++] = y07 + x07 | 0;
  out[oi++] = y08 + x08 | 0;
  out[oi++] = y09 + x09 | 0;
  out[oi++] = y10 + x10 | 0;
  out[oi++] = y11 + x11 | 0;
  out[oi++] = y12 + x12 | 0;
  out[oi++] = y13 + x13 | 0;
  out[oi++] = y14 + x14 | 0;
  out[oi++] = y15 + x15 | 0;
}
__name(XorAndSalsa, "XorAndSalsa");
function BlockMix(input2, ii, out, oi, r) {
  let head = oi + 0;
  let tail = oi + 16 * r;
  for (let i = 0; i < 16; i++)
    out[tail + i] = input2[ii + (2 * r - 1) * 16 + i];
  for (let i = 0; i < r; i++, head += 16, ii += 16) {
    XorAndSalsa(out, tail, input2, ii, out, head);
    if (i > 0)
      tail += 16;
    XorAndSalsa(out, head, input2, ii += 16, out, tail);
  }
}
__name(BlockMix, "BlockMix");
function scryptInit(password, salt, _opts) {
  const opts = checkOpts({
    dkLen: 32,
    asyncTick: 10,
    maxmem: 1024 ** 3 + 1024
  }, _opts);
  const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts;
  anumber(N);
  anumber(r);
  anumber(p);
  anumber(dkLen);
  anumber(asyncTick);
  anumber(maxmem);
  if (onProgress !== void 0 && typeof onProgress !== "function")
    throw new Error("progressCb should be function");
  const blockSize = 128 * r;
  const blockSize32 = blockSize / 4;
  const pow32 = Math.pow(2, 32);
  if (N <= 1 || (N & N - 1) !== 0 || N > pow32) {
    throw new Error("Scrypt: N must be larger than 1, a power of 2, and less than 2^32");
  }
  if (p < 0 || p > (pow32 - 1) * 32 / blockSize) {
    throw new Error("Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)");
  }
  if (dkLen < 0 || dkLen > (pow32 - 1) * 32) {
    throw new Error("Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32");
  }
  const memUsed = blockSize * (N + p);
  if (memUsed > maxmem) {
    throw new Error("Scrypt: memused is bigger than maxMem. Expected 128 * r * (N + p) > maxmem of " + maxmem);
  }
  const B = pbkdf2(sha256, password, salt, { c: 1, dkLen: blockSize * p });
  const B32 = u32(B);
  const V = u32(new Uint8Array(blockSize * N));
  const tmp = u32(new Uint8Array(blockSize));
  let blockMixCb = /* @__PURE__ */ __name(() => {
  }, "blockMixCb");
  if (onProgress) {
    const totalBlockMix = 2 * N * p;
    const callbackPer = Math.max(Math.floor(totalBlockMix / 1e4), 1);
    let blockMixCnt = 0;
    blockMixCb = /* @__PURE__ */ __name(() => {
      blockMixCnt++;
      if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix))
        onProgress(blockMixCnt / totalBlockMix);
    }, "blockMixCb");
  }
  return { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick };
}
__name(scryptInit, "scryptInit");
function scryptOutput(password, dkLen, B, V, tmp) {
  const res = pbkdf2(sha256, password, B, { c: 1, dkLen });
  clean(B, V, tmp);
  return res;
}
__name(scryptOutput, "scryptOutput");
function scrypt(password, salt, opts) {
  const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb } = scryptInit(password, salt, opts);
  swap32IfBE(B32);
  for (let pi = 0; pi < p; pi++) {
    const Pi = blockSize32 * pi;
    for (let i = 0; i < blockSize32; i++)
      V[i] = B32[Pi + i];
    for (let i = 0, pos = 0; i < N - 1; i++) {
      BlockMix(V, pos, V, pos += blockSize32, r);
      blockMixCb();
    }
    BlockMix(V, (N - 1) * blockSize32, B32, Pi, r);
    blockMixCb();
    for (let i = 0; i < N; i++) {
      const j = B32[Pi + blockSize32 - 16] % N;
      for (let k = 0; k < blockSize32; k++)
        tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k];
      BlockMix(tmp, 0, B32, Pi, r);
      blockMixCb();
    }
  }
  swap32IfBE(B32);
  return scryptOutput(password, dkLen, B, V, tmp);
}
__name(scrypt, "scrypt");

// src/db/queries.ts
function mapUser(row) {
  return {
    id: row.id,
    username: row.username,
    email: row.email,
    displayName: row.display_name,
    avatarKey: row.avatar_key,
    bio: row.bio || "",
    url: row.url || "",
    role: row.role,
    status: row.status
  };
}
__name(mapUser, "mapUser");
async function audit(db, input2) {
  await db.prepare(
    `INSERT INTO wm_audit_log(actor_id, action, target, detail, ip, created_at)
       VALUES (?, ?, ?, ?, ?, ?)`
  ).bind(
    input2.actorId || null,
    input2.action,
    input2.target || null,
    input2.detail === void 0 ? null : JSON.stringify(input2.detail),
    input2.ip || null,
    input2.createdAt
  ).run();
}
__name(audit, "audit");
async function first(statement) {
  return await statement.first() || null;
}
__name(first, "first");
async function all(statement) {
  const result = await statement.all();
  return result.results || [];
}
__name(all, "all");

// src/utils/time.ts
function nowSeconds() {
  return Math.floor(Date.now() / 1e3);
}
__name(nowSeconds, "nowSeconds");
function sameLocalDay(a, b) {
  return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
}
__name(sameLocalDay, "sameLocalDay");
function pad(value) {
  return String(value).padStart(2, "0");
}
__name(pad, "pad");
function formatMomentTime(seconds, now = /* @__PURE__ */ new Date()) {
  const date = new Date(seconds * 1e3);
  const diff = Math.max(0, Math.floor((now.getTime() - date.getTime()) / 1e3));
  if (diff < 60)
    return "\u521A\u521A";
  if (diff < 3600)
    return `${Math.floor(diff / 60)} \u5206\u949F\u524D`;
  if (sameLocalDay(date, now))
    return `${Math.floor(diff / 3600)} \u5C0F\u65F6\u524D`;
  const yesterday = new Date(now);
  yesterday.setDate(now.getDate() - 1);
  if (sameLocalDay(date, yesterday))
    return `\u6628\u5929 ${pad(date.getHours())}:${pad(date.getMinutes())}`;
  if (date.getFullYear() === now.getFullYear())
    return `${date.getMonth() + 1}\u6708${date.getDate()}\u65E5`;
  return `${date.getFullYear()}\u5E74${date.getMonth() + 1}\u6708${date.getDate()}\u65E5`;
}
__name(formatMomentTime, "formatMomentTime");

// src/services/settings.ts
var CACHE_KEY = "settings:cache";
var CACHE_TTL = 300;
var DEFAULT_SETTINGS = {
  site_name: "Wemoments",
  site_description: "",
  site_avatar_key: "",
  top_image_key: "",
  top_video_key: "",
  avatar_link: "",
  avatar_mirror: "",
  tencent_map_key: "",
  beian_info: "",
  list_collapse: true,
  custom_css: "",
  custom_js: "",
  analytics_code: "",
  allow_register: true,
  default_role: "subscriber",
  comment_mode: "registered",
  comment_review: false,
  upload_max_image_mb: 8,
  upload_max_video_mb: 50,
  cdn_base_url: ""
};
var SETTING_KEYS = Object.keys(DEFAULT_SETTINGS);
function normalizeValue(key, value) {
  const fallback = DEFAULT_SETTINGS[key];
  if (typeof fallback === "boolean")
    return Boolean(value);
  if (typeof fallback === "number") {
    const n = Number(value);
    return Number.isFinite(n) ? n : fallback;
  }
  if (key === "default_role") {
    return ["subscriber", "author", "admin"].includes(String(value)) ? value : fallback;
  }
  if (key === "comment_mode") {
    return ["everyone", "registered", "closed"].includes(String(value)) ? value : fallback;
  }
  return typeof value === "string" ? value : String(value ?? fallback);
}
__name(normalizeValue, "normalizeValue");
function parseStoredValue(raw2) {
  try {
    return JSON.parse(raw2);
  } catch {
    return raw2;
  }
}
__name(parseStoredValue, "parseStoredValue");
async function getSettings(env2) {
  const cached = await env2.KV.get(CACHE_KEY, "json");
  if (cached)
    return { ...DEFAULT_SETTINGS, ...cached };
  const rows = await all(env2.DB.prepare("SELECT key, value FROM wm_settings"));
  const settings = { ...DEFAULT_SETTINGS };
  for (const row of rows) {
    if (SETTING_KEYS.includes(row.key)) {
      const key = row.key;
      settings[key] = normalizeValue(key, parseStoredValue(row.value));
    }
  }
  await env2.KV.put(CACHE_KEY, JSON.stringify(settings), { expirationTtl: CACHE_TTL });
  return settings;
}
__name(getSettings, "getSettings");
async function setSettings(env2, values) {
  const batch = [];
  for (const [key, value] of Object.entries(values)) {
    if (!SETTING_KEYS.includes(key))
      continue;
    batch.push(
      env2.DB.prepare("INSERT INTO wm_settings(key, value) VALUES(?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").bind(
        key,
        JSON.stringify(normalizeValue(key, value))
      )
    );
  }
  if (batch.length > 0)
    await env2.DB.batch(batch);
  const settings = await getSettingsFresh(env2);
  await env2.KV.put(CACHE_KEY, JSON.stringify(settings), { expirationTtl: CACHE_TTL });
  return settings;
}
__name(setSettings, "setSettings");
async function getSettingsFresh(env2) {
  await env2.KV.delete(CACHE_KEY);
  const rows = await all(env2.DB.prepare("SELECT key, value FROM wm_settings"));
  const settings = { ...DEFAULT_SETTINGS };
  for (const row of rows) {
    if (SETTING_KEYS.includes(row.key)) {
      const key = row.key;
      settings[key] = normalizeValue(key, parseStoredValue(row.value));
    }
  }
  return settings;
}
__name(getSettingsFresh, "getSettingsFresh");

// src/services/auth.ts
var PASSWORD_N = 32768;
var PASSWORD_R = 8;
var PASSWORD_P = 1;
var PASSWORD_DK_LEN = 32;
var AuthError = class extends Error {
  status;
  code;
  constructor(message, status = 400, code = "AUTH_ERROR") {
    super(message);
    this.status = status;
    this.code = code;
  }
};
__name(AuthError, "AuthError");
function textBytes(value) {
  return new TextEncoder().encode(value);
}
__name(textBytes, "textBytes");
function constantTimeEqual(a, b) {
  if (a.length !== b.length)
    return false;
  let diff = 0;
  for (let i = 0; i < a.length; i += 1)
    diff |= a[i] ^ b[i];
  return diff === 0;
}
__name(constantTimeEqual, "constantTimeEqual");
async function hashPassword(password) {
  const salt = new Uint8Array(16);
  crypto.getRandomValues(salt);
  const hash = scrypt(textBytes(password), salt, {
    N: PASSWORD_N,
    r: PASSWORD_R,
    p: PASSWORD_P,
    dkLen: PASSWORD_DK_LEN
  });
  return `scrypt$N=${PASSWORD_N}$r=${PASSWORD_R}$p=${PASSWORD_P}$${bytesToBase64(salt)}$${bytesToBase64(hash)}`;
}
__name(hashPassword, "hashPassword");
async function verifyPassword(password, stored) {
  const [scheme, nPart, rPart, pPart, saltB64, hashB64] = stored.split("$");
  if (scheme !== "scrypt" || !nPart || !rPart || !pPart || !saltB64 || !hashB64)
    return false;
  const N = Number(nPart.replace("N=", ""));
  const r = Number(rPart.replace("r=", ""));
  const p = Number(pPart.replace("p=", ""));
  if (!Number.isFinite(N) || !Number.isFinite(r) || !Number.isFinite(p))
    return false;
  const expected = base64ToBytes(hashB64);
  const actual = scrypt(textBytes(password), base64ToBytes(saltB64), { N, r, p, dkLen: expected.length });
  return constantTimeEqual(actual, expected);
}
__name(verifyPassword, "verifyPassword");
async function countUsers(db) {
  const row = await db.prepare("SELECT COUNT(*) AS count FROM wm_users").first();
  return row?.count || 0;
}
__name(countUsers, "countUsers");
async function getUserById(db, id) {
  const row = await first(db.prepare("SELECT * FROM wm_users WHERE id = ?").bind(id));
  return row ? mapUser(row) : null;
}
__name(getUserById, "getUserById");
async function getUserRowByIdentifier(db, identifier) {
  return first(
    db.prepare("SELECT * FROM wm_users WHERE lower(username) = lower(?) OR lower(email) = lower(?)").bind(identifier, identifier)
  );
}
__name(getUserRowByIdentifier, "getUserRowByIdentifier");
async function registerUser(env2, input2) {
  const existingUsers = await countUsers(env2.DB);
  const settings = await getSettings(env2);
  const isBootstrap = existingUsers === 0 && Boolean(input2.bootstrapToken);
  if (existingUsers === 0 && !input2.bootstrapToken) {
    throw new AuthError("\u8BF7\u5148\u8BBF\u95EE /admin/bootstrap \u521D\u59CB\u5316\u7BA1\u7406\u5458", 403, "BOOTSTRAP_REQUIRED");
  }
  if (!isBootstrap && !settings.allow_register) {
    throw new AuthError("\u6CE8\u518C\u5DF2\u5173\u95ED", 403, "REGISTER_CLOSED");
  }
  if (isBootstrap && input2.bootstrapToken !== env2.ADMIN_BOOTSTRAP_TOKEN) {
    throw new AuthError("Bootstrap Token \u4E0D\u6B63\u786E", 403, "BOOTSTRAP_TOKEN_INVALID");
  }
  const role = isBootstrap ? "admin" : settings.default_role;
  const now = nowSeconds();
  const id = ulid();
  const passwordHash = await hashPassword(input2.password);
  try {
    await env2.DB.prepare(
      `INSERT INTO wm_users(id, username, email, display_name, password_hash, role, status, created_at, updated_at)
       VALUES (?, ?, ?, ?, ?, ?, 'active', ?, ?)`
    ).bind(id, input2.username, input2.email.toLowerCase(), input2.displayName, passwordHash, role, now, now).run();
  } catch (error3) {
    throw new AuthError("\u7528\u6237\u540D\u6216\u90AE\u7BB1\u5DF2\u88AB\u4F7F\u7528", 409, "USER_EXISTS");
  }
  const user = await getUserById(env2.DB, id);
  if (!user)
    throw new AuthError("\u521B\u5EFA\u7528\u6237\u5931\u8D25", 500, "USER_CREATE_FAILED");
  return user;
}
__name(registerUser, "registerUser");
async function loginUser(env2, identifier, password) {
  const row = await getUserRowByIdentifier(env2.DB, identifier);
  if (!row || !await verifyPassword(password, row.password_hash)) {
    throw new AuthError("\u8D26\u53F7\u6216\u5BC6\u7801\u4E0D\u6B63\u786E", 401, "BAD_CREDENTIALS");
  }
  if (row.status !== "active")
    throw new AuthError("\u8D26\u53F7\u4E0D\u53EF\u7528", 403, "USER_BLOCKED");
  await env2.DB.prepare("UPDATE wm_users SET last_login_at = ?, updated_at = ? WHERE id = ?").bind(nowSeconds(), nowSeconds(), row.id).run();
  return mapUser(row);
}
__name(loginUser, "loginUser");
async function createSession(env2, userId, request) {
  const token = randomToken(32);
  const tokenHash = await sha256Hex(token);
  const ttlDays = Number(env2.SESSION_TTL_DAYS || "30");
  const maxAge = Math.max(1, ttlDays) * 86400;
  const now = nowSeconds();
  const expiresAt = now + maxAge;
  await env2.DB.prepare(
    `INSERT INTO wm_sessions(token_hash, user_id, created_at, expires_at, user_agent, ip)
     VALUES (?, ?, ?, ?, ?, ?)`
  ).bind(tokenHash, userId, now, expiresAt, request.headers.get("user-agent") || "", request.headers.get("cf-connecting-ip") || "").run();
  await env2.KV.put(`session:${tokenHash}`, userId, { expirationTtl: maxAge });
  return { token, tokenHash, expiresAt, maxAge };
}
__name(createSession, "createSession");
async function getSessionUser(env2, token) {
  if (!token)
    return null;
  const tokenHash = await sha256Hex(token);
  const cachedUserId = await env2.KV.get(`session:${tokenHash}`);
  if (cachedUserId)
    return getUserById(env2.DB, cachedUserId);
  const now = nowSeconds();
  const row = await first(
    env2.DB.prepare("SELECT user_id, expires_at FROM wm_sessions WHERE token_hash = ? AND expires_at > ?").bind(tokenHash, now)
  );
  if (!row)
    return null;
  await env2.KV.put(`session:${tokenHash}`, row.user_id, { expirationTtl: Math.max(60, row.expires_at - now) });
  return getUserById(env2.DB, row.user_id);
}
__name(getSessionUser, "getSessionUser");
async function destroySession(env2, token) {
  if (!token)
    return;
  const tokenHash = await sha256Hex(token);
  await env2.DB.prepare("DELETE FROM wm_sessions WHERE token_hash = ?").bind(tokenHash).run();
  await env2.KV.delete(`session:${tokenHash}`);
}
__name(destroySession, "destroySession");
async function updatePassword(env2, user, oldPassword, newPassword) {
  const row = await first(env2.DB.prepare("SELECT * FROM wm_users WHERE id = ?").bind(user.id));
  if (!row || !await verifyPassword(oldPassword, row.password_hash)) {
    throw new AuthError("\u65E7\u5BC6\u7801\u4E0D\u6B63\u786E", 401, "BAD_OLD_PASSWORD");
  }
  await env2.DB.prepare("UPDATE wm_users SET password_hash = ?, updated_at = ? WHERE id = ?").bind(await hashPassword(newPassword), nowSeconds(), user.id).run();
}
__name(updatePassword, "updatePassword");

// src/middleware/session.ts
var CSRF_COOKIE = "wm_csrf";
function sessionCookieName(env2) {
  return env2.COOKIE_NAME || "wm_session";
}
__name(sessionCookieName, "sessionCookieName");
function getSessionToken(c) {
  return getCookie(c, sessionCookieName(c.env)) || "";
}
__name(getSessionToken, "getSessionToken");
function ensureCsrfToken(c) {
  let token = getCookie(c, CSRF_COOKIE);
  if (!token) {
    token = randomToken(24);
    setCookie(c, CSRF_COOKIE, token, {
      path: "/",
      httpOnly: false,
      sameSite: "Lax",
      secure: new URL(c.req.url).protocol === "https:"
    });
  }
  c.set("csrfToken", token);
  return token;
}
__name(ensureCsrfToken, "ensureCsrfToken");
var sessionMiddleware = /* @__PURE__ */ __name(async (c, next) => {
  const token = getSessionToken(c);
  const user = token ? await getSessionUser(c.env, token) : null;
  c.set("currentUser", user?.status === "active" ? user : null);
  ensureCsrfToken(c);
  await next();
}, "sessionMiddleware");

// src/middleware/csrf.ts
var WRITE_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
var HttpError = class extends Error {
  status;
  code;
  constructor(message, status = 400, code = "BAD_REQUEST") {
    super(message);
    this.status = status;
    this.code = code;
  }
};
__name(HttpError, "HttpError");
var csrfMiddleware = /* @__PURE__ */ __name(async (c, next) => {
  if (!WRITE_METHODS.has(c.req.method)) {
    await next();
    return;
  }
  const cookieToken = getCookie(c, CSRF_COOKIE);
  const headerToken = c.req.header("X-CSRF-Token");
  if (!cookieToken || !headerToken || cookieToken !== headerToken) {
    throw new HttpError("CSRF token \u65E0\u6548\u6216\u7F3A\u5931", 403, "CSRF_INVALID");
  }
  await next();
}, "csrfMiddleware");

// src/utils/html.ts
var LINK_RE = /(https?:\/\/[^\s<>"']+)/g;
function escapeHtml(input2) {
  return input2.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
}
__name(escapeHtml, "escapeHtml");
function escapeAttr(input2) {
  return escapeHtml(input2).replace(/`/g, "&#96;");
}
__name(escapeAttr, "escapeAttr");
function renderContentHtml(input2) {
  const escaped = escapeHtml(input2.trim());
  return escaped.replace(LINK_RE, (url) => `<a href="${escapeAttr(url)}" target="_blank" rel="noopener noreferrer">${escapeHtml(url)}</a>`).replace(/\n/g, "<br>");
}
__name(renderContentHtml, "renderContentHtml");
function safeJson(value) {
  return JSON.stringify(value).replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/&/g, "\\u0026");
}
__name(safeJson, "safeJson");

// src/utils/image.ts
function extensionFromMime(mime, filename = "") {
  const normalized = mime.toLowerCase();
  if (normalized === "image/jpeg")
    return "jpg";
  if (normalized === "image/png")
    return "png";
  if (normalized === "image/webp")
    return "webp";
  if (normalized === "image/gif")
    return "gif";
  if (normalized === "video/mp4")
    return "mp4";
  if (normalized === "video/webm")
    return "webm";
  const ext = filename.split(".").pop()?.toLowerCase().replace(/[^a-z0-9]/g, "");
  return ext || "bin";
}
__name(extensionFromMime, "extensionFromMime");
function isImageMime(mime) {
  return ["image/jpeg", "image/png", "image/webp", "image/gif"].includes(mime.toLowerCase());
}
__name(isImageMime, "isImageMime");
function isVideoMime(mime) {
  return ["video/mp4", "video/webm", "video/quicktime"].includes(mime.toLowerCase());
}
__name(isVideoMime, "isVideoMime");
function mediaUrl(cdnBaseUrl, key, fallback = "/assets/images/default-avatar.svg") {
  if (!key)
    return fallback;
  if (/^https?:\/\//i.test(key))
    return key;
  if (cdnBaseUrl)
    return `${cdnBaseUrl.replace(/\/+$/, "")}/${key.replace(/^\/+/, "")}`;
  return `/r2/${key.replace(/^\/+/, "")}`;
}
__name(mediaUrl, "mediaUrl");

// src/services/posts.ts
function mapPost(row, images, settings) {
  return {
    id: row.id,
    author: {
      id: row.author_id,
      username: row.username,
      displayName: row.display_name,
      avatarKey: row.avatar_key,
      avatarUrl: mediaUrl(settings.cdn_base_url, row.avatar_key)
    },
    type: row.type,
    visibility: row.visibility,
    status: row.status,
    isTop: row.is_top === 1,
    isAd: row.is_ad === 1,
    title: row.title || "",
    content: row.content,
    contentHtml: row.content_html,
    images,
    videoKey: row.video_key,
    videoUrl: row.video_key ? mediaUrl(settings.cdn_base_url, row.video_key, "") : null,
    position: row.position,
    positionLat: row.position_lat,
    positionLng: row.position_lng,
    shareUrl: row.share_url,
    shareThumb: row.share_thumb,
    likeCount: row.like_count,
    commentCount: row.comment_count,
    viewerLiked: row.viewer_liked === 1,
    createdAt: row.created_at,
    updatedAt: row.updated_at
  };
}
__name(mapPost, "mapPost");
async function loadImages(env2, postIds, settings) {
  const out = /* @__PURE__ */ new Map();
  for (const id of postIds)
    out.set(id, []);
  if (postIds.length === 0)
    return out;
  const placeholders = postIds.map(() => "?").join(",");
  const rows = await all(
    env2.DB.prepare(`SELECT post_id, r2_key, width, height FROM wm_post_images WHERE post_id IN (${placeholders}) ORDER BY position ASC`).bind(
      ...postIds
    )
  );
  for (const row of rows) {
    out.get(row.post_id)?.push({
      key: row.r2_key,
      url: mediaUrl(settings.cdn_base_url, row.r2_key, ""),
      width: row.width,
      height: row.height
    });
  }
  return out;
}
__name(loadImages, "loadImages");
function baseSelect(viewerId) {
  return `
    SELECT p.*, u.username, u.display_name, u.avatar_key,
      ${viewerId ? `CASE WHEN l.user_id IS NULL THEN 0 ELSE 1 END` : `0`} AS viewer_liked
    FROM wm_posts p
    JOIN wm_users u ON u.id = p.author_id
    ${viewerId ? `LEFT JOIN wm_likes l ON l.post_id = p.id AND l.user_id = ?` : ``}
  `;
}
__name(baseSelect, "baseSelect");
async function listPosts(env2, settings, options = {}) {
  const limit = Math.min(Math.max(options.limit || 20, 1), 50);
  const binds = [];
  if (options.viewer)
    binds.push(options.viewer.id);
  const where = [];
  if (!options.includeTrash)
    where.push(`p.status = 'published'`);
  if (!options.admin) {
    if (options.viewer) {
      where.push(`(p.visibility = 'public' OR p.author_id = ?)`);
      binds.push(options.viewer.id);
    } else {
      where.push(`p.visibility = 'public'`);
    }
  }
  if (options.authorUsername) {
    where.push(`u.username = ?`);
    binds.push(options.authorUsername);
  }
  if (options.type) {
    where.push(`p.type = ?`);
    binds.push(options.type);
  }
  if (options.q) {
    where.push(`(p.content LIKE ? OR p.title LIKE ?)`);
    binds.push(`%${options.q}%`, `%${options.q}%`);
  }
  if (options.cursor) {
    const [createdAt, id] = options.cursor.split("_");
    const cursorTime = Number(createdAt);
    if (Number.isFinite(cursorTime) && id) {
      where.push(`(p.created_at < ? OR (p.created_at = ? AND p.id < ?))`);
      binds.push(cursorTime, cursorTime, id);
    }
  }
  const sql = `${baseSelect(options.viewer?.id)}
    ${where.length ? `WHERE ${where.join(" AND ")}` : ""}
    ORDER BY p.is_top DESC, p.created_at DESC, p.id DESC
    LIMIT ?`;
  binds.push(limit + 1);
  const rows = await all(env2.DB.prepare(sql).bind(...binds));
  const pageRows = rows.slice(0, limit);
  const images = await loadImages(env2, pageRows.map((row) => row.id), settings);
  const posts = pageRows.map((row) => mapPost(row, images.get(row.id) || [], settings));
  const last = posts[posts.length - 1];
  return {
    posts,
    nextCursor: rows.length > limit && last ? `${last.createdAt}_${last.id}` : null
  };
}
__name(listPosts, "listPosts");
async function getPost(env2, settings, id, viewer, admin2 = false) {
  const binds = [];
  if (viewer)
    binds.push(viewer.id);
  binds.push(id);
  const visibility = admin2 ? "" : viewer ? `AND (p.visibility = 'public' OR p.author_id = ?)` : `AND p.visibility = 'public'`;
  if (!admin2 && viewer)
    binds.push(viewer.id);
  const row = await first(
    env2.DB.prepare(`${baseSelect(viewer?.id)} WHERE p.id = ? AND p.status != 'trash' ${visibility}`).bind(...binds)
  );
  if (!row)
    return null;
  const images = await loadImages(env2, [row.id], settings);
  return mapPost(row, images.get(row.id) || [], settings);
}
__name(getPost, "getPost");
async function createPost(env2, author, input2) {
  const id = ulid();
  const now = nowSeconds();
  await env2.DB.prepare(
    `INSERT INTO wm_posts(
      id, author_id, type, visibility, status, is_top, is_ad, title, content, content_html, video_key,
      position, position_lat, position_lng, share_url, share_thumb, created_at, updated_at
    ) VALUES (?, ?, ?, ?, 'published', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
  ).bind(
    id,
    author.id,
    input2.type,
    input2.visibility,
    input2.isTop ? 1 : 0,
    input2.isAd ? 1 : 0,
    input2.title || "",
    input2.content,
    renderContentHtml(input2.content),
    input2.videoKey || null,
    input2.position || null,
    input2.positionLat ?? null,
    input2.positionLng ?? null,
    input2.shareUrl || null,
    input2.shareThumb || null,
    now,
    now
  ).run();
  const imageStatements = input2.images.slice(0, 9).map(
    (key, index) => env2.DB.prepare("INSERT INTO wm_post_images(post_id, position, r2_key) VALUES (?, ?, ?)").bind(id, index, key)
  );
  if (imageStatements.length > 0)
    await env2.DB.batch(imageStatements);
  return id;
}
__name(createPost, "createPost");
async function updatePost(env2, id, actor, input2) {
  const existing = await first(env2.DB.prepare("SELECT author_id, video_key, position, position_lat, position_lng, share_url, share_thumb FROM wm_posts WHERE id = ?").bind(id));
  if (!existing)
    throw new Error("\u5185\u5BB9\u4E0D\u5B58\u5728");
  if (existing.author_id !== actor.id && actor.role !== "admin")
    throw new Error("\u65E0\u6743\u7F16\u8F91\u6B64\u5185\u5BB9");
  const now = nowSeconds();
  await env2.DB.prepare(
    `UPDATE wm_posts SET
      type = COALESCE(?, type),
      visibility = COALESCE(?, visibility),
      is_top = COALESCE(?, is_top),
      is_ad = COALESCE(?, is_ad),
      title = COALESCE(?, title),
      content = COALESCE(?, content),
      content_html = COALESCE(?, content_html),
      video_key = ?,
      position = ?,
      position_lat = ?,
      position_lng = ?,
      share_url = ?,
      share_thumb = ?,
      updated_at = ?
     WHERE id = ?`
  ).bind(
    input2.type ?? null,
    input2.visibility ?? null,
    input2.isTop === void 0 ? null : input2.isTop ? 1 : 0,
    input2.isAd === void 0 ? null : input2.isAd ? 1 : 0,
    input2.title ?? null,
    input2.content ?? null,
    input2.content === void 0 ? null : renderContentHtml(input2.content),
    input2.videoKey === void 0 ? existing.video_key : input2.videoKey,
    input2.position === void 0 ? existing.position : input2.position,
    input2.positionLat === void 0 ? existing.position_lat : input2.positionLat,
    input2.positionLng === void 0 ? existing.position_lng : input2.positionLng,
    input2.shareUrl === void 0 ? existing.share_url : input2.shareUrl,
    input2.shareThumb === void 0 ? existing.share_thumb : input2.shareThumb,
    now,
    id
  ).run();
  if (input2.images) {
    await env2.DB.prepare("DELETE FROM wm_post_images WHERE post_id = ?").bind(id).run();
    const statements = input2.images.slice(0, 9).map(
      (key, index) => env2.DB.prepare("INSERT INTO wm_post_images(post_id, position, r2_key) VALUES (?, ?, ?)").bind(id, index, key)
    );
    if (statements.length > 0)
      await env2.DB.batch(statements);
  }
}
__name(updatePost, "updatePost");
async function softDeletePost(env2, id, actor) {
  const row = await first(env2.DB.prepare("SELECT author_id FROM wm_posts WHERE id = ?").bind(id));
  if (!row)
    throw new Error("\u5185\u5BB9\u4E0D\u5B58\u5728");
  if (row.author_id !== actor.id && actor.role !== "admin")
    throw new Error("\u65E0\u6743\u5220\u9664\u6B64\u5185\u5BB9");
  await env2.DB.prepare(`UPDATE wm_posts SET status = 'trash', updated_at = ? WHERE id = ?`).bind(nowSeconds(), id).run();
}
__name(softDeletePost, "softDeletePost");

// src/services/comments.ts
function mapComment(row, viewer) {
  const authorName = row.display_name || row.guest_name || "\u8BBF\u5BA2";
  return {
    id: row.id,
    postId: row.post_id,
    parentId: row.parent_id,
    authorName,
    authorUrl: row.username ? `/u/${row.username}` : row.guest_url,
    avatarKey: row.avatar_key,
    replyToName: row.parent_user_display_name || row.parent_guest_name || null,
    content: row.content,
    contentHtml: escapeHtml(row.content).replace(/\n/g, "<br>"),
    status: row.status,
    createdAt: row.created_at,
    canDelete: Boolean(viewer && (viewer.role === "admin" || viewer.id === row.user_id || viewer.id === row.post_author_id))
  };
}
__name(mapComment, "mapComment");
async function listComments(env2, postId, viewer) {
  const rows = await all(
    env2.DB.prepare(
      `SELECT c.*, u.username, u.display_name, u.avatar_key,
        pu.display_name AS parent_user_display_name, pc.guest_name AS parent_guest_name,
        p.author_id AS post_author_id
       FROM wm_comments c
       JOIN wm_posts p ON p.id = c.post_id
       LEFT JOIN wm_users u ON u.id = c.user_id
       LEFT JOIN wm_comments pc ON pc.id = c.parent_id
       LEFT JOIN wm_users pu ON pu.id = pc.user_id
       WHERE c.post_id = ? AND c.status = 'approved'
       ORDER BY c.created_at ASC`
    ).bind(postId)
  );
  return rows.map((row) => mapComment(row, viewer));
}
__name(listComments, "listComments");
async function createComment(env2, input2) {
  const post = await first(
    env2.DB.prepare(`SELECT id FROM wm_posts WHERE id = ? AND status = 'published'`).bind(input2.postId)
  );
  if (!post)
    throw new Error("\u5185\u5BB9\u4E0D\u5B58\u5728");
  if (input2.parentId) {
    const parent = await first(
      env2.DB.prepare('SELECT id FROM wm_comments WHERE id = ? AND post_id = ? AND status = "approved"').bind(input2.parentId, input2.postId)
    );
    if (!parent)
      throw new Error("\u56DE\u590D\u76EE\u6807\u4E0D\u5B58\u5728");
  }
  const id = ulid();
  await env2.DB.prepare(
    `INSERT INTO wm_comments(
      id, post_id, parent_id, user_id, guest_name, guest_email, guest_url, content, status, ip, user_agent, created_at
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
  ).bind(
    id,
    input2.postId,
    input2.parentId || null,
    input2.user?.id || null,
    input2.user ? null : input2.guestName || "\u8BBF\u5BA2",
    input2.user ? null : input2.guestEmail || null,
    input2.user ? null : input2.guestUrl || null,
    input2.content,
    input2.status,
    input2.ip || null,
    input2.userAgent || null,
    nowSeconds()
  ).run();
  return id;
}
__name(createComment, "createComment");
async function deleteComment(env2, id, actor) {
  const row = await first(
    env2.DB.prepare(
      `SELECT c.user_id, p.author_id AS post_author_id
       FROM wm_comments c JOIN wm_posts p ON p.id = c.post_id
       WHERE c.id = ?`
    ).bind(id)
  );
  if (!row)
    throw new Error("\u8BC4\u8BBA\u4E0D\u5B58\u5728");
  if (actor.role !== "admin" && actor.id !== row.user_id && actor.id !== row.post_author_id)
    throw new Error("\u65E0\u6743\u5220\u9664\u8BC4\u8BBA");
  const ids = await all(
    env2.DB.prepare(
      `WITH RECURSIVE tree(id) AS (
        SELECT id FROM wm_comments WHERE id = ?
        UNION ALL
        SELECT c.id FROM wm_comments c JOIN tree t ON c.parent_id = t.id
       )
       SELECT id FROM tree`
    ).bind(id)
  );
  await env2.DB.prepare("DELETE FROM wm_comments WHERE id = ?").bind(id).run();
  return ids.map((item) => item.id);
}
__name(deleteComment, "deleteComment");

// src/services/links.ts
async function listPublicLinks(env2, settings) {
  const rows = await all(
    env2.DB.prepare(`SELECT id, name, url, avatar, description, category FROM wm_links WHERE visible = 1 ORDER BY category ASC, sort_order ASC, created_at DESC`)
  );
  return rows.map((row) => ({
    id: row.id,
    name: row.name,
    url: row.url,
    avatar: row.avatar ? mediaUrl(settings.cdn_base_url, row.avatar, row.avatar) : null,
    description: row.description || "",
    category: row.category || "default"
  }));
}
__name(listPublicLinks, "listPublicLinks");
async function listAdminLinks(env2) {
  const rows = await all(
    env2.DB.prepare(`SELECT id, name, url, avatar, description, category, visible, sort_order FROM wm_links ORDER BY category ASC, sort_order ASC, created_at DESC`)
  );
  return rows.map((row) => ({
    id: row.id,
    name: row.name,
    url: row.url,
    avatar: row.avatar,
    description: row.description || "",
    category: row.category || "default",
    visible: row.visible,
    sort_order: row.sort_order
  }));
}
__name(listAdminLinks, "listAdminLinks");
async function createLink(env2, input2) {
  const id = ulid();
  await env2.DB.prepare(
    `INSERT INTO wm_links(id, name, url, avatar, description, category, visible, sort_order, created_at)
     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`
  ).bind(id, input2.name, input2.url, input2.avatar || null, input2.description || "", input2.category || "default", input2.visible === false ? 0 : 1, input2.sortOrder || 0, nowSeconds()).run();
  return id;
}
__name(createLink, "createLink");
async function updateLink(env2, id, input2) {
  await env2.DB.prepare(
    `UPDATE wm_links SET
      name = COALESCE(?, name),
      url = COALESCE(?, url),
      avatar = COALESCE(?, avatar),
      description = COALESCE(?, description),
      category = COALESCE(?, category),
      visible = COALESCE(?, visible),
      sort_order = COALESCE(?, sort_order)
     WHERE id = ?`
  ).bind(
    input2.name ?? null,
    input2.url ?? null,
    input2.avatar ?? null,
    input2.description ?? null,
    input2.category ?? null,
    input2.visible === void 0 ? null : input2.visible ? 1 : 0,
    input2.sortOrder ?? null,
    id
  ).run();
}
__name(updateLink, "updateLink");
async function deleteLink(env2, id) {
  await env2.DB.prepare("DELETE FROM wm_links WHERE id = ?").bind(id).run();
}
__name(deleteLink, "deleteLink");

// node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/jsx/constants.js
var DOM_RENDERER = /* @__PURE__ */ Symbol("RENDERER");
var DOM_ERROR_HANDLER = /* @__PURE__ */ Symbol("ERROR_HANDLER");
var DOM_INTERNAL_TAG = /* @__PURE__ */ Symbol("INTERNAL");
var PERMALINK = /* @__PURE__ */ Symbol("PERMALINK");

// node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/jsx/dom/utils.js
var setInternalTagFlag = /* @__PURE__ */ __name((fn) => {
  ;
  fn[DOM_INTERNAL_TAG] = true;
  return fn;
}, "setInternalTagFlag");

// node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/jsx/dom/context.js
var createContextProviderFunction = /* @__PURE__ */ __name((values) => ({ value, children }) => {
  if (!children) {
    return void 0;
  }
  const props = {
    children: [
      {
        tag: setInternalTagFlag(() => {
          values.push(value);
        }),
        props: {}
      }
    ]
  };
  if (Array.isArray(children)) {
    props.children.push(...children.flat());
  } else {
    props.children.push(children);
  }
  props.children.push({
    tag: setInternalTagFlag(() => {
      values.pop();
    }),
    props: {}
  });
  const res = { tag: "", props, type: "" };
  res[DOM_ERROR_HANDLER] = (err) => {
    values.pop();
    throw err;
  };
  return res;
}, "createContextProviderFunction");

// node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/jsx/context.js
var globalContexts = [];
var createContext = /* @__PURE__ */ __name((defaultValue) => {
  const values = [defaultValue];
  const context2 = /* @__PURE__ */ __name((props) => {
    values.push(props.value);
    let string;
    try {
      string = props.children ? (Array.isArray(props.children) ? new JSXFragmentNode("", {}, props.children) : props.children).toString() : "";
    } catch (e) {
      values.pop();
      throw e;
    }
    if (string instanceof Promise) {
      return string.finally(() => values.pop()).then((resString) => raw(resString, resString.callbacks));
    } else {
      values.pop();
      return raw(string);
    }
  }, "context");
  context2.values = values;
  context2.Provider = context2;
  context2[DOM_RENDERER] = createContextProviderFunction(values);
  globalContexts.push(context2);
  return context2;
}, "createContext");
var useContext = /* @__PURE__ */ __name((context2) => {
  return context2.values.at(-1);
}, "useContext");

// node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/jsx/intrinsic-element/common.js
var deDupeKeyMap = {
  title: [],
  script: ["src"],
  style: ["data-href"],
  link: ["href"],
  meta: ["name", "httpEquiv", "charset", "itemProp"]
};
var domRenderers = {};
var dataPrecedenceAttr = "data-precedence";
var isStylesheetLinkWithPrecedence = /* @__PURE__ */ __name((props) => props.rel === "stylesheet" && "precedence" in props, "isStylesheetLinkWithPrecedence");
var shouldDeDupeByKey = /* @__PURE__ */ __name((tagName, supportSort) => {
  if (tagName === "link") {
    return supportSort;
  }
  return deDupeKeyMap[tagName].length > 0;
}, "shouldDeDupeByKey");

// node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/jsx/intrinsic-element/components.js
var components_exports = {};
__export(components_exports, {
  button: () => button,
  form: () => form,
  input: () => input,
  link: () => link,
  meta: () => meta,
  script: () => script,
  style: () => style,
  title: () => title2
});

// node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/jsx/children.js
var toArray = /* @__PURE__ */ __name((children) => Array.isArray(children) ? children : [children], "toArray");

// node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/jsx/intrinsic-element/components.js
var metaTagMap = /* @__PURE__ */ new WeakMap();
var insertIntoHead = /* @__PURE__ */ __name((tagName, tag, props, precedence) => ({ buffer, context: context2 }) => {
  if (!buffer) {
    return;
  }
  const map = metaTagMap.get(context2) || {};
  metaTagMap.set(context2, map);
  const tags = map[tagName] ||= [];
  let duped = false;
  const deDupeKeys = deDupeKeyMap[tagName];
  const deDupeByKey = shouldDeDupeByKey(tagName, precedence !== void 0);
  if (deDupeByKey) {
    LOOP:
      for (const [, tagProps] of tags) {
        if (tagName === "link" && !(tagProps.rel === "stylesheet" && tagProps[dataPrecedenceAttr] !== void 0)) {
          continue;
        }
        for (const key of deDupeKeys) {
          if ((tagProps?.[key] ?? null) === props?.[key]) {
            duped = true;
            break LOOP;
          }
        }
      }
  }
  if (duped) {
    buffer[0] = buffer[0].replaceAll(tag, "");
  } else if (deDupeByKey || tagName === "link") {
    tags.push([tag, props, precedence]);
  } else {
    tags.unshift([tag, props, precedence]);
  }
  if (buffer[0].indexOf("</head>") !== -1) {
    let insertTags;
    if (tagName === "link" || precedence !== void 0) {
      const precedences = [];
      insertTags = tags.map(([tag2, , tagPrecedence], index) => {
        if (tagPrecedence === void 0) {
          return [tag2, Number.MAX_SAFE_INTEGER, index];
        }
        let order = precedences.indexOf(tagPrecedence);
        if (order === -1) {
          precedences.push(tagPrecedence);
          order = precedences.length - 1;
        }
        return [tag2, order, index];
      }).sort((a, b) => a[1] - b[1] || a[2] - b[2]).map(([tag2]) => tag2);
    } else {
      insertTags = tags.map(([tag2]) => tag2);
    }
    insertTags.forEach((tag2) => {
      buffer[0] = buffer[0].replaceAll(tag2, "");
    });
    buffer[0] = buffer[0].replace(/(?=<\/head>)/, insertTags.join(""));
  }
}, "insertIntoHead");
var returnWithoutSpecialBehavior = /* @__PURE__ */ __name((tag, children, props) => raw(new JSXNode(tag, props, toArray(children ?? [])).toString()), "returnWithoutSpecialBehavior");
var documentMetadataTag = /* @__PURE__ */ __name((tag, children, props, sort) => {
  if ("itemProp" in props) {
    return returnWithoutSpecialBehavior(tag, children, props);
  }
  let { precedence, blocking, ...restProps } = props;
  precedence = sort ? precedence ?? "" : void 0;
  if (sort) {
    restProps[dataPrecedenceAttr] = precedence;
  }
  const string = new JSXNode(tag, restProps, toArray(children || [])).toString();
  if (string instanceof Promise) {
    return string.then(
      (resString) => raw(string, [
        ...resString.callbacks || [],
        insertIntoHead(tag, resString, restProps, precedence)
      ])
    );
  } else {
    return raw(string, [insertIntoHead(tag, string, restProps, precedence)]);
  }
}, "documentMetadataTag");
var title2 = /* @__PURE__ */ __name(({ children, ...props }) => {
  const nameSpaceContext2 = getNameSpaceContext();
  if (nameSpaceContext2) {
    const context2 = useContext(nameSpaceContext2);
    if (context2 === "svg" || context2 === "head") {
      return new JSXNode(
        "title",
        props,
        toArray(children ?? [])
      );
    }
  }
  return documentMetadataTag("title", children, props, false);
}, "title");
var script = /* @__PURE__ */ __name(({
  children,
  ...props
}) => {
  const nameSpaceContext2 = getNameSpaceContext();
  if (["src", "async"].some((k) => !props[k]) || nameSpaceContext2 && useContext(nameSpaceContext2) === "head") {
    return returnWithoutSpecialBehavior("script", children, props);
  }
  return documentMetadataTag("script", children, props, false);
}, "script");
var style = /* @__PURE__ */ __name(({
  children,
  ...props
}) => {
  if (!["href", "precedence"].every((k) => k in props)) {
    return returnWithoutSpecialBehavior("style", children, props);
  }
  props["data-href"] = props.href;
  delete props.href;
  return documentMetadataTag("style", children, props, true);
}, "style");
var link = /* @__PURE__ */ __name(({ children, ...props }) => {
  if (["onLoad", "onError"].some((k) => k in props) || props.rel === "stylesheet" && (!("precedence" in props) || "disabled" in props)) {
    return returnWithoutSpecialBehavior("link", children, props);
  }
  return documentMetadataTag("link", children, props, isStylesheetLinkWithPrecedence(props));
}, "link");
var meta = /* @__PURE__ */ __name(({ children, ...props }) => {
  const nameSpaceContext2 = getNameSpaceContext();
  if (nameSpaceContext2 && useContext(nameSpaceContext2) === "head") {
    return returnWithoutSpecialBehavior("meta", children, props);
  }
  return documentMetadataTag("meta", children, props, false);
}, "meta");
var newJSXNode = /* @__PURE__ */ __name((tag, { children, ...props }) => (
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  new JSXNode(tag, props, toArray(children ?? []))
), "newJSXNode");
var form = /* @__PURE__ */ __name((props) => {
  if (typeof props.action === "function") {
    props.action = PERMALINK in props.action ? props.action[PERMALINK] : void 0;
  }
  return newJSXNode("form", props);
}, "form");
var formActionableElement = /* @__PURE__ */ __name((tag, props) => {
  if (typeof props.formAction === "function") {
    props.formAction = PERMALINK in props.formAction ? props.formAction[PERMALINK] : void 0;
  }
  return newJSXNode(tag, props);
}, "formActionableElement");
var input = /* @__PURE__ */ __name((props) => formActionableElement("input", props), "input");
var button = /* @__PURE__ */ __name((props) => formActionableElement("button", props), "button");

// node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/jsx/utils.js
var normalizeElementKeyMap = /* @__PURE__ */ new Map([
  ["className", "class"],
  ["htmlFor", "for"],
  ["crossOrigin", "crossorigin"],
  ["httpEquiv", "http-equiv"],
  ["itemProp", "itemprop"],
  ["fetchPriority", "fetchpriority"],
  ["noModule", "nomodule"],
  ["formAction", "formaction"]
]);
var normalizeIntrinsicElementKey = /* @__PURE__ */ __name((key) => normalizeElementKeyMap.get(key) || key, "normalizeIntrinsicElementKey");
var invalidAttributeNameCharRe = /[\s"'<>/=`\\\x00-\x1f\x7f-\x9f]/;
var validAttributeNameCache = /* @__PURE__ */ new Set();
var validAttributeNameCacheMax = 1024;
var invalidTagNameCharRe = /^[!?]|[\s"'<>/=`\\\x00-\x1f\x7f-\x9f]/;
var validTagNameCache = /* @__PURE__ */ new Set();
var validTagNameCacheMax = 256;
var cacheValidName = /* @__PURE__ */ __name((cache, max, name) => {
  if (cache.size >= max) {
    cache.clear();
  }
  cache.add(name);
}, "cacheValidName");
var isValidTagName = /* @__PURE__ */ __name((name) => {
  if (validTagNameCache.has(name)) {
    return true;
  }
  if (typeof name !== "string") {
    return false;
  }
  if (name.length === 0) {
    return true;
  }
  if (invalidTagNameCharRe.test(name)) {
    return false;
  }
  cacheValidName(validTagNameCache, validTagNameCacheMax, name);
  return true;
}, "isValidTagName");
var isValidAttributeName = /* @__PURE__ */ __name((name) => {
  if (validAttributeNameCache.has(name)) {
    return true;
  }
  const len = name.length;
  if (len === 0) {
    return false;
  }
  for (let i = 0; i < len; i++) {
    const c = name.charCodeAt(i);
    if (!(c >= 97 && c <= 122 || // a-z
    c >= 65 && c <= 90 || // A-Z
    c >= 48 && c <= 57 || // 0-9
    c === 45 || // -
    c === 95 || // _
    c === 46 || // .
    c === 58)) {
      if (!invalidAttributeNameCharRe.test(name)) {
        cacheValidName(validAttributeNameCache, validAttributeNameCacheMax, name);
        return true;
      } else {
        return false;
      }
    }
  }
  cacheValidName(validAttributeNameCache, validAttributeNameCacheMax, name);
  return true;
}, "isValidAttributeName");
var invalidStylePropertyNameCharRe = /[\s"'():;\\/\[\]{}\x00-\x1f\x7f-\x9f]/;
var validStylePropertyNameCache = /* @__PURE__ */ new Set();
var validStylePropertyNameCacheMax = 1024;
var isValidStylePropertyName = /* @__PURE__ */ __name((name) => {
  if (validStylePropertyNameCache.has(name)) {
    return true;
  }
  const len = name.length;
  if (len === 0) {
    return false;
  }
  for (let i = 0; i < len; i++) {
    const c = name.charCodeAt(i);
    if (!(c >= 97 && c <= 122 || // a-z
    c >= 65 && c <= 90 || // A-Z
    c >= 48 && c <= 57 || // 0-9
    c === 45 || // -
    c === 95)) {
      if (!invalidStylePropertyNameCharRe.test(name)) {
        cacheValidName(validStylePropertyNameCache, validStylePropertyNameCacheMax, name);
        return true;
      } else {
        return false;
      }
    }
  }
  cacheValidName(validStylePropertyNameCache, validStylePropertyNameCacheMax, name);
  return true;
}, "isValidStylePropertyName");
var unsafeStyleValueCharRe = /[;"'\\/\[\](){}]/;
var hasUnsafeStyleValue = /* @__PURE__ */ __name((value) => {
  if (!unsafeStyleValueCharRe.test(value)) {
    return false;
  }
  let quote = 0;
  const blockStack = [];
  for (let i = 0, len = value.length; i < len; i++) {
    const c = value.charCodeAt(i);
    if (c === 92) {
      if (i === len - 1) {
        return true;
      }
      i++;
    } else if (quote !== 0) {
      if (c === 10 || c === 12 || c === 13) {
        return true;
      }
      if (c === quote) {
        quote = 0;
      }
    } else if (c === 47 && value.charCodeAt(i + 1) === 42) {
      const end = value.indexOf("*/", i + 2);
      if (end === -1) {
        return true;
      }
      i = end + 1;
    } else if (c === 34 || c === 39) {
      quote = c;
    } else if (c === 40) {
      blockStack.push(41);
    } else if (c === 91) {
      blockStack.push(93);
    } else if (c === 123 || c === 125) {
      return true;
    } else if (c === 41 || c === 93) {
      if (blockStack[blockStack.length - 1] !== c) {
        return true;
      }
      blockStack.pop();
    } else if (c === 59 && blockStack.length === 0) {
      return true;
    }
  }
  return quote !== 0 || blockStack.length !== 0;
}, "hasUnsafeStyleValue");
var styleObjectForEach = /* @__PURE__ */ __name((style2, fn) => {
  for (const [k, v] of Object.entries(style2)) {
    const key = k[0] === "-" || !/[A-Z]/.test(k) ? k : k.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`);
    if (!isValidStylePropertyName(key)) {
      continue;
    }
    if (v == null) {
      fn(key, null);
      continue;
    }
    let value;
    if (typeof v === "number") {
      value = !key.match(
        /^(?:a|border-im|column(?:-c|s)|flex(?:$|-[^b])|grid-(?:ar|[^a])|font-w|li|or|sca|st|ta|wido|z)|ty$/
      ) ? `${v}px` : `${v}`;
    } else if (typeof v === "string") {
      if (hasUnsafeStyleValue(v)) {
        continue;
      }
      value = v;
    } else {
      continue;
    }
    fn(key, value);
  }
}, "styleObjectForEach");

// node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/jsx/base.js
var nameSpaceContext = void 0;
var getNameSpaceContext = /* @__PURE__ */ __name(() => nameSpaceContext, "getNameSpaceContext");
var toSVGAttributeName = /* @__PURE__ */ __name((key) => /[A-Z]/.test(key) && // Presentation attributes are findable in style object. "clip-path", "font-size", "stroke-width", etc.
// Or other un-deprecated kebab-case attributes. "overline-position", "paint-order", "strikethrough-position", etc.
key.match(
  /^(?:al|basel|clip(?:Path|Rule)$|co|do|fill|fl|fo|gl|let|lig|i|marker[EMS]|o|pai|pointe|sh|st[or]|text[^L]|tr|u|ve|w)/
) ? key.replace(/([A-Z])/g, "-$1").toLowerCase() : key, "toSVGAttributeName");
var emptyTags = [
  "area",
  "base",
  "br",
  "col",
  "embed",
  "hr",
  "img",
  "input",
  "keygen",
  "link",
  "meta",
  "param",
  "source",
  "track",
  "wbr"
];
var booleanAttributes = [
  "allowfullscreen",
  "async",
  "autofocus",
  "autoplay",
  "checked",
  "controls",
  "default",
  "defer",
  "disabled",
  "download",
  "formnovalidate",
  "hidden",
  "inert",
  "ismap",
  "itemscope",
  "loop",
  "multiple",
  "muted",
  "nomodule",
  "novalidate",
  "open",
  "playsinline",
  "readonly",
  "required",
  "reversed",
  "selected"
];
var childrenToStringToBuffer = /* @__PURE__ */ __name((children, buffer) => {
  for (let i = 0, len = children.length; i < len; i++) {
    const child = children[i];
    if (typeof child === "string") {
      escapeToBuffer(child, buffer);
    } else if (typeof child === "boolean" || child === null || child === void 0) {
      continue;
    } else if (child instanceof JSXNode) {
      child.toStringToBuffer(buffer);
    } else if (typeof child === "number" || child.isEscaped) {
      ;
      buffer[0] += child;
    } else if (child instanceof Promise) {
      buffer.unshift("", child);
    } else {
      childrenToStringToBuffer(child, buffer);
    }
  }
}, "childrenToStringToBuffer");
var JSXNode = /* @__PURE__ */ __name(class {
  tag;
  props;
  key;
  children;
  isEscaped = true;
  localContexts;
  constructor(tag, props, children) {
    if (typeof tag !== "function" && !isValidTagName(tag)) {
      throw new Error(`Invalid JSX tag name: ${tag}`);
    }
    this.tag = tag;
    this.props = props;
    this.children = children;
  }
  get type() {
    return this.tag;
  }
  // Added for compatibility with libraries that rely on React's internal structure
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  get ref() {
    return this.props.ref || null;
  }
  toString() {
    const buffer = [""];
    this.localContexts?.forEach(([context2, value]) => {
      context2.values.push(value);
    });
    try {
      this.toStringToBuffer(buffer);
    } finally {
      this.localContexts?.forEach(([context2]) => {
        context2.values.pop();
      });
    }
    return buffer.length === 1 ? "callbacks" in buffer ? resolveCallbackSync(raw(buffer[0], buffer.callbacks)).toString() : buffer[0] : stringBufferToString(buffer, buffer.callbacks);
  }
  toStringToBuffer(buffer) {
    const tag = this.tag;
    const props = this.props;
    let { children } = this;
    buffer[0] += `<${tag}`;
    const normalizeKey = tag === "svg" || nameSpaceContext && useContext(nameSpaceContext) === "svg" ? (key) => toSVGAttributeName(normalizeIntrinsicElementKey(key)) : (key) => normalizeIntrinsicElementKey(key);
    for (let [key, v] of Object.entries(props)) {
      key = normalizeKey(key);
      if (!isValidAttributeName(key)) {
        continue;
      }
      if (key === "children") {
      } else if (key === "style" && typeof v === "object") {
        let styleStr = "";
        styleObjectForEach(v, (property, value) => {
          if (value != null) {
            styleStr += `${styleStr ? ";" : ""}${property}:${value}`;
          }
        });
        buffer[0] += ' style="';
        escapeToBuffer(styleStr, buffer);
        buffer[0] += '"';
      } else if (typeof v === "string") {
        buffer[0] += ` ${key}="`;
        escapeToBuffer(v, buffer);
        buffer[0] += '"';
      } else if (v === null || v === void 0) {
      } else if (typeof v === "number" || v.isEscaped) {
        buffer[0] += ` ${key}="${v}"`;
      } else if (typeof v === "boolean" && booleanAttributes.includes(key)) {
        if (v) {
          buffer[0] += ` ${key}=""`;
        }
      } else if (key === "dangerouslySetInnerHTML") {
        if (children.length > 0) {
          throw new Error("Can only set one of `children` or `props.dangerouslySetInnerHTML`.");
        }
        children = [raw(v.__html)];
      } else if (v instanceof Promise) {
        buffer[0] += ` ${key}="`;
        buffer.unshift('"', v);
      } else if (typeof v === "function") {
        if (!key.startsWith("on") && key !== "ref") {
          throw new Error(`Invalid prop '${key}' of type 'function' supplied to '${tag}'.`);
        }
      } else {
        buffer[0] += ` ${key}="`;
        escapeToBuffer(v.toString(), buffer);
        buffer[0] += '"';
      }
    }
    if (emptyTags.includes(tag) && children.length === 0) {
      buffer[0] += "/>";
      return;
    }
    buffer[0] += ">";
    childrenToStringToBuffer(children, buffer);
    buffer[0] += `</${tag}>`;
  }
}, "JSXNode");
var JSXFunctionNode = /* @__PURE__ */ __name(class extends JSXNode {
  toStringToBuffer(buffer) {
    const { children } = this;
    const props = { ...this.props };
    if (children.length) {
      props.children = children.length === 1 ? children[0] : children;
    }
    const res = this.tag.call(null, props);
    if (typeof res === "boolean" || res == null) {
      return;
    } else if (res instanceof Promise) {
      if (globalContexts.length === 0) {
        buffer.unshift("", res);
      } else {
        const currentContexts = globalContexts.map((c) => [c, c.values.at(-1)]);
        buffer.unshift(
          "",
          res.then((childRes) => {
            if (childRes instanceof JSXNode) {
              childRes.localContexts = currentContexts;
            }
            return childRes;
          })
        );
      }
    } else if (res instanceof JSXNode) {
      res.toStringToBuffer(buffer);
    } else if (typeof res === "number" || res.isEscaped) {
      buffer[0] += res;
      if (res.callbacks) {
        buffer.callbacks ||= [];
        buffer.callbacks.push(...res.callbacks);
      }
    } else {
      escapeToBuffer(res, buffer);
    }
  }
}, "JSXFunctionNode");
var JSXFragmentNode = /* @__PURE__ */ __name(class extends JSXNode {
  toStringToBuffer(buffer) {
    childrenToStringToBuffer(this.children, buffer);
  }
}, "JSXFragmentNode");
var initDomRenderer = false;
var jsxFn = /* @__PURE__ */ __name((tag, props, children) => {
  if (!initDomRenderer) {
    for (const k in domRenderers) {
      ;
      components_exports[k][DOM_RENDERER] = domRenderers[k];
    }
    initDomRenderer = true;
  }
  if (typeof tag === "function") {
    return new JSXFunctionNode(tag, props, children);
  } else if (components_exports[tag]) {
    return new JSXFunctionNode(
      components_exports[tag],
      props,
      children
    );
  } else if (tag === "svg" || tag === "head") {
    nameSpaceContext ||= createContext("");
    return new JSXNode(tag, props, [
      new JSXFunctionNode(
        nameSpaceContext,
        {
          value: tag
        },
        children
      )
    ]);
  } else {
    return new JSXNode(tag, props, children);
  }
}, "jsxFn");
var Fragment = /* @__PURE__ */ __name(({
  children
}) => {
  return new JSXFragmentNode(
    "",
    {
      children
    },
    Array.isArray(children) ? children : children ? [children] : []
  );
}, "Fragment");

// node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/jsx/jsx-dev-runtime.js
function jsxDEV(tag, props, key) {
  let node;
  if (!props || !("children" in props)) {
    node = jsxFn(tag, props, []);
  } else {
    const children = props.children;
    node = Array.isArray(children) ? jsxFn(tag, props, children) : jsxFn(tag, props, [children]);
  }
  node.key = key;
  return node;
}
__name(jsxDEV, "jsxDEV");

// src/views/components/icons.tsx
function svg(path, props = {}) {
  return /* @__PURE__ */ jsxDEV("svg", { class: props.class || "wm-icon", viewBox: "0 0 24 24", "aria-hidden": props.title ? void 0 : "true", role: props.title ? "img" : void 0, children: [
    props.title ? /* @__PURE__ */ jsxDEV("title", { children: props.title }) : null,
    path
  ] });
}
__name(svg, "svg");
var Icons = {
  user: (props) => svg(
    /* @__PURE__ */ jsxDEV(Fragment, { children: [
      /* @__PURE__ */ jsxDEV("path", { d: "M12 12.2a4.6 4.6 0 1 0 0-9.2 4.6 4.6 0 0 0 0 9.2Z" }),
      /* @__PURE__ */ jsxDEV("path", { d: "M4.2 21c.8-4 3.5-6.2 7.8-6.2s7 2.2 7.8 6.2" })
    ] }),
    props
  ),
  links: (props) => svg(
    /* @__PURE__ */ jsxDEV(Fragment, { children: [
      /* @__PURE__ */ jsxDEV("path", { d: "M8.6 12.6a3.8 3.8 0 1 0 0-7.6 3.8 3.8 0 0 0 0 7.6Z" }),
      /* @__PURE__ */ jsxDEV("path", { d: "M3 20.5c.7-3.4 2.6-5.1 5.6-5.1 1.1 0 2 .2 2.8.7" }),
      /* @__PURE__ */ jsxDEV("path", { d: "M16.2 13.2a3.1 3.1 0 1 0 0-6.2 3.1 3.1 0 0 0 0 6.2Z" }),
      /* @__PURE__ */ jsxDEV("path", { d: "M13.4 20.5c.6-2.8 2.2-4.2 4.6-4.2 1.6 0 2.9.6 3.8 1.8" })
    ] }),
    props
  ),
  settings: (props) => svg(
    /* @__PURE__ */ jsxDEV(Fragment, { children: [
      /* @__PURE__ */ jsxDEV("path", { d: "M12 15.6a3.6 3.6 0 1 0 0-7.2 3.6 3.6 0 0 0 0 7.2Z" }),
      /* @__PURE__ */ jsxDEV("path", { d: "m19.4 13.5 1.1.9-1.8 3.1-1.4-.5a7.9 7.9 0 0 1-1.9 1.1l-.2 1.5H8.8l-.2-1.5A7.9 7.9 0 0 1 6.7 17l-1.4.5-1.8-3.1 1.1-.9a7.5 7.5 0 0 1 0-2.2l-1.1-.9 1.8-3.1 1.4.5a7.9 7.9 0 0 1 1.9-1.1l.2-1.5h6.4l.2 1.5a7.9 7.9 0 0 1 1.9 1.1l1.4-.5 1.8 3.1-1.1.9a7.5 7.5 0 0 1 0 2.2Z" })
    ] }),
    props
  ),
  camera: (props) => svg(
    /* @__PURE__ */ jsxDEV(Fragment, { children: [
      /* @__PURE__ */ jsxDEV("path", { d: "M4 7.8h3.1l1.3-2h7.2l1.3 2H20a2 2 0 0 1 2 2v8.4a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9.8a2 2 0 0 1 2-2Z" }),
      /* @__PURE__ */ jsxDEV("path", { d: "M12 17a4 4 0 1 0 0-8 4 4 0 0 0 0 8Z" })
    ] }),
    props
  ),
  more: (props) => svg(
    /* @__PURE__ */ jsxDEV(Fragment, { children: [
      /* @__PURE__ */ jsxDEV("circle", { cx: "6", cy: "12", r: "1.7" }),
      /* @__PURE__ */ jsxDEV("circle", { cx: "12", cy: "12", r: "1.7" }),
      /* @__PURE__ */ jsxDEV("circle", { cx: "18", cy: "12", r: "1.7" })
    ] }),
    props
  ),
  heart: (props) => svg(
    /* @__PURE__ */ jsxDEV("path", { d: "M12 20.3s-7.5-4.8-9.2-10A4.8 4.8 0 0 1 11 5.7l1 1 1-1a4.8 4.8 0 0 1 8.2 4.6c-1.7 5.2-9.2 10-9.2 10Z" }),
    props
  ),
  message: (props) => svg(/* @__PURE__ */ jsxDEV("path", { d: "M4.5 5.5h15v10.7h-8.2l-4.8 3v-3H4.5V5.5Z" }), props),
  close: (props) => svg(
    /* @__PURE__ */ jsxDEV(Fragment, { children: [
      /* @__PURE__ */ jsxDEV("path", { d: "M6 6l12 12" }),
      /* @__PURE__ */ jsxDEV("path", { d: "M18 6 6 18" })
    ] }),
    props
  ),
  plus: (props) => svg(
    /* @__PURE__ */ jsxDEV(Fragment, { children: [
      /* @__PURE__ */ jsxDEV("path", { d: "M12 5v14" }),
      /* @__PURE__ */ jsxDEV("path", { d: "M5 12h14" })
    ] }),
    props
  ),
  location: (props) => svg(
    /* @__PURE__ */ jsxDEV(Fragment, { children: [
      /* @__PURE__ */ jsxDEV("path", { d: "M12 21s7-6 7-12a7 7 0 1 0-14 0c0 6 7 12 7 12Z" }),
      /* @__PURE__ */ jsxDEV("circle", { cx: "12", cy: "9", r: "2.3" })
    ] }),
    props
  )
};

// src/views/components/post-item.tsx
function PostItem(props) {
  const { post, settings } = props;
  const comments = props.comments || [];
  const avatar = mediaUrl(settings.cdn_base_url, post.author.avatarKey);
  const imageCount = post.images.length;
  const gridClass = imageCount === 1 ? "single" : imageCount === 4 ? "four" : "grid";
  return /* @__PURE__ */ jsxDEV("article", { class: "post-item", id: `post-${post.id}`, "data-post-id": post.id, "data-liked": post.viewerLiked ? "1" : "0", children: [
    /* @__PURE__ */ jsxDEV("a", { class: "post-avatar", href: `/u/${post.author.username}`, children: /* @__PURE__ */ jsxDEV("img", { src: avatar, alt: `${post.author.displayName} \u7684\u5934\u50CF`, loading: "lazy" }) }),
    /* @__PURE__ */ jsxDEV("div", { class: "post-body", children: [
      /* @__PURE__ */ jsxDEV("div", { class: "post-head", children: [
        /* @__PURE__ */ jsxDEV("a", { class: "post-author", href: `/u/${post.author.username}`, children: post.author.displayName }),
        /* @__PURE__ */ jsxDEV("div", { class: "post-badges", children: [
          post.isTop ? /* @__PURE__ */ jsxDEV("span", { children: "\u7F6E\u9876" }) : null,
          post.isAd ? /* @__PURE__ */ jsxDEV("span", { children: "\u5E7F\u544A" }) : null,
          post.visibility === "private" ? /* @__PURE__ */ jsxDEV("span", { children: "\u79C1\u5BC6" }) : null
        ] })
      ] }),
      post.title ? /* @__PURE__ */ jsxDEV("h2", { class: "post-title", children: /* @__PURE__ */ jsxDEV("a", { href: `/p/${post.id}`, children: post.title }) }) : null,
      post.contentHtml ? /* @__PURE__ */ jsxDEV("div", { class: "post-content", dangerouslySetInnerHTML: { __html: post.contentHtml } }) : null,
      post.shareUrl ? /* @__PURE__ */ jsxDEV("a", { class: "share-card", href: post.shareUrl, target: "_blank", rel: "noopener noreferrer", children: [
        post.shareThumb ? /* @__PURE__ */ jsxDEV("img", { src: post.shareThumb, alt: "", loading: "lazy" }) : null,
        /* @__PURE__ */ jsxDEV("span", { children: post.title || post.shareUrl })
      ] }) : null,
      post.videoUrl ? /* @__PURE__ */ jsxDEV("video", { class: "post-video", src: post.videoUrl, controls: true, preload: "metadata", playsinline: true }) : null,
      imageCount > 0 ? /* @__PURE__ */ jsxDEV("div", { class: `post-images ${gridClass}`, "data-count": imageCount, children: post.images.slice(0, 9).map((image, index) => /* @__PURE__ */ jsxDEV("a", { class: "post-image", href: image.url, "data-fancybox": `gallery-${post.id}`, "data-caption": `${post.author.displayName} \u7684\u56FE\u7247 ${index + 1}`, children: [
        /* @__PURE__ */ jsxDEV("img", { src: image.url, alt: "", loading: "lazy" }),
        index === 8 && imageCount > 9 ? /* @__PURE__ */ jsxDEV("span", { class: "post-image-more", children: [
          "+",
          imageCount - 9
        ] }) : null
      ] })) }) : null,
      post.position ? /* @__PURE__ */ jsxDEV("div", { class: "post-location", children: [
        Icons.location({ class: "wm-icon tiny" }),
        /* @__PURE__ */ jsxDEV("span", { children: post.position })
      ] }) : null,
      /* @__PURE__ */ jsxDEV("div", { class: "post-meta", children: [
        /* @__PURE__ */ jsxDEV("a", { class: "post-time", href: `/p/${post.id}`, children: formatMomentTime(post.createdAt) }),
        /* @__PURE__ */ jsxDEV("button", { class: "post-more-button", type: "button", "data-action": "toggle-actions", "aria-label": "\u5C55\u5F00\u64CD\u4F5C", children: Icons.more({ class: "wm-icon" }) }),
        /* @__PURE__ */ jsxDEV("div", { class: "post-time-comment-modal", hidden: true, children: [
          /* @__PURE__ */ jsxDEV("button", { type: "button", "data-action": "like-post", children: [
            Icons.heart({ class: "wm-icon tiny" }),
            /* @__PURE__ */ jsxDEV("span", { children: post.viewerLiked ? "\u5DF2\u8D5E" : "\u8D5E" })
          ] }),
          /* @__PURE__ */ jsxDEV("button", { type: "button", "data-action": "comment-post", children: [
            Icons.message({ class: "wm-icon tiny" }),
            /* @__PURE__ */ jsxDEV("span", { children: "\u8BC4\u8BBA" })
          ] })
        ] })
      ] }),
      /* @__PURE__ */ jsxDEV("div", { class: "post-comment-container", "data-comment-container": true, hidden: post.likeCount === 0 && comments.length === 0, children: [
        /* @__PURE__ */ jsxDEV("div", { class: "post-like-line", hidden: post.likeCount === 0, children: [
          Icons.heart({ class: "wm-icon tiny" }),
          /* @__PURE__ */ jsxDEV("span", { "data-like-text": true, children: [
            "\u5171 ",
            /* @__PURE__ */ jsxDEV("b", { children: post.likeCount }),
            " \u4EBA\u8D5E\u8FC7"
          ] })
        ] }),
        /* @__PURE__ */ jsxDEV("div", { class: "post-comment-list", children: comments.map((comment) => /* @__PURE__ */ jsxDEV("div", { class: "post-comment", "data-comment-id": comment.id, children: [
          /* @__PURE__ */ jsxDEV("button", { type: "button", class: "comment-text", "data-action": "reply-comment", "data-comment-id": comment.id, "data-author": comment.authorName, children: [
            /* @__PURE__ */ jsxDEV("a", { href: comment.authorUrl || "#", children: comment.authorName }),
            comment.replyToName ? /* @__PURE__ */ jsxDEV("span", { children: [
              " \u56DE\u590D ",
              /* @__PURE__ */ jsxDEV("b", { children: comment.replyToName })
            ] }) : null,
            /* @__PURE__ */ jsxDEV("span", { children: ": " }),
            /* @__PURE__ */ jsxDEV("span", { dangerouslySetInnerHTML: { __html: comment.contentHtml } })
          ] }),
          comment.canDelete ? /* @__PURE__ */ jsxDEV("button", { class: "comment-delete", type: "button", "data-action": "delete-comment", "data-comment-id": comment.id, children: "\u5220\u9664" }) : null
        ] })) })
      ] }),
      /* @__PURE__ */ jsxDEV("form", { class: "inline-comment-form", "data-comment-form": true, hidden: true, children: [
        /* @__PURE__ */ jsxDEV("input", { type: "hidden", name: "postId", value: post.id }),
        /* @__PURE__ */ jsxDEV("input", { type: "hidden", name: "parentId", value: "" }),
        /* @__PURE__ */ jsxDEV("input", { class: "guest-field", name: "guestName", placeholder: "\u6635\u79F0", autocomplete: "name", hidden: Boolean(props.currentUser) }),
        /* @__PURE__ */ jsxDEV("textarea", { name: "content", rows: 2, maxlength: 1e3, placeholder: "\u5199\u8BC4\u8BBA...", required: true }),
        /* @__PURE__ */ jsxDEV("div", { class: "inline-comment-actions", children: [
          /* @__PURE__ */ jsxDEV("button", { type: "button", "data-action": "cancel-comment", children: "\u53D6\u6D88" }),
          /* @__PURE__ */ jsxDEV("button", { type: "submit", children: "\u53D1\u9001" })
        ] })
      ] })
    ] })
  ] });
}
__name(PostItem, "PostItem");

// src/views/components/login-modal.tsx
function LoginModal() {
  return /* @__PURE__ */ jsxDEV("div", { class: "wm-modal", "x-show": "modals.login", "x-cloak": true, ...{ "x-transition.opacity.duration.300ms": "" }, children: [
    /* @__PURE__ */ jsxDEV("div", { class: "wm-modal-mask", "data-close-modal": "login" }),
    /* @__PURE__ */ jsxDEV("section", { class: "wm-modal-card auth-card", role: "dialog", "aria-modal": "true", "aria-labelledby": "login-title", children: [
      /* @__PURE__ */ jsxDEV("button", { class: "modal-close", type: "button", "data-close-modal": "login", "aria-label": "\u5173\u95ED", children: Icons.close() }),
      /* @__PURE__ */ jsxDEV("h2", { id: "login-title", children: "\u767B\u5F55\u5FAE\u8BB0" }),
      /* @__PURE__ */ jsxDEV("form", { "data-auth-form": "login", children: [
        /* @__PURE__ */ jsxDEV("label", { children: [
          /* @__PURE__ */ jsxDEV("span", { children: "\u7528\u6237\u540D\u6216\u90AE\u7BB1" }),
          /* @__PURE__ */ jsxDEV("input", { name: "identifier", autocomplete: "username", required: true })
        ] }),
        /* @__PURE__ */ jsxDEV("label", { children: [
          /* @__PURE__ */ jsxDEV("span", { children: "\u5BC6\u7801" }),
          /* @__PURE__ */ jsxDEV("input", { name: "password", type: "password", autocomplete: "current-password", required: true })
        ] }),
        /* @__PURE__ */ jsxDEV("button", { class: "primary-button", type: "submit", children: "\u767B\u5F55" })
      ] }),
      /* @__PURE__ */ jsxDEV("p", { class: "auth-switch", children: [
        "\u8FD8\u6CA1\u6709\u8D26\u53F7\uFF1F",
        /* @__PURE__ */ jsxDEV("button", { type: "button", "data-switch-modal": "register", children: "\u6CE8\u518C" })
      ] })
    ] })
  ] });
}
__name(LoginModal, "LoginModal");

// src/views/components/register-modal.tsx
function RegisterModal(props) {
  return /* @__PURE__ */ jsxDEV("div", { class: "wm-modal", "x-show": "modals.register", "x-cloak": true, ...{ "x-transition.opacity.duration.300ms": "" }, children: [
    /* @__PURE__ */ jsxDEV("div", { class: "wm-modal-mask", "data-close-modal": "register" }),
    /* @__PURE__ */ jsxDEV("section", { class: "wm-modal-card auth-card", role: "dialog", "aria-modal": "true", "aria-labelledby": "register-title", children: [
      /* @__PURE__ */ jsxDEV("button", { class: "modal-close", type: "button", "data-close-modal": "register", "aria-label": "\u5173\u95ED", children: Icons.close() }),
      /* @__PURE__ */ jsxDEV("h2", { id: "register-title", children: "\u6CE8\u518C\u8D26\u53F7" }),
      props.allowRegister ? /* @__PURE__ */ jsxDEV("form", { "data-auth-form": "register", children: [
        /* @__PURE__ */ jsxDEV("label", { children: [
          /* @__PURE__ */ jsxDEV("span", { children: "\u7528\u6237\u540D" }),
          /* @__PURE__ */ jsxDEV("input", { name: "username", pattern: "[a-zA-Z0-9_]{3,20}", maxlength: 20, autocomplete: "username", required: true })
        ] }),
        /* @__PURE__ */ jsxDEV("label", { children: [
          /* @__PURE__ */ jsxDEV("span", { children: "\u90AE\u7BB1" }),
          /* @__PURE__ */ jsxDEV("input", { name: "email", type: "email", autocomplete: "email", required: true })
        ] }),
        /* @__PURE__ */ jsxDEV("label", { children: [
          /* @__PURE__ */ jsxDEV("span", { children: "\u6635\u79F0" }),
          /* @__PURE__ */ jsxDEV("input", { name: "displayName", maxlength: 24, autocomplete: "name", required: true })
        ] }),
        /* @__PURE__ */ jsxDEV("label", { children: [
          /* @__PURE__ */ jsxDEV("span", { children: "\u5BC6\u7801" }),
          /* @__PURE__ */ jsxDEV("input", { name: "password", type: "password", minlength: 8, autocomplete: "new-password", required: true })
        ] }),
        /* @__PURE__ */ jsxDEV("button", { class: "primary-button", type: "submit", children: "\u6CE8\u518C\u5E76\u767B\u5F55" })
      ] }) : /* @__PURE__ */ jsxDEV("p", { class: "empty-state", children: "\u5DF2\u5173\u95ED\u6CE8\u518C" }),
      /* @__PURE__ */ jsxDEV("p", { class: "auth-switch", children: [
        "\u5DF2\u6709\u8D26\u53F7\uFF1F",
        /* @__PURE__ */ jsxDEV("button", { type: "button", "data-switch-modal": "login", children: "\u767B\u5F55" })
      ] })
    ] })
  ] });
}
__name(RegisterModal, "RegisterModal");

// src/views/components/setting-modal.tsx
function SettingModal() {
  return /* @__PURE__ */ jsxDEV("div", { class: "wm-modal", "x-show": "modals.settings", "x-cloak": true, ...{ "x-transition.opacity.duration.300ms": "" }, children: [
    /* @__PURE__ */ jsxDEV("div", { class: "wm-modal-mask", "data-close-modal": "settings" }),
    /* @__PURE__ */ jsxDEV("section", { class: "wm-modal-card settings-card", role: "dialog", "aria-modal": "true", "aria-labelledby": "settings-title", children: [
      /* @__PURE__ */ jsxDEV("button", { class: "modal-close", type: "button", "data-close-modal": "settings", "aria-label": "\u5173\u95ED", children: Icons.close() }),
      /* @__PURE__ */ jsxDEV("h2", { id: "settings-title", children: "\u8BBE\u7F6E" }),
      /* @__PURE__ */ jsxDEV("div", { class: "setting-row", children: [
        /* @__PURE__ */ jsxDEV("div", { children: [
          /* @__PURE__ */ jsxDEV("strong", { children: "\u6697\u9ED1\u6A21\u5F0F" }),
          /* @__PURE__ */ jsxDEV("span", { children: "\u5237\u65B0\u540E\u4FDD\u6301" })
        ] }),
        /* @__PURE__ */ jsxDEV("label", { class: "switch", children: [
          /* @__PURE__ */ jsxDEV("input", { type: "checkbox", "data-theme-toggle": true }),
          /* @__PURE__ */ jsxDEV("i", {})
        ] })
      ] })
    ] })
  ] });
}
__name(SettingModal, "SettingModal");

// src/views/components/links-modal.tsx
function LinksModal(props) {
  return /* @__PURE__ */ jsxDEV("div", { class: "wm-modal", "x-show": "modals.links", "x-cloak": true, ...{ "x-transition.opacity.duration.300ms": "" }, children: [
    /* @__PURE__ */ jsxDEV("div", { class: "wm-modal-mask", "data-close-modal": "links" }),
    /* @__PURE__ */ jsxDEV("section", { class: "wm-modal-card links-card", role: "dialog", "aria-modal": "true", "aria-labelledby": "links-title", children: [
      /* @__PURE__ */ jsxDEV("button", { class: "modal-close", type: "button", "data-close-modal": "links", "aria-label": "\u5173\u95ED", children: Icons.close() }),
      /* @__PURE__ */ jsxDEV("h2", { id: "links-title", children: "\u53CB\u94FE" }),
      /* @__PURE__ */ jsxDEV("div", { class: "links-grid", children: props.links.length ? props.links.map((link2) => /* @__PURE__ */ jsxDEV("a", { class: "friend-link", href: link2.url, target: "_blank", rel: "noopener noreferrer", children: [
        /* @__PURE__ */ jsxDEV("img", { src: link2.avatar || "/assets/images/default-avatar.svg", alt: "", loading: "lazy" }),
        /* @__PURE__ */ jsxDEV("span", { children: [
          /* @__PURE__ */ jsxDEV("strong", { children: link2.name }),
          /* @__PURE__ */ jsxDEV("small", { children: link2.description })
        ] })
      ] })) : /* @__PURE__ */ jsxDEV("p", { class: "empty-state", children: "\u6682\u65E0\u53CB\u94FE" }) })
    ] })
  ] });
}
__name(LinksModal, "LinksModal");

// src/views/components/write-modal.tsx
function WriteModal() {
  return /* @__PURE__ */ jsxDEV("div", { class: "wm-modal", "x-show": "modals.write", "x-cloak": true, ...{ "x-transition.opacity.duration.300ms": "" }, children: [
    /* @__PURE__ */ jsxDEV("div", { class: "wm-modal-mask", "data-close-modal": "write" }),
    /* @__PURE__ */ jsxDEV("section", { class: "wm-modal-card write-card", role: "dialog", "aria-modal": "true", "aria-labelledby": "write-title", children: [
      /* @__PURE__ */ jsxDEV("button", { class: "modal-close", type: "button", "data-close-modal": "write", "aria-label": "\u5173\u95ED", children: Icons.close() }),
      /* @__PURE__ */ jsxDEV("h2", { id: "write-title", children: "\u5199\u8BF4\u8BF4" }),
      /* @__PURE__ */ jsxDEV("form", { "data-write-form": true, children: [
        /* @__PURE__ */ jsxDEV("textarea", { name: "content", maxlength: 5e3, rows: 6, placeholder: "\u8FD9\u4E00\u523B\u7684\u60F3\u6CD5...", required: true }),
        /* @__PURE__ */ jsxDEV("div", { class: "write-count", children: [
          /* @__PURE__ */ jsxDEV("span", { "data-write-count": true, children: "0" }),
          "/5000"
        ] }),
        /* @__PURE__ */ jsxDEV("div", { class: "media-picker", "data-media-picker": true, children: [
          /* @__PURE__ */ jsxDEV("button", { class: "media-add", type: "button", "data-action": "pick-image", children: [
            Icons.plus({ class: "wm-icon" }),
            /* @__PURE__ */ jsxDEV("span", { children: "\u56FE\u7247" })
          ] }),
          /* @__PURE__ */ jsxDEV("button", { class: "media-add", type: "button", "data-action": "pick-video", children: [
            Icons.camera({ class: "wm-icon" }),
            /* @__PURE__ */ jsxDEV("span", { children: "\u89C6\u9891" })
          ] })
        ] }),
        /* @__PURE__ */ jsxDEV("input", { type: "file", accept: "image/jpeg,image/png,image/webp,image/gif", multiple: true, hidden: true, "data-image-input": true }),
        /* @__PURE__ */ jsxDEV("input", { type: "file", accept: "video/mp4,video/webm,video/quicktime", hidden: true, "data-video-input": true }),
        /* @__PURE__ */ jsxDEV("div", { class: "write-options", children: [
          /* @__PURE__ */ jsxDEV("label", { children: [
            /* @__PURE__ */ jsxDEV("input", { type: "radio", name: "visibility", value: "public", checked: true }),
            "\u516C\u5F00"
          ] }),
          /* @__PURE__ */ jsxDEV("label", { children: [
            /* @__PURE__ */ jsxDEV("input", { type: "radio", name: "visibility", value: "private" }),
            "\u79C1\u5BC6"
          ] }),
          /* @__PURE__ */ jsxDEV("label", { children: [
            /* @__PURE__ */ jsxDEV("input", { type: "checkbox", name: "isTop" }),
            "\u7F6E\u9876"
          ] }),
          /* @__PURE__ */ jsxDEV("label", { children: [
            /* @__PURE__ */ jsxDEV("input", { type: "checkbox", name: "isAd" }),
            "\u5E7F\u544A"
          ] }),
          /* @__PURE__ */ jsxDEV("button", { type: "button", "data-action": "use-location", children: [
            Icons.location({ class: "wm-icon tiny" }),
            /* @__PURE__ */ jsxDEV("span", { "data-location-label": true, children: "\u5B9A\u4F4D" })
          ] }),
          /* @__PURE__ */ jsxDEV("input", { type: "hidden", name: "position" }),
          /* @__PURE__ */ jsxDEV("input", { type: "hidden", name: "positionLat" }),
          /* @__PURE__ */ jsxDEV("input", { type: "hidden", name: "positionLng" })
        ] }),
        /* @__PURE__ */ jsxDEV("button", { class: "primary-button", type: "submit", children: "\u53D1\u5E03" })
      ] })
    ] })
  ] });
}
__name(WriteModal, "WriteModal");

// src/views/components/dialog.tsx
function DialogRoot() {
  return /* @__PURE__ */ jsxDEV("div", { id: "wm-dialog-root", class: "wm-dialog-root", "aria-live": "polite" });
}
__name(DialogRoot, "DialogRoot");

// src/views/layout.tsx
function Layout(props) {
  const siteTitle = props.title ? `${props.title} - ${props.settings.site_name}` : props.settings.site_name;
  const avatarUrl = mediaUrl(props.settings.cdn_base_url, props.settings.site_avatar_key);
  const topImageUrl = mediaUrl(props.settings.cdn_base_url, props.settings.top_image_key, "");
  const topVideoUrl = mediaUrl(props.settings.cdn_base_url, props.settings.top_video_key, "");
  const config2 = {
    apiBase: "/api",
    uploadBase: "/api/uploads",
    csrfToken: props.csrfToken,
    defaultAvatar: "/assets/images/default-avatar.svg",
    homeUrl: "/",
    locationLookupEnabled: Boolean(props.settings.tencent_map_key),
    currentUser: props.currentUser ? {
      id: props.currentUser.id,
      username: props.currentUser.username,
      displayName: props.currentUser.displayName,
      role: props.currentUser.role,
      avatarUrl: mediaUrl(props.settings.cdn_base_url, props.currentUser.avatarKey)
    } : null,
    currentUserIsAdmin: props.currentUser?.role === "admin",
    commentMode: props.settings.comment_mode
  };
  return /* @__PURE__ */ jsxDEV("html", { lang: "zh-CN", children: [
    /* @__PURE__ */ jsxDEV("head", { children: [
      /* @__PURE__ */ jsxDEV("meta", { charset: "utf-8" }),
      /* @__PURE__ */ jsxDEV("meta", { name: "viewport", content: "width=device-width, initial-scale=1" }),
      /* @__PURE__ */ jsxDEV("meta", { name: "color-scheme", content: "light dark" }),
      /* @__PURE__ */ jsxDEV("title", { children: siteTitle }),
      /* @__PURE__ */ jsxDEV("script", { dangerouslySetInnerHTML: { __html: "(function(){var t=localStorage.getItem('wemoments_theme_mode');if(t==='dark')document.documentElement.classList.add('dark');})();" } }),
      /* @__PURE__ */ jsxDEV("link", { rel: "stylesheet", href: "/assets/css/fancybox.css" }),
      /* @__PURE__ */ jsxDEV("link", { rel: "stylesheet", href: "/assets/css/wemoments.css" }),
      props.settings.custom_css ? /* @__PURE__ */ jsxDEV("style", { dangerouslySetInnerHTML: { __html: props.settings.custom_css } }) : null,
      /* @__PURE__ */ jsxDEV("script", { dangerouslySetInnerHTML: { __html: `window.WEMOMENTS_CONFIG=${safeJson(config2)};` } })
    ] }),
    /* @__PURE__ */ jsxDEV("body", { "x-data": "wemomentsShell()", children: [
      /* @__PURE__ */ jsxDEV("main", { class: "page-shell", children: [
        /* @__PURE__ */ jsxDEV("nav", { class: "top-nav", "data-top-nav": true, children: [
          /* @__PURE__ */ jsxDEV("div", { class: "nav-left", children: [
            /* @__PURE__ */ jsxDEV("button", { type: "button", "data-open-modal": props.currentUser ? "settings" : "login", "aria-label": props.currentUser ? "\u7528\u6237\u8BBE\u7F6E" : "\u767B\u5F55", children: Icons.user() }),
            /* @__PURE__ */ jsxDEV("button", { type: "button", "data-open-modal": "links", "aria-label": "\u53CB\u94FE", children: Icons.links() }),
            /* @__PURE__ */ jsxDEV("button", { type: "button", "data-open-modal": "settings", "aria-label": "\u8BBE\u7F6E", children: Icons.settings() })
          ] }),
          /* @__PURE__ */ jsxDEV("a", { class: "nav-title", href: "/", children: props.settings.site_name }),
          /* @__PURE__ */ jsxDEV("div", { class: "nav-right", children: props.currentUser ? /* @__PURE__ */ jsxDEV("button", { type: "button", "data-open-modal": "write", "aria-label": "\u53D1\u5E03\u8BF4\u8BF4", children: Icons.camera() }) : /* @__PURE__ */ jsxDEV("button", { type: "button", "data-open-modal": "login", "aria-label": "\u767B\u5F55\u540E\u53D1\u5E03", children: Icons.camera() }) })
        ] }),
        props.showHero !== false ? /* @__PURE__ */ jsxDEV("header", { class: "header-container", children: [
          topVideoUrl ? /* @__PURE__ */ jsxDEV("video", { class: "header-video", src: topVideoUrl, autoplay: true, muted: true, loop: true, playsinline: true, poster: topImageUrl || void 0 }) : /* @__PURE__ */ jsxDEV("div", { class: "header-image", style: topImageUrl ? `background-image:url('${topImageUrl}')` : void 0 }),
          /* @__PURE__ */ jsxDEV("div", { class: "site-profile", children: [
            /* @__PURE__ */ jsxDEV("div", { class: "site-copy", children: [
              /* @__PURE__ */ jsxDEV("h1", { children: props.settings.site_name }),
              props.settings.site_description ? /* @__PURE__ */ jsxDEV("p", { children: props.settings.site_description }) : null
            ] }),
            /* @__PURE__ */ jsxDEV("a", { href: props.settings.avatar_link || "/", class: "site-avatar", children: /* @__PURE__ */ jsxDEV("img", { src: avatarUrl, alt: `${props.settings.site_name} \u5934\u50CF` }) })
          ] })
        ] }) : null,
        /* @__PURE__ */ jsxDEV("section", { class: "content-container", children: props.children }),
        props.settings.beian_info ? /* @__PURE__ */ jsxDEV("footer", { class: "site-footer", children: props.settings.beian_info }) : null
      ] }),
      /* @__PURE__ */ jsxDEV(LoginModal, {}),
      /* @__PURE__ */ jsxDEV(RegisterModal, { allowRegister: props.settings.allow_register }),
      /* @__PURE__ */ jsxDEV(SettingModal, {}),
      /* @__PURE__ */ jsxDEV(LinksModal, { links: props.links || [] }),
      props.currentUser ? /* @__PURE__ */ jsxDEV(WriteModal, {}) : null,
      /* @__PURE__ */ jsxDEV(DialogRoot, {}),
      /* @__PURE__ */ jsxDEV("script", { defer: true, src: "/assets/js/wemoments.js" }),
      /* @__PURE__ */ jsxDEV("script", { defer: true, src: "/assets/js/axios.min.js" }),
      /* @__PURE__ */ jsxDEV("script", { defer: true, src: "/assets/js/fancybox.umd.js" }),
      /* @__PURE__ */ jsxDEV("script", { defer: true, src: "/assets/js/alpine.min.js" }),
      props.settings.analytics_code ? /* @__PURE__ */ jsxDEV("script", { dangerouslySetInnerHTML: { __html: props.settings.analytics_code } }) : null,
      props.settings.custom_js ? /* @__PURE__ */ jsxDEV("script", { dangerouslySetInnerHTML: { __html: props.settings.custom_js } }) : null
    ] })
  ] });
}
__name(Layout, "Layout");

// src/views/home.tsx
function HomePage(props) {
  return /* @__PURE__ */ jsxDEV(Layout, { settings: props.settings, currentUser: props.currentUser, csrfToken: props.csrfToken, links: props.links, title: props.title, children: [
    /* @__PURE__ */ jsxDEV("div", { class: "feed-list", "data-feed-list": true, "data-next-cursor": props.nextCursor || "", children: props.posts.length ? props.posts.map((post) => /* @__PURE__ */ jsxDEV(PostItem, { post, comments: props.commentsByPost.get(post.id) || [], settings: props.settings, currentUser: props.currentUser })) : /* @__PURE__ */ jsxDEV("p", { class: "empty-state", children: "\u8FD8\u6CA1\u6709\u516C\u5F00\u5185\u5BB9" }) }),
    /* @__PURE__ */ jsxDEV("div", { class: "feed-loading", "data-feed-loading": true, hidden: true, children: "\u52A0\u8F7D\u4E2D..." })
  ] });
}
__name(HomePage, "HomePage");

// src/views/post-detail.tsx
function PostDetailPage(props) {
  return /* @__PURE__ */ jsxDEV(Layout, { settings: props.settings, currentUser: props.currentUser, csrfToken: props.csrfToken, links: props.links, title: "\u8BE6\u60C5", showHero: false, children: /* @__PURE__ */ jsxDEV("div", { class: "detail-page", children: /* @__PURE__ */ jsxDEV(PostItem, { post: props.post, comments: props.comments, settings: props.settings, currentUser: props.currentUser }) }) });
}
__name(PostDetailPage, "PostDetailPage");

// src/views/login.tsx
function LoginPage(props) {
  return /* @__PURE__ */ jsxDEV(Layout, { settings: props.settings, currentUser: props.currentUser, csrfToken: props.csrfToken, links: props.links, title: "\u767B\u5F55", showHero: false, children: /* @__PURE__ */ jsxDEV("section", { class: "standalone-auth", children: [
    /* @__PURE__ */ jsxDEV("h1", { children: "\u767B\u5F55\u5FAE\u8BB0" }),
    /* @__PURE__ */ jsxDEV("form", { "data-auth-form": "login", children: [
      /* @__PURE__ */ jsxDEV("label", { children: [
        /* @__PURE__ */ jsxDEV("span", { children: "\u7528\u6237\u540D\u6216\u90AE\u7BB1" }),
        /* @__PURE__ */ jsxDEV("input", { name: "identifier", autocomplete: "username", required: true })
      ] }),
      /* @__PURE__ */ jsxDEV("label", { children: [
        /* @__PURE__ */ jsxDEV("span", { children: "\u5BC6\u7801" }),
        /* @__PURE__ */ jsxDEV("input", { name: "password", type: "password", autocomplete: "current-password", required: true })
      ] }),
      /* @__PURE__ */ jsxDEV("button", { class: "primary-button", type: "submit", children: "\u767B\u5F55" })
    ] })
  ] }) });
}
__name(LoginPage, "LoginPage");

// src/views/register.tsx
function RegisterPage(props) {
  return /* @__PURE__ */ jsxDEV(Layout, { settings: props.settings, currentUser: props.currentUser, csrfToken: props.csrfToken, links: props.links, title: "\u6CE8\u518C", showHero: false, children: /* @__PURE__ */ jsxDEV("section", { class: "standalone-auth", children: [
    /* @__PURE__ */ jsxDEV("h1", { children: "\u6CE8\u518C\u8D26\u53F7" }),
    props.settings.allow_register ? /* @__PURE__ */ jsxDEV("form", { "data-auth-form": "register", children: [
      /* @__PURE__ */ jsxDEV("label", { children: [
        /* @__PURE__ */ jsxDEV("span", { children: "\u7528\u6237\u540D" }),
        /* @__PURE__ */ jsxDEV("input", { name: "username", pattern: "[a-zA-Z0-9_]{3,20}", maxlength: 20, required: true })
      ] }),
      /* @__PURE__ */ jsxDEV("label", { children: [
        /* @__PURE__ */ jsxDEV("span", { children: "\u90AE\u7BB1" }),
        /* @__PURE__ */ jsxDEV("input", { name: "email", type: "email", required: true })
      ] }),
      /* @__PURE__ */ jsxDEV("label", { children: [
        /* @__PURE__ */ jsxDEV("span", { children: "\u6635\u79F0" }),
        /* @__PURE__ */ jsxDEV("input", { name: "displayName", maxlength: 24, required: true })
      ] }),
      /* @__PURE__ */ jsxDEV("label", { children: [
        /* @__PURE__ */ jsxDEV("span", { children: "\u5BC6\u7801" }),
        /* @__PURE__ */ jsxDEV("input", { name: "password", type: "password", minlength: 8, required: true })
      ] }),
      /* @__PURE__ */ jsxDEV("button", { class: "primary-button", type: "submit", children: "\u6CE8\u518C\u5E76\u767B\u5F55" })
    ] }) : /* @__PURE__ */ jsxDEV("p", { class: "empty-state", children: "\u5DF2\u5173\u95ED\u6CE8\u518C" })
  ] }) });
}
__name(RegisterPage, "RegisterPage");

// src/views/user.tsx
function UserPage(props) {
  return /* @__PURE__ */ jsxDEV(Layout, { settings: props.settings, currentUser: props.currentUser, csrfToken: props.csrfToken, links: props.links, title: props.profile.displayName, showHero: false, children: [
    /* @__PURE__ */ jsxDEV("section", { class: "profile-card", children: [
      /* @__PURE__ */ jsxDEV("img", { src: mediaUrl(props.settings.cdn_base_url, props.profile.avatarKey), alt: "" }),
      /* @__PURE__ */ jsxDEV("div", { children: [
        /* @__PURE__ */ jsxDEV("h1", { children: props.profile.displayName }),
        /* @__PURE__ */ jsxDEV("p", { children: [
          "@",
          props.profile.username
        ] }),
        props.profile.bio ? /* @__PURE__ */ jsxDEV("p", { children: props.profile.bio }) : null,
        props.profile.url ? /* @__PURE__ */ jsxDEV("a", { href: props.profile.url, target: "_blank", rel: "noopener noreferrer", children: props.profile.url }) : null
      ] })
    ] }),
    /* @__PURE__ */ jsxDEV("div", { class: "feed-list", children: props.posts.map((post) => /* @__PURE__ */ jsxDEV(PostItem, { post, comments: props.commentsByPost.get(post.id) || [], settings: props.settings, currentUser: props.currentUser })) })
  ] });
}
__name(UserPage, "UserPage");

// src/views/simple.tsx
function LinksPage(props) {
  const categories = Array.from(new Set(props.links.map((link2) => link2.category || "default")));
  return /* @__PURE__ */ jsxDEV(Layout, { settings: props.settings, currentUser: props.currentUser, csrfToken: props.csrfToken, links: props.links, title: "\u53CB\u94FE", showHero: false, children: /* @__PURE__ */ jsxDEV("section", { class: "plain-page", children: [
    /* @__PURE__ */ jsxDEV("h1", { children: "\u53CB\u94FE" }),
    categories.length ? categories.map((category) => /* @__PURE__ */ jsxDEV("div", { class: "link-category", children: [
      /* @__PURE__ */ jsxDEV("h2", { children: category }),
      /* @__PURE__ */ jsxDEV("div", { class: "links-grid full", children: props.links.filter((link2) => (link2.category || "default") === category).map((link2) => /* @__PURE__ */ jsxDEV("a", { class: "friend-link", href: link2.url, target: "_blank", rel: "noopener noreferrer", children: [
        /* @__PURE__ */ jsxDEV("img", { src: link2.avatar || "/assets/images/default-avatar.svg", alt: "", loading: "lazy" }),
        /* @__PURE__ */ jsxDEV("span", { children: [
          /* @__PURE__ */ jsxDEV("strong", { children: link2.name }),
          /* @__PURE__ */ jsxDEV("small", { children: link2.description })
        ] })
      ] })) })
    ] })) : /* @__PURE__ */ jsxDEV("p", { class: "empty-state", children: "\u6682\u65E0\u53CB\u94FE" })
  ] }) });
}
__name(LinksPage, "LinksPage");
function MessagePage(props) {
  return /* @__PURE__ */ jsxDEV(Layout, { settings: props.settings, currentUser: props.currentUser, csrfToken: props.csrfToken, links: props.links, title: props.title, showHero: false, children: /* @__PURE__ */ jsxDEV("section", { class: "plain-page", children: [
    /* @__PURE__ */ jsxDEV("h1", { children: props.title }),
    /* @__PURE__ */ jsxDEV("p", { children: props.message })
  ] }) });
}
__name(MessagePage, "MessagePage");

// src/routes/pages.tsx
var pages = new Hono2();
async function common(c) {
  const settings = await getSettings(c.env);
  const links = await listPublicLinks(c.env, settings);
  return { settings, links, currentUser: c.get("currentUser"), csrfToken: c.get("csrfToken") };
}
__name(common, "common");
async function commentsForPosts(env2, postIds, viewer) {
  const entries = await Promise.all(postIds.map(async (id) => [id, await listComments(env2, id, viewer)]));
  return new Map(entries);
}
__name(commentsForPosts, "commentsForPosts");
pages.get("/", async (c) => {
  const ctx = await common(c);
  const result = await listPosts(c.env, ctx.settings, { viewer: ctx.currentUser, limit: 20 });
  const commentsByPost = await commentsForPosts(c.env, result.posts.map((post) => post.id), ctx.currentUser);
  return c.html(
    /* @__PURE__ */ jsxDEV(
      HomePage,
      {
        settings: ctx.settings,
        currentUser: ctx.currentUser,
        csrfToken: ctx.csrfToken,
        posts: result.posts,
        commentsByPost,
        nextCursor: result.nextCursor,
        links: ctx.links
      }
    )
  );
});
pages.get("/p/:id", async (c) => {
  const ctx = await common(c);
  const post = await getPost(c.env, ctx.settings, c.req.param("id"), ctx.currentUser);
  if (!post)
    return c.notFound();
  const comments = await listComments(c.env, post.id, ctx.currentUser);
  return c.html(/* @__PURE__ */ jsxDEV(PostDetailPage, { settings: ctx.settings, currentUser: ctx.currentUser, csrfToken: ctx.csrfToken, post, comments, links: ctx.links }));
});
pages.get("/u/:username", async (c) => {
  const ctx = await common(c);
  const profile3 = await first(
    c.env.DB.prepare('SELECT username, display_name, avatar_key, bio, url FROM wm_users WHERE username = ? AND status = "active"').bind(c.req.param("username"))
  );
  if (!profile3)
    return c.notFound();
  const result = await listPosts(c.env, ctx.settings, { viewer: ctx.currentUser, authorUsername: profile3.username, limit: 20 });
  const commentsByPost = await commentsForPosts(c.env, result.posts.map((post) => post.id), ctx.currentUser);
  return c.html(
    /* @__PURE__ */ jsxDEV(
      UserPage,
      {
        profile: { username: profile3.username, displayName: profile3.display_name, avatarKey: profile3.avatar_key, bio: profile3.bio || "", url: profile3.url || "" },
        settings: ctx.settings,
        currentUser: ctx.currentUser,
        csrfToken: ctx.csrfToken,
        posts: result.posts,
        commentsByPost,
        links: ctx.links
      }
    )
  );
});
pages.get("/login", async (c) => {
  const ctx = await common(c);
  return c.html(/* @__PURE__ */ jsxDEV(LoginPage, { settings: ctx.settings, currentUser: ctx.currentUser, csrfToken: ctx.csrfToken, links: ctx.links }));
});
pages.get("/register", async (c) => {
  const ctx = await common(c);
  return c.html(/* @__PURE__ */ jsxDEV(RegisterPage, { settings: ctx.settings, currentUser: ctx.currentUser, csrfToken: ctx.csrfToken, links: ctx.links }));
});
pages.get("/forgot", async (c) => {
  const ctx = await common(c);
  return c.html(/* @__PURE__ */ jsxDEV(MessagePage, { title: "\u627E\u56DE\u5BC6\u7801", message: "\u627E\u56DE\u5BC6\u7801\u63A5\u53E3\u5DF2\u9884\u7559\uFF0Cv1 \u4F1A\u5C06\u91CD\u7F6E\u90AE\u4EF6\u8F93\u51FA\u5230\u65E5\u5FD7\u3002", settings: ctx.settings, currentUser: ctx.currentUser, csrfToken: ctx.csrfToken, links: ctx.links }));
});
pages.get("/links", async (c) => {
  const ctx = await common(c);
  return c.html(/* @__PURE__ */ jsxDEV(LinksPage, { settings: ctx.settings, currentUser: ctx.currentUser, csrfToken: ctx.csrfToken, links: ctx.links }));
});
pages.get("/search", async (c) => {
  const ctx = await common(c);
  const q = c.req.query("q") || "";
  const result = await listPosts(c.env, ctx.settings, { viewer: ctx.currentUser, q, limit: 20 });
  const commentsByPost = await commentsForPosts(c.env, result.posts.map((post) => post.id), ctx.currentUser);
  return c.html(
    /* @__PURE__ */ jsxDEV(
      HomePage,
      {
        title: q ? `\u641C\u7D22\uFF1A${q}` : "\u641C\u7D22",
        settings: ctx.settings,
        currentUser: ctx.currentUser,
        csrfToken: ctx.csrfToken,
        posts: result.posts,
        commentsByPost,
        nextCursor: result.nextCursor,
        links: ctx.links
      }
    )
  );
});
pages.get("/r2/*", async (c) => {
  const settings = await getSettings(c.env);
  const key = decodeURIComponent(c.req.path.replace(/^\/r2\//, ""));
  if (!key)
    return c.notFound();
  if (settings.cdn_base_url)
    return c.redirect(mediaUrl(settings.cdn_base_url, key, ""), 301);
  const object = await c.env.R2.get(key);
  if (!object)
    return c.notFound();
  const headers = new Headers();
  object.writeHttpMetadata(headers);
  headers.set("ETag", object.httpEtag);
  headers.set("Cache-Control", "public, max-age=31536000, immutable");
  return new Response(object.body, { headers });
});
pages.get("/robots.txt", (c) => c.text("User-agent: *\nAllow: /\n"));
pages.get("/assets/*", (c) => c.env.ASSETS.fetch(c.req.raw));

// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/external.js
var external_exports = {};
__export(external_exports, {
  BRAND: () => BRAND,
  DIRTY: () => DIRTY,
  EMPTY_PATH: () => EMPTY_PATH,
  INVALID: () => INVALID,
  NEVER: () => NEVER,
  OK: () => OK,
  ParseStatus: () => ParseStatus,
  Schema: () => ZodType,
  ZodAny: () => ZodAny,
  ZodArray: () => ZodArray,
  ZodBigInt: () => ZodBigInt,
  ZodBoolean: () => ZodBoolean,
  ZodBranded: () => ZodBranded,
  ZodCatch: () => ZodCatch,
  ZodDate: () => ZodDate,
  ZodDefault: () => ZodDefault,
  ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
  ZodEffects: () => ZodEffects,
  ZodEnum: () => ZodEnum,
  ZodError: () => ZodError,
  ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,
  ZodFunction: () => ZodFunction,
  ZodIntersection: () => ZodIntersection,
  ZodIssueCode: () => ZodIssueCode,
  ZodLazy: () => ZodLazy,
  ZodLiteral: () => ZodLiteral,
  ZodMap: () => ZodMap,
  ZodNaN: () => ZodNaN,
  ZodNativeEnum: () => ZodNativeEnum,
  ZodNever: () => ZodNever,
  ZodNull: () => ZodNull,
  ZodNullable: () => ZodNullable,
  ZodNumber: () => ZodNumber,
  ZodObject: () => ZodObject,
  ZodOptional: () => ZodOptional,
  ZodParsedType: () => ZodParsedType,
  ZodPipeline: () => ZodPipeline,
  ZodPromise: () => ZodPromise,
  ZodReadonly: () => ZodReadonly,
  ZodRecord: () => ZodRecord,
  ZodSchema: () => ZodType,
  ZodSet: () => ZodSet,
  ZodString: () => ZodString,
  ZodSymbol: () => ZodSymbol,
  ZodTransformer: () => ZodEffects,
  ZodTuple: () => ZodTuple,
  ZodType: () => ZodType,
  ZodUndefined: () => ZodUndefined,
  ZodUnion: () => ZodUnion,
  ZodUnknown: () => ZodUnknown,
  ZodVoid: () => ZodVoid,
  addIssueToContext: () => addIssueToContext,
  any: () => anyType,
  array: () => arrayType,
  bigint: () => bigIntType,
  boolean: () => booleanType,
  coerce: () => coerce,
  custom: () => custom,
  date: () => dateType,
  datetimeRegex: () => datetimeRegex,
  defaultErrorMap: () => en_default,
  discriminatedUnion: () => discriminatedUnionType,
  effect: () => effectsType,
  enum: () => enumType,
  function: () => functionType,
  getErrorMap: () => getErrorMap,
  getParsedType: () => getParsedType,
  instanceof: () => instanceOfType,
  intersection: () => intersectionType,
  isAborted: () => isAborted,
  isAsync: () => isAsync,
  isDirty: () => isDirty,
  isValid: () => isValid,
  late: () => late,
  lazy: () => lazyType,
  literal: () => literalType,
  makeIssue: () => makeIssue,
  map: () => mapType,
  nan: () => nanType,
  nativeEnum: () => nativeEnumType,
  never: () => neverType,
  null: () => nullType,
  nullable: () => nullableType,
  number: () => numberType,
  object: () => objectType,
  objectUtil: () => objectUtil,
  oboolean: () => oboolean,
  onumber: () => onumber,
  optional: () => optionalType,
  ostring: () => ostring,
  pipeline: () => pipelineType,
  preprocess: () => preprocessType,
  promise: () => promiseType,
  quotelessJson: () => quotelessJson,
  record: () => recordType,
  set: () => setType,
  setErrorMap: () => setErrorMap,
  strictObject: () => strictObjectType,
  string: () => stringType,
  symbol: () => symbolType,
  transformer: () => effectsType,
  tuple: () => tupleType,
  undefined: () => undefinedType,
  union: () => unionType,
  unknown: () => unknownType,
  util: () => util,
  void: () => voidType
});

// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/util.js
var util;
(function(util2) {
  util2.assertEqual = (_) => {
  };
  function assertIs(_arg) {
  }
  __name(assertIs, "assertIs");
  util2.assertIs = assertIs;
  function assertNever(_x) {
    throw new Error();
  }
  __name(assertNever, "assertNever");
  util2.assertNever = assertNever;
  util2.arrayToEnum = (items) => {
    const obj = {};
    for (const item of items) {
      obj[item] = item;
    }
    return obj;
  };
  util2.getValidEnumValues = (obj) => {
    const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
    const filtered = {};
    for (const k of validKeys) {
      filtered[k] = obj[k];
    }
    return util2.objectValues(filtered);
  };
  util2.objectValues = (obj) => {
    return util2.objectKeys(obj).map(function(e) {
      return obj[e];
    });
  };
  util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
    const keys = [];
    for (const key in object) {
      if (Object.prototype.hasOwnProperty.call(object, key)) {
        keys.push(key);
      }
    }
    return keys;
  };
  util2.find = (arr, checker) => {
    for (const item of arr) {
      if (checker(item))
        return item;
    }
    return void 0;
  };
  util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
  function joinValues(array, separator = " | ") {
    return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
  }
  __name(joinValues, "joinValues");
  util2.joinValues = joinValues;
  util2.jsonStringifyReplacer = (_, value) => {
    if (typeof value === "bigint") {
      return value.toString();
    }
    return value;
  };
})(util || (util = {}));
var objectUtil;
(function(objectUtil2) {
  objectUtil2.mergeShapes = (first2, second) => {
    return {
      ...first2,
      ...second
      // second overwrites first
    };
  };
})(objectUtil || (objectUtil = {}));
var ZodParsedType = util.arrayToEnum([
  "string",
  "nan",
  "number",
  "integer",
  "float",
  "boolean",
  "date",
  "bigint",
  "symbol",
  "function",
  "undefined",
  "null",
  "array",
  "object",
  "unknown",
  "promise",
  "void",
  "never",
  "map",
  "set"
]);
var getParsedType = /* @__PURE__ */ __name((data) => {
  const t = typeof data;
  switch (t) {
    case "undefined":
      return ZodParsedType.undefined;
    case "string":
      return ZodParsedType.string;
    case "number":
      return Number.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;
  }
}, "getParsedType");

// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/ZodError.js
var 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"
]);
var quotelessJson = /* @__PURE__ */ __name((obj) => {
  const json = JSON.stringify(obj, null, 2);
  return json.replace(/"([^"]+)":/g, "$1:");
}, "quotelessJson");
var ZodError = class extends Error {
  get errors() {
    return this.issues;
  }
  constructor(issues) {
    super();
    this.issues = [];
    this.addIssue = (sub) => {
      this.issues = [...this.issues, sub];
    };
    this.addIssues = (subs = []) => {
      this.issues = [...this.issues, ...subs];
    };
    const actualProto = new.target.prototype;
    if (Object.setPrototypeOf) {
      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 = /* @__PURE__ */ __name((error3) => {
      for (const issue of error3.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: [] };
            } else {
              curr[el] = curr[el] || { _errors: [] };
              curr[el]._errors.push(mapper(issue));
            }
            curr = curr[el];
            i++;
          }
        }
      }
    }, "processError");
    processError(this);
    return fieldErrors;
  }
  static assert(value) {
    if (!(value instanceof ZodError)) {
      throw new Error(`Not a ZodError: ${value}`);
    }
  }
  toString() {
    return this.message;
  }
  get message() {
    return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
  }
  get isEmpty() {
    return this.issues.length === 0;
  }
  flatten(mapper = (issue) => issue.message) {
    const fieldErrors = {};
    const formErrors = [];
    for (const sub of this.issues) {
      if (sub.path.length > 0) {
        const firstEl = sub.path[0];
        fieldErrors[firstEl] = fieldErrors[firstEl] || [];
        fieldErrors[firstEl].push(mapper(sub));
      } else {
        formErrors.push(mapper(sub));
      }
    }
    return { formErrors, fieldErrors };
  }
  get formErrors() {
    return this.flatten();
  }
};
__name(ZodError, "ZodError");
ZodError.create = (issues) => {
  const error3 = new ZodError(issues);
  return error3;
};

// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/locales/en.js
var errorMap = /* @__PURE__ */ __name((issue, _ctx) => {
  let message;
  switch (issue.code) {
    case ZodIssueCode.invalid_type:
      if (issue.received === ZodParsedType.undefined) {
        message = "Required";
      } else {
        message = `Expected ${issue.expected}, received ${issue.received}`;
      }
      break;
    case ZodIssueCode.invalid_literal:
      message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
      break;
    case ZodIssueCode.unrecognized_keys:
      message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
      break;
    case ZodIssueCode.invalid_union:
      message = `Invalid input`;
      break;
    case ZodIssueCode.invalid_union_discriminator:
      message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
      break;
    case ZodIssueCode.invalid_enum_value:
      message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${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 "${issue.validation.includes}"`;
          if (typeof issue.validation.position === "number") {
            message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
          }
        } else if ("startsWith" in issue.validation) {
          message = `Invalid input: must start with "${issue.validation.startsWith}"`;
        } else if ("endsWith" in issue.validation) {
          message = `Invalid input: must end with "${issue.validation.endsWith}"`;
        } else {
          util.assertNever(issue.validation);
        }
      } else if (issue.validation !== "regex") {
        message = `Invalid ${issue.validation}`;
      } else {
        message = "Invalid";
      }
      break;
    case ZodIssueCode.too_small:
      if (issue.type === "array")
        message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
      else if (issue.type === "string")
        message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
      else if (issue.type === "number")
        message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
      else if (issue.type === "bigint")
        message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
      else if (issue.type === "date")
        message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
      else
        message = "Invalid input";
      break;
    case ZodIssueCode.too_big:
      if (issue.type === "array")
        message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
      else if (issue.type === "string")
        message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
      else if (issue.type === "number")
        message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
      else if (issue.type === "bigint")
        message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
      else if (issue.type === "date")
        message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${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 ${issue.multipleOf}`;
      break;
    case ZodIssueCode.not_finite:
      message = "Number must be finite";
      break;
    default:
      message = _ctx.defaultError;
      util.assertNever(issue);
  }
  return { message };
}, "errorMap");
var en_default = errorMap;

// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/errors.js
var overrideErrorMap = en_default;
function setErrorMap(map) {
  overrideErrorMap = map;
}
__name(setErrorMap, "setErrorMap");
function getErrorMap() {
  return overrideErrorMap;
}
__name(getErrorMap, "getErrorMap");

// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js
var makeIssue = /* @__PURE__ */ __name((params) => {
  const { data, path, errorMaps, issueData } = params;
  const fullPath = [...path, ...issueData.path || []];
  const fullIssue = {
    ...issueData,
    path: fullPath
  };
  if (issueData.message !== void 0) {
    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
  };
}, "makeIssue");
var EMPTY_PATH = [];
function addIssueToContext(ctx, issueData) {
  const overrideMap = getErrorMap();
  const issue = makeIssue({
    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 === en_default ? void 0 : en_default
      // then global default map
    ].filter((x) => !!x)
  });
  ctx.common.issues.push(issue);
}
__name(addIssueToContext, "addIssueToContext");
var ParseStatus = class {
  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 };
  }
};
__name(ParseStatus, "ParseStatus");
var INVALID = Object.freeze({
  status: "aborted"
});
var DIRTY = /* @__PURE__ */ __name((value) => ({ status: "dirty", value }), "DIRTY");
var OK = /* @__PURE__ */ __name((value) => ({ status: "valid", value }), "OK");
var isAborted = /* @__PURE__ */ __name((x) => x.status === "aborted", "isAborted");
var isDirty = /* @__PURE__ */ __name((x) => x.status === "dirty", "isDirty");
var isValid = /* @__PURE__ */ __name((x) => x.status === "valid", "isValid");
var isAsync = /* @__PURE__ */ __name((x) => typeof Promise !== "undefined" && x instanceof Promise, "isAsync");

// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/errorUtil.js
var errorUtil;
(function(errorUtil2) {
  errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
  errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
})(errorUtil || (errorUtil = {}));

// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/types.js
var ParseInputLazyPath = class {
  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 (Array.isArray(this._key)) {
        this._cachedPath.push(...this._path, ...this._key);
      } else {
        this._cachedPath.push(...this._path, this._key);
      }
    }
    return this._cachedPath;
  }
};
__name(ParseInputLazyPath, "ParseInputLazyPath");
var handleResult = /* @__PURE__ */ __name((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 error3 = new ZodError(ctx.common.issues);
        this._error = error3;
        return this._error;
      }
    };
  }
}, "handleResult");
function processCreateParams(params) {
  if (!params)
    return {};
  const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
  if (errorMap2 && (invalid_type_error || required_error)) {
    throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
  }
  if (errorMap2)
    return { errorMap: errorMap2, description };
  const customMap = /* @__PURE__ */ __name((iss, ctx) => {
    const { message } = params;
    if (iss.code === "invalid_enum_value") {
      return { message: message ?? ctx.defaultError };
    }
    if (typeof ctx.data === "undefined") {
      return { message: message ?? required_error ?? ctx.defaultError };
    }
    if (iss.code !== "invalid_type")
      return { message: ctx.defaultError };
    return { message: message ?? invalid_type_error ?? ctx.defaultError };
  }, "customMap");
  return { errorMap: customMap, description };
}
__name(processCreateParams, "processCreateParams");
var ZodType = class {
  get description() {
    return this._def.description;
  }
  _getType(input2) {
    return getParsedType(input2.data);
  }
  _getOrReturnCtx(input2, ctx) {
    return ctx || {
      common: input2.parent.common,
      data: input2.data,
      parsedType: getParsedType(input2.data),
      schemaErrorMap: this._def.errorMap,
      path: input2.path,
      parent: input2.parent
    };
  }
  _processInputParams(input2) {
    return {
      status: new ParseStatus(),
      ctx: {
        common: input2.parent.common,
        data: input2.data,
        parsedType: getParsedType(input2.data),
        schemaErrorMap: this._def.errorMap,
        path: input2.path,
        parent: input2.parent
      }
    };
  }
  _parseSync(input2) {
    const result = this._parse(input2);
    if (isAsync(result)) {
      throw new Error("Synchronous parse encountered promise.");
    }
    return result;
  }
  _parseAsync(input2) {
    const result = this._parse(input2);
    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) {
    const ctx = {
      common: {
        issues: [],
        async: params?.async ?? false,
        contextualErrorMap: params?.errorMap
      },
      path: 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) {
    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 (err?.message?.toLowerCase()?.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?.errorMap,
        async: true
      },
      path: 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 = /* @__PURE__ */ __name((val) => {
      if (typeof message === "string" || typeof message === "undefined") {
        return { message };
      } else if (typeof message === "function") {
        return message(val);
      } else {
        return message;
      }
    }, "getIssueProperties");
    return this._refinement((val, ctx) => {
      const result = check(val);
      const setError = /* @__PURE__ */ __name(() => ctx.addIssue({
        code: ZodIssueCode.custom,
        ...getIssueProperties(val)
      }), "setError");
      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) {
    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(void 0).success;
  }
  isNullable() {
    return this.safeParse(null).success;
  }
};
__name(ZodType, "ZodType");
var cuidRegex = /^c[^\s-]{8,}$/i;
var cuid2Regex = /^[0-9a-z]+$/;
var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
var 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;
var nanoidRegex = /^[a-z0-9_-]{21}$/i;
var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
var 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)?)??$/;
var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
var emojiRegex;
var 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])$/;
var 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])$/;
var 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]))$/;
var 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])$/;
var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
var 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])))`;
var dateRegex = new RegExp(`^${dateRegexSource}$`);
function timeRegexSource(args) {
  let secondsRegexSource = `[0-5]\\d`;
  if (args.precision) {
    secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
  } else if (args.precision == null) {
    secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
  }
  const secondsQuantifier = args.precision ? "+" : "?";
  return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
}
__name(timeRegexSource, "timeRegexSource");
function timeRegex(args) {
  return new RegExp(`^${timeRegexSource(args)}$`);
}
__name(timeRegex, "timeRegex");
function datetimeRegex(args) {
  let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
  const opts = [];
  opts.push(args.local ? `Z?` : `Z`);
  if (args.offset)
    opts.push(`([+-]\\d{2}:?\\d{2})`);
  regex = `${regex}(${opts.join("|")})`;
  return new RegExp(`^${regex}$`);
}
__name(datetimeRegex, "datetimeRegex");
function isValidIP(ip2, version2) {
  if ((version2 === "v4" || !version2) && ipv4Regex.test(ip2)) {
    return true;
  }
  if ((version2 === "v6" || !version2) && ipv6Regex.test(ip2)) {
    return true;
  }
  return false;
}
__name(isValidIP, "isValidIP");
function isValidJWT(jwt, alg) {
  if (!jwtRegex.test(jwt))
    return false;
  try {
    const [header] = jwt.split(".");
    if (!header)
      return false;
    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 ("typ" in decoded && decoded?.typ !== "JWT")
      return false;
    if (!decoded.alg)
      return false;
    if (alg && decoded.alg !== alg)
      return false;
    return true;
  } catch {
    return false;
  }
}
__name(isValidJWT, "isValidJWT");
function isValidCidr(ip2, version2) {
  if ((version2 === "v4" || !version2) && ipv4CidrRegex.test(ip2)) {
    return true;
  }
  if ((version2 === "v6" || !version2) && ipv6CidrRegex.test(ip2)) {
    return true;
  }
  return false;
}
__name(isValidCidr, "isValidCidr");
var ZodString = class extends ZodType {
  _parse(input2) {
    if (this._def.coerce) {
      input2.data = String(input2.data);
    }
    const parsedType = this._getType(input2);
    if (parsedType !== ZodParsedType.string) {
      const ctx2 = this._getOrReturnCtx(input2);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.string,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    const status = new ParseStatus();
    let ctx = void 0;
    for (const check of this._def.checks) {
      if (check.kind === "min") {
        if (input2.data.length < check.value) {
          ctx = this._getOrReturnCtx(input2, 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 (input2.data.length > check.value) {
          ctx = this._getOrReturnCtx(input2, 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 = input2.data.length > check.value;
        const tooSmall = input2.data.length < check.value;
        if (tooBig || tooSmall) {
          ctx = this._getOrReturnCtx(input2, 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(input2.data)) {
          ctx = this._getOrReturnCtx(input2, 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(input2.data)) {
          ctx = this._getOrReturnCtx(input2, ctx);
          addIssueToContext(ctx, {
            validation: "emoji",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "uuid") {
        if (!uuidRegex.test(input2.data)) {
          ctx = this._getOrReturnCtx(input2, ctx);
          addIssueToContext(ctx, {
            validation: "uuid",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "nanoid") {
        if (!nanoidRegex.test(input2.data)) {
          ctx = this._getOrReturnCtx(input2, ctx);
          addIssueToContext(ctx, {
            validation: "nanoid",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "cuid") {
        if (!cuidRegex.test(input2.data)) {
          ctx = this._getOrReturnCtx(input2, ctx);
          addIssueToContext(ctx, {
            validation: "cuid",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "cuid2") {
        if (!cuid2Regex.test(input2.data)) {
          ctx = this._getOrReturnCtx(input2, ctx);
          addIssueToContext(ctx, {
            validation: "cuid2",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "ulid") {
        if (!ulidRegex.test(input2.data)) {
          ctx = this._getOrReturnCtx(input2, ctx);
          addIssueToContext(ctx, {
            validation: "ulid",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "url") {
        try {
          new URL(input2.data);
        } catch {
          ctx = this._getOrReturnCtx(input2, 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(input2.data);
        if (!testResult) {
          ctx = this._getOrReturnCtx(input2, ctx);
          addIssueToContext(ctx, {
            validation: "regex",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "trim") {
        input2.data = input2.data.trim();
      } else if (check.kind === "includes") {
        if (!input2.data.includes(check.value, check.position)) {
          ctx = this._getOrReturnCtx(input2, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: { includes: check.value, position: check.position },
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "toLowerCase") {
        input2.data = input2.data.toLowerCase();
      } else if (check.kind === "toUpperCase") {
        input2.data = input2.data.toUpperCase();
      } else if (check.kind === "startsWith") {
        if (!input2.data.startsWith(check.value)) {
          ctx = this._getOrReturnCtx(input2, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: { startsWith: check.value },
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "endsWith") {
        if (!input2.data.endsWith(check.value)) {
          ctx = this._getOrReturnCtx(input2, 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(input2.data)) {
          ctx = this._getOrReturnCtx(input2, 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(input2.data)) {
          ctx = this._getOrReturnCtx(input2, 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(input2.data)) {
          ctx = this._getOrReturnCtx(input2, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: "time",
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "duration") {
        if (!durationRegex.test(input2.data)) {
          ctx = this._getOrReturnCtx(input2, ctx);
          addIssueToContext(ctx, {
            validation: "duration",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "ip") {
        if (!isValidIP(input2.data, check.version)) {
          ctx = this._getOrReturnCtx(input2, ctx);
          addIssueToContext(ctx, {
            validation: "ip",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "jwt") {
        if (!isValidJWT(input2.data, check.alg)) {
          ctx = this._getOrReturnCtx(input2, ctx);
          addIssueToContext(ctx, {
            validation: "jwt",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "cidr") {
        if (!isValidCidr(input2.data, check.version)) {
          ctx = this._getOrReturnCtx(input2, ctx);
          addIssueToContext(ctx, {
            validation: "cidr",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "base64") {
        if (!base64Regex.test(input2.data)) {
          ctx = this._getOrReturnCtx(input2, ctx);
          addIssueToContext(ctx, {
            validation: "base64",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "base64url") {
        if (!base64urlRegex.test(input2.data)) {
          ctx = this._getOrReturnCtx(input2, ctx);
          addIssueToContext(ctx, {
            validation: "base64url",
            code: ZodIssueCode.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else {
        util.assertNever(check);
      }
    }
    return { status: status.value, value: input2.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) {
    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) {
    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?.precision === "undefined" ? null : options?.precision,
      offset: options?.offset ?? false,
      local: options?.local ?? false,
      ...errorUtil.errToObj(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?.precision === "undefined" ? null : options?.precision,
      ...errorUtil.errToObj(options?.message)
    });
  }
  duration(message) {
    return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
  }
  regex(regex, message) {
    return this._addCheck({
      kind: "regex",
      regex,
      ...errorUtil.errToObj(message)
    });
  }
  includes(value, options) {
    return this._addCheck({
      kind: "includes",
      value,
      position: options?.position,
      ...errorUtil.errToObj(options?.message)
    });
  }
  startsWith(value, message) {
    return this._addCheck({
      kind: "startsWith",
      value,
      ...errorUtil.errToObj(message)
    });
  }
  endsWith(value, message) {
    return this._addCheck({
      kind: "endsWith",
      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() {
    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;
  }
};
__name(ZodString, "ZodString");
ZodString.create = (params) => {
  return new ZodString({
    checks: [],
    typeName: ZodFirstPartyTypeKind.ZodString,
    coerce: params?.coerce ?? false,
    ...processCreateParams(params)
  });
};
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 = Number.parseInt(val.toFixed(decCount).replace(".", ""));
  const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
  return valInt % stepInt / 10 ** decCount;
}
__name(floatSafeRemainder, "floatSafeRemainder");
var ZodNumber = class extends ZodType {
  constructor() {
    super(...arguments);
    this.min = this.gte;
    this.max = this.lte;
    this.step = this.multipleOf;
  }
  _parse(input2) {
    if (this._def.coerce) {
      input2.data = Number(input2.data);
    }
    const parsedType = this._getType(input2);
    if (parsedType !== ZodParsedType.number) {
      const ctx2 = this._getOrReturnCtx(input2);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.number,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    let ctx = void 0;
    const status = new ParseStatus();
    for (const check of this._def.checks) {
      if (check.kind === "int") {
        if (!util.isInteger(input2.data)) {
          ctx = this._getOrReturnCtx(input2, 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 ? input2.data < check.value : input2.data <= check.value;
        if (tooSmall) {
          ctx = this._getOrReturnCtx(input2, 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 ? input2.data > check.value : input2.data >= check.value;
        if (tooBig) {
          ctx = this._getOrReturnCtx(input2, 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(input2.data, check.value) !== 0) {
          ctx = this._getOrReturnCtx(input2, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.not_multiple_of,
            multipleOf: check.value,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "finite") {
        if (!Number.isFinite(input2.data)) {
          ctx = this._getOrReturnCtx(input2, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.not_finite,
            message: check.message
          });
          status.dirty();
        }
      } else {
        util.assertNever(check);
      }
    }
    return { status: status.value, value: input2.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,
      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;
    let 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);
  }
};
__name(ZodNumber, "ZodNumber");
ZodNumber.create = (params) => {
  return new ZodNumber({
    checks: [],
    typeName: ZodFirstPartyTypeKind.ZodNumber,
    coerce: params?.coerce || false,
    ...processCreateParams(params)
  });
};
var ZodBigInt = class extends ZodType {
  constructor() {
    super(...arguments);
    this.min = this.gte;
    this.max = this.lte;
  }
  _parse(input2) {
    if (this._def.coerce) {
      try {
        input2.data = BigInt(input2.data);
      } catch {
        return this._getInvalidInput(input2);
      }
    }
    const parsedType = this._getType(input2);
    if (parsedType !== ZodParsedType.bigint) {
      return this._getInvalidInput(input2);
    }
    let ctx = void 0;
    const status = new ParseStatus();
    for (const check of this._def.checks) {
      if (check.kind === "min") {
        const tooSmall = check.inclusive ? input2.data < check.value : input2.data <= check.value;
        if (tooSmall) {
          ctx = this._getOrReturnCtx(input2, 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 ? input2.data > check.value : input2.data >= check.value;
        if (tooBig) {
          ctx = this._getOrReturnCtx(input2, 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 (input2.data % check.value !== BigInt(0)) {
          ctx = this._getOrReturnCtx(input2, 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: input2.data };
  }
  _getInvalidInput(input2) {
    const ctx = this._getOrReturnCtx(input2);
    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;
  }
};
__name(ZodBigInt, "ZodBigInt");
ZodBigInt.create = (params) => {
  return new ZodBigInt({
    checks: [],
    typeName: ZodFirstPartyTypeKind.ZodBigInt,
    coerce: params?.coerce ?? false,
    ...processCreateParams(params)
  });
};
var ZodBoolean = class extends ZodType {
  _parse(input2) {
    if (this._def.coerce) {
      input2.data = Boolean(input2.data);
    }
    const parsedType = this._getType(input2);
    if (parsedType !== ZodParsedType.boolean) {
      const ctx = this._getOrReturnCtx(input2);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.boolean,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input2.data);
  }
};
__name(ZodBoolean, "ZodBoolean");
ZodBoolean.create = (params) => {
  return new ZodBoolean({
    typeName: ZodFirstPartyTypeKind.ZodBoolean,
    coerce: params?.coerce || false,
    ...processCreateParams(params)
  });
};
var ZodDate = class extends ZodType {
  _parse(input2) {
    if (this._def.coerce) {
      input2.data = new Date(input2.data);
    }
    const parsedType = this._getType(input2);
    if (parsedType !== ZodParsedType.date) {
      const ctx2 = this._getOrReturnCtx(input2);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.date,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    if (Number.isNaN(input2.data.getTime())) {
      const ctx2 = this._getOrReturnCtx(input2);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_date
      });
      return INVALID;
    }
    const status = new ParseStatus();
    let ctx = void 0;
    for (const check of this._def.checks) {
      if (check.kind === "min") {
        if (input2.data.getTime() < check.value) {
          ctx = this._getOrReturnCtx(input2, 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 (input2.data.getTime() > check.value) {
          ctx = this._getOrReturnCtx(input2, 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(input2.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;
  }
};
__name(ZodDate, "ZodDate");
ZodDate.create = (params) => {
  return new ZodDate({
    checks: [],
    coerce: params?.coerce || false,
    typeName: ZodFirstPartyTypeKind.ZodDate,
    ...processCreateParams(params)
  });
};
var ZodSymbol = class extends ZodType {
  _parse(input2) {
    const parsedType = this._getType(input2);
    if (parsedType !== ZodParsedType.symbol) {
      const ctx = this._getOrReturnCtx(input2);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.symbol,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input2.data);
  }
};
__name(ZodSymbol, "ZodSymbol");
ZodSymbol.create = (params) => {
  return new ZodSymbol({
    typeName: ZodFirstPartyTypeKind.ZodSymbol,
    ...processCreateParams(params)
  });
};
var ZodUndefined = class extends ZodType {
  _parse(input2) {
    const parsedType = this._getType(input2);
    if (parsedType !== ZodParsedType.undefined) {
      const ctx = this._getOrReturnCtx(input2);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.undefined,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input2.data);
  }
};
__name(ZodUndefined, "ZodUndefined");
ZodUndefined.create = (params) => {
  return new ZodUndefined({
    typeName: ZodFirstPartyTypeKind.ZodUndefined,
    ...processCreateParams(params)
  });
};
var ZodNull = class extends ZodType {
  _parse(input2) {
    const parsedType = this._getType(input2);
    if (parsedType !== ZodParsedType.null) {
      const ctx = this._getOrReturnCtx(input2);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.null,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input2.data);
  }
};
__name(ZodNull, "ZodNull");
ZodNull.create = (params) => {
  return new ZodNull({
    typeName: ZodFirstPartyTypeKind.ZodNull,
    ...processCreateParams(params)
  });
};
var ZodAny = class extends ZodType {
  constructor() {
    super(...arguments);
    this._any = true;
  }
  _parse(input2) {
    return OK(input2.data);
  }
};
__name(ZodAny, "ZodAny");
ZodAny.create = (params) => {
  return new ZodAny({
    typeName: ZodFirstPartyTypeKind.ZodAny,
    ...processCreateParams(params)
  });
};
var ZodUnknown = class extends ZodType {
  constructor() {
    super(...arguments);
    this._unknown = true;
  }
  _parse(input2) {
    return OK(input2.data);
  }
};
__name(ZodUnknown, "ZodUnknown");
ZodUnknown.create = (params) => {
  return new ZodUnknown({
    typeName: ZodFirstPartyTypeKind.ZodUnknown,
    ...processCreateParams(params)
  });
};
var ZodNever = class extends ZodType {
  _parse(input2) {
    const ctx = this._getOrReturnCtx(input2);
    addIssueToContext(ctx, {
      code: ZodIssueCode.invalid_type,
      expected: ZodParsedType.never,
      received: ctx.parsedType
    });
    return INVALID;
  }
};
__name(ZodNever, "ZodNever");
ZodNever.create = (params) => {
  return new ZodNever({
    typeName: ZodFirstPartyTypeKind.ZodNever,
    ...processCreateParams(params)
  });
};
var ZodVoid = class extends ZodType {
  _parse(input2) {
    const parsedType = this._getType(input2);
    if (parsedType !== ZodParsedType.undefined) {
      const ctx = this._getOrReturnCtx(input2);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.void,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK(input2.data);
  }
};
__name(ZodVoid, "ZodVoid");
ZodVoid.create = (params) => {
  return new ZodVoid({
    typeName: ZodFirstPartyTypeKind.ZodVoid,
    ...processCreateParams(params)
  });
};
var ZodArray = class extends ZodType {
  _parse(input2) {
    const { ctx, status } = this._processInputParams(input2);
    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 : void 0,
          maximum: tooBig ? def.exactLength.value : void 0,
          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((result2) => {
        return ParseStatus.mergeArray(status, result2);
      });
    }
    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);
  }
};
__name(ZodArray, "ZodArray");
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;
  }
}
__name(deepPartialify, "deepPartialify");
var ZodObject = class extends ZodType {
  constructor() {
    super(...arguments);
    this._cached = null;
    this.nonstrict = this.passthrough;
    this.augment = this.extend;
  }
  _getCached() {
    if (this._cached !== null)
      return this._cached;
    const shape = this._def.shape();
    const keys = util.objectKeys(shape);
    this._cached = { shape, keys };
    return this._cached;
  }
  _parse(input2) {
    const parsedType = this._getType(input2);
    if (parsedType !== ZodParsedType.object) {
      const ctx2 = this._getOrReturnCtx(input2);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.object,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    const { status, ctx } = this._processInputParams(input2);
    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 {
      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 !== void 0 ? {
        errorMap: (issue, ctx) => {
          const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
          if (issue.code === "unrecognized_keys")
            return {
              message: errorUtil.errToObj(message).message ?? 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 = {};
    for (const key of util.objectKeys(mask)) {
      if (mask[key] && this.shape[key]) {
        shape[key] = this.shape[key];
      }
    }
    return new ZodObject({
      ...this._def,
      shape: () => shape
    });
  }
  omit(mask) {
    const shape = {};
    for (const key of util.objectKeys(this.shape)) {
      if (!mask[key]) {
        shape[key] = this.shape[key];
      }
    }
    return new ZodObject({
      ...this._def,
      shape: () => shape
    });
  }
  /**
   * @deprecated
   */
  deepPartial() {
    return deepPartialify(this);
  }
  partial(mask) {
    const newShape = {};
    for (const key of util.objectKeys(this.shape)) {
      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 = {};
    for (const key of util.objectKeys(this.shape)) {
      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));
  }
};
__name(ZodObject, "ZodObject");
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)
  });
};
var ZodUnion = class extends ZodType {
  _parse(input2) {
    const { ctx } = this._processInputParams(input2);
    const options = this._def.options;
    function handleResults(results) {
      for (const result of results) {
        if (result.result.status === "valid") {
          return result.result;
        }
      }
      for (const result of results) {
        if (result.result.status === "dirty") {
          ctx.common.issues.push(...result.ctx.common.issues);
          return result.result;
        }
      }
      const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_union,
        unionErrors
      });
      return INVALID;
    }
    __name(handleResults, "handleResults");
    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 = void 0;
      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((issues2) => new ZodError(issues2));
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_union,
        unionErrors
      });
      return INVALID;
    }
  }
  get options() {
    return this._def.options;
  }
};
__name(ZodUnion, "ZodUnion");
ZodUnion.create = (types, params) => {
  return new ZodUnion({
    options: types,
    typeName: ZodFirstPartyTypeKind.ZodUnion,
    ...processCreateParams(params)
  });
};
var getDiscriminator = /* @__PURE__ */ __name((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) {
    return util.objectValues(type.enum);
  } else if (type instanceof ZodDefault) {
    return getDiscriminator(type._def.innerType);
  } else if (type instanceof ZodUndefined) {
    return [void 0];
  } else if (type instanceof ZodNull) {
    return [null];
  } else if (type instanceof ZodOptional) {
    return [void 0, ...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 [];
  }
}, "getDiscriminator");
var ZodDiscriminatedUnion = class extends ZodType {
  _parse(input2) {
    const { ctx } = this._processInputParams(input2);
    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) {
    const optionsMap = /* @__PURE__ */ new Map();
    for (const type of options) {
      const discriminatorValues = getDiscriminator(type.shape[discriminator]);
      if (!discriminatorValues.length) {
        throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
      }
      for (const value of discriminatorValues) {
        if (optionsMap.has(value)) {
          throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
        }
        optionsMap.set(value, type);
      }
    }
    return new ZodDiscriminatedUnion({
      typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
      discriminator,
      options,
      optionsMap,
      ...processCreateParams(params)
    });
  }
};
__name(ZodDiscriminatedUnion, "ZodDiscriminatedUnion");
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 };
  }
}
__name(mergeValues, "mergeValues");
var ZodIntersection = class extends ZodType {
  _parse(input2) {
    const { status, ctx } = this._processInputParams(input2);
    const handleParsed = /* @__PURE__ */ __name((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 };
    }, "handleParsed");
    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(([left, right]) => 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
      }));
    }
  }
};
__name(ZodIntersection, "ZodIntersection");
ZodIntersection.create = (left, right, params) => {
  return new ZodIntersection({
    left,
    right,
    typeName: ZodFirstPartyTypeKind.ZodIntersection,
    ...processCreateParams(params)
  });
};
var ZodTuple = class extends ZodType {
  _parse(input2) {
    const { status, ctx } = this._processInputParams(input2);
    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);
    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
    });
  }
};
__name(ZodTuple, "ZodTuple");
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)
  });
};
var ZodRecord = class extends ZodType {
  get keySchema() {
    return this._def.keyType;
  }
  get valueSchema() {
    return this._def.valueType;
  }
  _parse(input2) {
    const { status, ctx } = this._processInputParams(input2);
    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(first2, second, third) {
    if (second instanceof ZodType) {
      return new ZodRecord({
        keyType: first2,
        valueType: second,
        typeName: ZodFirstPartyTypeKind.ZodRecord,
        ...processCreateParams(third)
      });
    }
    return new ZodRecord({
      keyType: ZodString.create(),
      valueType: first2,
      typeName: ZodFirstPartyTypeKind.ZodRecord,
      ...processCreateParams(second)
    });
  }
};
__name(ZodRecord, "ZodRecord");
var ZodMap = class extends ZodType {
  get keySchema() {
    return this._def.keyType;
  }
  get valueSchema() {
    return this._def.valueType;
  }
  _parse(input2) {
    const { status, ctx } = this._processInputParams(input2);
    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(([key, value], index) => {
      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 = /* @__PURE__ */ 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 = /* @__PURE__ */ 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 };
    }
  }
};
__name(ZodMap, "ZodMap");
ZodMap.create = (keyType, valueType, params) => {
  return new ZodMap({
    valueType,
    keyType,
    typeName: ZodFirstPartyTypeKind.ZodMap,
    ...processCreateParams(params)
  });
};
var ZodSet = class extends ZodType {
  _parse(input2) {
    const { status, ctx } = this._processInputParams(input2);
    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(elements2) {
      const parsedSet = /* @__PURE__ */ new Set();
      for (const element of elements2) {
        if (element.status === "aborted")
          return INVALID;
        if (element.status === "dirty")
          status.dirty();
        parsedSet.add(element.value);
      }
      return { status: status.value, value: parsedSet };
    }
    __name(finalizeSet, "finalizeSet");
    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((elements2) => finalizeSet(elements2));
    } 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);
  }
};
__name(ZodSet, "ZodSet");
ZodSet.create = (valueType, params) => {
  return new ZodSet({
    valueType,
    minSize: null,
    maxSize: null,
    typeName: ZodFirstPartyTypeKind.ZodSet,
    ...processCreateParams(params)
  });
};
var ZodFunction = class extends ZodType {
  constructor() {
    super(...arguments);
    this.validate = this.implement;
  }
  _parse(input2) {
    const { ctx } = this._processInputParams(input2);
    if (ctx.parsedType !== ZodParsedType.function) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.function,
        received: ctx.parsedType
      });
      return INVALID;
    }
    function makeArgsIssue(args, error3) {
      return makeIssue({
        data: args,
        path: ctx.path,
        errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
        issueData: {
          code: ZodIssueCode.invalid_arguments,
          argumentsError: error3
        }
      });
    }
    __name(makeArgsIssue, "makeArgsIssue");
    function makeReturnsIssue(returns, error3) {
      return makeIssue({
        data: returns,
        path: ctx.path,
        errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
        issueData: {
          code: ZodIssueCode.invalid_return_type,
          returnTypeError: error3
        }
      });
    }
    __name(makeReturnsIssue, "makeReturnsIssue");
    const params = { errorMap: ctx.common.contextualErrorMap };
    const fn = ctx.data;
    if (this._def.returns instanceof ZodPromise) {
      const me = this;
      return OK(async function(...args) {
        const error3 = new ZodError([]);
        const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
          error3.addIssue(makeArgsIssue(args, e));
          throw error3;
        });
        const result = await Reflect.apply(fn, this, parsedArgs);
        const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
          error3.addIssue(makeReturnsIssue(result, e));
          throw error3;
        });
        return parsedReturns;
      });
    } else {
      const me = this;
      return OK(function(...args) {
        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(...items) {
    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)
    });
  }
};
__name(ZodFunction, "ZodFunction");
var ZodLazy = class extends ZodType {
  get schema() {
    return this._def.getter();
  }
  _parse(input2) {
    const { ctx } = this._processInputParams(input2);
    const lazySchema = this._def.getter();
    return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
  }
};
__name(ZodLazy, "ZodLazy");
ZodLazy.create = (getter, params) => {
  return new ZodLazy({
    getter,
    typeName: ZodFirstPartyTypeKind.ZodLazy,
    ...processCreateParams(params)
  });
};
var ZodLiteral = class extends ZodType {
  _parse(input2) {
    if (input2.data !== this._def.value) {
      const ctx = this._getOrReturnCtx(input2);
      addIssueToContext(ctx, {
        received: ctx.data,
        code: ZodIssueCode.invalid_literal,
        expected: this._def.value
      });
      return INVALID;
    }
    return { status: "valid", value: input2.data };
  }
  get value() {
    return this._def.value;
  }
};
__name(ZodLiteral, "ZodLiteral");
ZodLiteral.create = (value, params) => {
  return new ZodLiteral({
    value,
    typeName: ZodFirstPartyTypeKind.ZodLiteral,
    ...processCreateParams(params)
  });
};
function createZodEnum(values, params) {
  return new ZodEnum({
    values,
    typeName: ZodFirstPartyTypeKind.ZodEnum,
    ...processCreateParams(params)
  });
}
__name(createZodEnum, "createZodEnum");
var ZodEnum = class extends ZodType {
  _parse(input2) {
    if (typeof input2.data !== "string") {
      const ctx = this._getOrReturnCtx(input2);
      const expectedValues = this._def.values;
      addIssueToContext(ctx, {
        expected: util.joinValues(expectedValues),
        received: ctx.parsedType,
        code: ZodIssueCode.invalid_type
      });
      return INVALID;
    }
    if (!this._cache) {
      this._cache = new Set(this._def.values);
    }
    if (!this._cache.has(input2.data)) {
      const ctx = this._getOrReturnCtx(input2);
      const expectedValues = this._def.values;
      addIssueToContext(ctx, {
        received: ctx.data,
        code: ZodIssueCode.invalid_enum_value,
        options: expectedValues
      });
      return INVALID;
    }
    return OK(input2.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, newDef = this._def) {
    return ZodEnum.create(values, {
      ...this._def,
      ...newDef
    });
  }
  exclude(values, newDef = this._def) {
    return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
      ...this._def,
      ...newDef
    });
  }
};
__name(ZodEnum, "ZodEnum");
ZodEnum.create = createZodEnum;
var ZodNativeEnum = class extends ZodType {
  _parse(input2) {
    const nativeEnumValues = util.getValidEnumValues(this._def.values);
    const ctx = this._getOrReturnCtx(input2);
    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 (!this._cache) {
      this._cache = new Set(util.getValidEnumValues(this._def.values));
    }
    if (!this._cache.has(input2.data)) {
      const expectedValues = util.objectValues(nativeEnumValues);
      addIssueToContext(ctx, {
        received: ctx.data,
        code: ZodIssueCode.invalid_enum_value,
        options: expectedValues
      });
      return INVALID;
    }
    return OK(input2.data);
  }
  get enum() {
    return this._def.values;
  }
};
__name(ZodNativeEnum, "ZodNativeEnum");
ZodNativeEnum.create = (values, params) => {
  return new ZodNativeEnum({
    values,
    typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
    ...processCreateParams(params)
  });
};
var ZodPromise = class extends ZodType {
  unwrap() {
    return this._def.type;
  }
  _parse(input2) {
    const { ctx } = this._processInputParams(input2);
    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
      });
    }));
  }
};
__name(ZodPromise, "ZodPromise");
ZodPromise.create = (schema, params) => {
  return new ZodPromise({
    type: schema,
    typeName: ZodFirstPartyTypeKind.ZodPromise,
    ...processCreateParams(params)
  });
};
var ZodEffects = class extends ZodType {
  innerType() {
    return this._def.schema;
  }
  sourceType() {
    return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
  }
  _parse(input2) {
    const { status, ctx } = this._processInputParams(input2);
    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 (processed2) => {
          if (status.value === "aborted")
            return INVALID;
          const result = await this._def.schema._parseAsync({
            data: processed2,
            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 = /* @__PURE__ */ __name((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;
      }, "executeRefinement");
      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();
        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 INVALID;
        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 INVALID;
          return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
            status: status.value,
            value: result
          }));
        });
      }
    }
    util.assertNever(effect);
  }
};
__name(ZodEffects, "ZodEffects");
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)
  });
};
var ZodOptional = class extends ZodType {
  _parse(input2) {
    const parsedType = this._getType(input2);
    if (parsedType === ZodParsedType.undefined) {
      return OK(void 0);
    }
    return this._def.innerType._parse(input2);
  }
  unwrap() {
    return this._def.innerType;
  }
};
__name(ZodOptional, "ZodOptional");
ZodOptional.create = (type, params) => {
  return new ZodOptional({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodOptional,
    ...processCreateParams(params)
  });
};
var ZodNullable = class extends ZodType {
  _parse(input2) {
    const parsedType = this._getType(input2);
    if (parsedType === ZodParsedType.null) {
      return OK(null);
    }
    return this._def.innerType._parse(input2);
  }
  unwrap() {
    return this._def.innerType;
  }
};
__name(ZodNullable, "ZodNullable");
ZodNullable.create = (type, params) => {
  return new ZodNullable({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodNullable,
    ...processCreateParams(params)
  });
};
var ZodDefault = class extends ZodType {
  _parse(input2) {
    const { ctx } = this._processInputParams(input2);
    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;
  }
};
__name(ZodDefault, "ZodDefault");
ZodDefault.create = (type, params) => {
  return new ZodDefault({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodDefault,
    defaultValue: typeof params.default === "function" ? params.default : () => params.default,
    ...processCreateParams(params)
  });
};
var ZodCatch = class extends ZodType {
  _parse(input2) {
    const { ctx } = this._processInputParams(input2);
    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((result2) => {
        return {
          status: "valid",
          value: result2.status === "valid" ? result2.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;
  }
};
__name(ZodCatch, "ZodCatch");
ZodCatch.create = (type, params) => {
  return new ZodCatch({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodCatch,
    catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
    ...processCreateParams(params)
  });
};
var ZodNaN = class extends ZodType {
  _parse(input2) {
    const parsedType = this._getType(input2);
    if (parsedType !== ZodParsedType.nan) {
      const ctx = this._getOrReturnCtx(input2);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.nan,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return { status: "valid", value: input2.data };
  }
};
__name(ZodNaN, "ZodNaN");
ZodNaN.create = (params) => {
  return new ZodNaN({
    typeName: ZodFirstPartyTypeKind.ZodNaN,
    ...processCreateParams(params)
  });
};
var BRAND = Symbol("zod_brand");
var ZodBranded = class extends ZodType {
  _parse(input2) {
    const { ctx } = this._processInputParams(input2);
    const data = ctx.data;
    return this._def.type._parse({
      data,
      path: ctx.path,
      parent: ctx
    });
  }
  unwrap() {
    return this._def.type;
  }
};
__name(ZodBranded, "ZodBranded");
var ZodPipeline = class extends ZodType {
  _parse(input2) {
    const { status, ctx } = this._processInputParams(input2);
    if (ctx.common.async) {
      const handleAsync = /* @__PURE__ */ __name(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
          });
        }
      }, "handleAsync");
      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
    });
  }
};
__name(ZodPipeline, "ZodPipeline");
var ZodReadonly = class extends ZodType {
  _parse(input2) {
    const result = this._def.innerType._parse(input2);
    const freeze = /* @__PURE__ */ __name((data) => {
      if (isValid(data)) {
        data.value = Object.freeze(data.value);
      }
      return data;
    }, "freeze");
    return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
  }
  unwrap() {
    return this._def.innerType;
  }
};
__name(ZodReadonly, "ZodReadonly");
ZodReadonly.create = (type, params) => {
  return new ZodReadonly({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodReadonly,
    ...processCreateParams(params)
  });
};
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;
}
__name(cleanParams, "cleanParams");
function custom(check, _params = {}, fatal) {
  if (check)
    return ZodAny.create().superRefine((data, ctx) => {
      const r = check(data);
      if (r instanceof Promise) {
        return r.then((r2) => {
          if (!r2) {
            const params = cleanParams(_params, data);
            const _fatal = params.fatal ?? fatal ?? true;
            ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
          }
        });
      }
      if (!r) {
        const params = cleanParams(_params, data);
        const _fatal = params.fatal ?? fatal ?? true;
        ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
      }
      return;
    });
  return ZodAny.create();
}
__name(custom, "custom");
var late = {
  object: ZodObject.lazycreate
};
var ZodFirstPartyTypeKind;
(function(ZodFirstPartyTypeKind2) {
  ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
  ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
  ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
  ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
  ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
  ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
  ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
  ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
  ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
  ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
  ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
  ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
  ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
  ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
  ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
  ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
  ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
  ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
  ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
  ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
  ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
  ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
  ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
  ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
  ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
  ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
  ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
  ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
  ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
  ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
  ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
  ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
  ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
  ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
  ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
  ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
var instanceOfType = /* @__PURE__ */ __name((cls, params = {
  message: `Input not instance of ${cls.name}`
}) => custom((data) => data instanceof cls, params), "instanceOfType");
var stringType = ZodString.create;
var numberType = ZodNumber.create;
var nanType = ZodNaN.create;
var bigIntType = ZodBigInt.create;
var booleanType = ZodBoolean.create;
var dateType = ZodDate.create;
var symbolType = ZodSymbol.create;
var undefinedType = ZodUndefined.create;
var nullType = ZodNull.create;
var anyType = ZodAny.create;
var unknownType = ZodUnknown.create;
var neverType = ZodNever.create;
var voidType = ZodVoid.create;
var arrayType = ZodArray.create;
var objectType = ZodObject.create;
var strictObjectType = ZodObject.strictCreate;
var unionType = ZodUnion.create;
var discriminatedUnionType = ZodDiscriminatedUnion.create;
var intersectionType = ZodIntersection.create;
var tupleType = ZodTuple.create;
var recordType = ZodRecord.create;
var mapType = ZodMap.create;
var setType = ZodSet.create;
var functionType = ZodFunction.create;
var lazyType = ZodLazy.create;
var literalType = ZodLiteral.create;
var enumType = ZodEnum.create;
var nativeEnumType = ZodNativeEnum.create;
var promiseType = ZodPromise.create;
var effectsType = ZodEffects.create;
var optionalType = ZodOptional.create;
var nullableType = ZodNullable.create;
var preprocessType = ZodEffects.createWithPreprocess;
var pipelineType = ZodPipeline.create;
var ostring = /* @__PURE__ */ __name(() => stringType().optional(), "ostring");
var onumber = /* @__PURE__ */ __name(() => numberType().optional(), "onumber");
var oboolean = /* @__PURE__ */ __name(() => booleanType().optional(), "oboolean");
var 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 })
};
var NEVER = INVALID;

// src/services/ratelimit.ts
var RateLimitError = class extends Error {
  code = "RATE_LIMITED";
  status = 429;
};
__name(RateLimitError, "RateLimitError");
async function enforceRateLimit(env2, key, limit, windowSeconds) {
  const now = Math.floor(Date.now() / 1e3);
  const bucket = Math.floor(now / windowSeconds);
  const kvKey = `ratelimit:${key}:${bucket}`;
  const current = Number(await env2.KV.get(kvKey) || "0") + 1;
  await env2.KV.put(kvKey, String(current), { expirationTtl: windowSeconds + 30 });
  if (current > limit)
    throw new RateLimitError("\u64CD\u4F5C\u592A\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5");
  return { count: current, remaining: Math.max(0, limit - current) };
}
__name(enforceRateLimit, "enforceRateLimit");

// src/services/likes.ts
async function likePost(env2, postId, user) {
  const result = await env2.DB.prepare("INSERT OR IGNORE INTO wm_likes(post_id, user_id, created_at) VALUES (?, ?, ?)").bind(postId, user.id, nowSeconds()).run();
  const count3 = await env2.DB.prepare("SELECT like_count FROM wm_posts WHERE id = ?").bind(postId).first();
  return { already: result.meta.changes === 0, likeCount: count3?.like_count || 0 };
}
__name(likePost, "likePost");
async function unlikePost(env2, postId, user) {
  await env2.DB.prepare("DELETE FROM wm_likes WHERE post_id = ? AND user_id = ?").bind(postId, user.id).run();
  const count3 = await env2.DB.prepare("SELECT like_count FROM wm_posts WHERE id = ?").bind(postId).first();
  return { likeCount: count3?.like_count || 0 };
}
__name(unlikePost, "unlikePost");
async function listLikes(env2, settings, postId) {
  const rows = await all(
    env2.DB.prepare(
      `SELECT u.id, u.username, u.display_name, u.avatar_key
       FROM wm_likes l JOIN wm_users u ON u.id = l.user_id
       WHERE l.post_id = ?
       ORDER BY l.created_at ASC
       LIMIT 8`
    ).bind(postId)
  );
  const count3 = await env2.DB.prepare("SELECT like_count FROM wm_posts WHERE id = ?").bind(postId).first();
  return {
    users: rows.map((row) => ({
      id: row.id,
      username: row.username,
      displayName: row.display_name,
      avatarUrl: mediaUrl(settings.cdn_base_url, row.avatar_key)
    })),
    count: count3?.like_count || 0
  };
}
__name(listLikes, "listLikes");

// src/services/uploads.ts
function prefixForKind(kind) {
  if (kind === "video")
    return "videos";
  if (kind === "avatar")
    return "avatars";
  if (kind === "site")
    return "site";
  return "images";
}
__name(prefixForKind, "prefixForKind");
function validateUpload(kind, size, mime, settings) {
  if (kind === "image" || kind === "avatar" || kind === "site") {
    if (!isImageMime(mime))
      throw new Error("\u4E0D\u652F\u6301\u7684\u56FE\u7247\u683C\u5F0F");
    if (size > settings.upload_max_image_mb * 1024 * 1024)
      throw new Error(`\u56FE\u7247\u4E0D\u80FD\u8D85\u8FC7 ${settings.upload_max_image_mb}MB`);
    return;
  }
  if (!isVideoMime(mime))
    throw new Error("\u4E0D\u652F\u6301\u7684\u89C6\u9891\u683C\u5F0F");
  if (size > settings.upload_max_video_mb * 1024 * 1024)
    throw new Error(`\u89C6\u9891\u4E0D\u80FD\u8D85\u8FC7 ${settings.upload_max_video_mb}MB`);
}
__name(validateUpload, "validateUpload");
async function signUpload(env2, settings, user, input2, origin) {
  validateUpload(input2.kind, input2.size, input2.mime, settings);
  const ext = extensionFromMime(input2.mime, input2.filename);
  const key = `${prefixForKind(input2.kind)}/${user.id}/${ulid()}.${ext}`;
  const token = randomToken(32);
  const expiresAt = Math.floor(Date.now() / 1e3) + 300;
  const meta2 = {
    key,
    kind: input2.kind,
    userId: user.id,
    size: input2.size,
    mime: input2.mime,
    expiresAt
  };
  await env2.KV.put(`upload:${token}`, JSON.stringify(meta2), { expirationTtl: 300 });
  return {
    key,
    putUrl: `${origin}/api/uploads/direct/${encodeURIComponent(token)}`,
    headers: {
      "Content-Type": input2.mime,
      "X-Upload-Size": String(input2.size)
    },
    expiresAt
  };
}
__name(signUpload, "signUpload");
async function putSignedUpload(env2, token, request) {
  const meta2 = await env2.KV.get(`upload:${token}`, "json");
  if (!meta2)
    throw new Error("\u4E0A\u4F20\u94FE\u63A5\u5DF2\u8FC7\u671F");
  const contentType = request.headers.get("content-type") || "";
  const contentLength = Number(request.headers.get("content-length") || request.headers.get("x-upload-size") || "0");
  if (contentType.split(";")[0].toLowerCase() !== meta2.mime.toLowerCase())
    throw new Error("\u4E0A\u4F20\u7C7B\u578B\u4E0D\u5339\u914D");
  if (contentLength && contentLength !== meta2.size)
    throw new Error("\u4E0A\u4F20\u5927\u5C0F\u4E0D\u5339\u914D");
  await env2.R2.put(meta2.key, request.body, {
    httpMetadata: { contentType: meta2.mime },
    customMetadata: {
      kind: meta2.kind,
      userId: meta2.userId
    }
  });
  await env2.KV.delete(`upload:${token}`);
  return meta2;
}
__name(putSignedUpload, "putSignedUpload");
async function confirmUpload(env2, key) {
  const object = await env2.R2.head(key);
  if (!object)
    throw new Error("\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u672A\u4E0A\u4F20\u5B8C\u6210");
  return { key, size: object.size, uploaded: true };
}
__name(confirmUpload, "confirmUpload");

// src/routes/helpers.ts
function apiOk(c, data, status = 200) {
  return c.json({ success: true, data }, status);
}
__name(apiOk, "apiOk");
function apiFail(c, message, status = 400, code = "BAD_REQUEST") {
  return c.json({ success: false, message, code }, status);
}
__name(apiFail, "apiFail");
function setSessionCookie(c, token, maxAge) {
  setCookie(c, sessionCookieName(c.env), token, {
    path: "/",
    httpOnly: true,
    sameSite: "Lax",
    secure: new URL(c.req.url).protocol === "https:",
    maxAge
  });
}
__name(setSessionCookie, "setSessionCookie");
function clearSessionCookie(c) {
  deleteCookie(c, sessionCookieName(c.env), { path: "/" });
}
__name(clearSessionCookie, "clearSessionCookie");
function publicUser(user, settings) {
  return {
    id: user.id,
    username: user.username,
    email: user.email,
    displayName: user.displayName,
    avatarUrl: mediaUrl(settings.cdn_base_url, user.avatarKey),
    bio: user.bio,
    url: user.url,
    role: user.role
  };
}
__name(publicUser, "publicUser");

// src/routes/api.ts
var api = new Hono2();
function ip(c) {
  return c.req.header("cf-connecting-ip") || c.req.header("x-forwarded-for") || "local";
}
__name(ip, "ip");
function requireUser(user) {
  if (!user) {
    const error3 = new Error("\u8BF7\u5148\u767B\u5F55");
    error3.status = 401;
    error3.code = "UNAUTHENTICATED";
    throw error3;
  }
  return user;
}
__name(requireUser, "requireUser");
async function parseJson(c, schema) {
  const json = await c.req.json().catch(() => null);
  const parsed = schema.safeParse(json);
  if (!parsed.success) {
    const error3 = new Error(parsed.error.issues[0]?.message || "\u8BF7\u6C42\u53C2\u6570\u65E0\u6548");
    error3.status = 422;
    error3.code = "VALIDATION_ERROR";
    throw error3;
  }
  return parsed.data;
}
__name(parseJson, "parseJson");
var authRegisterSchema = external_exports.object({
  username: external_exports.string().regex(/^[a-zA-Z0-9_]{3,20}$/, "\u7528\u6237\u540D\u9700\u4E3A 3-20 \u4F4D\u5B57\u6BCD\u6570\u5B57\u6216\u4E0B\u5212\u7EBF"),
  email: external_exports.string().email("\u90AE\u7BB1\u683C\u5F0F\u4E0D\u6B63\u786E"),
  password: external_exports.string().min(8, "\u5BC6\u7801\u81F3\u5C11 8 \u4F4D"),
  displayName: external_exports.string().min(1).max(24),
  bootstrapToken: external_exports.string().optional()
});
var authLoginSchema = external_exports.object({
  identifier: external_exports.string().min(1),
  password: external_exports.string().min(1)
});
api.post("/auth/register", async (c) => {
  await enforceRateLimit(c.env, `register:${ip(c)}`, 5, 60);
  const input2 = await parseJson(c, authRegisterSchema);
  const user = await registerUser(c.env, input2);
  const session = await createSession(c.env, user.id, c.req.raw);
  setSessionCookie(c, session.token, session.maxAge);
  const settings = await getSettings(c.env);
  return apiOk(c, { user: publicUser(user, settings), csrfToken: c.get("csrfToken") });
});
api.post("/auth/login", async (c) => {
  await enforceRateLimit(c.env, `login:${ip(c)}`, 5, 60);
  const input2 = await parseJson(c, authLoginSchema);
  const user = await loginUser(c.env, input2.identifier, input2.password);
  const session = await createSession(c.env, user.id, c.req.raw);
  setSessionCookie(c, session.token, session.maxAge);
  const settings = await getSettings(c.env);
  return apiOk(c, { user: publicUser(user, settings), csrfToken: c.get("csrfToken") });
});
api.post("/auth/logout", async (c) => {
  const token = getCookie(c, c.env.COOKIE_NAME || "wm_session") || "";
  await destroySession(c.env, token);
  clearSessionCookie(c);
  return apiOk(c, { loggedOut: true });
});
api.get("/auth/me", async (c) => {
  const settings = await getSettings(c.env);
  const user = c.get("currentUser");
  return apiOk(c, { user: user ? publicUser(user, settings) : null });
});
api.post("/auth/password", async (c) => {
  const user = requireUser(c.get("currentUser"));
  const input2 = await parseJson(c, external_exports.object({ oldPassword: external_exports.string(), newPassword: external_exports.string().min(8) }));
  await updatePassword(c.env, user, input2.oldPassword, input2.newPassword);
  return apiOk(c, { changed: true });
});
api.get("/posts", async (c) => {
  const settings = await getSettings(c.env);
  const result = await listPosts(c.env, settings, {
    viewer: c.get("currentUser"),
    cursor: c.req.query("cursor"),
    limit: Number(c.req.query("limit") || "20"),
    authorUsername: c.req.query("author"),
    type: c.req.query("type") === "article" ? "article" : c.req.query("type") === "moment" ? "moment" : null,
    q: c.req.query("q")
  });
  return apiOk(c, result);
});
api.get("/posts/:id", async (c) => {
  const settings = await getSettings(c.env);
  const post = await getPost(c.env, settings, c.req.param("id"), c.get("currentUser"));
  if (!post)
    return apiFail(c, "\u5185\u5BB9\u4E0D\u5B58\u5728", 404, "NOT_FOUND");
  return apiOk(c, { post });
});
var postSchema = external_exports.object({
  type: external_exports.enum(["moment", "article"]).default("moment"),
  visibility: external_exports.enum(["public", "private"]).default("public"),
  isTop: external_exports.boolean().default(false),
  isAd: external_exports.boolean().default(false),
  content: external_exports.string().min(1).max(5e3),
  images: external_exports.array(external_exports.string()).max(9).default([]),
  videoKey: external_exports.string().nullable().optional(),
  position: external_exports.string().max(120).nullable().optional(),
  positionLat: external_exports.number().nullable().optional(),
  positionLng: external_exports.number().nullable().optional(),
  title: external_exports.string().max(120).optional(),
  shareUrl: external_exports.string().url().nullable().optional(),
  shareThumb: external_exports.string().nullable().optional()
});
api.post("/posts", async (c) => {
  const user = requireUser(c.get("currentUser"));
  await enforceRateLimit(c.env, `post:${user.id}`, 10, 3600);
  const input2 = await parseJson(c, postSchema);
  const id = await createPost(c.env, user, {
    type: input2.type || "moment",
    visibility: input2.visibility || "public",
    isTop: input2.isTop || false,
    isAd: input2.isAd || false,
    content: input2.content,
    images: input2.images || [],
    videoKey: input2.videoKey,
    position: input2.position,
    positionLat: input2.positionLat,
    positionLng: input2.positionLng,
    title: input2.title,
    shareUrl: input2.shareUrl,
    shareThumb: input2.shareThumb
  });
  const settings = await getSettings(c.env);
  const post = await getPost(c.env, settings, id, user);
  return apiOk(c, { post }, 201);
});
api.patch("/posts/:id", async (c) => {
  const user = requireUser(c.get("currentUser"));
  const input2 = await parseJson(c, postSchema.partial());
  await updatePost(c.env, c.req.param("id"), user, input2);
  const settings = await getSettings(c.env);
  return apiOk(c, { post: await getPost(c.env, settings, c.req.param("id"), user, user.role === "admin") });
});
api.delete("/posts/:id", async (c) => {
  const user = requireUser(c.get("currentUser"));
  await softDeletePost(c.env, c.req.param("id"), user);
  return apiOk(c, { deleted: true });
});
api.get("/posts/:id/edit", async (c) => {
  const user = requireUser(c.get("currentUser"));
  const settings = await getSettings(c.env);
  const post = await getPost(c.env, settings, c.req.param("id"), user, user.role === "admin");
  if (!post || post.author.id !== user.id && user.role !== "admin")
    return apiFail(c, "\u5185\u5BB9\u4E0D\u5B58\u5728", 404, "NOT_FOUND");
  return apiOk(c, { post });
});
api.get("/posts/:id/comments", async (c) => {
  return apiOk(c, { comments: await listComments(c.env, c.req.param("id"), c.get("currentUser")) });
});
api.post("/comments", async (c) => {
  const settings = await getSettings(c.env);
  const user = c.get("currentUser");
  if (settings.comment_mode === "closed")
    return apiFail(c, "\u8BC4\u8BBA\u5DF2\u5173\u95ED", 403, "COMMENTS_CLOSED");
  if (settings.comment_mode === "registered" && !user)
    return apiFail(c, "\u767B\u5F55\u540E\u8BC4\u8BBA", 401, "LOGIN_REQUIRED");
  if (user)
    await enforceRateLimit(c.env, `comment:${user.id}`, 30, 3600);
  else
    await enforceRateLimit(c.env, `comment:${ip(c)}`, 30, 3600);
  const input2 = await parseJson(
    c,
    external_exports.object({
      postId: external_exports.string().min(1),
      parentId: external_exports.string().nullable().optional(),
      content: external_exports.string().min(1).max(1e3),
      guestName: external_exports.string().max(40).nullable().optional(),
      guestEmail: external_exports.string().email().nullable().optional(),
      guestUrl: external_exports.string().url().nullable().optional()
    })
  );
  const id = await createComment(c.env, {
    ...input2,
    user,
    status: settings.comment_review && user?.role !== "admin" ? "pending" : "approved",
    ip: ip(c),
    userAgent: c.req.header("user-agent") || ""
  });
  return apiOk(c, { id, status: settings.comment_review ? "pending" : "approved" }, 201);
});
api.delete("/comments/:id", async (c) => {
  const user = requireUser(c.get("currentUser"));
  const deletedIds = await deleteComment(c.env, c.req.param("id"), user);
  return apiOk(c, { deletedIds });
});
api.post("/posts/:id/like", async (c) => {
  const user = requireUser(c.get("currentUser"));
  return apiOk(c, await likePost(c.env, c.req.param("id"), user));
});
api.delete("/posts/:id/like", async (c) => {
  const user = requireUser(c.get("currentUser"));
  return apiOk(c, await unlikePost(c.env, c.req.param("id"), user));
});
api.get("/posts/:id/likes", async (c) => {
  const settings = await getSettings(c.env);
  return apiOk(c, await listLikes(c.env, settings, c.req.param("id")));
});
api.post("/uploads/sign", async (c) => {
  const user = requireUser(c.get("currentUser"));
  const settings = await getSettings(c.env);
  const input2 = await parseJson(
    c,
    external_exports.object({
      kind: external_exports.enum(["image", "video", "avatar", "site"]),
      filename: external_exports.string().min(1),
      size: external_exports.number().int().positive(),
      mime: external_exports.string().min(1)
    })
  );
  return apiOk(c, await signUpload(c.env, settings, user, input2, new URL(c.req.url).origin));
});
api.put("/uploads/direct/:token", async (c) => {
  const meta2 = await putSignedUpload(c.env, c.req.param("token"), c.req.raw);
  return apiOk(c, { key: meta2.key, uploaded: true });
});
api.post("/uploads/confirm", async (c) => {
  requireUser(c.get("currentUser"));
  const input2 = await parseJson(c, external_exports.object({ key: external_exports.string().min(1) }));
  return apiOk(c, await confirmUpload(c.env, input2.key));
});
api.get("/links", async (c) => {
  const settings = await getSettings(c.env);
  return apiOk(c, { links: await listPublicLinks(c.env, settings) });
});
api.get("/users/:username", async (c) => {
  const settings = await getSettings(c.env);
  const row = await first(
    c.env.DB.prepare('SELECT id, username, display_name, avatar_key, bio, url, role FROM wm_users WHERE username = ? AND status = "active"').bind(c.req.param("username"))
  );
  if (!row)
    return apiFail(c, "\u7528\u6237\u4E0D\u5B58\u5728", 404, "NOT_FOUND");
  return apiOk(c, {
    user: {
      id: row.id,
      username: row.username,
      displayName: row.display_name,
      avatarUrl: mediaUrl(settings.cdn_base_url, row.avatar_key),
      bio: row.bio || "",
      url: row.url || "",
      role: row.role
    }
  });
});
api.patch("/users/me", async (c) => {
  const user = requireUser(c.get("currentUser"));
  const input2 = await parseJson(
    c,
    external_exports.object({
      displayName: external_exports.string().min(1).max(24).optional(),
      avatarKey: external_exports.string().nullable().optional(),
      bio: external_exports.string().max(240).optional(),
      url: external_exports.string().url().or(external_exports.literal("")).optional()
    })
  );
  await c.env.DB.prepare(
    `UPDATE wm_users SET
      display_name = COALESCE(?, display_name),
      avatar_key = COALESCE(?, avatar_key),
      bio = COALESCE(?, bio),
      url = COALESCE(?, url),
      updated_at = strftime('%s','now')
     WHERE id = ?`
  ).bind(input2.displayName ?? null, input2.avatarKey ?? null, input2.bio ?? null, input2.url ?? null, user.id).run();
  const settings = await getSettings(c.env);
  const fresh = await first(
    c.env.DB.prepare("SELECT id, username, email, display_name, avatar_key, bio, url, role FROM wm_users WHERE id = ?").bind(user.id)
  );
  return apiOk(c, { user: fresh ? { ...fresh, avatarUrl: mediaUrl(settings.cdn_base_url, fresh.avatar_key) } : null });
});
api.get("/geo/lookup", async (c) => {
  const settings = await getSettings(c.env);
  const lat = c.req.query("lat");
  const lng = c.req.query("lng");
  const key = settings.tencent_map_key || c.env.TENCENT_MAP_KEY;
  if (!key || !lat || !lng)
    return apiOk(c, { position: "" });
  const res = await fetch(`https://apis.map.qq.com/ws/geocoder/v1/?location=${encodeURIComponent(`${lat},${lng}`)}&key=${encodeURIComponent(key)}`);
  const data = await res.json();
  const city = data.result?.address_component?.city || "";
  const place = data.result?.formatted_addresses?.recommend || "";
  return apiOk(c, { position: [city, place].filter(Boolean).join("\xB7") });
});

// src/middleware/admin.ts
var adminOnly = /* @__PURE__ */ __name(async (c, next) => {
  const user = c.get("currentUser");
  if (!user) {
    return c.redirect(`/login?next=${encodeURIComponent(c.req.path)}`);
  }
  if (user.role !== "admin")
    return c.text("Forbidden", 403);
  await next();
}, "adminOnly");
var adminApiOnly = /* @__PURE__ */ __name(async (c, next) => {
  const user = c.get("currentUser");
  if (!user)
    return c.json({ success: false, message: "\u8BF7\u5148\u767B\u5F55", code: "UNAUTHENTICATED" }, 401);
  if (user.role !== "admin")
    return c.json({ success: false, message: "\u9700\u8981\u7BA1\u7406\u5458\u6743\u9650", code: "FORBIDDEN" }, 403);
  await next();
}, "adminApiOnly");
async function shouldBootstrap(env2) {
  return await countUsers(env2.DB) === 0;
}
__name(shouldBootstrap, "shouldBootstrap");

// src/views/admin/bootstrap.tsx
function AdminBootstrapPage(props) {
  return /* @__PURE__ */ jsxDEV("html", { lang: "zh-CN", children: [
    /* @__PURE__ */ jsxDEV("head", { children: [
      /* @__PURE__ */ jsxDEV("meta", { charset: "utf-8" }),
      /* @__PURE__ */ jsxDEV("meta", { name: "viewport", content: "width=device-width, initial-scale=1" }),
      /* @__PURE__ */ jsxDEV("title", { children: [
        "\u521D\u59CB\u5316 - ",
        props.settings.site_name
      ] }),
      /* @__PURE__ */ jsxDEV("link", { rel: "stylesheet", href: "/assets/css/wemoments.css" }),
      /* @__PURE__ */ jsxDEV("script", { dangerouslySetInnerHTML: { __html: `window.WEMOMENTS_CONFIG=${safeJson({ csrfToken: props.csrfToken })};` } })
    ] }),
    /* @__PURE__ */ jsxDEV("body", { children: [
      /* @__PURE__ */ jsxDEV("main", { class: "bootstrap-page", children: /* @__PURE__ */ jsxDEV("section", { class: "standalone-auth", children: [
        /* @__PURE__ */ jsxDEV("h1", { children: "\u521B\u5EFA\u9996\u4E2A\u7BA1\u7406\u5458" }),
        /* @__PURE__ */ jsxDEV("form", { "data-bootstrap-form": true, children: [
          /* @__PURE__ */ jsxDEV("label", { children: [
            /* @__PURE__ */ jsxDEV("span", { children: "Bootstrap Token" }),
            /* @__PURE__ */ jsxDEV("input", { name: "bootstrapToken", required: true })
          ] }),
          /* @__PURE__ */ jsxDEV("label", { children: [
            /* @__PURE__ */ jsxDEV("span", { children: "\u7528\u6237\u540D" }),
            /* @__PURE__ */ jsxDEV("input", { name: "username", pattern: "[a-zA-Z0-9_]{3,20}", required: true })
          ] }),
          /* @__PURE__ */ jsxDEV("label", { children: [
            /* @__PURE__ */ jsxDEV("span", { children: "\u90AE\u7BB1" }),
            /* @__PURE__ */ jsxDEV("input", { name: "email", type: "email", required: true })
          ] }),
          /* @__PURE__ */ jsxDEV("label", { children: [
            /* @__PURE__ */ jsxDEV("span", { children: "\u6635\u79F0" }),
            /* @__PURE__ */ jsxDEV("input", { name: "displayName", required: true })
          ] }),
          /* @__PURE__ */ jsxDEV("label", { children: [
            /* @__PURE__ */ jsxDEV("span", { children: "\u5BC6\u7801" }),
            /* @__PURE__ */ jsxDEV("input", { name: "password", type: "password", minlength: 8, required: true })
          ] }),
          /* @__PURE__ */ jsxDEV("button", { class: "primary-button", type: "submit", children: "\u521B\u5EFA\u7BA1\u7406\u5458" })
        ] })
      ] }) }),
      /* @__PURE__ */ jsxDEV("script", { defer: true, src: "/assets/js/axios.min.js" }),
      /* @__PURE__ */ jsxDEV("script", { defer: true, src: "/assets/js/wemoments-admin.js" })
    ] })
  ] });
}
__name(AdminBootstrapPage, "AdminBootstrapPage");

// src/views/admin/layout.tsx
var nav = [
  ["\u4EEA\u8868\u76D8", "/admin"],
  ["\u7528\u6237", "/admin/users"],
  ["\u5185\u5BB9", "/admin/posts"],
  ["\u8BC4\u8BBA", "/admin/comments"],
  ["\u53CB\u94FE", "/admin/links"],
  ["\u8BBE\u7F6E", "/admin/settings"],
  ["\u5BA1\u8BA1", "/admin/audit"]
];
function AdminLayout(props) {
  const config2 = {
    apiBase: "/api",
    csrfToken: props.csrfToken,
    currentUser: props.currentUser,
    currentUserIsAdmin: true
  };
  return /* @__PURE__ */ jsxDEV("html", { lang: "zh-CN", children: [
    /* @__PURE__ */ jsxDEV("head", { children: [
      /* @__PURE__ */ jsxDEV("meta", { charset: "utf-8" }),
      /* @__PURE__ */ jsxDEV("meta", { name: "viewport", content: "width=device-width, initial-scale=1" }),
      /* @__PURE__ */ jsxDEV("title", { children: [
        props.title,
        " - ",
        props.settings.site_name
      ] }),
      /* @__PURE__ */ jsxDEV("script", { dangerouslySetInnerHTML: { __html: "(function(){var t=localStorage.getItem('wemoments_theme_mode');if(t==='dark')document.documentElement.classList.add('dark');})();" } }),
      /* @__PURE__ */ jsxDEV("link", { rel: "stylesheet", href: "/assets/css/wemoments.css" }),
      /* @__PURE__ */ jsxDEV("script", { dangerouslySetInnerHTML: { __html: `window.WEMOMENTS_CONFIG=${safeJson(config2)};` } })
    ] }),
    /* @__PURE__ */ jsxDEV("body", { class: "admin-body", children: [
      /* @__PURE__ */ jsxDEV("div", { class: "admin-shell", children: [
        /* @__PURE__ */ jsxDEV("aside", { class: "admin-sidebar", children: [
          /* @__PURE__ */ jsxDEV("a", { class: "admin-brand", href: "/", children: props.settings.site_name }),
          /* @__PURE__ */ jsxDEV("nav", { children: nav.map(([label, href]) => /* @__PURE__ */ jsxDEV("a", { class: props.active === href ? "active" : "", href, children: label })) })
        ] }),
        /* @__PURE__ */ jsxDEV("main", { class: "admin-main", children: [
          /* @__PURE__ */ jsxDEV("header", { class: "admin-topbar", children: [
            /* @__PURE__ */ jsxDEV("h1", { children: props.title }),
            /* @__PURE__ */ jsxDEV("div", { children: [
              /* @__PURE__ */ jsxDEV("a", { href: "/", children: "\u524D\u53F0" }),
              /* @__PURE__ */ jsxDEV("span", { children: props.currentUser.displayName })
            ] })
          ] }),
          props.children
        ] })
      ] }),
      /* @__PURE__ */ jsxDEV("script", { defer: true, src: "/assets/js/axios.min.js" }),
      /* @__PURE__ */ jsxDEV("script", { defer: true, src: "/assets/js/wemoments-admin.js" })
    ] })
  ] });
}
__name(AdminLayout, "AdminLayout");

// src/views/admin/dashboard.tsx
function AdminDashboard(props) {
  const max = Math.max(1, ...props.stats.trend.map((item) => item.posts));
  const points = props.stats.trend.map((item, index) => `${index * 42},${80 - item.posts / max * 70}`).join(" ");
  return /* @__PURE__ */ jsxDEV(AdminLayout, { title: "\u4EEA\u8868\u76D8", settings: props.settings, currentUser: props.currentUser, csrfToken: props.csrfToken, active: "/admin", children: [
    /* @__PURE__ */ jsxDEV("section", { class: "admin-stats", children: [
      /* @__PURE__ */ jsxDEV("div", { children: [
        /* @__PURE__ */ jsxDEV("strong", { children: props.stats.users }),
        /* @__PURE__ */ jsxDEV("span", { children: "\u7528\u6237" })
      ] }),
      /* @__PURE__ */ jsxDEV("div", { children: [
        /* @__PURE__ */ jsxDEV("strong", { children: props.stats.posts }),
        /* @__PURE__ */ jsxDEV("span", { children: "\u5185\u5BB9" })
      ] }),
      /* @__PURE__ */ jsxDEV("div", { children: [
        /* @__PURE__ */ jsxDEV("strong", { children: props.stats.comments }),
        /* @__PURE__ */ jsxDEV("span", { children: "\u8BC4\u8BBA" })
      ] }),
      /* @__PURE__ */ jsxDEV("div", { children: [
        /* @__PURE__ */ jsxDEV("strong", { children: props.stats.likes }),
        /* @__PURE__ */ jsxDEV("span", { children: "\u70B9\u8D5E" })
      ] })
    ] }),
    /* @__PURE__ */ jsxDEV("section", { class: "admin-panel", children: [
      /* @__PURE__ */ jsxDEV("h2", { children: "\u8FD1 7 \u5929\u53D1\u5E03" }),
      /* @__PURE__ */ jsxDEV("svg", { class: "trend-svg", viewBox: "0 0 252 90", role: "img", "aria-label": "\u8FD1 7 \u5929\u53D1\u5E03\u8D8B\u52BF", children: /* @__PURE__ */ jsxDEV("polyline", { points, fill: "none", stroke: "#07C160", "stroke-width": "3", "stroke-linecap": "round", "stroke-linejoin": "round" }) })
    ] })
  ] });
}
__name(AdminDashboard, "AdminDashboard");

// src/views/admin/users.tsx
function AdminUsersPage(props) {
  return /* @__PURE__ */ jsxDEV(AdminLayout, { title: "\u7528\u6237\u7BA1\u7406", settings: props.settings, currentUser: props.currentUser, csrfToken: props.csrfToken, active: "/admin/users", children: /* @__PURE__ */ jsxDEV("section", { class: "admin-panel", children: /* @__PURE__ */ jsxDEV("table", { class: "admin-table", children: [
    /* @__PURE__ */ jsxDEV("thead", { children: /* @__PURE__ */ jsxDEV("tr", { children: [
      /* @__PURE__ */ jsxDEV("th", { children: "\u7528\u6237" }),
      /* @__PURE__ */ jsxDEV("th", { children: "\u90AE\u7BB1" }),
      /* @__PURE__ */ jsxDEV("th", { children: "\u89D2\u8272" }),
      /* @__PURE__ */ jsxDEV("th", { children: "\u72B6\u6001" }),
      /* @__PURE__ */ jsxDEV("th", { children: "\u64CD\u4F5C" })
    ] }) }),
    /* @__PURE__ */ jsxDEV("tbody", { children: props.users.map((user) => /* @__PURE__ */ jsxDEV("tr", { "data-user-id": user.id, children: [
      /* @__PURE__ */ jsxDEV("td", { children: [
        /* @__PURE__ */ jsxDEV("strong", { children: user.display_name }),
        /* @__PURE__ */ jsxDEV("small", { children: [
          "@",
          user.username
        ] })
      ] }),
      /* @__PURE__ */ jsxDEV("td", { children: user.email }),
      /* @__PURE__ */ jsxDEV("td", { children: /* @__PURE__ */ jsxDEV("select", { "data-admin-user-role": true, children: ["subscriber", "author", "admin"].map((role) => /* @__PURE__ */ jsxDEV("option", { value: role, selected: role === user.role, children: role })) }) }),
      /* @__PURE__ */ jsxDEV("td", { children: user.status }),
      /* @__PURE__ */ jsxDEV("td", { children: /* @__PURE__ */ jsxDEV("button", { "data-admin-action": "ban-user", children: user.status === "banned" ? "\u6062\u590D" : "\u5C01\u7981" }) })
    ] })) })
  ] }) }) });
}
__name(AdminUsersPage, "AdminUsersPage");

// src/views/admin/posts.tsx
function AdminPostsPage(props) {
  return /* @__PURE__ */ jsxDEV(AdminLayout, { title: "\u5185\u5BB9\u7BA1\u7406", settings: props.settings, currentUser: props.currentUser, csrfToken: props.csrfToken, active: "/admin/posts", children: /* @__PURE__ */ jsxDEV("section", { class: "admin-panel", children: [
    /* @__PURE__ */ jsxDEV("div", { class: "bulk-actions", children: [
      /* @__PURE__ */ jsxDEV("select", { "data-bulk-action": true, children: [
        /* @__PURE__ */ jsxDEV("option", { value: "trash", children: "\u79FB\u5165\u56DE\u6536\u7AD9" }),
        /* @__PURE__ */ jsxDEV("option", { value: "publish", children: "\u53D1\u5E03" }),
        /* @__PURE__ */ jsxDEV("option", { value: "topOn", children: "\u7F6E\u9876" }),
        /* @__PURE__ */ jsxDEV("option", { value: "topOff", children: "\u53D6\u6D88\u7F6E\u9876" }),
        /* @__PURE__ */ jsxDEV("option", { value: "adOn", children: "\u6807\u8BB0\u5E7F\u544A" }),
        /* @__PURE__ */ jsxDEV("option", { value: "adOff", children: "\u53D6\u6D88\u5E7F\u544A" }),
        /* @__PURE__ */ jsxDEV("option", { value: "delete", children: "\u5F7B\u5E95\u5220\u9664" })
      ] }),
      /* @__PURE__ */ jsxDEV("button", { "data-admin-action": "bulk-posts", children: "\u5E94\u7528" })
    ] }),
    /* @__PURE__ */ jsxDEV("table", { class: "admin-table", children: [
      /* @__PURE__ */ jsxDEV("thead", { children: /* @__PURE__ */ jsxDEV("tr", { children: [
        /* @__PURE__ */ jsxDEV("th", { children: /* @__PURE__ */ jsxDEV("input", { type: "checkbox", "data-check-all": true }) }),
        /* @__PURE__ */ jsxDEV("th", { children: "\u5185\u5BB9" }),
        /* @__PURE__ */ jsxDEV("th", { children: "\u4F5C\u8005" }),
        /* @__PURE__ */ jsxDEV("th", { children: "\u53EF\u89C1\u6027" }),
        /* @__PURE__ */ jsxDEV("th", { children: "\u72B6\u6001" }),
        /* @__PURE__ */ jsxDEV("th", { children: "\u6807\u8BB0" })
      ] }) }),
      /* @__PURE__ */ jsxDEV("tbody", { children: props.posts.map((post) => /* @__PURE__ */ jsxDEV("tr", { children: [
        /* @__PURE__ */ jsxDEV("td", { children: /* @__PURE__ */ jsxDEV("input", { type: "checkbox", value: post.id, "data-post-check": true }) }),
        /* @__PURE__ */ jsxDEV("td", { children: /* @__PURE__ */ jsxDEV("a", { href: `/p/${post.id}`, children: post.title || post.content.slice(0, 42) || post.id }) }),
        /* @__PURE__ */ jsxDEV("td", { children: post.display_name }),
        /* @__PURE__ */ jsxDEV("td", { children: post.visibility }),
        /* @__PURE__ */ jsxDEV("td", { children: post.status }),
        /* @__PURE__ */ jsxDEV("td", { children: [
          post.is_top ? "\u7F6E\u9876 " : "",
          post.is_ad ? "\u5E7F\u544A" : ""
        ] })
      ] })) })
    ] })
  ] }) });
}
__name(AdminPostsPage, "AdminPostsPage");

// src/views/admin/comments.tsx
function AdminCommentsPage(props) {
  return /* @__PURE__ */ jsxDEV(AdminLayout, { title: "\u8BC4\u8BBA\u7BA1\u7406", settings: props.settings, currentUser: props.currentUser, csrfToken: props.csrfToken, active: "/admin/comments", children: /* @__PURE__ */ jsxDEV("section", { class: "admin-panel", children: /* @__PURE__ */ jsxDEV("table", { class: "admin-table", children: [
    /* @__PURE__ */ jsxDEV("thead", { children: /* @__PURE__ */ jsxDEV("tr", { children: [
      /* @__PURE__ */ jsxDEV("th", { children: "\u4F5C\u8005" }),
      /* @__PURE__ */ jsxDEV("th", { children: "\u8BC4\u8BBA" }),
      /* @__PURE__ */ jsxDEV("th", { children: "\u72B6\u6001" }),
      /* @__PURE__ */ jsxDEV("th", { children: "\u64CD\u4F5C" })
    ] }) }),
    /* @__PURE__ */ jsxDEV("tbody", { children: props.comments.map((comment) => /* @__PURE__ */ jsxDEV("tr", { "data-comment-id": comment.id, children: [
      /* @__PURE__ */ jsxDEV("td", { children: comment.author_name }),
      /* @__PURE__ */ jsxDEV("td", { children: /* @__PURE__ */ jsxDEV("a", { href: `/p/${comment.post_id}`, children: comment.content }) }),
      /* @__PURE__ */ jsxDEV("td", { children: comment.status }),
      /* @__PURE__ */ jsxDEV("td", { children: [
        /* @__PURE__ */ jsxDEV("button", { "data-admin-action": "approve-comment", children: "\u901A\u8FC7" }),
        /* @__PURE__ */ jsxDEV("button", { "data-admin-action": "trash-comment", children: "\u5220\u9664" })
      ] })
    ] })) })
  ] }) }) });
}
__name(AdminCommentsPage, "AdminCommentsPage");

// src/views/admin/links.tsx
function AdminLinksPage(props) {
  return /* @__PURE__ */ jsxDEV(AdminLayout, { title: "\u53CB\u94FE\u7BA1\u7406", settings: props.settings, currentUser: props.currentUser, csrfToken: props.csrfToken, active: "/admin/links", children: /* @__PURE__ */ jsxDEV("section", { class: "admin-panel", children: [
    /* @__PURE__ */ jsxDEV("form", { class: "admin-inline-form", "data-admin-link-form": true, children: [
      /* @__PURE__ */ jsxDEV("input", { name: "name", placeholder: "\u540D\u79F0", required: true }),
      /* @__PURE__ */ jsxDEV("input", { name: "url", placeholder: "URL", type: "url", required: true }),
      /* @__PURE__ */ jsxDEV("input", { name: "description", placeholder: "\u63CF\u8FF0" }),
      /* @__PURE__ */ jsxDEV("input", { name: "category", placeholder: "\u5206\u7C7B", value: "default" }),
      /* @__PURE__ */ jsxDEV("button", { type: "submit", children: "\u6DFB\u52A0" })
    ] }),
    /* @__PURE__ */ jsxDEV("table", { class: "admin-table", children: [
      /* @__PURE__ */ jsxDEV("thead", { children: /* @__PURE__ */ jsxDEV("tr", { children: [
        /* @__PURE__ */ jsxDEV("th", { children: "\u540D\u79F0" }),
        /* @__PURE__ */ jsxDEV("th", { children: "URL" }),
        /* @__PURE__ */ jsxDEV("th", { children: "\u5206\u7C7B" }),
        /* @__PURE__ */ jsxDEV("th", { children: "\u6392\u5E8F" }),
        /* @__PURE__ */ jsxDEV("th", { children: "\u64CD\u4F5C" })
      ] }) }),
      /* @__PURE__ */ jsxDEV("tbody", { children: props.links.map((link2) => /* @__PURE__ */ jsxDEV("tr", { "data-link-id": link2.id, children: [
        /* @__PURE__ */ jsxDEV("td", { children: link2.name }),
        /* @__PURE__ */ jsxDEV("td", { children: /* @__PURE__ */ jsxDEV("a", { href: link2.url, target: "_blank", rel: "noopener noreferrer", children: link2.url }) }),
        /* @__PURE__ */ jsxDEV("td", { children: link2.category }),
        /* @__PURE__ */ jsxDEV("td", { children: link2.sort_order }),
        /* @__PURE__ */ jsxDEV("td", { children: /* @__PURE__ */ jsxDEV("button", { "data-admin-action": "delete-link", children: "\u5220\u9664" }) })
      ] })) })
    ] })
  ] }) });
}
__name(AdminLinksPage, "AdminLinksPage");

// src/views/admin/settings.tsx
function AdminSettingsPage(props) {
  const settings = props.settings;
  return /* @__PURE__ */ jsxDEV(AdminLayout, { title: "\u7AD9\u70B9\u8BBE\u7F6E", settings, currentUser: props.currentUser, csrfToken: props.csrfToken, active: "/admin/settings", children: /* @__PURE__ */ jsxDEV("section", { class: "admin-panel", children: /* @__PURE__ */ jsxDEV("form", { class: "admin-settings-form", "data-admin-settings-form": true, children: [
    /* @__PURE__ */ jsxDEV("h2", { children: "\u57FA\u7840" }),
    /* @__PURE__ */ jsxDEV("label", { children: [
      /* @__PURE__ */ jsxDEV("span", { children: "\u7AD9\u70B9\u6807\u9898" }),
      /* @__PURE__ */ jsxDEV("input", { name: "site_name", value: settings.site_name })
    ] }),
    /* @__PURE__ */ jsxDEV("label", { children: [
      /* @__PURE__ */ jsxDEV("span", { children: "\u526F\u6807\u9898" }),
      /* @__PURE__ */ jsxDEV("input", { name: "site_description", value: settings.site_description })
    ] }),
    /* @__PURE__ */ jsxDEV("label", { children: [
      /* @__PURE__ */ jsxDEV("span", { children: "\u5907\u6848\u53F7" }),
      /* @__PURE__ */ jsxDEV("input", { name: "beian_info", value: settings.beian_info })
    ] }),
    /* @__PURE__ */ jsxDEV("h2", { children: "\u5916\u89C2" }),
    /* @__PURE__ */ jsxDEV("label", { children: [
      /* @__PURE__ */ jsxDEV("span", { children: "\u7AD9\u70B9\u5934\u50CF R2 Key" }),
      /* @__PURE__ */ jsxDEV("input", { name: "site_avatar_key", value: settings.site_avatar_key })
    ] }),
    /* @__PURE__ */ jsxDEV("label", { children: [
      /* @__PURE__ */ jsxDEV("span", { children: "\u9876\u90E8\u56FE\u7247 R2 Key" }),
      /* @__PURE__ */ jsxDEV("input", { name: "top_image_key", value: settings.top_image_key })
    ] }),
    /* @__PURE__ */ jsxDEV("label", { children: [
      /* @__PURE__ */ jsxDEV("span", { children: "\u9876\u90E8\u89C6\u9891 R2 Key" }),
      /* @__PURE__ */ jsxDEV("input", { name: "top_video_key", value: settings.top_video_key })
    ] }),
    /* @__PURE__ */ jsxDEV("label", { children: [
      /* @__PURE__ */ jsxDEV("span", { children: "CDN Base URL" }),
      /* @__PURE__ */ jsxDEV("input", { name: "cdn_base_url", value: settings.cdn_base_url })
    ] }),
    /* @__PURE__ */ jsxDEV("h2", { children: "\u5185\u5BB9" }),
    /* @__PURE__ */ jsxDEV("label", { children: [
      /* @__PURE__ */ jsxDEV("span", { children: "\u5F00\u653E\u6CE8\u518C" }),
      /* @__PURE__ */ jsxDEV("select", { name: "allow_register", children: [
        /* @__PURE__ */ jsxDEV("option", { value: "true", selected: settings.allow_register, children: "\u5F00\u542F" }),
        /* @__PURE__ */ jsxDEV("option", { value: "false", selected: !settings.allow_register, children: "\u5173\u95ED" })
      ] })
    ] }),
    /* @__PURE__ */ jsxDEV("label", { children: [
      /* @__PURE__ */ jsxDEV("span", { children: "\u9ED8\u8BA4\u89D2\u8272" }),
      /* @__PURE__ */ jsxDEV("select", { name: "default_role", children: [
        /* @__PURE__ */ jsxDEV("option", { value: "subscriber", selected: settings.default_role === "subscriber", children: "subscriber" }),
        /* @__PURE__ */ jsxDEV("option", { value: "author", selected: settings.default_role === "author", children: "author" }),
        /* @__PURE__ */ jsxDEV("option", { value: "admin", selected: settings.default_role === "admin", children: "admin" })
      ] })
    ] }),
    /* @__PURE__ */ jsxDEV("label", { children: [
      /* @__PURE__ */ jsxDEV("span", { children: "\u8BC4\u8BBA\u6A21\u5F0F" }),
      /* @__PURE__ */ jsxDEV("select", { name: "comment_mode", children: [
        /* @__PURE__ */ jsxDEV("option", { value: "everyone", selected: settings.comment_mode === "everyone", children: "everyone" }),
        /* @__PURE__ */ jsxDEV("option", { value: "registered", selected: settings.comment_mode === "registered", children: "registered" }),
        /* @__PURE__ */ jsxDEV("option", { value: "closed", selected: settings.comment_mode === "closed", children: "closed" })
      ] })
    ] }),
    /* @__PURE__ */ jsxDEV("label", { children: [
      /* @__PURE__ */ jsxDEV("span", { children: "\u8BC4\u8BBA\u5BA1\u6838" }),
      /* @__PURE__ */ jsxDEV("select", { name: "comment_review", children: [
        /* @__PURE__ */ jsxDEV("option", { value: "true", selected: settings.comment_review, children: "\u5F00\u542F" }),
        /* @__PURE__ */ jsxDEV("option", { value: "false", selected: !settings.comment_review, children: "\u5173\u95ED" })
      ] })
    ] }),
    /* @__PURE__ */ jsxDEV("h2", { children: "\u4E0A\u4F20" }),
    /* @__PURE__ */ jsxDEV("label", { children: [
      /* @__PURE__ */ jsxDEV("span", { children: "\u56FE\u7247\u6700\u5927 MB" }),
      /* @__PURE__ */ jsxDEV("input", { name: "upload_max_image_mb", type: "number", value: settings.upload_max_image_mb, min: "1", max: "100" })
    ] }),
    /* @__PURE__ */ jsxDEV("label", { children: [
      /* @__PURE__ */ jsxDEV("span", { children: "\u89C6\u9891\u6700\u5927 MB" }),
      /* @__PURE__ */ jsxDEV("input", { name: "upload_max_video_mb", type: "number", value: settings.upload_max_video_mb, min: "1", max: "500" })
    ] }),
    /* @__PURE__ */ jsxDEV("h2", { children: "\u96C6\u6210" }),
    /* @__PURE__ */ jsxDEV("label", { children: [
      /* @__PURE__ */ jsxDEV("span", { children: "\u817E\u8BAF\u5730\u56FE Key" }),
      /* @__PURE__ */ jsxDEV("input", { name: "tencent_map_key", value: settings.tencent_map_key })
    ] }),
    /* @__PURE__ */ jsxDEV("h2", { children: "\u81EA\u5B9A\u4E49\u4EE3\u7801" }),
    /* @__PURE__ */ jsxDEV("label", { children: [
      /* @__PURE__ */ jsxDEV("span", { children: "\u81EA\u5B9A\u4E49 CSS" }),
      /* @__PURE__ */ jsxDEV("textarea", { name: "custom_css", rows: 6, children: settings.custom_css })
    ] }),
    /* @__PURE__ */ jsxDEV("label", { children: [
      /* @__PURE__ */ jsxDEV("span", { children: "\u81EA\u5B9A\u4E49 JS" }),
      /* @__PURE__ */ jsxDEV("textarea", { name: "custom_js", rows: 6, children: settings.custom_js })
    ] }),
    /* @__PURE__ */ jsxDEV("label", { children: [
      /* @__PURE__ */ jsxDEV("span", { children: "\u7EDF\u8BA1\u4EE3\u7801" }),
      /* @__PURE__ */ jsxDEV("textarea", { name: "analytics_code", rows: 6, children: settings.analytics_code })
    ] }),
    /* @__PURE__ */ jsxDEV("button", { class: "primary-button", type: "submit", children: "\u4FDD\u5B58\u8BBE\u7F6E" })
  ] }) }) });
}
__name(AdminSettingsPage, "AdminSettingsPage");

// src/views/admin/audit.tsx
function AdminAuditPage(props) {
  return /* @__PURE__ */ jsxDEV(AdminLayout, { title: "\u5BA1\u8BA1\u65E5\u5FD7", settings: props.settings, currentUser: props.currentUser, csrfToken: props.csrfToken, active: "/admin/audit", children: /* @__PURE__ */ jsxDEV("section", { class: "admin-panel", children: /* @__PURE__ */ jsxDEV("table", { class: "admin-table", children: [
    /* @__PURE__ */ jsxDEV("thead", { children: /* @__PURE__ */ jsxDEV("tr", { children: [
      /* @__PURE__ */ jsxDEV("th", { children: "ID" }),
      /* @__PURE__ */ jsxDEV("th", { children: "\u52A8\u4F5C" }),
      /* @__PURE__ */ jsxDEV("th", { children: "\u76EE\u6807" }),
      /* @__PURE__ */ jsxDEV("th", { children: "\u8BE6\u60C5" }),
      /* @__PURE__ */ jsxDEV("th", { children: "IP" })
    ] }) }),
    /* @__PURE__ */ jsxDEV("tbody", { children: props.logs.map((log3) => /* @__PURE__ */ jsxDEV("tr", { children: [
      /* @__PURE__ */ jsxDEV("td", { children: log3.id }),
      /* @__PURE__ */ jsxDEV("td", { children: log3.action }),
      /* @__PURE__ */ jsxDEV("td", { children: log3.target }),
      /* @__PURE__ */ jsxDEV("td", { children: /* @__PURE__ */ jsxDEV("code", { children: log3.detail }) }),
      /* @__PURE__ */ jsxDEV("td", { children: log3.ip })
    ] })) })
  ] }) }) });
}
__name(AdminAuditPage, "AdminAuditPage");

// src/routes/admin.tsx
var admin = new Hono2();
async function parseJson2(c, schema) {
  const json = await c.req.json().catch(() => null);
  const parsed = schema.safeParse(json);
  if (!parsed.success) {
    const error3 = new Error(parsed.error.issues[0]?.message || "\u8BF7\u6C42\u53C2\u6570\u65E0\u6548");
    error3.status = 422;
    error3.code = "VALIDATION_ERROR";
    throw error3;
  }
  return parsed.data;
}
__name(parseJson2, "parseJson");
function clientIp(c) {
  return c.req.header("cf-connecting-ip") || c.req.header("x-forwarded-for") || "local";
}
__name(clientIp, "clientIp");
admin.get("/bootstrap", async (c) => {
  if (!await shouldBootstrap(c.env))
    return c.redirect("/admin");
  const settings = await getSettings(c.env);
  return c.html(/* @__PURE__ */ jsxDEV(AdminBootstrapPage, { settings, csrfToken: c.get("csrfToken") }));
});
admin.post("/api/bootstrap", async (c) => {
  if (!await shouldBootstrap(c.env))
    return apiOk(c, { disabled: true });
  const input2 = await parseJson2(
    c,
    external_exports.object({
      username: external_exports.string().regex(/^[a-zA-Z0-9_]{3,20}$/),
      email: external_exports.string().email(),
      password: external_exports.string().min(8),
      displayName: external_exports.string().min(1),
      bootstrapToken: external_exports.string().min(1)
    })
  );
  const user = await registerUser(c.env, input2);
  const session = await createSession(c.env, user.id, c.req.raw);
  setSessionCookie(c, session.token, session.maxAge);
  await audit(c.env.DB, { actorId: user.id, action: "bootstrap.createAdmin", target: user.id, ip: clientIp(c), createdAt: nowSeconds() });
  return apiOk(c, { user });
});
admin.use("*", async (c, next) => {
  if (c.req.path.endsWith("/bootstrap") || c.req.path.endsWith("/api/bootstrap")) {
    await next();
    return;
  }
  if (await shouldBootstrap(c.env))
    return c.redirect("/admin/bootstrap");
  return adminOnly(c, next);
});
admin.use("/api/*", adminApiOnly);
admin.get("/", async (c) => {
  const settings = await getSettings(c.env);
  const [users, posts, comments, likes] = await Promise.all([
    c.env.DB.prepare("SELECT COUNT(*) AS count FROM wm_users").first(),
    c.env.DB.prepare('SELECT COUNT(*) AS count FROM wm_posts WHERE status != "trash"').first(),
    c.env.DB.prepare('SELECT COUNT(*) AS count FROM wm_comments WHERE status != "trash"').first(),
    c.env.DB.prepare("SELECT COUNT(*) AS count FROM wm_likes").first()
  ]);
  const trendRows = await all(
    c.env.DB.prepare(
      `SELECT date(created_at, 'unixepoch') AS day, COUNT(*) AS posts
       FROM wm_posts
       WHERE created_at >= strftime('%s','now','-6 days')
       GROUP BY day
       ORDER BY day ASC`
    )
  );
  const days = Array.from({ length: 7 }, (_, i) => {
    const d = /* @__PURE__ */ new Date();
    d.setDate(d.getDate() - (6 - i));
    return d.toISOString().slice(0, 10);
  });
  const trend = days.map((day) => ({ day, posts: trendRows.find((row) => row.day === day)?.posts || 0 }));
  return c.html(
    /* @__PURE__ */ jsxDEV(
      AdminDashboard,
      {
        settings,
        currentUser: c.get("currentUser"),
        csrfToken: c.get("csrfToken"),
        stats: { users: users?.count || 0, posts: posts?.count || 0, comments: comments?.count || 0, likes: likes?.count || 0, trend }
      }
    )
  );
});
admin.get("/users", async (c) => {
  const settings = await getSettings(c.env);
  const users = await all(
    c.env.DB.prepare("SELECT id, username, email, display_name, role, status, created_at FROM wm_users ORDER BY created_at DESC LIMIT 100")
  );
  return c.html(/* @__PURE__ */ jsxDEV(AdminUsersPage, { settings, currentUser: c.get("currentUser"), csrfToken: c.get("csrfToken"), users }));
});
admin.get("/posts", async (c) => {
  const settings = await getSettings(c.env);
  const posts = await all(
    c.env.DB.prepare(
      `SELECT p.id, p.title, p.content, u.display_name, p.visibility, p.status, p.is_top, p.is_ad, p.created_at
       FROM wm_posts p JOIN wm_users u ON u.id = p.author_id
       ORDER BY p.created_at DESC LIMIT 100`
    )
  );
  return c.html(/* @__PURE__ */ jsxDEV(AdminPostsPage, { settings, currentUser: c.get("currentUser"), csrfToken: c.get("csrfToken"), posts }));
});
admin.get("/comments", async (c) => {
  const settings = await getSettings(c.env);
  const comments = await all(
    c.env.DB.prepare(
      `SELECT c.id, c.post_id, c.content, c.status, COALESCE(u.display_name, c.guest_name, '\u8BBF\u5BA2') AS author_name, c.created_at
       FROM wm_comments c LEFT JOIN wm_users u ON u.id = c.user_id
       ORDER BY c.created_at DESC LIMIT 100`
    )
  );
  return c.html(/* @__PURE__ */ jsxDEV(AdminCommentsPage, { settings, currentUser: c.get("currentUser"), csrfToken: c.get("csrfToken"), comments }));
});
admin.get("/links", async (c) => {
  const settings = await getSettings(c.env);
  const links = await listAdminLinks(c.env);
  return c.html(/* @__PURE__ */ jsxDEV(AdminLinksPage, { settings, currentUser: c.get("currentUser"), csrfToken: c.get("csrfToken"), links }));
});
admin.get("/settings", async (c) => {
  const settings = await getSettings(c.env);
  return c.html(/* @__PURE__ */ jsxDEV(AdminSettingsPage, { settings, currentUser: c.get("currentUser"), csrfToken: c.get("csrfToken") }));
});
admin.get("/audit", async (c) => {
  const settings = await getSettings(c.env);
  const logs = await all(
    c.env.DB.prepare("SELECT id, actor_id, action, target, detail, ip, created_at FROM wm_audit_log ORDER BY created_at DESC, id DESC LIMIT 100")
  );
  return c.html(/* @__PURE__ */ jsxDEV(AdminAuditPage, { settings, currentUser: c.get("currentUser"), csrfToken: c.get("csrfToken"), logs }));
});
admin.post("/api/users/:id/role", async (c) => {
  const input2 = await parseJson2(c, external_exports.object({ role: external_exports.enum(["subscriber", "author", "admin"]) }));
  await c.env.DB.prepare("UPDATE wm_users SET role = ?, updated_at = ? WHERE id = ?").bind(input2.role, nowSeconds(), c.req.param("id")).run();
  await audit(c.env.DB, { actorId: c.get("currentUser")?.id, action: "user.role", target: c.req.param("id"), detail: input2, ip: clientIp(c), createdAt: nowSeconds() });
  return apiOk(c, { saved: true });
});
admin.post("/api/users/:id/ban", async (c) => {
  const row = await c.env.DB.prepare("SELECT status FROM wm_users WHERE id = ?").bind(c.req.param("id")).first();
  const next = row?.status === "banned" ? "active" : "banned";
  await c.env.DB.prepare("UPDATE wm_users SET status = ?, updated_at = ? WHERE id = ?").bind(next, nowSeconds(), c.req.param("id")).run();
  await audit(c.env.DB, { actorId: c.get("currentUser")?.id, action: "user.ban", target: c.req.param("id"), detail: { status: next }, ip: clientIp(c), createdAt: nowSeconds() });
  return apiOk(c, { status: next });
});
admin.post("/api/posts/bulk", async (c) => {
  const input2 = await parseJson2(
    c,
    external_exports.object({
      ids: external_exports.array(external_exports.string()).min(1).max(100),
      action: external_exports.enum(["delete", "topOn", "topOff", "adOn", "adOff", "publish", "trash"])
    })
  );
  const placeholders = input2.ids.map(() => "?").join(",");
  const sqlByAction = {
    delete: `DELETE FROM wm_posts WHERE id IN (${placeholders})`,
    topOn: `UPDATE wm_posts SET is_top = 1 WHERE id IN (${placeholders})`,
    topOff: `UPDATE wm_posts SET is_top = 0 WHERE id IN (${placeholders})`,
    adOn: `UPDATE wm_posts SET is_ad = 1 WHERE id IN (${placeholders})`,
    adOff: `UPDATE wm_posts SET is_ad = 0 WHERE id IN (${placeholders})`,
    publish: `UPDATE wm_posts SET status = 'published' WHERE id IN (${placeholders})`,
    trash: `UPDATE wm_posts SET status = 'trash' WHERE id IN (${placeholders})`
  };
  await c.env.DB.prepare(sqlByAction[input2.action]).bind(...input2.ids).run();
  await audit(c.env.DB, { actorId: c.get("currentUser")?.id, action: `post.bulk.${input2.action}`, detail: { ids: input2.ids }, ip: clientIp(c), createdAt: nowSeconds() });
  return apiOk(c, { updated: input2.ids.length });
});
admin.post("/api/settings", async (c) => {
  const json = await c.req.json().catch(() => ({}));
  const values = {};
  for (const key of SETTING_KEYS)
    if (Object.prototype.hasOwnProperty.call(json, key))
      values[key] = json[key];
  const settings = await setSettings(c.env, values);
  await audit(c.env.DB, { actorId: c.get("currentUser")?.id, action: "settings.update", detail: values, ip: clientIp(c), createdAt: nowSeconds() });
  return apiOk(c, { settings });
});
admin.post("/api/comments/:id/status", async (c) => {
  const input2 = await parseJson2(c, external_exports.object({ status: external_exports.enum(["approved", "pending", "spam", "trash"]) }));
  await c.env.DB.prepare("UPDATE wm_comments SET status = ? WHERE id = ?").bind(input2.status, c.req.param("id")).run();
  await audit(c.env.DB, { actorId: c.get("currentUser")?.id, action: "comment.status", target: c.req.param("id"), detail: input2, ip: clientIp(c), createdAt: nowSeconds() });
  return apiOk(c, { saved: true });
});
admin.delete("/api/comments/:id", async (c) => {
  await c.env.DB.prepare("DELETE FROM wm_comments WHERE id = ?").bind(c.req.param("id")).run();
  await audit(c.env.DB, { actorId: c.get("currentUser")?.id, action: "comment.delete", target: c.req.param("id"), ip: clientIp(c), createdAt: nowSeconds() });
  return apiOk(c, { deleted: true });
});
var linkSchema = external_exports.object({
  name: external_exports.string().min(1),
  url: external_exports.string().url(),
  avatar: external_exports.string().nullable().optional(),
  description: external_exports.string().optional(),
  category: external_exports.string().optional(),
  visible: external_exports.boolean().optional(),
  sortOrder: external_exports.number().int().optional()
});
admin.post("/api/links", async (c) => {
  const input2 = await parseJson2(c, linkSchema);
  const id = await createLink(c.env, input2);
  await audit(c.env.DB, { actorId: c.get("currentUser")?.id, action: "link.create", target: id, detail: input2, ip: clientIp(c), createdAt: nowSeconds() });
  return apiOk(c, { id }, 201);
});
admin.patch("/api/links/:id", async (c) => {
  const input2 = await parseJson2(c, linkSchema.partial());
  await updateLink(c.env, c.req.param("id"), input2);
  await audit(c.env.DB, { actorId: c.get("currentUser")?.id, action: "link.update", target: c.req.param("id"), detail: input2, ip: clientIp(c), createdAt: nowSeconds() });
  return apiOk(c, { saved: true });
});
admin.delete("/api/links/:id", async (c) => {
  await deleteLink(c.env, c.req.param("id"));
  await audit(c.env.DB, { actorId: c.get("currentUser")?.id, action: "link.delete", target: c.req.param("id"), ip: clientIp(c), createdAt: nowSeconds() });
  return apiOk(c, { deleted: true });
});

// src/index.ts
var app = new Hono2();
app.use("*", requestLogger);
app.use("*", sessionMiddleware);
app.use("/api/*", csrfMiddleware);
app.use("/admin/api/*", csrfMiddleware);
app.route("/api", api);
app.route("/admin", admin);
app.route("/", pages);
app.notFound((c) => {
  if (c.req.path.startsWith("/api") || c.req.path.startsWith("/admin/api")) {
    return c.json({ success: false, message: "\u8D44\u6E90\u4E0D\u5B58\u5728", code: "NOT_FOUND" }, 404);
  }
  return c.text("Not Found", 404);
});
app.onError(async (error3, c) => {
  const status = "status" in error3 && typeof error3.status === "number" ? error3.status : 500;
  const code = "code" in error3 && typeof error3.code === "string" ? error3.code : status >= 500 ? "INTERNAL_ERROR" : "BAD_REQUEST";
  const message = error3 instanceof HttpError || status < 500 ? error3.message : "\u670D\u52A1\u5668\u6682\u65F6\u4E0D\u53EF\u7528";
  if (status >= 500) {
    console.error(error3);
    await audit(c.env.DB, {
      actorId: c.get("currentUser")?.id,
      action: "error.500",
      target: c.req.path,
      detail: { message: error3.message, requestId: c.get("requestId") },
      ip: c.req.header("cf-connecting-ip") || "",
      createdAt: nowSeconds()
    }).catch(() => void 0);
  }
  if (c.req.path.startsWith("/api") || c.req.path.startsWith("/admin/api")) {
    return c.json({ success: false, message, code }, status);
  }
  return c.text(message, status);
});
var src_default = app;
export {
  src_default as default
};
/*! Bundled license information:

@noble/hashes/esm/utils.js:
  (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
*/
//# sourceMappingURL=index.js.map
