import {
  Input
} from "/build/_shared/chunk-E6JFCF7O.js";
import {
  import_dayjs,
  require_timezone
} from "/build/_shared/chunk-RZ7SUTHK.js";
import {
  flexRender,
  getCoreRowModel,
  getExpandedRowModel,
  getFilteredRowModel,
  getSortedRowModel,
  useReactTable
} from "/build/_shared/chunk-BE5T5FJF.js";
import {
  Pagination
} from "/build/_shared/chunk-66K6NTQO.js";
import {
  PageDocLink
} from "/build/_shared/chunk-T75MUU5G.js";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger
} from "/build/_shared/chunk-BWG25Z4X.js";
import "/build/_shared/chunk-JZ6W5YHO.js";
import {
  Button
} from "/build/_shared/chunk-UWBTKPLD.js";
import {
  SquareArrowUpRight
} from "/build/_shared/chunk-7FHGZRTC.js";
import {
  Badge,
  idShortener
} from "/build/_shared/chunk-634BMO4L.js";
import "/build/_shared/chunk-HUUSILLY.js";
import {
  PageSubtitle
} from "/build/_shared/chunk-VV3RU6RL.js";
import "/build/_shared/chunk-VO5VXZGS.js";
import "/build/_shared/chunk-4R7ODGQQ.js";
import "/build/_shared/chunk-A4I3UNHM.js";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow
} from "/build/_shared/chunk-P3C75TI5.js";
import {
  PageLayout
} from "/build/_shared/chunk-BXT5AGPN.js";
import "/build/_shared/chunk-5YPGPC4O.js";
import "/build/_shared/chunk-7K73PJIB.js";
import {
  ChevronDown,
  ChevronRight,
  Eye,
  Search,
  Trash
} from "/build/_shared/chunk-EJE2TVVM.js";
import {
  ChevronDownIcon,
  ChevronUpIcon,
  DotsHorizontalIcon
} from "/build/_shared/chunk-LGQ4GCFK.js";
import {
  useUnmount
} from "/build/_shared/chunk-7NMI3PDC.js";
import "/build/_shared/chunk-AI5FD5Y6.js";
import {
  withAuth
} from "/build/_shared/chunk-NHF4CNMF.js";
import "/build/_shared/chunk-KQKP3VNY.js";
import {
  Link,
  init_esm2 as init_esm,
  useFetcher,
  useLoaderData,
  useParams,
  useSearchParams
} from "/build/_shared/chunk-ZC2TL3GZ.js";
import {
  require_jsx_dev_runtime
} from "/build/_shared/chunk-ED7KKCRB.js";
import "/build/_shared/chunk-RYE6BCZB.js";
import {
  require_react
} from "/build/_shared/chunk-PECDPABK.js";
import {
  require_node
} from "/build/_shared/chunk-G7CHZRZX.js";
import "/build/_shared/chunk-TLLKLDIT.js";
import {
  Routes
} from "/build/_shared/chunk-N27UEDHN.js";
import {
  createHotContext,
  init_remix_hmr
} from "/build/_shared/chunk-G7KTOMTD.js";
import "/build/_shared/chunk-ZIPKILLR.js";
import {
  __commonJS,
  __toESM
} from "/build/_shared/chunk-PNG5AS42.js";

// ../../node_modules/lodash.debounce/index.js
var require_lodash = __commonJS({
  "../../node_modules/lodash.debounce/index.js"(exports, module) {
    var FUNC_ERROR_TEXT = "Expected a function";
    var NAN = 0 / 0;
    var symbolTag = "[object Symbol]";
    var reTrim = /^\s+|\s+$/g;
    var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
    var reIsBinary = /^0b[01]+$/i;
    var reIsOctal = /^0o[0-7]+$/i;
    var freeParseInt = parseInt;
    var freeGlobal = typeof globalThis == "object" && globalThis && globalThis.Object === Object && globalThis;
    var freeSelf = typeof self == "object" && self && self.Object === Object && self;
    var root = freeGlobal || freeSelf || Function("return this")();
    var objectProto = Object.prototype;
    var objectToString = objectProto.toString;
    var nativeMax = Math.max;
    var nativeMin = Math.min;
    var now = function() {
      return root.Date.now();
    };
    function debounce2(func, wait, options) {
      var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true;
      if (typeof func != "function") {
        throw new TypeError(FUNC_ERROR_TEXT);
      }
      wait = toNumber(wait) || 0;
      if (isObject(options)) {
        leading = !!options.leading;
        maxing = "maxWait" in options;
        maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
        trailing = "trailing" in options ? !!options.trailing : trailing;
      }
      function invokeFunc(time) {
        var args = lastArgs, thisArg = lastThis;
        lastArgs = lastThis = void 0;
        lastInvokeTime = time;
        result = func.apply(thisArg, args);
        return result;
      }
      function leadingEdge(time) {
        lastInvokeTime = time;
        timerId = setTimeout(timerExpired, wait);
        return leading ? invokeFunc(time) : result;
      }
      function remainingWait(time) {
        var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, result2 = wait - timeSinceLastCall;
        return maxing ? nativeMin(result2, maxWait - timeSinceLastInvoke) : result2;
      }
      function shouldInvoke(time) {
        var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime;
        return lastCallTime === void 0 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
      }
      function timerExpired() {
        var time = now();
        if (shouldInvoke(time)) {
          return trailingEdge(time);
        }
        timerId = setTimeout(timerExpired, remainingWait(time));
      }
      function trailingEdge(time) {
        timerId = void 0;
        if (trailing && lastArgs) {
          return invokeFunc(time);
        }
        lastArgs = lastThis = void 0;
        return result;
      }
      function cancel() {
        if (timerId !== void 0) {
          clearTimeout(timerId);
        }
        lastInvokeTime = 0;
        lastArgs = lastCallTime = lastThis = timerId = void 0;
      }
      function flush() {
        return timerId === void 0 ? result : trailingEdge(now());
      }
      function debounced() {
        var time = now(), isInvoking = shouldInvoke(time);
        lastArgs = arguments;
        lastThis = this;
        lastCallTime = time;
        if (isInvoking) {
          if (timerId === void 0) {
            return leadingEdge(lastCallTime);
          }
          if (maxing) {
            timerId = setTimeout(timerExpired, wait);
            return invokeFunc(lastCallTime);
          }
        }
        if (timerId === void 0) {
          timerId = setTimeout(timerExpired, wait);
        }
        return result;
      }
      debounced.cancel = cancel;
      debounced.flush = flush;
      return debounced;
    }
    function isObject(value) {
      var type = typeof value;
      return !!value && (type == "object" || type == "function");
    }
    function isObjectLike(value) {
      return !!value && typeof value == "object";
    }
    function isSymbol(value) {
      return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag;
    }
    function toNumber(value) {
      if (typeof value == "number") {
        return value;
      }
      if (isSymbol(value)) {
        return NAN;
      }
      if (isObject(value)) {
        var other = typeof value.valueOf == "function" ? value.valueOf() : value;
        value = isObject(other) ? other + "" : other;
      }
      if (typeof value != "string") {
        return value === 0 ? value : +value;
      }
      value = value.replace(reTrim, "");
      var isBinary = reIsBinary.test(value);
      return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
    }
    module.exports = debounce2;
  }
});

// app/routes/app+/project+/$projectId+/env+/$envId+/traces+/index.tsx
init_remix_hmr();
var import_node = __toESM(require_node(), 1);
init_esm();

// app/pages/traces/TracesPage.tsx
init_remix_hmr();
init_esm();
var React = __toESM(require_react(), 1);
var import_react5 = __toESM(require_react(), 1);

// app/hooks/useDebounceValue.ts
init_remix_hmr();
var import_react2 = __toESM(require_react(), 1);

// app/hooks/useDebounceCallback.ts
init_remix_hmr();
var import_lodash = __toESM(require_lodash(), 1);
var import_react = __toESM(require_react(), 1);
if (import.meta) {
  import.meta.hot = createHotContext(
    //@ts-expect-error
    "app/hooks/useDebounceCallback.ts"
  );
  import.meta.hot.lastModified = "1711302155289.486";
}
function useDebounceCallback(func, delay = 500, options) {
  const debouncedFunc = (0, import_react.useRef)();
  useUnmount(() => {
    if (debouncedFunc.current) {
      debouncedFunc.current.cancel();
    }
  });
  const debounced = (0, import_react.useMemo)(() => {
    const debouncedFuncInstance = (0, import_lodash.default)(func, delay, options);
    const wrappedFunc = (...args) => {
      return debouncedFuncInstance(...args);
    };
    wrappedFunc.cancel = () => {
      debouncedFuncInstance.cancel();
    };
    wrappedFunc.isPending = () => {
      return !!debouncedFunc.current;
    };
    wrappedFunc.flush = () => {
      return debouncedFuncInstance.flush();
    };
    return wrappedFunc;
  }, [func, delay, options]);
  (0, import_react.useEffect)(() => {
    debouncedFunc.current = (0, import_lodash.default)(func, delay, options);
  }, [func, delay, options]);
  return debounced;
}

// app/hooks/useDebounceValue.ts
if (import.meta) {
  import.meta.hot = createHotContext(
    //@ts-expect-error
    "app/hooks/useDebounceValue.ts"
  );
  import.meta.hot.lastModified = "1710795853618.2888";
}
function useDebounceValue(initialValue, delay, options) {
  const eq = options?.equalityFn ?? ((left, right) => left === right);
  const unwrappedInitialValue = initialValue instanceof Function ? initialValue() : initialValue;
  const [debouncedValue, setDebouncedValue] = (0, import_react2.useState)(unwrappedInitialValue);
  const previousValueRef = (0, import_react2.useRef)(unwrappedInitialValue);
  const updateDebouncedValue = useDebounceCallback(setDebouncedValue, delay, options);
  if (!eq(previousValueRef.current, unwrappedInitialValue)) {
    updateDebouncedValue(unwrappedInitialValue);
    previousValueRef.current = unwrappedInitialValue;
  }
  return [debouncedValue, updateDebouncedValue];
}

// app/pages/traces/types.ts
init_remix_hmr();
if (import.meta) {
  import.meta.hot = createHotContext(
    //@ts-expect-error
    "app/pages/traces/types.ts"
  );
  import.meta.hot.lastModified = "1713211579532.1519";
}
var formatTraces = (traces) => {
  return traces.map((trace) => {
    const logMap = {};
    trace.logs.forEach((log) => {
      const row = formatLog(log);
      if (log.parentLogId === null) {
        if (!logMap[trace.id]) {
          logMap[trace.id] = [];
        }
        logMap[trace.id].push(row);
      } else {
        if (!logMap[log.parentLogId]) {
          logMap[log.parentLogId] = [];
        }
        logMap[log.parentLogId].push(row);
      }
    });
    const assignSubRows = (parentRows, depth) => {
      parentRows.forEach((row) => {
        row.depth = depth;
        if (logMap[row.id]) {
          row.subRows = logMap[row.id];
          assignSubRows(row.subRows, depth + 1);
        }
      });
    };
    const topLevelRows = logMap[trace.id] || [];
    assignSubRows(topLevelRows, 2);
    return {
      type: "trace",
      traceId: trace.id,
      id: trace.id,
      name: trace.name,
      startTime: trace.startTime,
      latency: trace.duration,
      totalCost: trace.totalCost,
      totalTokens: trace.totalTokens,
      model: null,
      subRows: topLevelRows,
      depth: 1
    };
  });
};
var formatLog = (log) => {
  return {
    type: "log",
    traceId: log.traceId,
    id: log.id,
    name: log.name,
    startTime: log.startTime || log.createdAt,
    latency: log.duration,
    totalCost: log.totalCost,
    totalTokens: log.totalTokens,
    model: log.model,
    subRows: [],
    depth: 0
  };
};

// app/pages/traces/components/TracesTableHeader.tsx
init_remix_hmr();
var import_jsx_dev_runtime = __toESM(require_jsx_dev_runtime(), 1);
if (!window.$RefreshReg$ || !window.$RefreshSig$ || !window.$RefreshRuntime$) {
  console.warn("remix:hmr: React Fast Refresh only works when the Remix compiler is running in development mode.");
} else {
  prevRefreshReg = window.$RefreshReg$;
  prevRefreshSig = window.$RefreshSig$;
  window.$RefreshReg$ = (type, id) => {
    window.$RefreshRuntime$.register(type, '"app/pages/traces/components/TracesTableHeader.tsx"' + id);
  };
  window.$RefreshSig$ = window.$RefreshRuntime$.createSignatureFunctionForTransform;
}
var prevRefreshReg;
var prevRefreshSig;
if (import.meta) {
  import.meta.hot = createHotContext(
    //@ts-expect-error
    "app/pages/traces/components/TracesTableHeader.tsx"
  );
}
var TracesTableHeader = ({
  searchQuery,
  onSearch,
  currentPage,
  totalPages
}) => {
  return /* @__PURE__ */ (0, import_jsx_dev_runtime.jsxDEV)("div", { className: "gap- mb-4 flex items-center justify-between", children: [
    /* @__PURE__ */ (0, import_jsx_dev_runtime.jsxDEV)("div", { className: "relative flex max-w-[400px] flex-1", children: [
      /* @__PURE__ */ (0, import_jsx_dev_runtime.jsxDEV)(Input, { placeholder: "Search by log name", value: searchQuery, onChange: (e) => onSearch(e.target.value), className: "w-full rounded border py-2 pl-10 pr-4" }, void 0, false, {
        fileName: "app/pages/traces/components/TracesTableHeader.tsx",
        lineNumber: 32,
        columnNumber: 9
      }, this),
      /* @__PURE__ */ (0, import_jsx_dev_runtime.jsxDEV)("div", { className: "absolute inset-y-0 left-0 flex items-center pl-3", children: /* @__PURE__ */ (0, import_jsx_dev_runtime.jsxDEV)(Search, { className: "h-4 w-4 text-gray-500" }, void 0, false, {
        fileName: "app/pages/traces/components/TracesTableHeader.tsx",
        lineNumber: 35,
        columnNumber: 11
      }, this) }, void 0, false, {
        fileName: "app/pages/traces/components/TracesTableHeader.tsx",
        lineNumber: 34,
        columnNumber: 9
      }, this)
    ] }, void 0, true, {
      fileName: "app/pages/traces/components/TracesTableHeader.tsx",
      lineNumber: 31,
      columnNumber: 7
    }, this),
    /* @__PURE__ */ (0, import_jsx_dev_runtime.jsxDEV)("div", { className: "flex flex-row gap-2", children: /* @__PURE__ */ (0, import_jsx_dev_runtime.jsxDEV)("div", { className: "flex items-center justify-end space-x-2", children: /* @__PURE__ */ (0, import_jsx_dev_runtime.jsxDEV)("div", { className: "space-x-2", children: /* @__PURE__ */ (0, import_jsx_dev_runtime.jsxDEV)(Pagination, { currentPage, totalPages }, void 0, false, {
      fileName: "app/pages/traces/components/TracesTableHeader.tsx",
      lineNumber: 42,
      columnNumber: 13
    }, this) }, void 0, false, {
      fileName: "app/pages/traces/components/TracesTableHeader.tsx",
      lineNumber: 41,
      columnNumber: 11
    }, this) }, void 0, false, {
      fileName: "app/pages/traces/components/TracesTableHeader.tsx",
      lineNumber: 40,
      columnNumber: 9
    }, this) }, void 0, false, {
      fileName: "app/pages/traces/components/TracesTableHeader.tsx",
      lineNumber: 39,
      columnNumber: 7
    }, this)
  ] }, void 0, true, {
    fileName: "app/pages/traces/components/TracesTableHeader.tsx",
    lineNumber: 30,
    columnNumber: 10
  }, this);
};
_c = TracesTableHeader;
var _c;
$RefreshReg$(_c, "TracesTableHeader");
window.$RefreshReg$ = prevRefreshReg;
window.$RefreshSig$ = prevRefreshSig;

// app/pages/traces/constants/columns.tsx
init_remix_hmr();
init_esm();

// app/pages/traces/constants/utils.ts
init_remix_hmr();
if (import.meta) {
  import.meta.hot = createHotContext(
    //@ts-expect-error
    "app/pages/traces/constants/utils.ts"
  );
  import.meta.hot.lastModified = "1713211579531.9705";
}
var calcPadding = (row) => {
  const depth = row.original.depth;
  const hasSubRows = !!row.original.subRows.length;
  const containerPadding = depth >= 2 ? `${depth * 16}px` : "0px";
  const linkPadding = hasSubRows ? "0px" : "8px";
  return { containerPadding, linkPadding };
};

// app/pages/traces/constants/columns.tsx
var import_jsx_dev_runtime2 = __toESM(require_jsx_dev_runtime(), 1);
if (import.meta) {
  import.meta.hot = createHotContext(
    //@ts-expect-error
    "app/pages/traces/constants/columns.tsx"
  );
}
var COLUMNS = [
  // {
  //   id: "select",
  //   header: ({ table }) => (
  //     <Checkbox
  //       checked={table.getIsAllPageRowsSelected() || (table.getIsSomePageRowsSelected() && "indeterminate")}
  //       onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
  //       aria-label="Select all"
  //     />
  //   ),
  //   cell: ({ row }) => (
  //     <Checkbox
  //       checked={row.getIsSelected()}
  //       onCheckedChange={(value) => row.toggleSelected(!!value)}
  //       aria-label="Select row"
  //     />
  //   ),
  //   enableSorting: false,
  //   enableHiding: false,
  // },
  {
    accessorKey: "name",
    header: "Name",
    cell: ({ row }) => {
      const { containerPadding, linkPadding } = calcPadding(row);
      const params = useParams();
      const name = row.getValue("name")?.substring(0, 15);
      const traceId = row.original.traceId;
      const logId = row.original.id;
      const traceVariant = idShortener(traceId || "").variant;
      const isTrace = row.original.type === "trace";
      const to = Routes.app.project.env.traceId({
        projectId: params.projectId,
        envId: params.envId,
        traceId,
        logId
      });
      return /* @__PURE__ */ (0, import_jsx_dev_runtime2.jsxDEV)("div", { style: { paddingLeft: containerPadding }, children: [
        row.getCanExpand() ? /* @__PURE__ */ (0, import_jsx_dev_runtime2.jsxDEV)(
          "button",
          {
            ...{
              onClick: row.getToggleExpandedHandler(),
              style: { cursor: "pointer", paddingRight: "8px" }
            },
            children: row.getIsExpanded() ? /* @__PURE__ */ (0, import_jsx_dev_runtime2.jsxDEV)(ChevronDown, { className: "h-4 w-4" }, void 0, false, {
              fileName: "app/pages/traces/constants/columns.tsx",
              lineNumber: 76,
              columnNumber: 38
            }, this) : /* @__PURE__ */ (0, import_jsx_dev_runtime2.jsxDEV)(ChevronRight, { className: "h-4 w-4" }, void 0, false, {
              fileName: "app/pages/traces/constants/columns.tsx",
              lineNumber: 76,
              columnNumber: 78
            }, this)
          },
          void 0,
          false,
          {
            fileName: "app/pages/traces/constants/columns.tsx",
            lineNumber: 70,
            columnNumber: 9
          },
          this
        ) : null,
        /* @__PURE__ */ (0, import_jsx_dev_runtime2.jsxDEV)(Link, { style: { paddingLeft: linkPadding }, to, children: /* @__PURE__ */ (0, import_jsx_dev_runtime2.jsxDEV)(Badge, { variant: isTrace ? traceVariant : "white", children: [
          /* @__PURE__ */ (0, import_jsx_dev_runtime2.jsxDEV)(SquareArrowUpRight, {}, void 0, false, {
            fileName: "app/pages/traces/constants/columns.tsx",
            lineNumber: 81,
            columnNumber: 15
          }, this),
          "\xA0",
          name ?? "",
          name?.length !== row.original.name?.length && "..."
        ] }, void 0, true, {
          fileName: "app/pages/traces/constants/columns.tsx",
          lineNumber: 80,
          columnNumber: 13
        }, this) }, void 0, false, {
          fileName: "app/pages/traces/constants/columns.tsx",
          lineNumber: 79,
          columnNumber: 11
        }, this)
      ] }, void 0, true, {
        fileName: "app/pages/traces/constants/columns.tsx",
        lineNumber: 68,
        columnNumber: 7
      }, this);
    }
  },
  {
    accessorKey: "startTime",
    header: "Start Time",
    cell: ({ row }) => {
      const date = row.getValue("startTime");
      return /* @__PURE__ */ (0, import_jsx_dev_runtime2.jsxDEV)("div", { children: date ?? "\u2014" }, void 0, false, {
        fileName: "app/pages/traces/constants/columns.tsx",
        lineNumber: 96,
        columnNumber: 12
      }, this);
    }
  },
  {
    accessorKey: "latency",
    header: "Latency",
    cell: ({ row }) => {
      const latency = row.getValue("latency");
      return /* @__PURE__ */ (0, import_jsx_dev_runtime2.jsxDEV)("div", { children: latency ? `${latency}s` : "\u2014" }, void 0, false, {
        fileName: "app/pages/traces/constants/columns.tsx",
        lineNumber: 104,
        columnNumber: 12
      }, this);
    }
  },
  {
    accessorKey: "totalTokens",
    header: "Tokens",
    cell: ({ row }) => /* @__PURE__ */ (0, import_jsx_dev_runtime2.jsxDEV)("div", { children: row.getValue("totalTokens") ?? "\u2014" }, void 0, false, {
      fileName: "app/pages/traces/constants/columns.tsx",
      lineNumber: 110,
      columnNumber: 22
    }, this)
  },
  {
    accessorKey: "totalCost",
    header: "Cost",
    cell: ({ row }) => {
      const totalCost = row.getValue("totalCost");
      return /* @__PURE__ */ (0, import_jsx_dev_runtime2.jsxDEV)("div", { children: totalCost ? `$${totalCost}` : "\u2014" }, void 0, false, {
        fileName: "app/pages/traces/constants/columns.tsx",
        lineNumber: 117,
        columnNumber: 12
      }, this);
    }
  },
  {
    accessorKey: "model",
    header: "Model",
    cell: ({ row }) => {
      const model = row.getValue("model");
      return /* @__PURE__ */ (0, import_jsx_dev_runtime2.jsxDEV)("div", { children: model ?? "\u2014" }, void 0, false, {
        fileName: "app/pages/traces/constants/columns.tsx",
        lineNumber: 125,
        columnNumber: 12
      }, this);
    }
  },
  {
    id: "actions",
    enableHiding: false,
    cell: ({ row }) => {
      const params = useParams();
      const fetcher = useFetcher();
      const traceId = row.getValue("traceId");
      const handleDelete = () => {
        fetcher.submit(null, {
          method: "DELETE",
          action: Routes.actions.trace.delete({
            projectId: params.projectId,
            traceId
          })
        });
      };
      return /* @__PURE__ */ (0, import_jsx_dev_runtime2.jsxDEV)(DropdownMenu, { children: [
        /* @__PURE__ */ (0, import_jsx_dev_runtime2.jsxDEV)(DropdownMenuTrigger, { asChild: true, children: /* @__PURE__ */ (0, import_jsx_dev_runtime2.jsxDEV)(Button, { variant: "ghost", className: "h-8 w-8 p-0", children: [
          /* @__PURE__ */ (0, import_jsx_dev_runtime2.jsxDEV)("span", { className: "sr-only", children: "Open menu" }, void 0, false, {
            fileName: "app/pages/traces/constants/columns.tsx",
            lineNumber: 150,
            columnNumber: 15
          }, this),
          /* @__PURE__ */ (0, import_jsx_dev_runtime2.jsxDEV)(DotsHorizontalIcon, { className: "h-4 w-4" }, void 0, false, {
            fileName: "app/pages/traces/constants/columns.tsx",
            lineNumber: 151,
            columnNumber: 15
          }, this)
        ] }, void 0, true, {
          fileName: "app/pages/traces/constants/columns.tsx",
          lineNumber: 149,
          columnNumber: 13
        }, this) }, void 0, false, {
          fileName: "app/pages/traces/constants/columns.tsx",
          lineNumber: 148,
          columnNumber: 11
        }, this),
        /* @__PURE__ */ (0, import_jsx_dev_runtime2.jsxDEV)(DropdownMenuContent, { align: "end", children: [
          /* @__PURE__ */ (0, import_jsx_dev_runtime2.jsxDEV)(DropdownMenuLabel, { children: "Actions" }, void 0, false, {
            fileName: "app/pages/traces/constants/columns.tsx",
            lineNumber: 155,
            columnNumber: 13
          }, this),
          /* @__PURE__ */ (0, import_jsx_dev_runtime2.jsxDEV)(DropdownMenuItem, { className: "gap-2", disabled: true, children: [
            /* @__PURE__ */ (0, import_jsx_dev_runtime2.jsxDEV)(Eye, { size: 16 }, void 0, false, {
              fileName: "app/pages/traces/constants/columns.tsx",
              lineNumber: 157,
              columnNumber: 15
            }, this),
            " Quick View"
          ] }, void 0, true, {
            fileName: "app/pages/traces/constants/columns.tsx",
            lineNumber: 156,
            columnNumber: 13
          }, this),
          /* @__PURE__ */ (0, import_jsx_dev_runtime2.jsxDEV)(DropdownMenuSeparator, {}, void 0, false, {
            fileName: "app/pages/traces/constants/columns.tsx",
            lineNumber: 159,
            columnNumber: 13
          }, this),
          /* @__PURE__ */ (0, import_jsx_dev_runtime2.jsxDEV)(DropdownMenuItem, { className: "text-destructive gap-2", onClick: handleDelete, children: [
            /* @__PURE__ */ (0, import_jsx_dev_runtime2.jsxDEV)(Trash, { size: 16 }, void 0, false, {
              fileName: "app/pages/traces/constants/columns.tsx",
              lineNumber: 161,
              columnNumber: 15
            }, this),
            " Delete Trace"
          ] }, void 0, true, {
            fileName: "app/pages/traces/constants/columns.tsx",
            lineNumber: 160,
            columnNumber: 13
          }, this)
        ] }, void 0, true, {
          fileName: "app/pages/traces/constants/columns.tsx",
          lineNumber: 154,
          columnNumber: 11
        }, this)
      ] }, void 0, true, {
        fileName: "app/pages/traces/constants/columns.tsx",
        lineNumber: 147,
        columnNumber: 7
      }, this);
    }
  }
];

// app/pages/traces/TracesPage.tsx
var import_jsx_dev_runtime3 = __toESM(require_jsx_dev_runtime(), 1);
if (!window.$RefreshReg$ || !window.$RefreshSig$ || !window.$RefreshRuntime$) {
  console.warn("remix:hmr: React Fast Refresh only works when the Remix compiler is running in development mode.");
} else {
  prevRefreshReg = window.$RefreshReg$;
  prevRefreshSig = window.$RefreshSig$;
  window.$RefreshReg$ = (type, id) => {
    window.$RefreshRuntime$.register(type, '"app/pages/traces/TracesPage.tsx"' + id);
  };
  window.$RefreshSig$ = window.$RefreshRuntime$.createSignatureFunctionForTransform;
}
var prevRefreshReg;
var prevRefreshSig;
var _s = $RefreshSig$();
if (import.meta) {
  import.meta.hot = createHotContext(
    //@ts-expect-error
    "app/pages/traces/TracesPage.tsx"
  );
}
function TracesPage({
  traces,
  currentPage,
  totalPages
}) {
  _s();
  const [searchParams, setSearchParams] = useSearchParams();
  const [searchQuery, setSearchQuery] = React.useState(searchParams.get("q") || "");
  const [debouncedSearchQuery] = useDebounceValue(searchQuery, 300);
  const paramsSortColumn = searchParams.get("sortColumn");
  const paramsSortDirection = searchParams.get("sortDirection");
  const defaultSorting = paramsSortColumn && paramsSortDirection ? [{
    id: paramsSortColumn,
    desc: paramsSortDirection === "desc"
  }] : [];
  const [sorting, setSorting] = React.useState(defaultSorting);
  const [columnFilters, setColumnFilters] = React.useState([]);
  const [columnVisibility, setColumnVisibility] = React.useState({
    inputTokens: false,
    outputTokens: false,
    inputCost: false,
    outputCost: false
  });
  const [rowSelection, setRowSelection] = React.useState({});
  const [expanded, setExpanded] = React.useState({});
  const onSortingChange = (updaterOrValue) => {
    setSorting((oldSorting) => {
      const newSorting = typeof updaterOrValue === "function" ? updaterOrValue(oldSorting) : updaterOrValue;
      const params = new URLSearchParams(searchParams.toString());
      const sortColumn = newSorting.length ? newSorting[0].id : void 0;
      const sortDirection = newSorting.length ? newSorting[0].desc ? "desc" : "asc" : void 0;
      if (sortColumn && sortDirection) {
        params.set("sortColumn", sortColumn);
        params.set("sortDirection", sortDirection);
      } else {
        params.delete("sortColumn");
        params.delete("sortDirection");
      }
      setSearchParams(params);
      return newSorting;
    });
  };
  const updateSearchQueryParam = () => {
    setSearchParams((prev) => {
      if (debouncedSearchQuery) {
        prev.set("q", debouncedSearchQuery);
      } else {
        prev.delete("q");
      }
      return prev;
    });
  };
  (0, import_react5.useEffect)(updateSearchQueryParam, [debouncedSearchQuery]);
  const formattedRows = formatTraces(traces);
  const table = useReactTable({
    data: formattedRows,
    columns: COLUMNS,
    manualPagination: true,
    manualSorting: true,
    enableSorting: true,
    getSubRows: (row) => row.subRows,
    onExpandedChange: setExpanded,
    onSortingChange,
    onColumnFiltersChange: setColumnFilters,
    getCoreRowModel: getCoreRowModel(),
    getSortedRowModel: getSortedRowModel(),
    getFilteredRowModel: getFilteredRowModel(),
    getExpandedRowModel: getExpandedRowModel(),
    onColumnVisibilityChange: setColumnVisibility,
    onRowSelectionChange: setRowSelection,
    state: {
      expanded,
      sorting,
      columnFilters,
      columnVisibility,
      rowSelection
    }
  });
  const breadcrumbs = [{
    label: "Traces"
  }];
  const subtitle = () => {
    return /* @__PURE__ */ (0, import_jsx_dev_runtime3.jsxDEV)(PageSubtitle, { children: [
      "Traces group several logs under a single entity.",
      " ",
      /* @__PURE__ */ (0, import_jsx_dev_runtime3.jsxDEV)(PageDocLink, { to: Routes.external.docs.traces, children: "Trace Docs." }, void 0, false, {
        fileName: "app/pages/traces/TracesPage.tsx",
        lineNumber: 120,
        columnNumber: 9
      }, this)
    ] }, void 0, true, {
      fileName: "app/pages/traces/TracesPage.tsx",
      lineNumber: 118,
      columnNumber: 12
    }, this);
  };
  return /* @__PURE__ */ (0, import_jsx_dev_runtime3.jsxDEV)(PageLayout, { breadcrumbs, subtitle, children: /* @__PURE__ */ (0, import_jsx_dev_runtime3.jsxDEV)("div", { children: [
    /* @__PURE__ */ (0, import_jsx_dev_runtime3.jsxDEV)(TracesTableHeader, { searchQuery, onSearch: setSearchQuery, currentPage, totalPages }, void 0, false, {
      fileName: "app/pages/traces/TracesPage.tsx",
      lineNumber: 125,
      columnNumber: 9
    }, this),
    /* @__PURE__ */ (0, import_jsx_dev_runtime3.jsxDEV)("div", { className: "mb-2 rounded-md border", children: /* @__PURE__ */ (0, import_jsx_dev_runtime3.jsxDEV)(Table, { children: [
      /* @__PURE__ */ (0, import_jsx_dev_runtime3.jsxDEV)(TableHeader, { children: table.getHeaderGroups().map((headerGroup) => /* @__PURE__ */ (0, import_jsx_dev_runtime3.jsxDEV)(TableRow, { children: headerGroup.headers.map((header) => {
        const isSorted = header.column.getIsSorted();
        return /* @__PURE__ */ (0, import_jsx_dev_runtime3.jsxDEV)(TableHead, { className: header.column.getCanSort() ? "hover:text-accent-foreground cursor-pointer" : "", onClick: header.column.getToggleSortingHandler(), children: /* @__PURE__ */ (0, import_jsx_dev_runtime3.jsxDEV)("div", { className: "flex items-center gap-1" + (isSorted ? " font-semibold" : ""), children: [
          header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext()),
          /* @__PURE__ */ (0, import_jsx_dev_runtime3.jsxDEV)("span", { children: isSorted && (header.column.getIsSorted() === "desc" ? /* @__PURE__ */ (0, import_jsx_dev_runtime3.jsxDEV)(ChevronDownIcon, {}, void 0, false, {
            fileName: "app/pages/traces/TracesPage.tsx",
            lineNumber: 139,
            columnNumber: 84
          }, this) : /* @__PURE__ */ (0, import_jsx_dev_runtime3.jsxDEV)(ChevronUpIcon, {}, void 0, false, {
            fileName: "app/pages/traces/TracesPage.tsx",
            lineNumber: 139,
            columnNumber: 106
          }, this)) }, void 0, false, {
            fileName: "app/pages/traces/TracesPage.tsx",
            lineNumber: 138,
            columnNumber: 27
          }, this)
        ] }, void 0, true, {
          fileName: "app/pages/traces/TracesPage.tsx",
          lineNumber: 136,
          columnNumber: 25
        }, this) }, header.id, false, {
          fileName: "app/pages/traces/TracesPage.tsx",
          lineNumber: 134,
          columnNumber: 24
        }, this);
      }) }, headerGroup.id, false, {
        fileName: "app/pages/traces/TracesPage.tsx",
        lineNumber: 131,
        columnNumber: 59
      }, this)) }, void 0, false, {
        fileName: "app/pages/traces/TracesPage.tsx",
        lineNumber: 130,
        columnNumber: 13
      }, this),
      /* @__PURE__ */ (0, import_jsx_dev_runtime3.jsxDEV)(TableBody, { children: table.getRowModel().rows?.length ? table.getRowModel().rows.map((row) => /* @__PURE__ */ (0, import_jsx_dev_runtime3.jsxDEV)(TableRow, { "data-state": row.getIsSelected() && "selected", children: row.getVisibleCells().map((cell) => /* @__PURE__ */ (0, import_jsx_dev_runtime3.jsxDEV)(TableCell, { children: flexRender(cell.column.columnDef.cell, cell.getContext()) }, cell.id, false, {
        fileName: "app/pages/traces/TracesPage.tsx",
        lineNumber: 148,
        columnNumber: 56
      }, this)) }, row.id, false, {
        fileName: "app/pages/traces/TracesPage.tsx",
        lineNumber: 147,
        columnNumber: 87
      }, this)) : /* @__PURE__ */ (0, import_jsx_dev_runtime3.jsxDEV)(TableRow, { children: /* @__PURE__ */ (0, import_jsx_dev_runtime3.jsxDEV)(TableCell, { colSpan: COLUMNS.length, className: "h-24 text-center", children: "No results." }, void 0, false, {
        fileName: "app/pages/traces/TracesPage.tsx",
        lineNumber: 150,
        columnNumber: 19
      }, this) }, void 0, false, {
        fileName: "app/pages/traces/TracesPage.tsx",
        lineNumber: 149,
        columnNumber: 34
      }, this) }, void 0, false, {
        fileName: "app/pages/traces/TracesPage.tsx",
        lineNumber: 146,
        columnNumber: 13
      }, this)
    ] }, void 0, true, {
      fileName: "app/pages/traces/TracesPage.tsx",
      lineNumber: 129,
      columnNumber: 11
    }, this) }, void 0, false, {
      fileName: "app/pages/traces/TracesPage.tsx",
      lineNumber: 128,
      columnNumber: 9
    }, this)
  ] }, void 0, true, {
    fileName: "app/pages/traces/TracesPage.tsx",
    lineNumber: 124,
    columnNumber: 7
  }, this) }, void 0, false, {
    fileName: "app/pages/traces/TracesPage.tsx",
    lineNumber: 123,
    columnNumber: 10
  }, this);
}
_s(TracesPage, "4i1sRuQ8ZmfINSmw6eRvzm72YuM=", false, function() {
  return [useSearchParams, useDebounceValue, useReactTable];
});
_c2 = TracesPage;
var _c2;
$RefreshReg$(_c2, "TracesPage");
window.$RefreshReg$ = prevRefreshReg;
window.$RefreshSig$ = prevRefreshSig;

// app/pages/traces/utils/dateFormatter.ts
init_remix_hmr();
if (import.meta) {
  import.meta.hot = createHotContext(
    //@ts-expect-error
    "app/pages/traces/utils/dateFormatter.ts"
  );
  import.meta.hot.lastModified = "1713211579532.535";
}
var formatTraceDates = (traces, timezone) => {
  return traces.map((trace) => {
    const updatedLogs = trace.logs.map((log) => {
      return {
        ...log,
        createdAt: (0, import_dayjs.default)(log.createdAt).tz(timezone).format("h:mm:ssa - D/M/YY"),
        startTime: (0, import_dayjs.default)(log.startTime).tz(timezone).format("h:mm:ssa - D/M/YY")
      };
    });
    return {
      ...trace,
      logs: updatedLogs,
      startTime: (0, import_dayjs.default)(trace.startTime).tz(timezone).format("h:mm:ssa - D/M/YY")
    };
  });
};

// app/routes/app+/project+/$projectId+/env+/$envId+/traces+/index.tsx
var import_timezone = __toESM(require_timezone(), 1);
var import_jsx_dev_runtime4 = __toESM(require_jsx_dev_runtime(), 1);
if (!window.$RefreshReg$ || !window.$RefreshSig$ || !window.$RefreshRuntime$) {
  console.warn("remix:hmr: React Fast Refresh only works when the Remix compiler is running in development mode.");
} else {
  prevRefreshReg = window.$RefreshReg$;
  prevRefreshSig = window.$RefreshSig$;
  window.$RefreshReg$ = (type, id) => {
    window.$RefreshRuntime$.register(type, '"app/routes/app+/project+/$projectId+/env+/$envId+/traces+/index.tsx"' + id);
  };
  window.$RefreshSig$ = window.$RefreshRuntime$.createSignatureFunctionForTransform;
}
var prevRefreshReg;
var prevRefreshSig;
var _s2 = $RefreshSig$();
if (import.meta) {
  import.meta.hot = createHotContext(
    //@ts-expect-error
    "app/routes/app+/project+/$projectId+/env+/$envId+/traces+/index.tsx"
  );
  import.meta.hot.lastModified = "1713211579533.561";
}
var loader = withAuth(async ({
  request,
  api,
  params
}) => {
  const envId = params.envId;
  const {
    searchParams
  } = new URL(request.url);
  const page = parseInt(searchParams.get("page") || "1");
  const sortColumn = searchParams.get("sortColumn");
  const sortDirection = searchParams.get("sortDirection");
  const searchQuery = searchParams.get("q");
  const pageSize = 20;
  const skipAmount = (page - 1) * pageSize;
  const response = await api.trace.traceControllerGetTracesForEnv({
    envId,
    take: pageSize.toString(),
    skip: skipAmount.toString(),
    sortColumn: sortColumn && sortColumn !== "undefined" ? sortColumn : void 0,
    sortDirection: sortDirection && sortDirection !== "undefined" ? sortDirection : void 0,
    searchQuery: searchQuery && searchQuery !== "undefined" ? searchQuery : void 0
  });
  const {
    traces,
    totalCount
  } = response;
  const timezone = await (0, import_timezone.getTimezone)(request);
  const formattedTraces = formatTraceDates(traces, timezone);
  return (0, import_node.json)({
    traces: formattedTraces,
    currentPage: page,
    totalPages: totalCount ? Math.ceil(totalCount / pageSize) : 0,
    timezone
  });
});
function TracesRoute() {
  _s2();
  const {
    traces,
    currentPage,
    totalPages,
    timezone
  } = useLoaderData();
  const formattedTraces = timezone ? traces : formatTraceDates(traces, timezone);
  return /* @__PURE__ */ (0, import_jsx_dev_runtime4.jsxDEV)(TracesPage, { traces: formattedTraces, currentPage, totalPages }, void 0, false, {
    fileName: "app/routes/app+/project+/$projectId+/env+/$envId+/traces+/index.tsx",
    lineNumber: 73,
    columnNumber: 10
  }, this);
}
_s2(TracesRoute, "AliRmUYgFMKPRyA0+MXo+fMgKDo=", false, function() {
  return [useLoaderData];
});
_c3 = TracesRoute;
var _c3;
$RefreshReg$(_c3, "TracesRoute");
window.$RefreshReg$ = prevRefreshReg;
window.$RefreshSig$ = prevRefreshSig;
export {
  TracesRoute as default
};
//# sourceMappingURL=/build/routes/app+/project+/$projectId+/env+/$envId+/traces+/index-PNSADJBB.js.map
