"use strict";
/* Socket Lib - Built with esbuild */
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var debug_exports = {};
__export(debug_exports, {
  debug: () => debug,
  debugCache: () => debugCache,
  debugCacheNs: () => debugCacheNs,
  debugDir: () => debugDir,
  debugDirNs: () => debugDirNs,
  debugLog: () => debugLog,
  debugLogNs: () => debugLogNs,
  debugNs: () => debugNs,
  debuglog: () => debuglog,
  debugtime: () => debugtime,
  isDebug: () => isDebug,
  isDebugNs: () => isDebugNs
});
module.exports = __toCommonJS(debug_exports);
var import_debug = require("./env/debug");
var import_socket = require("./env/socket");
var import_is_unicode_supported = __toESM(require("./external/@socketregistry/is-unicode-supported"));
var import_debug2 = __toESM(require("./external/debug"));
var import_logger = require("./logger");
var import_objects = require("./objects");
var import_spinner = require("./spinner");
var import_strings = require("./strings");
const ReflectApply = Reflect.apply;
const logger = (0, import_logger.getDefaultLogger)();
const debugByNamespace = /* @__PURE__ */ new Map();
// @__NO_SIDE_EFFECTS__
function getDebugJsInstance(namespace) {
  let inst = debugByNamespace.get(namespace);
  if (inst) {
    return inst;
  }
  if (!(0, import_debug.getDebug)() && (0, import_socket.getSocketDebug)() && (namespace === "error" || namespace === "notice")) {
    import_debug2.default.enable(namespace);
  }
  inst = (0, import_debug2.default)(namespace);
  inst.log = customLog;
  debugByNamespace.set(namespace, inst);
  return inst;
}
let _util;
// @__NO_SIDE_EFFECTS__
function getUtil() {
  if (_util === void 0) {
    _util = require("node:util");
  }
  return _util;
}
// @__NO_SIDE_EFFECTS__
function getCallerInfo(stackOffset = 3) {
  let name = "";
  const captureStackTrace = Error.captureStackTrace;
  if (typeof captureStackTrace === "function") {
    const obj = {};
    captureStackTrace(obj, getCallerInfo);
    const stack = obj.stack;
    if (typeof stack === "string") {
      let lineCount = 0;
      let lineStart = 0;
      for (let i = 0, { length } = stack; i < length; i += 1) {
        if (stack[i] === "\n") {
          lineCount += 1;
          if (lineCount < stackOffset) {
            lineStart = i + 1;
          } else {
            const line = stack.slice(lineStart, i).trimStart();
            const match = /(?<=^at\s+).*?(?=\s+\(|$)/.exec(line)?.[0];
            if (match) {
              name = match.replace(/^(?:async|bound|get|new|set)\s+/, "");
              if (name.startsWith("Object.")) {
                const afterDot = name.slice(
                  7
                  /*'Object.'.length*/
                );
                if (!(0, import_objects.hasOwn)(Object, afterDot)) {
                  name = afterDot;
                }
              }
            }
            break;
          }
        }
      }
    }
  }
  return name;
}
// @__NO_SIDE_EFFECTS__
function customLog(...args) {
  const util = /* @__PURE__ */ getUtil();
  const inspectOpts = import_debug2.default.inspectOpts ? {
    ...import_debug2.default.inspectOpts,
    showHidden: import_debug2.default.inspectOpts.showHidden === null ? void 0 : import_debug2.default.inspectOpts.showHidden,
    depth: import_debug2.default.inspectOpts.depth === null || typeof import_debug2.default.inspectOpts.depth === "boolean" ? void 0 : import_debug2.default.inspectOpts.depth
  } : {};
  ReflectApply(logger.info, logger, [
    util.formatWithOptions(inspectOpts, ...args)
  ]);
}
// @__NO_SIDE_EFFECTS__
function extractOptions(namespaces) {
  return namespaces !== null && typeof namespaces === "object" ? { __proto__: null, ...namespaces } : { __proto__: null, namespaces };
}
// @__NO_SIDE_EFFECTS__
function isEnabled(namespaces) {
  if (!(0, import_socket.getSocketDebug)()) {
    return false;
  }
  if (typeof namespaces !== "string" || !namespaces || namespaces === "*") {
    return true;
  }
  const split = namespaces.trim().replace(/\s+/g, ",").split(",").filter(Boolean);
  const names = [];
  const skips = [];
  for (const ns of split) {
    if (ns.startsWith("-")) {
      skips.push(ns.slice(1));
    } else {
      names.push(ns);
    }
  }
  if (names.length && !names.some((ns) => (/* @__PURE__ */ getDebugJsInstance(ns)).enabled)) {
    return false;
  }
  return skips.every((ns) => !(/* @__PURE__ */ getDebugJsInstance(ns)).enabled);
}
function debugDirNs(namespacesOrOpts, obj, inspectOpts) {
  const options = /* @__PURE__ */ extractOptions(namespacesOrOpts);
  const { namespaces } = options;
  if (!/* @__PURE__ */ isEnabled(namespaces)) {
    return;
  }
  const callerName = /* @__PURE__ */ getCallerInfo(4) || "anonymous";
  if (pointingTriangle === void 0) {
    const supported = (0, import_is_unicode_supported.default)();
    pointingTriangle = supported ? "\u25B8" : ">";
  }
  let opts = inspectOpts;
  if (opts === void 0) {
    const debugOpts = import_debug2.default.inspectOpts;
    if (debugOpts) {
      opts = {
        ...debugOpts,
        showHidden: debugOpts.showHidden === null ? void 0 : debugOpts.showHidden,
        depth: debugOpts.depth === null || typeof debugOpts.depth === "boolean" ? null : debugOpts.depth
      };
    }
  }
  const spinnerInstance = options.spinner || (0, import_spinner.getDefaultSpinner)();
  const wasSpinning = spinnerInstance?.isSpinning;
  spinnerInstance?.stop();
  logger.info(`[DEBUG] ${callerName} ${pointingTriangle} object inspection:`);
  logger.dir(obj, inspectOpts);
  if (wasSpinning) {
    spinnerInstance?.start();
  }
}
let pointingTriangle;
function debugNs(namespacesOrOpts, ...args) {
  const options = /* @__PURE__ */ extractOptions(namespacesOrOpts);
  const { namespaces } = options;
  if (!/* @__PURE__ */ isEnabled(namespaces)) {
    return;
  }
  const name = /* @__PURE__ */ getCallerInfo(4) || "anonymous";
  if (pointingTriangle === void 0) {
    const supported = (0, import_is_unicode_supported.default)();
    pointingTriangle = supported ? "\u25B8" : ">";
  }
  const text = args.at(0);
  const logArgs = typeof text === "string" ? [
    (0, import_strings.applyLinePrefix)(
      `${name ? `${name} ${pointingTriangle} ` : ""}${text}`,
      { prefix: "[DEBUG] " }
    ),
    ...args.slice(1)
  ] : args;
  const spinnerInstance = options.spinner || (0, import_spinner.getDefaultSpinner)();
  const wasSpinning = spinnerInstance?.isSpinning;
  spinnerInstance?.stop();
  ReflectApply(logger.info, logger, logArgs);
  if (wasSpinning) {
    spinnerInstance?.start();
  }
}
function debugLogNs(namespacesOrOpts, ...args) {
  const options = /* @__PURE__ */ extractOptions(namespacesOrOpts);
  const { namespaces } = options;
  if (!/* @__PURE__ */ isEnabled(namespaces)) {
    return;
  }
  const callerName = /* @__PURE__ */ getCallerInfo(4) || "anonymous";
  if (pointingTriangle === void 0) {
    const supported = (0, import_is_unicode_supported.default)();
    pointingTriangle = supported ? "\u25B8" : ">";
  }
  const text = args.at(0);
  const logArgs = typeof text === "string" ? [
    (0, import_strings.applyLinePrefix)(
      `${callerName ? `${callerName} ${pointingTriangle} ` : ""}${text}`,
      { prefix: "[DEBUG] " }
    ),
    ...args.slice(1)
  ] : [`[DEBUG] ${callerName} ${pointingTriangle}`, ...args];
  const spinnerInstance = options.spinner || (0, import_spinner.getDefaultSpinner)();
  const wasSpinning = spinnerInstance?.isSpinning;
  spinnerInstance?.stop();
  ReflectApply(logger.info, logger, logArgs);
  if (wasSpinning) {
    spinnerInstance?.start();
  }
}
function debugCacheNs(namespacesOrOpts, operation, key, meta) {
  const options = /* @__PURE__ */ extractOptions(namespacesOrOpts);
  const { namespaces } = options;
  if (!/* @__PURE__ */ isEnabled(namespaces)) {
    return;
  }
  const callerName = /* @__PURE__ */ getCallerInfo(4) || "cache";
  if (pointingTriangle === void 0) {
    const supported = (0, import_is_unicode_supported.default)();
    pointingTriangle = supported ? "\u25B8" : ">";
  }
  const prefix = `[CACHE] ${callerName} ${pointingTriangle} ${operation}: ${key}`;
  const logArgs = meta !== void 0 ? [prefix, meta] : [prefix];
  const spinnerInstance = options.spinner || (0, import_spinner.getDefaultSpinner)();
  const wasSpinning = spinnerInstance?.isSpinning;
  spinnerInstance?.stop();
  ReflectApply(logger.info, logger, logArgs);
  if (wasSpinning) {
    spinnerInstance?.start();
  }
}
// @__NO_SIDE_EFFECTS__
function debugCache(operation, key, meta) {
  if (!(0, import_socket.getSocketDebug)()) {
    return;
  }
  const callerName = /* @__PURE__ */ getCallerInfo(3) || "cache";
  if (pointingTriangle === void 0) {
    const supported = (0, import_is_unicode_supported.default)();
    pointingTriangle = supported ? "\u25B8" : ">";
  }
  const prefix = `[CACHE] ${callerName} ${pointingTriangle} ${operation}: ${key}`;
  const args = meta !== void 0 ? [prefix, meta] : [prefix];
  console.log(...args);
}
// @__NO_SIDE_EFFECTS__
function isDebugNs(namespaces) {
  return !!(0, import_socket.getSocketDebug)() && /* @__PURE__ */ isEnabled(namespaces);
}
function debug(...args) {
  debugNs("*", ...args);
}
function debugDir(obj, inspectOpts) {
  debugDirNs("*", obj, inspectOpts);
}
function debugLog(...args) {
  debugLogNs("*", ...args);
}
// @__NO_SIDE_EFFECTS__
function isDebug() {
  return !!(0, import_socket.getSocketDebug)();
}
// @__NO_SIDE_EFFECTS__
function debuglog(section) {
  const util = /* @__PURE__ */ getUtil();
  return util.debuglog(section);
}
// @__NO_SIDE_EFFECTS__
function debugtime(label) {
  const util = /* @__PURE__ */ getUtil();
  let startTime;
  const impl = () => {
    if (startTime === void 0) {
      startTime = Date.now();
    } else {
      const duration = Date.now() - startTime;
      util.debuglog("time")(`${label}: ${duration}ms`);
      startTime = void 0;
    }
  };
  impl.start = () => {
    startTime = Date.now();
  };
  impl.end = () => {
    if (startTime !== void 0) {
      const duration = Date.now() - startTime;
      util.debuglog("time")(`${label}: ${duration}ms`);
      startTime = void 0;
    }
  };
  return impl;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  debug,
  debugCache,
  debugCacheNs,
  debugDir,
  debugDirNs,
  debugLog,
  debugLogNs,
  debugNs,
  debuglog,
  debugtime,
  isDebug,
  isDebugNs
});
