@cupcodev/ui 2.0.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -237,6 +237,11 @@ __export(src_exports, {
237
237
  NavigationMenuList: () => NavigationMenuList,
238
238
  NavigationMenuTrigger: () => NavigationMenuTrigger,
239
239
  NavigationMenuViewport: () => NavigationMenuViewport,
240
+ PRESENCE_ACTIVITY_THROTTLE_MS_ENV_KEY: () => PRESENCE_ACTIVITY_THROTTLE_MS_ENV_KEY,
241
+ PRESENCE_HEARTBEAT_INTERVAL_MS_ENV_KEY: () => PRESENCE_HEARTBEAT_INTERVAL_MS_ENV_KEY,
242
+ PRESENCE_IDLE_TIMEOUT_MS_ENV_KEY: () => PRESENCE_IDLE_TIMEOUT_MS_ENV_KEY,
243
+ PRESENCE_OFFLINE_TIMEOUT_MS_ENV_KEY: () => PRESENCE_OFFLINE_TIMEOUT_MS_ENV_KEY,
244
+ PRESENCE_RUNTIME_ENV_KEYS: () => PRESENCE_RUNTIME_ENV_KEYS,
240
245
  Pagination: () => Pagination,
241
246
  PaginationContent: () => PaginationContent,
242
247
  PaginationEllipsis: () => PaginationEllipsis,
@@ -350,6 +355,8 @@ __export(src_exports, {
350
355
  TooltipCupcode: () => TooltipCupcode,
351
356
  TooltipProvider: () => TooltipProvider,
352
357
  TooltipTrigger: () => TooltipTrigger,
358
+ USER_PRESENCE_LAST_ACTIVE_COLUMN_ENV_KEY: () => USER_PRESENCE_LAST_ACTIVE_COLUMN_ENV_KEY,
359
+ USER_PRESENCE_SOURCE_COLUMN_ENV_KEY: () => USER_PRESENCE_SOURCE_COLUMN_ENV_KEY,
353
360
  UserMenuCupcode: () => UserMenuCupcode,
354
361
  badgeVariants: () => badgeVariants,
355
362
  buildAuthorizeUrl: () => buildAuthorizeUrl,
@@ -1360,10 +1367,10 @@ var Dock = ({ items, className }) => {
1360
1367
  const itemsRef = (0, import_react5.useRef)([]);
1361
1368
  const OVERSHOOT = 5;
1362
1369
  (0, import_react5.useEffect)(() => {
1363
- var _a74;
1370
+ var _a78;
1364
1371
  const activeItem = itemsRef.current[activeIndex];
1365
1372
  if (!activeItem) return;
1366
- const containerRect = (_a74 = activeItem.parentElement) == null ? void 0 : _a74.getBoundingClientRect();
1373
+ const containerRect = (_a78 = activeItem.parentElement) == null ? void 0 : _a78.getBoundingClientRect();
1367
1374
  const itemRect = activeItem.getBoundingClientRect();
1368
1375
  if (!containerRect) return;
1369
1376
  const relativeLeft = itemRect.left - containerRect.left;
@@ -1425,9 +1432,9 @@ var Dock = ({ items, className }) => {
1425
1432
  "button",
1426
1433
  {
1427
1434
  onClick: () => {
1428
- var _a74;
1435
+ var _a78;
1429
1436
  setActiveIndex(index);
1430
- (_a74 = item.onClick) == null ? void 0 : _a74.call(item);
1437
+ (_a78 = item.onClick) == null ? void 0 : _a78.call(item);
1431
1438
  },
1432
1439
  className: cn(
1433
1440
  "flex items-center justify-center w-12 h-12 rounded-xl",
@@ -1471,6 +1478,20 @@ var CUPCODE_APP_VERSION_ENV_KEYS = [
1471
1478
  "NEXT_PUBLIC_APP_VERSION",
1472
1479
  "REACT_APP_VERSION"
1473
1480
  ];
1481
+ var USER_PRESENCE_SOURCE_COLUMN_ENV_KEY = "VITE_USER_PRESENCE_SOURCE_COLUMN";
1482
+ var USER_PRESENCE_LAST_ACTIVE_COLUMN_ENV_KEY = "VITE_USER_PRESENCE_LAST_ACTIVE_COLUMN";
1483
+ var PRESENCE_IDLE_TIMEOUT_MS_ENV_KEY = "VITE_PRESENCE_IDLE_TIMEOUT_MS";
1484
+ var PRESENCE_OFFLINE_TIMEOUT_MS_ENV_KEY = "VITE_PRESENCE_OFFLINE_TIMEOUT_MS";
1485
+ var PRESENCE_HEARTBEAT_INTERVAL_MS_ENV_KEY = "VITE_PRESENCE_HEARTBEAT_INTERVAL_MS";
1486
+ var PRESENCE_ACTIVITY_THROTTLE_MS_ENV_KEY = "VITE_PRESENCE_ACTIVITY_THROTTLE_MS";
1487
+ var PRESENCE_RUNTIME_ENV_KEYS = [
1488
+ USER_PRESENCE_SOURCE_COLUMN_ENV_KEY,
1489
+ USER_PRESENCE_LAST_ACTIVE_COLUMN_ENV_KEY,
1490
+ PRESENCE_IDLE_TIMEOUT_MS_ENV_KEY,
1491
+ PRESENCE_OFFLINE_TIMEOUT_MS_ENV_KEY,
1492
+ PRESENCE_HEARTBEAT_INTERVAL_MS_ENV_KEY,
1493
+ PRESENCE_ACTIVITY_THROTTLE_MS_ENV_KEY
1494
+ ];
1474
1495
  var runtimeStore = {};
1475
1496
  var normalizeValue = (value) => {
1476
1497
  if (value === null || typeof value === "undefined") return void 0;
@@ -1481,9 +1502,9 @@ var normalizeValue = (value) => {
1481
1502
  return String(value);
1482
1503
  };
1483
1504
  var setCupcodeRuntimeEnv = (values) => {
1484
- var _a74;
1505
+ var _a78;
1485
1506
  const globalRef = globalThis;
1486
- const nextGlobalEnv = { ...(_a74 = globalRef.__CUPCODE_ENV__) != null ? _a74 : {} };
1507
+ const nextGlobalEnv = { ...(_a78 = globalRef.__CUPCODE_ENV__) != null ? _a78 : {} };
1487
1508
  Object.entries(values).forEach(([key, value]) => {
1488
1509
  const normalized = normalizeValue(value);
1489
1510
  runtimeStore[key] = normalized;
@@ -1492,8 +1513,8 @@ var setCupcodeRuntimeEnv = (values) => {
1492
1513
  globalRef.__CUPCODE_ENV__ = nextGlobalEnv;
1493
1514
  };
1494
1515
  var readFromProcessEnv = (key) => {
1495
- var _a74;
1496
- const processEnv = (_a74 = globalThis.process) == null ? void 0 : _a74.env;
1516
+ var _a78;
1517
+ const processEnv = (_a78 = globalThis.process) == null ? void 0 : _a78.env;
1497
1518
  return normalizeValue(processEnv == null ? void 0 : processEnv[key]);
1498
1519
  };
1499
1520
  var readFromImportMetaEnv = (key) => {
@@ -1505,12 +1526,12 @@ var readFromImportMetaEnv = (key) => {
1505
1526
  }
1506
1527
  };
1507
1528
  var getRuntimeEnv = (key) => {
1508
- var _a74;
1529
+ var _a78;
1509
1530
  const normalizedKey = key.trim();
1510
1531
  if (!normalizedKey) return void 0;
1511
1532
  const fromRuntimeStore = runtimeStore[normalizedKey];
1512
1533
  if (fromRuntimeStore) return fromRuntimeStore;
1513
- const fromGlobalStore = normalizeValue((_a74 = globalThis.__CUPCODE_ENV__) == null ? void 0 : _a74[normalizedKey]);
1534
+ const fromGlobalStore = normalizeValue((_a78 = globalThis.__CUPCODE_ENV__) == null ? void 0 : _a78[normalizedKey]);
1514
1535
  if (fromGlobalStore) return fromGlobalStore;
1515
1536
  const fromGlobalKey = normalizeValue(globalThis[normalizedKey]);
1516
1537
  if (fromGlobalKey) return fromGlobalKey;
@@ -1519,12 +1540,12 @@ var getRuntimeEnv = (key) => {
1519
1540
  return readFromProcessEnv(normalizedKey);
1520
1541
  };
1521
1542
  var getRuntimeEnvOr = (key, fallback) => {
1522
- var _a74;
1523
- return (_a74 = getRuntimeEnv(key)) != null ? _a74 : fallback;
1543
+ var _a78;
1544
+ return (_a78 = getRuntimeEnv(key)) != null ? _a78 : fallback;
1524
1545
  };
1525
1546
  var isRuntimeDev = () => {
1526
- var _a74, _b7, _c;
1527
- const explicitDev = (_a74 = getRuntimeEnv("DEV")) != null ? _a74 : getRuntimeEnv("VITE_DEV");
1547
+ var _a78, _b7, _c;
1548
+ const explicitDev = (_a78 = getRuntimeEnv("DEV")) != null ? _a78 : getRuntimeEnv("VITE_DEV");
1528
1549
  if (explicitDev) {
1529
1550
  const normalized = explicitDev.toLowerCase();
1530
1551
  return normalized === "1" || normalized === "true";
@@ -1550,11 +1571,11 @@ var isUuid = (value) => {
1550
1571
  return UUID_REGEX.test(value.trim());
1551
1572
  };
1552
1573
  function parseAssetId(input) {
1553
- var _a74, _b7, _c, _d;
1574
+ var _a78, _b7, _c, _d;
1554
1575
  const raw = input == null ? void 0 : input.trim();
1555
1576
  if (!raw) return void 0;
1556
1577
  if (UUID_REGEX.test(raw)) return raw;
1557
- const matchFromRaw = (_a74 = raw.match(UUID_IN_TEXT_REGEX)) == null ? void 0 : _a74[0];
1578
+ const matchFromRaw = (_a78 = raw.match(UUID_IN_TEXT_REGEX)) == null ? void 0 : _a78[0];
1558
1579
  if (isUuid(matchFromRaw)) return matchFromRaw;
1559
1580
  try {
1560
1581
  const url = new URL(raw);
@@ -1690,7 +1711,7 @@ var DockWrapper = ({ categories, activeCategoryId }) => {
1690
1711
  return void 0;
1691
1712
  }, [sortedCategories]);
1692
1713
  (0, import_react7.useEffect)(() => {
1693
- var _a74;
1714
+ var _a78;
1694
1715
  const root = rootRef.current;
1695
1716
  if (!root) return;
1696
1717
  const $ = (sel) => root.querySelector(sel);
@@ -1702,7 +1723,7 @@ var DockWrapper = ({ categories, activeCategoryId }) => {
1702
1723
  const getDockItems = () => Array.from(root.querySelectorAll(INTERACTIVE_SELECTOR));
1703
1724
  const dockItems = getDockItems();
1704
1725
  if (!tabbar || !dock || !listMenuShow || !tabbarUl || dockItems.length === 0) return;
1705
- const persistentId = (_a74 = activeCategoryId != null ? activeCategoryId : lastInteractiveId) != null ? _a74 : null;
1726
+ const persistentId = (_a78 = activeCategoryId != null ? activeCategoryId : lastInteractiveId) != null ? _a78 : null;
1706
1727
  let openItem = null;
1707
1728
  let latestToggleToken = null;
1708
1729
  const persistentSelector = persistentId != null ? `${INTERACTIVE_SELECTOR}[data-cat-id="${persistentId}"]` : null;
@@ -2001,8 +2022,8 @@ var DockWrapper = ({ categories, activeCategoryId }) => {
2001
2022
  }, total);
2002
2023
  }
2003
2024
  const hideBootstrapTooltip = (el) => {
2004
- var _a75, _b7;
2005
- const tooltip = ((_b7 = (_a75 = window.bootstrap) == null ? void 0 : _a75.Tooltip) == null ? void 0 : _b7.getInstance) ? window.bootstrap.Tooltip.getInstance(el) : null;
2025
+ var _a79, _b7;
2026
+ const tooltip = ((_b7 = (_a79 = window.bootstrap) == null ? void 0 : _a79.Tooltip) == null ? void 0 : _b7.getInstance) ? window.bootstrap.Tooltip.getInstance(el) : null;
2006
2027
  tooltip == null ? void 0 : tooltip.hide();
2007
2028
  };
2008
2029
  const openMenuForItem = (item, menu) => {
@@ -2020,14 +2041,14 @@ var DockWrapper = ({ categories, activeCategoryId }) => {
2020
2041
  latestToggleToken = null;
2021
2042
  };
2022
2043
  const closeActiveMenu = (opts = {}) => {
2023
- var _a75;
2044
+ var _a79;
2024
2045
  if (!opts.onClosed) {
2025
2046
  latestToggleToken = null;
2026
2047
  }
2027
2048
  const itemToClose = openItem;
2028
2049
  if (!itemToClose) {
2029
2050
  if (!opts.preserveWrapper) ensurePersistentHighlight();
2030
- (_a75 = opts.onClosed) == null ? void 0 : _a75.call(opts);
2051
+ (_a79 = opts.onClosed) == null ? void 0 : _a79.call(opts);
2031
2052
  return;
2032
2053
  }
2033
2054
  const menu = getMenuFor(itemToClose);
@@ -2035,7 +2056,7 @@ var DockWrapper = ({ categories, activeCategoryId }) => {
2035
2056
  itemToClose.classList.remove("active");
2036
2057
  delete itemToClose.dataset.menuOpen;
2037
2058
  const finalize = () => {
2038
- var _a76;
2059
+ var _a80;
2039
2060
  if (!opts.preserveWrapper) {
2040
2061
  listMenuShow.classList.remove("show");
2041
2062
  tabbar.classList.remove("is-active-menu");
@@ -2043,7 +2064,7 @@ var DockWrapper = ({ categories, activeCategoryId }) => {
2043
2064
  setTabbarTheme(null);
2044
2065
  ensurePersistentHighlight();
2045
2066
  }
2046
- (_a76 = opts.onClosed) == null ? void 0 : _a76.call(opts);
2067
+ (_a80 = opts.onClosed) == null ? void 0 : _a80.call(opts);
2047
2068
  };
2048
2069
  closeMenu(menu, finalize);
2049
2070
  };
@@ -2146,7 +2167,7 @@ var DockWrapper = ({ categories, activeCategoryId }) => {
2146
2167
  /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("div", { className: "glass-overlay" }),
2147
2168
  /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("div", { className: "glass-specular" }),
2148
2169
  /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("ul", { className: "flex-center", children: sortedCategories.map((cat) => {
2149
- var _a74;
2170
+ var _a78;
2150
2171
  if (cat.type === "divider") {
2151
2172
  return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
2152
2173
  "li",
@@ -2158,7 +2179,7 @@ var DockWrapper = ({ categories, activeCategoryId }) => {
2158
2179
  cat.id
2159
2180
  );
2160
2181
  }
2161
- const hasCards = (((_a74 = cat.cards) == null ? void 0 : _a74.length) || 0) > 0;
2182
+ const hasCards = (((_a78 = cat.cards) == null ? void 0 : _a78.length) || 0) > 0;
2162
2183
  const link = cat.href;
2163
2184
  const isCurrent = cat.id === activeCategoryId;
2164
2185
  return /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)(
@@ -2192,12 +2213,12 @@ var DockWrapper = ({ categories, activeCategoryId }) => {
2192
2213
  );
2193
2214
  }) }),
2194
2215
  /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("div", { className: "list-menu-mob-show", children: sortedCategories.filter((cat) => {
2195
- var _a74;
2196
- return cat.type !== "divider" && (((_a74 = cat.cards) == null ? void 0 : _a74.length) || 0) > 0;
2216
+ var _a78;
2217
+ return cat.type !== "divider" && (((_a78 = cat.cards) == null ? void 0 : _a78.length) || 0) > 0;
2197
2218
  }).map((cat) => {
2198
- var _a74;
2199
- return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("div", { className: "mob-list-menu hide", "data-tagget": cat.slug, children: /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("div", { className: `submenu-stack ${cat.slug}`, children: ((_a74 = cat.cards) != null ? _a74 : []).map((card, i) => {
2200
- var _a75;
2219
+ var _a78;
2220
+ return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("div", { className: "mob-list-menu hide", "data-tagget": cat.slug, children: /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("div", { className: `submenu-stack ${cat.slug}`, children: ((_a78 = cat.cards) != null ? _a78 : []).map((card, i) => {
2221
+ var _a79;
2201
2222
  return /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)(
2202
2223
  "div",
2203
2224
  {
@@ -2213,8 +2234,8 @@ var DockWrapper = ({ categories, activeCategoryId }) => {
2213
2234
  /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("div", { className: "title", children: card.title }),
2214
2235
  card.description ? /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("div", { className: "description", children: card.description }) : null
2215
2236
  ] }),
2216
- /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("div", { className: "actions", children: ((_a75 = card.buttons) != null ? _a75 : []).slice(0, 2).map((btn, idx) => {
2217
- var _a76, _b7, _c, _d;
2237
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("div", { className: "actions", children: ((_a79 = card.buttons) != null ? _a79 : []).slice(0, 2).map((btn, idx) => {
2238
+ var _a80, _b7, _c, _d;
2218
2239
  const className = idx === 0 ? "saiba-mais" : "saiba-mais-1";
2219
2240
  if (btn.type === "popup") {
2220
2241
  return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
@@ -2229,7 +2250,7 @@ var DockWrapper = ({ categories, activeCategoryId }) => {
2229
2250
  window.dispatchEvent(new Event(`qw:open:${btn.popupId}`));
2230
2251
  }
2231
2252
  },
2232
- children: (_a76 = btn.label) != null ? _a76 : "Abrir"
2253
+ children: (_a80 = btn.label) != null ? _a80 : "Abrir"
2233
2254
  },
2234
2255
  `${cat.id}-card-${i}-btn-${idx}`
2235
2256
  );
@@ -2988,10 +3009,10 @@ var NavbarCupcode = ({
2988
3009
  React9.useEffect(() => {
2989
3010
  if (!isOpen) return;
2990
3011
  const handlePointerDown = (event) => {
2991
- var _a74;
3012
+ var _a78;
2992
3013
  const target = event.target;
2993
3014
  if (!(target instanceof Node)) return;
2994
- if (!((_a74 = navRef.current) == null ? void 0 : _a74.contains(target))) {
3015
+ if (!((_a78 = navRef.current) == null ? void 0 : _a78.contains(target))) {
2995
3016
  setIsOpen(false);
2996
3017
  }
2997
3018
  };
@@ -3051,8 +3072,8 @@ var NavbarCupcode = ({
3051
3072
  isActive && "text-primary after:w-full"
3052
3073
  );
3053
3074
  const handleClick = (event) => {
3054
- var _a74;
3055
- (_a74 = item.onClick) == null ? void 0 : _a74.call(item, event);
3075
+ var _a78;
3076
+ (_a78 = item.onClick) == null ? void 0 : _a78.call(item, event);
3056
3077
  };
3057
3078
  if (item.href.startsWith("#")) {
3058
3079
  return /* @__PURE__ */ (0, import_jsx_runtime21.jsxs)(
@@ -3113,8 +3134,8 @@ var NavbarCupcode = ({
3113
3134
  isActive && "text-primary"
3114
3135
  );
3115
3136
  const handleClick = (event) => {
3116
- var _a74;
3117
- (_a74 = item.onClick) == null ? void 0 : _a74.call(item, event);
3137
+ var _a78;
3138
+ (_a78 = item.onClick) == null ? void 0 : _a78.call(item, event);
3118
3139
  setIsOpen(false);
3119
3140
  };
3120
3141
  if (item.href.startsWith("#")) {
@@ -3914,12 +3935,12 @@ var rpcPreferredSchema = TELESCUP_RPC_SCHEMA;
3914
3935
  var RPC_MISSING_SCHEMAS_BY_PATH = /* @__PURE__ */ new Map();
3915
3936
  var FUNCTION_NOT_FOUND_CACHE = /* @__PURE__ */ new Set();
3916
3937
  var buildRestHeaders = (token, options) => {
3917
- var _a74;
3938
+ var _a78;
3918
3939
  const headers = {};
3919
3940
  if (SUPABASE_ANON_KEY) {
3920
3941
  headers.apikey = SUPABASE_ANON_KEY;
3921
3942
  }
3922
- const authorizationToken = (_a74 = resolveRpcAuthorizationToken(token)) != null ? _a74 : token;
3943
+ const authorizationToken = (_a78 = resolveRpcAuthorizationToken(token)) != null ? _a78 : token;
3923
3944
  if (authorizationToken) {
3924
3945
  headers.Authorization = `Bearer ${authorizationToken}`;
3925
3946
  }
@@ -4054,22 +4075,22 @@ var parseAssetSize = (value) => {
4054
4075
  return Number.isFinite(parsed) ? parsed : void 0;
4055
4076
  };
4056
4077
  var getFileExtension = (filename) => {
4057
- var _a74;
4078
+ var _a78;
4058
4079
  if (!filename) return void 0;
4059
4080
  const parts = filename.split(".");
4060
4081
  if (parts.length < 2) return void 0;
4061
- const candidate = (_a74 = parts[parts.length - 1]) == null ? void 0 : _a74.trim().toLowerCase();
4082
+ const candidate = (_a78 = parts[parts.length - 1]) == null ? void 0 : _a78.trim().toLowerCase();
4062
4083
  return candidate || void 0;
4063
4084
  };
4064
4085
  var resolveCategory = (row, activeMeta) => {
4065
- var _a74;
4066
- return (_a74 = readString(row.category)) != null ? _a74 : readString(activeMeta.category);
4086
+ var _a78;
4087
+ return (_a78 = readString(row.category)) != null ? _a78 : readString(activeMeta.category);
4067
4088
  };
4068
4089
  var resolveFolderName = (row) => readString(row.folder_name);
4069
4090
  var toTelescupAsset = (row, selectedLanguage) => {
4070
- var _a74, _b7, _c, _d, _e;
4091
+ var _a78, _b7, _c, _d, _e;
4071
4092
  const metaByLang = normalizeMetaByLanguage(row.meta);
4072
- const activeMeta = (_b7 = (_a74 = metaByLang[selectedLanguage]) != null ? _a74 : metaByLang.pt) != null ? _b7 : {};
4093
+ const activeMeta = (_b7 = (_a78 = metaByLang[selectedLanguage]) != null ? _a78 : metaByLang.pt) != null ? _b7 : {};
4073
4094
  return {
4074
4095
  id: (_c = row.id) != null ? _c : "",
4075
4096
  name: row.filename,
@@ -4095,9 +4116,9 @@ var buildFacetsFromItems = (items) => {
4095
4116
  const extensions = /* @__PURE__ */ new Map();
4096
4117
  const tags = /* @__PURE__ */ new Map();
4097
4118
  items.forEach((item) => {
4098
- var _a74, _b7, _c, _d, _e, _f, _g;
4119
+ var _a78, _b7, _c, _d, _e, _f, _g;
4099
4120
  if (item.category) {
4100
- categories.set(item.category, ((_a74 = categories.get(item.category)) != null ? _a74 : 0) + 1);
4121
+ categories.set(item.category, ((_a78 = categories.get(item.category)) != null ? _a78 : 0) + 1);
4101
4122
  }
4102
4123
  if (item.folderId) {
4103
4124
  const current = folders.get(item.folderId);
@@ -4113,16 +4134,16 @@ var buildFacetsFromItems = (items) => {
4113
4134
  extensions.set(item.extension, ((_e = extensions.get(item.extension)) != null ? _e : 0) + 1);
4114
4135
  }
4115
4136
  (_g = (_f = item.meta) == null ? void 0 : _f.tags) == null ? void 0 : _g.forEach((tag) => {
4116
- var _a75;
4137
+ var _a79;
4117
4138
  const normalizedTag = tag.trim();
4118
4139
  if (!normalizedTag) return;
4119
- tags.set(normalizedTag, ((_a75 = tags.get(normalizedTag)) != null ? _a75 : 0) + 1);
4140
+ tags.set(normalizedTag, ((_a79 = tags.get(normalizedTag)) != null ? _a79 : 0) + 1);
4120
4141
  });
4121
4142
  });
4122
4143
  const toFacetValues = (map) => Array.from(map.entries()).map(([value, count2]) => ({ value, count: count2 })).sort((a, b) => a.value.localeCompare(b.value));
4123
4144
  const toFolderFacetValues = (map) => Array.from(map.entries()).map(([value, info]) => ({ value, label: info.label, count: info.count })).sort((a, b) => {
4124
- var _a74, _b7;
4125
- return ((_a74 = a.label) != null ? _a74 : a.value).localeCompare((_b7 = b.label) != null ? _b7 : b.value);
4145
+ var _a78, _b7;
4146
+ return ((_a78 = a.label) != null ? _a78 : a.value).localeCompare((_b7 = b.label) != null ? _b7 : b.value);
4126
4147
  });
4127
4148
  return {
4128
4149
  categories: toFacetValues(categories),
@@ -4140,7 +4161,7 @@ var isManagerScopeRetryable = (error) => {
4140
4161
  return /permission|not allowed|wrong key type|insufficient|unauthorized/i.test(detailsText);
4141
4162
  };
4142
4163
  async function listAssetsViaRpc(config, filters) {
4143
- var _a74, _b7, _c, _d, _e, _f, _g, _h, _i;
4164
+ var _a78, _b7, _c, _d, _e, _f, _g, _h, _i;
4144
4165
  if (!SUPABASE_ANON_KEY) {
4145
4166
  throw new TelescupClientError(
4146
4167
  "VITE_SUPABASE_ANON_KEY (ou VITE_SUPABASE_PUBLISHABLE_KEY) n\xE3o encontrado para fallback RPC do Telescup."
@@ -4159,7 +4180,7 @@ async function listAssetsViaRpc(config, filters) {
4159
4180
  );
4160
4181
  }
4161
4182
  const pageSize = Math.min(100, Math.max(1, toPositiveInt(filters.pageSize, 24)));
4162
- const page = toPositiveInt((_a74 = filters.cursor) != null ? _a74 : filters.page, 1);
4183
+ const page = toPositiveInt((_a78 = filters.cursor) != null ? _a78 : filters.page, 1);
4163
4184
  const selectedLanguage = normalizeLanguageKey(filters.language);
4164
4185
  const bodyBase = {
4165
4186
  p_user_id: userId,
@@ -4259,13 +4280,13 @@ var getRpcSchemaCandidates = (rpcPath) => {
4259
4280
  return filtered.length ? filtered : ordered;
4260
4281
  };
4261
4282
  var markRpcSchemaMissing = (rpcPath, schema) => {
4262
- var _a74;
4263
- const set = (_a74 = RPC_MISSING_SCHEMAS_BY_PATH.get(rpcPath)) != null ? _a74 : /* @__PURE__ */ new Set();
4283
+ var _a78;
4284
+ const set = (_a78 = RPC_MISSING_SCHEMAS_BY_PATH.get(rpcPath)) != null ? _a78 : /* @__PURE__ */ new Set();
4264
4285
  set.add(schema);
4265
4286
  RPC_MISSING_SCHEMAS_BY_PATH.set(rpcPath, set);
4266
4287
  };
4267
4288
  async function requestRpc(config, rpcPath, payload) {
4268
- var _a74, _b7;
4289
+ var _a78, _b7;
4269
4290
  if (!SUPABASE_ANON_KEY) {
4270
4291
  throw new TelescupClientError(
4271
4292
  "VITE_SUPABASE_ANON_KEY (ou VITE_SUPABASE_PUBLISHABLE_KEY) n\xE3o encontrado para fallback RPC do Telescup."
@@ -4308,7 +4329,7 @@ async function requestRpc(config, rpcPath, payload) {
4308
4329
  throw new TelescupClientError(`Falha de rede ao chamar RPC ${rpcPath}.`, { details: error });
4309
4330
  }
4310
4331
  if (response.ok) {
4311
- const contentType = (_a74 = response.headers.get("content-type")) != null ? _a74 : "";
4332
+ const contentType = (_a78 = response.headers.get("content-type")) != null ? _a78 : "";
4312
4333
  if (!contentType.includes("application/json")) {
4313
4334
  const text = await response.text();
4314
4335
  if (!text) return {};
@@ -4360,7 +4381,7 @@ async function requestRpc(config, rpcPath, payload) {
4360
4381
  throw new TelescupClientError(`Falha ao chamar RPC ${rpcPath}.`);
4361
4382
  }
4362
4383
  var toTelescupError = async (response, fallbackMessage) => {
4363
- var _a74;
4384
+ var _a78;
4364
4385
  let payload = void 0;
4365
4386
  try {
4366
4387
  payload = await response.json();
@@ -4368,7 +4389,7 @@ var toTelescupError = async (response, fallbackMessage) => {
4368
4389
  payload = await response.text();
4369
4390
  }
4370
4391
  const payloadObject = payload != null ? payload : {};
4371
- const message = typeof payload === "string" ? payload : (_a74 = payloadObject.message) != null ? _a74 : `${fallbackMessage} (${response.status}).`;
4392
+ const message = typeof payload === "string" ? payload : (_a78 = payloadObject.message) != null ? _a78 : `${fallbackMessage} (${response.status}).`;
4372
4393
  return new TelescupClientError(message, {
4373
4394
  status: response.status,
4374
4395
  code: payloadObject.code,
@@ -4416,11 +4437,11 @@ var mergeFacetEntries = (current, incoming) => {
4416
4437
  const map = /* @__PURE__ */ new Map();
4417
4438
  current == null ? void 0 : current.forEach((entry) => map.set(entry.value, entry));
4418
4439
  incoming == null ? void 0 : incoming.forEach((entry) => {
4419
- var _a74, _b7, _c;
4440
+ var _a78, _b7, _c;
4420
4441
  const previous = map.get(entry.value);
4421
4442
  map.set(entry.value, {
4422
4443
  value: entry.value,
4423
- label: (_b7 = (_a74 = entry.label) != null ? _a74 : previous == null ? void 0 : previous.label) != null ? _b7 : entry.value,
4444
+ label: (_b7 = (_a78 = entry.label) != null ? _a78 : previous == null ? void 0 : previous.label) != null ? _b7 : entry.value,
4424
4445
  count: (_c = entry.count) != null ? _c : previous == null ? void 0 : previous.count
4425
4446
  });
4426
4447
  });
@@ -4440,10 +4461,10 @@ var mergeFacets = (base, incoming) => {
4440
4461
  var toFacetEntriesFromRows = (rows, valueKeys, labelKeys) => {
4441
4462
  const result = /* @__PURE__ */ new Map();
4442
4463
  rows.forEach((row) => {
4443
- var _a74;
4464
+ var _a78;
4444
4465
  const value = readFirstString(row, valueKeys);
4445
4466
  if (!value) return;
4446
- const label = (_a74 = readFirstString(row, labelKeys)) != null ? _a74 : value;
4467
+ const label = (_a78 = readFirstString(row, labelKeys)) != null ? _a78 : value;
4447
4468
  result.set(value, { value, label });
4448
4469
  });
4449
4470
  return Array.from(result.values()).sort((a, b) => a.label.localeCompare(b.label));
@@ -4509,7 +4530,7 @@ async function loadFacetsFromTelescupTablesCached(config) {
4509
4530
  return facets;
4510
4531
  }
4511
4532
  async function request(config, path, options = {}) {
4512
- var _a74, _b7, _c;
4533
+ var _a78, _b7, _c;
4513
4534
  const token = await config.getAccessToken();
4514
4535
  if (!token) {
4515
4536
  throw new TelescupClientError("Token de acesso n\xE3o encontrado.");
@@ -4517,7 +4538,7 @@ async function request(config, path, options = {}) {
4517
4538
  const functionsBaseUrl = resolveFunctionsBaseUrl(config.baseUrl);
4518
4539
  const url = joinUrl(functionsBaseUrl, path);
4519
4540
  const isAssetApiRoute = path.startsWith("asset-api/");
4520
- const authorizationToken = isAssetApiRoute ? (_a74 = resolveRpcAuthorizationToken(token)) != null ? _a74 : token : token;
4541
+ const authorizationToken = isAssetApiRoute ? (_a78 = resolveRpcAuthorizationToken(token)) != null ? _a78 : token : token;
4521
4542
  const headers = {
4522
4543
  Authorization: `Bearer ${authorizationToken}`,
4523
4544
  ...options.headers
@@ -4567,8 +4588,8 @@ var normalizeFunctionLanguage = (value) => {
4567
4588
  return normalized;
4568
4589
  };
4569
4590
  var toFunctionListPayload = (filters) => {
4570
- var _a74, _b7, _c, _d, _e, _f;
4571
- const page = toPositiveInt((_a74 = filters.cursor) != null ? _a74 : filters.page, 1);
4591
+ var _a78, _b7, _c, _d, _e, _f;
4592
+ const page = toPositiveInt((_a78 = filters.cursor) != null ? _a78 : filters.page, 1);
4572
4593
  const pageSize = Math.min(500, Math.max(1, toPositiveInt(filters.pageSize, 24)));
4573
4594
  return {
4574
4595
  query: (_b7 = filters.query) != null ? _b7 : "",
@@ -4606,8 +4627,8 @@ var toFolderPath = (value) => {
4606
4627
  return normalized.slice(0, lastSlash);
4607
4628
  };
4608
4629
  var normalizeFilterText = (value) => {
4609
- var _a74;
4610
- return (_a74 = value == null ? void 0 : value.trim().toLowerCase()) != null ? _a74 : "";
4630
+ var _a78;
4631
+ return (_a78 = value == null ? void 0 : value.trim().toLowerCase()) != null ? _a78 : "";
4611
4632
  };
4612
4633
  var hasActiveFacetFilter = (filters) => Boolean(filters.type && filters.type !== "all") || Boolean(filters.extension) || Boolean(filters.category) || Boolean(filters.folderId) || Boolean(filters.usage) || filters.hasAlt === true;
4613
4634
  var normalizeExtensionFilter = (value) => {
@@ -4622,16 +4643,16 @@ var normalizeFolderFilter = (value) => {
4622
4643
  var sortAssets = (items, sort, order) => {
4623
4644
  const direction = order === "asc" ? 1 : -1;
4624
4645
  const byName = (a, b) => {
4625
- var _a74, _b7, _c, _d;
4626
- return ((_b7 = (_a74 = a.fileName) != null ? _a74 : a.name) != null ? _b7 : "").localeCompare((_d = (_c = b.fileName) != null ? _c : b.name) != null ? _d : "");
4646
+ var _a78, _b7, _c, _d;
4647
+ return ((_b7 = (_a78 = a.fileName) != null ? _a78 : a.name) != null ? _b7 : "").localeCompare((_d = (_c = b.fileName) != null ? _c : b.name) != null ? _d : "");
4627
4648
  };
4628
4649
  const byDate = (a, b, key) => {
4629
- var _a74, _b7;
4630
- return (Date.parse((_a74 = a[key]) != null ? _a74 : "") || 0) - (Date.parse((_b7 = b[key]) != null ? _b7 : "") || 0);
4650
+ var _a78, _b7;
4651
+ return (Date.parse((_a78 = a[key]) != null ? _a78 : "") || 0) - (Date.parse((_b7 = b[key]) != null ? _b7 : "") || 0);
4631
4652
  };
4632
4653
  const bySize = (a, b) => {
4633
- var _a74, _b7;
4634
- return ((_a74 = a.size) != null ? _a74 : 0) - ((_b7 = b.size) != null ? _b7 : 0);
4654
+ var _a78, _b7;
4655
+ return ((_a78 = a.size) != null ? _a78 : 0) - ((_b7 = b.size) != null ? _b7 : 0);
4635
4656
  };
4636
4657
  const sorted = [...items];
4637
4658
  sorted.sort((a, b) => {
@@ -4666,7 +4687,7 @@ var applyAssetApiSearchFilters = (items, filters) => {
4666
4687
  const folderFilter = normalizeFolderFilter(filters.folderId);
4667
4688
  const requireAlt = filters.hasAlt === true;
4668
4689
  return items.filter((asset) => {
4669
- var _a74, _b7, _c, _d, _e, _f, _g, _h, _i;
4690
+ var _a78, _b7, _c, _d, _e, _f, _g, _h, _i;
4670
4691
  const haystack = [
4671
4692
  asset.id,
4672
4693
  asset.name,
@@ -4675,7 +4696,7 @@ var applyAssetApiSearchFilters = (items, filters) => {
4675
4696
  asset.folderName,
4676
4697
  asset.category,
4677
4698
  asset.usage,
4678
- (_a74 = asset.meta) == null ? void 0 : _a74.title,
4699
+ (_a78 = asset.meta) == null ? void 0 : _a78.title,
4679
4700
  (_b7 = asset.meta) == null ? void 0 : _b7.description,
4680
4701
  (_c = asset.meta) == null ? void 0 : _c.alt,
4681
4702
  ...Array.isArray((_d = asset.meta) == null ? void 0 : _d.tags) ? asset.meta.tags : []
@@ -4695,10 +4716,10 @@ var applyAssetApiSearchFilters = (items, filters) => {
4695
4716
  });
4696
4717
  };
4697
4718
  var mapAssetApiSearchRowToAsset = (row) => {
4698
- var _a74, _b7, _c, _d;
4719
+ var _a78, _b7, _c, _d;
4699
4720
  const id = readFirstString(row, ["asset_id", "id"]);
4700
4721
  if (!id) return null;
4701
- const fileName = (_a74 = readFirstString(row, ["original_filename", "filename", "title"])) != null ? _a74 : readFirstString(row, ["file_path"]);
4722
+ const fileName = (_a78 = readFirstString(row, ["original_filename", "filename", "title"])) != null ? _a78 : readFirstString(row, ["file_path"]);
4702
4723
  const mimeType = readFirstString(row, ["mime_type", "mime"]);
4703
4724
  const extension = getFileExtension(readFirstString(row, ["file_path", "filename", "original_filename"]));
4704
4725
  const tags = Array.isArray(row.tags) ? row.tags.filter((item) => typeof item === "string") : void 0;
@@ -4746,9 +4767,9 @@ var mapAssetApiSearchRowToAsset = (row) => {
4746
4767
  };
4747
4768
  };
4748
4769
  async function listAssetsViaAssetApiSearch(config, filters) {
4749
- var _a74, _b7;
4770
+ var _a78, _b7;
4750
4771
  const pageSize = Math.min(500, Math.max(1, toPositiveInt(filters.pageSize, 24)));
4751
- const page = toPositiveInt((_a74 = filters.cursor) != null ? _a74 : filters.page, 1);
4772
+ const page = toPositiveInt((_a78 = filters.cursor) != null ? _a78 : filters.page, 1);
4752
4773
  const hasFilter = hasActiveFacetFilter(filters);
4753
4774
  const baseLimit = page * pageSize + 1;
4754
4775
  const seedLimit = hasFilter ? baseLimit : Math.max(baseLimit, TELESCUP_ASSET_API_FACET_SEED_LIMIT);
@@ -4785,8 +4806,8 @@ async function listAssetsViaAssetApiSearch(config, filters) {
4785
4806
  };
4786
4807
  }
4787
4808
  var mapGenericRowToAsset = (row) => {
4788
- var _a74, _b7;
4789
- const id = (_a74 = readFirstString(row, ["asset_id", "id", "file_id", "uuid"])) != null ? _a74 : typeof row.id === "number" ? String(row.id) : void 0;
4809
+ var _a78, _b7;
4810
+ const id = (_a78 = readFirstString(row, ["asset_id", "id", "file_id", "uuid"])) != null ? _a78 : typeof row.id === "number" ? String(row.id) : void 0;
4790
4811
  if (!id) return null;
4791
4812
  const fileName = readFirstString(row, ["filename", "file_name", "name", "title", "original_name"]);
4792
4813
  const mimeType = readFirstString(row, ["mime", "mime_type", "content_type", "file_mime"]);
@@ -4808,16 +4829,16 @@ var mapGenericRowToAsset = (row) => {
4808
4829
  };
4809
4830
  };
4810
4831
  var normalizeListResponseFromFunctions = (response, filters) => {
4811
- var _a74, _b7, _c, _d, _e, _f;
4832
+ var _a78, _b7, _c, _d, _e, _f;
4812
4833
  const payload = response != null ? response : {};
4813
4834
  const itemsRaw = Array.isArray(payload.items) ? payload.items : [];
4814
4835
  const selectedLanguage = normalizeLanguageKey(filters.language);
4815
4836
  const items = itemsRaw.map((row) => {
4816
- var _a75, _b8, _c2;
4837
+ var _a79, _b8, _c2;
4817
4838
  const mapped = mapGenericRowToAsset(row);
4818
4839
  if (!mapped) return null;
4819
4840
  const metaByLang = normalizeMetaByLanguage(row.meta);
4820
- const activeMeta = (_b8 = (_a75 = metaByLang[selectedLanguage]) != null ? _a75 : metaByLang.pt) != null ? _b8 : {};
4841
+ const activeMeta = (_b8 = (_a79 = metaByLang[selectedLanguage]) != null ? _a79 : metaByLang.pt) != null ? _b8 : {};
4821
4842
  const usageFromObject = readUsageContext(row.usage);
4822
4843
  const normalized = {
4823
4844
  ...mapped,
@@ -4829,7 +4850,7 @@ var normalizeListResponseFromFunctions = (response, filters) => {
4829
4850
  };
4830
4851
  return normalized;
4831
4852
  }).filter((item) => item !== null);
4832
- const total = (_c = (_b7 = (_a74 = readNumber(payload.total)) != null ? _a74 : readNumber(payload.totalCount)) != null ? _b7 : readNumber(payload.total_count)) != null ? _c : items.length;
4853
+ const total = (_c = (_b7 = (_a78 = readNumber(payload.total)) != null ? _a78 : readNumber(payload.totalCount)) != null ? _b7 : readNumber(payload.total_count)) != null ? _c : items.length;
4833
4854
  const page = toPositiveInt((_e = (_d = payload.page) != null ? _d : filters.cursor) != null ? _e : filters.page, 1);
4834
4855
  const pageSize = Math.min(100, Math.max(1, toPositiveInt((_f = payload.pageSize) != null ? _f : filters.pageSize, 24)));
4835
4856
  const nextCursor = total > page * pageSize ? String(page + 1) : void 0;
@@ -4849,12 +4870,12 @@ var mapConflictForQueue = (value) => {
4849
4870
  return "conflict";
4850
4871
  };
4851
4872
  var toInitPayloadForFunctions = (payload) => {
4852
- var _a74, _b7;
4873
+ var _a78, _b7;
4853
4874
  return {
4854
4875
  filename: payload.fileName,
4855
4876
  size: payload.size,
4856
4877
  mime: payload.mimeType,
4857
- folder_id: (_a74 = payload.folderId) != null ? _a74 : null,
4878
+ folder_id: (_a78 = payload.folderId) != null ? _a78 : null,
4858
4879
  overwritePolicy: (_b7 = payload.conflict) != null ? _b7 : "ask",
4859
4880
  fileName: payload.fileName,
4860
4881
  mimeType: payload.mimeType,
@@ -4863,9 +4884,9 @@ var toInitPayloadForFunctions = (payload) => {
4863
4884
  };
4864
4885
  };
4865
4886
  var normalizeInitResponseFromFunctions = (response) => {
4866
- var _a74, _b7, _c, _d, _e, _f, _g;
4887
+ var _a78, _b7, _c, _d, _e, _f, _g;
4867
4888
  const payload = response != null ? response : {};
4868
- const existingRaw = (_a74 = payload.existingAsset) != null ? _a74 : payload.existing_asset;
4889
+ const existingRaw = (_a78 = payload.existingAsset) != null ? _a78 : payload.existing_asset;
4869
4890
  const existingAsset = existingRaw ? (_b7 = mapGenericRowToAsset(existingRaw)) != null ? _b7 : void 0 : void 0;
4870
4891
  const assetRaw = payload.asset;
4871
4892
  const asset = assetRaw ? (_c = mapGenericRowToAsset(assetRaw)) != null ? _c : void 0 : void 0;
@@ -4887,10 +4908,10 @@ var normalizeInitResponseFromFunctions = (response) => {
4887
4908
  };
4888
4909
  };
4889
4910
  var toCompletePayloadForFunctions = (payload) => {
4890
- var _a74, _b7, _c;
4911
+ var _a78, _b7, _c;
4891
4912
  return {
4892
4913
  uploadId: payload.uploadId,
4893
- assetDraftId: (_a74 = payload.assetDraftId) != null ? _a74 : payload.assetId,
4914
+ assetDraftId: (_a78 = payload.assetDraftId) != null ? _a78 : payload.assetId,
4894
4915
  storageKey: payload.storageKey,
4895
4916
  finalFilename: (_b7 = payload.finalFilename) != null ? _b7 : payload.fileName,
4896
4917
  folder_id: (_c = payload.folderId) != null ? _c : null,
@@ -4900,9 +4921,9 @@ var toCompletePayloadForFunctions = (payload) => {
4900
4921
  };
4901
4922
  };
4902
4923
  var normalizeCompleteResponseFromFunctions = (response) => {
4903
- var _a74, _b7;
4924
+ var _a78, _b7;
4904
4925
  const payload = response != null ? response : {};
4905
- const assetRaw = (_a74 = payload.asset) != null ? _a74 : payload;
4926
+ const assetRaw = (_a78 = payload.asset) != null ? _a78 : payload;
4906
4927
  const mapped = mapGenericRowToAsset(assetRaw);
4907
4928
  if (mapped) return { asset: mapped };
4908
4929
  const assetId = (_b7 = readFirstString(assetRaw, ["id", "asset_id"])) != null ? _b7 : readFirstString(payload, ["assetId", "asset_id"]);
@@ -4912,9 +4933,9 @@ var normalizeCompleteResponseFromFunctions = (response) => {
4912
4933
  return { asset: { id: assetId } };
4913
4934
  };
4914
4935
  var toMetaPayloadForFunctions = (payload) => {
4915
- var _a74, _b7;
4936
+ var _a78, _b7;
4916
4937
  if (TELESCUP_UPDATE_META_FUNCTION === "update-asset-meta") {
4917
- const categories = ((_a74 = payload.meta) == null ? void 0 : _a74.category) ? [payload.meta.category] : [];
4938
+ const categories = ((_a78 = payload.meta) == null ? void 0 : _a78.category) ? [payload.meta.category] : [];
4918
4939
  return {
4919
4940
  asset_id: payload.assetId,
4920
4941
  categories
@@ -5028,7 +5049,7 @@ var createTelescupClient = (config) => ({
5028
5049
  body: toMetaPayloadForFunctions(payload)
5029
5050
  }),
5030
5051
  uploadDirect: async (file) => {
5031
- var _a74;
5052
+ var _a78;
5032
5053
  const token = await config.getAccessToken();
5033
5054
  const userId = resolveUserIdFromToken(token);
5034
5055
  if (!userId) {
@@ -5056,7 +5077,7 @@ var createTelescupClient = (config) => ({
5056
5077
  }
5057
5078
  });
5058
5079
  const payload = response != null ? response : {};
5059
- const asset = mapAssetApiSearchRowToAsset((_a74 = payload.asset) != null ? _a74 : {});
5080
+ const asset = mapAssetApiSearchRowToAsset((_a78 = payload.asset) != null ? _a78 : {});
5060
5081
  if (!asset) {
5061
5082
  throw new TelescupClientError("Resposta inv\xE1lida do upload direto (asset-api).");
5062
5083
  }
@@ -5077,17 +5098,17 @@ var mergeFacetValues = (current, incoming) => {
5077
5098
  const map = /* @__PURE__ */ new Map();
5078
5099
  current == null ? void 0 : current.forEach((entry) => map.set(entry.value, entry));
5079
5100
  incoming == null ? void 0 : incoming.forEach((entry) => {
5080
- var _a74, _b7, _c;
5101
+ var _a78, _b7, _c;
5081
5102
  const previous = map.get(entry.value);
5082
5103
  map.set(entry.value, {
5083
5104
  value: entry.value,
5084
- label: (_b7 = (_a74 = entry.label) != null ? _a74 : previous == null ? void 0 : previous.label) != null ? _b7 : entry.value,
5105
+ label: (_b7 = (_a78 = entry.label) != null ? _a78 : previous == null ? void 0 : previous.label) != null ? _b7 : entry.value,
5085
5106
  count: (_c = entry.count) != null ? _c : previous == null ? void 0 : previous.count
5086
5107
  });
5087
5108
  });
5088
5109
  return Array.from(map.values()).sort((a, b) => {
5089
- var _a74, _b7;
5090
- return ((_a74 = a.label) != null ? _a74 : a.value).localeCompare((_b7 = b.label) != null ? _b7 : b.value);
5110
+ var _a78, _b7;
5111
+ return ((_a78 = a.label) != null ? _a78 : a.value).localeCompare((_b7 = b.label) != null ? _b7 : b.value);
5091
5112
  });
5092
5113
  };
5093
5114
  var DEFAULT_CACHE_MS = 3e5;
@@ -5181,9 +5202,9 @@ function useTelescupAssets(options) {
5181
5202
  ...sanitizeFilters(filters),
5182
5203
  pageSize
5183
5204
  }).then((data) => {
5184
- var _a74;
5205
+ var _a78;
5185
5206
  return {
5186
- items: (_a74 = data.items) != null ? _a74 : [],
5207
+ items: (_a78 = data.items) != null ? _a78 : [],
5187
5208
  nextCursor: data.nextCursor,
5188
5209
  total: data.total,
5189
5210
  facets: data.facets
@@ -5207,7 +5228,7 @@ function useTelescupAssets(options) {
5207
5228
  [cacheKey, cacheTimeMs, enabled, filters, pageSize, resolvedClient]
5208
5229
  );
5209
5230
  const loadMore = (0, import_react13.useCallback)(async () => {
5210
- var _a74, _b7, _c, _d, _e, _f, _g;
5231
+ var _a78, _b7, _c, _d, _e, _f, _g;
5211
5232
  if (!state.nextCursor || isLoadingMore || isLoading) return;
5212
5233
  const requestSeq = requestSeqRef.current;
5213
5234
  setIsLoadingMore(true);
@@ -5221,7 +5242,7 @@ function useTelescupAssets(options) {
5221
5242
  });
5222
5243
  if (!aliveRef.current || requestSeq !== requestSeqRef.current) return;
5223
5244
  const merged = {
5224
- items: [...state.items, ...(_a74 = data.items) != null ? _a74 : []],
5245
+ items: [...state.items, ...(_a78 = data.items) != null ? _a78 : []],
5225
5246
  nextCursor: data.nextCursor,
5226
5247
  total: (_b7 = data.total) != null ? _b7 : state.total,
5227
5248
  facets: {
@@ -5380,12 +5401,13 @@ ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName;
5380
5401
  // src/components/cupcode/TelescupAssetPicker.tsx
5381
5402
  var import_lucide_react9 = require("lucide-react");
5382
5403
  var import_jsx_runtime35 = require("react/jsx-runtime");
5404
+ var import_meta2 = {};
5383
5405
  var IMAGE_EXTENSIONS = /* @__PURE__ */ new Set(["jpg", "jpeg", "png", "gif", "webp", "avif", "svg", "bmp", "ico", "tif", "tiff"]);
5384
5406
  var VIDEO_EXTENSIONS = /* @__PURE__ */ new Set(["mp4", "mov", "webm", "mkv", "avi", "m4v", "wmv"]);
5385
5407
  var AUDIO_EXTENSIONS = /* @__PURE__ */ new Set(["mp3", "wav", "aac", "ogg", "flac", "m4a"]);
5386
5408
  var resolveAssetFamily = (asset) => {
5387
- var _a74, _b7, _c;
5388
- const explicitType = (_a74 = asset.type) == null ? void 0 : _a74.toLowerCase();
5409
+ var _a78, _b7, _c;
5410
+ const explicitType = (_a78 = asset.type) == null ? void 0 : _a78.toLowerCase();
5389
5411
  if (explicitType === "image" || explicitType === "video" || explicitType === "audio" || explicitType === "file") {
5390
5412
  return explicitType;
5391
5413
  }
@@ -5401,9 +5423,9 @@ var resolveAssetFamily = (asset) => {
5401
5423
  return "file";
5402
5424
  };
5403
5425
  var matchesAllowedAsset = (asset, allowed) => {
5404
- var _a74, _b7, _c, _d;
5426
+ var _a78, _b7, _c, _d;
5405
5427
  if (!allowed || allowed.length === 0) return true;
5406
- const mime = (_b7 = (_a74 = asset.mimeType) == null ? void 0 : _a74.toLowerCase()) != null ? _b7 : "";
5428
+ const mime = (_b7 = (_a78 = asset.mimeType) == null ? void 0 : _a78.toLowerCase()) != null ? _b7 : "";
5407
5429
  const ext = asset.extension ? `.${asset.extension.toLowerCase()}` : "";
5408
5430
  const type = (_d = (_c = asset.type) == null ? void 0 : _c.toLowerCase()) != null ? _d : "";
5409
5431
  const family = resolveAssetFamily(asset);
@@ -5458,10 +5480,10 @@ var UUID_REGEX3 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[
5458
5480
  var ROOT_FOLDERS_TO_HIDE = /* @__PURE__ */ new Set(["images", "videos"]);
5459
5481
  var normalizeFolderToken = (value) => value.trim().replace(/^\/+|\/+$/g, "").toLowerCase();
5460
5482
  var getLeafName = (value) => {
5461
- var _a74;
5483
+ var _a78;
5462
5484
  const normalized = normalizeFolderToken(value);
5463
5485
  const parts = normalized.split("/").filter(Boolean);
5464
- return (_a74 = parts[parts.length - 1]) != null ? _a74 : normalized;
5486
+ return (_a78 = parts[parts.length - 1]) != null ? _a78 : normalized;
5465
5487
  };
5466
5488
  var scoreFolderValue = (value, label) => {
5467
5489
  const normalizedValue = normalizeFolderToken(value);
@@ -5477,8 +5499,8 @@ var normalizeFacetOptions = (entries) => {
5477
5499
  if (!entries || !entries.length) return [];
5478
5500
  const byLabel = /* @__PURE__ */ new Map();
5479
5501
  entries.forEach((entry) => {
5480
- var _a74, _b7, _c, _d;
5481
- const value = (_a74 = entry.value) == null ? void 0 : _a74.trim();
5502
+ var _a78, _b7, _c, _d;
5503
+ const value = (_a78 = entry.value) == null ? void 0 : _a78.trim();
5482
5504
  if (!value) return;
5483
5505
  const label = ((_b7 = entry.label) == null ? void 0 : _b7.trim()) || value;
5484
5506
  const key = normalizeFolderToken(label);
@@ -5508,16 +5530,16 @@ var normalizeFacetOptions = (entries) => {
5508
5530
  const options = Array.from(byLabel.values());
5509
5531
  const groups = /* @__PURE__ */ new Map();
5510
5532
  options.forEach((option) => {
5511
- var _a74;
5533
+ var _a78;
5512
5534
  const leaf = getLeafName(option.label || option.value);
5513
- const list = (_a74 = groups.get(leaf)) != null ? _a74 : [];
5535
+ const list = (_a78 = groups.get(leaf)) != null ? _a78 : [];
5514
5536
  list.push(option);
5515
5537
  groups.set(leaf, list);
5516
5538
  });
5517
5539
  const collapsed = options.filter((option) => {
5518
- var _a74;
5540
+ var _a78;
5519
5541
  const leaf = getLeafName(option.label || option.value);
5520
- const group = (_a74 = groups.get(leaf)) != null ? _a74 : [];
5542
+ const group = (_a78 = groups.get(leaf)) != null ? _a78 : [];
5521
5543
  const hasPathVariant = group.some((entry) => normalizeFolderToken(entry.label).includes("/"));
5522
5544
  if (!hasPathVariant) return true;
5523
5545
  return normalizeFolderToken(option.label).includes("/");
@@ -5528,8 +5550,8 @@ var normalizeFacetOptions = (entries) => {
5528
5550
  var collectFacetOptions = (items, pick, pickLabel) => {
5529
5551
  const options = /* @__PURE__ */ new Map();
5530
5552
  items.forEach((asset) => {
5531
- var _a74, _b7, _c, _d;
5532
- const value = (_a74 = pick(asset)) == null ? void 0 : _a74.trim();
5553
+ var _a78, _b7, _c, _d;
5554
+ const value = (_a78 = pick(asset)) == null ? void 0 : _a78.trim();
5533
5555
  if (!value) return;
5534
5556
  const current = options.get(value);
5535
5557
  options.set(value, {
@@ -5558,6 +5580,27 @@ var TelescupAssetPicker = ({
5558
5580
  const [typeFilter, setTypeFilter] = (0, import_react14.useState)("all");
5559
5581
  const [folderFilter, setFolderFilter] = (0, import_react14.useState)("all");
5560
5582
  const [previewAsset, setPreviewAsset] = (0, import_react14.useState)(null);
5583
+ const allowedFamilies = (0, import_react14.useMemo)(() => {
5584
+ if (!allowedTypes || allowedTypes.length === 0) {
5585
+ return { image: true, video: true };
5586
+ }
5587
+ const flags = { image: false, video: false };
5588
+ allowedTypes.forEach((rawRule) => {
5589
+ const rule = rawRule.toLowerCase();
5590
+ if (rule.includes("image") || rule.includes(".jpg") || rule.includes(".jpeg") || rule.includes(".png") || rule.includes(".webp")) {
5591
+ flags.image = true;
5592
+ }
5593
+ if (rule.includes("video") || rule.includes(".mp4") || rule.includes(".webm") || rule.includes(".mov")) {
5594
+ flags.video = true;
5595
+ }
5596
+ });
5597
+ return flags;
5598
+ }, [allowedTypes]);
5599
+ import_react14.default.useEffect(() => {
5600
+ if (typeFilter === "video" && !allowedFamilies.video) {
5601
+ setTypeFilter("all");
5602
+ }
5603
+ }, [allowedFamilies.video, typeFilter]);
5561
5604
  const baseFilters = (0, import_react14.useMemo)(
5562
5605
  () => ({
5563
5606
  query: query || void 0,
@@ -5587,21 +5630,21 @@ var TelescupAssetPicker = ({
5587
5630
  return folderOptions.find((option) => option.value === folderFilter);
5588
5631
  }, [folderFilter, folderOptions]);
5589
5632
  const filteredItems = (0, import_react14.useMemo)(() => {
5590
- var _a74;
5633
+ var _a78;
5591
5634
  const selectedFolderAliases = new Set(
5592
- ((_a74 = selectedFolderOption == null ? void 0 : selectedFolderOption.aliases) != null ? _a74 : folderFilter === "all" ? [] : [folderFilter]).map(
5635
+ ((_a78 = selectedFolderOption == null ? void 0 : selectedFolderOption.aliases) != null ? _a78 : folderFilter === "all" ? [] : [folderFilter]).map(
5593
5636
  (entry) => normalizeFolderToken(entry)
5594
5637
  )
5595
5638
  );
5596
5639
  return items.filter((asset) => {
5597
- var _a75, _b7;
5640
+ var _a79, _b7;
5598
5641
  if (!matchesAllowedAsset(asset, allowedTypes)) return false;
5599
5642
  if (typeFilter !== "all") {
5600
5643
  const family = resolveAssetFamily(asset);
5601
5644
  if (family !== typeFilter) return false;
5602
5645
  }
5603
5646
  if (folderFilter !== "all") {
5604
- const folderIdToken = normalizeFolderToken((_a75 = asset.folderId) != null ? _a75 : "");
5647
+ const folderIdToken = normalizeFolderToken((_a79 = asset.folderId) != null ? _a79 : "");
5605
5648
  const folderNameToken = normalizeFolderToken((_b7 = asset.folderName) != null ? _b7 : "");
5606
5649
  if (!selectedFolderAliases.has(folderIdToken) && !selectedFolderAliases.has(folderNameToken)) {
5607
5650
  return false;
@@ -5610,6 +5653,46 @@ var TelescupAssetPicker = ({
5610
5653
  return true;
5611
5654
  });
5612
5655
  }, [allowedTypes, folderFilter, items, selectedFolderOption == null ? void 0 : selectedFolderOption.aliases, typeFilter]);
5656
+ import_react14.default.useEffect(() => {
5657
+ if (!import_meta2.env.DEV) return;
5658
+ const familyCount = items.reduce((acc, asset) => {
5659
+ var _a78, _b7;
5660
+ const key = (_a78 = resolveAssetFamily(asset)) != null ? _a78 : "unknown";
5661
+ acc[key] = ((_b7 = acc[key]) != null ? _b7 : 0) + 1;
5662
+ return acc;
5663
+ }, {});
5664
+ console.log("[telescup][picker]", {
5665
+ query,
5666
+ typeFilter,
5667
+ folderFilter,
5668
+ allowedTypes,
5669
+ totalFromApi: total,
5670
+ itemsLoaded: items.length,
5671
+ filteredItems: filteredItems.length,
5672
+ hasMore,
5673
+ isLoading,
5674
+ isLoadingMore,
5675
+ familyCount,
5676
+ sampleItems: items.slice(0, 5).map((asset) => ({
5677
+ id: asset.id,
5678
+ type: asset.type,
5679
+ mimeType: asset.mimeType,
5680
+ extension: asset.extension,
5681
+ family: resolveAssetFamily(asset)
5682
+ }))
5683
+ });
5684
+ }, [
5685
+ filteredItems.length,
5686
+ folderFilter,
5687
+ hasMore,
5688
+ isLoading,
5689
+ isLoadingMore,
5690
+ items,
5691
+ query,
5692
+ allowedTypes,
5693
+ total,
5694
+ typeFilter
5695
+ ]);
5613
5696
  const handleSelect = (0, import_react14.useCallback)(
5614
5697
  (asset) => {
5615
5698
  let nextIds = [];
@@ -5650,8 +5733,8 @@ var TelescupAssetPicker = ({
5650
5733
  /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(SelectTrigger, { className: "border-border/70 bg-background/60 dark:border-white/15", children: /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(SelectValue, { placeholder: labels.filters.type }) }),
5651
5734
  /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(SelectContent, { children: [
5652
5735
  /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(SelectItem, { value: "all", children: labels.filters.allTypes }),
5653
- /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(SelectItem, { value: "image", children: "Imagem" }),
5654
- /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(SelectItem, { value: "video", children: "V\xEDdeo" })
5736
+ allowedFamilies.image ? /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(SelectItem, { value: "image", children: "Imagem" }) : null,
5737
+ allowedFamilies.video ? /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(SelectItem, { value: "video", children: "V\xEDdeo" }) : null
5655
5738
  ] })
5656
5739
  ] }),
5657
5740
  /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Select, { value: folderFilter, onValueChange: setFolderFilter, children: [
@@ -5825,7 +5908,7 @@ function useTelescupUploadQueue(options) {
5825
5908
  activeRef.current += 1;
5826
5909
  updateItem(next.id, { status: "uploading", progress: 0, error: void 0 });
5827
5910
  const run = async () => {
5828
- var _a74, _b7, _c;
5911
+ var _a78, _b7, _c;
5829
5912
  try {
5830
5913
  if (TELESCUP_UPLOAD_MODE === "direct") {
5831
5914
  const completed2 = await client.uploadDirect(next.file);
@@ -5844,7 +5927,7 @@ function useTelescupUploadQueue(options) {
5844
5927
  size: next.file.size,
5845
5928
  mimeType: next.file.type,
5846
5929
  folderId,
5847
- conflict: (_a74 = next.conflictPolicy) != null ? _a74 : conflictPolicy
5930
+ conflict: (_a78 = next.conflictPolicy) != null ? _a78 : conflictPolicy
5848
5931
  });
5849
5932
  const conflictDetected = init.conflict === "ask" || init.conflict === "conflict" || init.conflict === "exists" || init.existingAsset && !init.uploadUrl;
5850
5933
  if (conflictDetected) {
@@ -5982,7 +6065,7 @@ var TelescupUploader = ({
5982
6065
  className,
5983
6066
  onAssetUploaded
5984
6067
  }) => {
5985
- var _a74;
6068
+ var _a78;
5986
6069
  const inputRef = (0, import_react16.useRef)(null);
5987
6070
  const [dragActive, setDragActive] = (0, import_react16.useState)(false);
5988
6071
  const {
@@ -6049,8 +6132,8 @@ var TelescupUploader = ({
6049
6132
  size: "sm",
6050
6133
  variant: "secondary",
6051
6134
  onClick: () => {
6052
- var _a75;
6053
- return (_a75 = inputRef.current) == null ? void 0 : _a75.click();
6135
+ var _a79;
6136
+ return (_a79 = inputRef.current) == null ? void 0 : _a79.click();
6054
6137
  },
6055
6138
  children: labels.uploader.browse
6056
6139
  }
@@ -6064,8 +6147,8 @@ var TelescupUploader = ({
6064
6147
  accept,
6065
6148
  multiple,
6066
6149
  onChange: (event) => {
6067
- var _a75;
6068
- if ((_a75 = event.target.files) == null ? void 0 : _a75.length) {
6150
+ var _a79;
6151
+ if ((_a79 = event.target.files) == null ? void 0 : _a79.length) {
6069
6152
  handleFiles(event.target.files);
6070
6153
  event.currentTarget.value = "";
6071
6154
  }
@@ -6100,7 +6183,7 @@ var TelescupUploader = ({
6100
6183
  /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(AlertDialogTitle, { children: labels.conflict.title }),
6101
6184
  /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(AlertDialogDescription, { children: labels.conflict.description })
6102
6185
  ] }),
6103
- ((_a74 = conflictItem == null ? void 0 : conflictItem.existingAsset) == null ? void 0 : _a74.id) ? /* @__PURE__ */ (0, import_jsx_runtime37.jsxs)("div", { className: "mt-3 rounded-lg border border-border bg-muted/30 p-3", children: [
6186
+ ((_a78 = conflictItem == null ? void 0 : conflictItem.existingAsset) == null ? void 0 : _a78.id) ? /* @__PURE__ */ (0, import_jsx_runtime37.jsxs)("div", { className: "mt-3 rounded-lg border border-border bg-muted/30 p-3", children: [
6104
6187
  /* @__PURE__ */ (0, import_jsx_runtime37.jsx)("p", { className: "text-xs font-semibold text-muted-foreground", children: "Asset existente" }),
6105
6188
  /* @__PURE__ */ (0, import_jsx_runtime37.jsx)("div", { className: "mt-2 h-28 overflow-hidden rounded-md", children: /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(
6106
6189
  TelescupImage,
@@ -6323,7 +6406,7 @@ var DEFAULT_LABELS = {
6323
6406
  }
6324
6407
  };
6325
6408
  var mergeLabels = (overrides) => {
6326
- var _a74;
6409
+ var _a78;
6327
6410
  if (!overrides) return DEFAULT_LABELS;
6328
6411
  return {
6329
6412
  ...DEFAULT_LABELS,
@@ -6337,16 +6420,16 @@ var mergeLabels = (overrides) => {
6337
6420
  meta: {
6338
6421
  ...DEFAULT_LABELS.meta,
6339
6422
  ...overrides.meta,
6340
- fields: { ...DEFAULT_LABELS.meta.fields, ...(_a74 = overrides.meta) == null ? void 0 : _a74.fields }
6423
+ fields: { ...DEFAULT_LABELS.meta.fields, ...(_a78 = overrides.meta) == null ? void 0 : _a78.fields }
6341
6424
  },
6342
6425
  toasts: { ...DEFAULT_LABELS.toasts, ...overrides.toasts }
6343
6426
  };
6344
6427
  };
6345
6428
  var LANGUAGES = ["pt", "en", "es"];
6346
6429
  var getAssetMeta = (asset, lang) => {
6347
- var _a74, _b7;
6430
+ var _a78, _b7;
6348
6431
  if (!asset) return {};
6349
- if ((_a74 = asset.metaByLang) == null ? void 0 : _a74[lang]) return asset.metaByLang[lang];
6432
+ if ((_a78 = asset.metaByLang) == null ? void 0 : _a78[lang]) return asset.metaByLang[lang];
6350
6433
  return (_b7 = asset.meta) != null ? _b7 : {};
6351
6434
  };
6352
6435
  var TelescupMetaEditor = ({
@@ -6357,8 +6440,8 @@ var TelescupMetaEditor = ({
6357
6440
  labels,
6358
6441
  onAssetUpdated
6359
6442
  }) => {
6360
- var _a74, _b7, _c, _d, _e, _f, _g, _h;
6361
- const [activeAssetId, setActiveAssetId] = (0, import_react17.useState)((_b7 = (_a74 = assets[0]) == null ? void 0 : _a74.id) != null ? _b7 : "");
6443
+ var _a78, _b7, _c, _d, _e, _f, _g, _h;
6444
+ const [activeAssetId, setActiveAssetId] = (0, import_react17.useState)((_b7 = (_a78 = assets[0]) == null ? void 0 : _a78.id) != null ? _b7 : "");
6362
6445
  const [activeLang, setActiveLang] = (0, import_react17.useState)(
6363
6446
  LANGUAGES.includes(defaultLanguage) ? defaultLanguage : "pt"
6364
6447
  );
@@ -6376,18 +6459,18 @@ var TelescupMetaEditor = ({
6376
6459
  }, [activeAssetId, assets]);
6377
6460
  const asset = assets.find((item) => item.id === activeAssetId);
6378
6461
  const currentDraft = (0, import_react17.useMemo)(() => {
6379
- var _a75;
6380
- const existing = (_a75 = drafts[activeAssetId]) == null ? void 0 : _a75[activeLang];
6462
+ var _a79;
6463
+ const existing = (_a79 = drafts[activeAssetId]) == null ? void 0 : _a79[activeLang];
6381
6464
  if (existing) return existing;
6382
6465
  return getAssetMeta(asset, activeLang);
6383
6466
  }, [activeAssetId, activeLang, asset, drafts]);
6384
6467
  const updateDraft = (field, value) => {
6385
6468
  setDrafts((prev) => {
6386
- var _a75;
6469
+ var _a79;
6387
6470
  return {
6388
6471
  ...prev,
6389
6472
  [activeAssetId]: {
6390
- ...(_a75 = prev[activeAssetId]) != null ? _a75 : {},
6473
+ ...(_a79 = prev[activeAssetId]) != null ? _a79 : {},
6391
6474
  [activeLang]: {
6392
6475
  ...currentDraft,
6393
6476
  [field]: value
@@ -6455,11 +6538,11 @@ var TelescupMetaEditor = ({
6455
6538
  onAssetUpdated == null ? void 0 : onAssetUpdated(updated);
6456
6539
  const updatedMeta = getAssetMeta(updated, activeLang);
6457
6540
  setDrafts((prev) => {
6458
- var _a75;
6541
+ var _a79;
6459
6542
  return {
6460
6543
  ...prev,
6461
6544
  [asset.id]: {
6462
- ...(_a75 = prev[asset.id]) != null ? _a75 : {},
6545
+ ...(_a79 = prev[asset.id]) != null ? _a79 : {},
6463
6546
  [activeLang]: updatedMeta
6464
6547
  }
6465
6548
  };
@@ -7080,14 +7163,14 @@ var normalizeContrastMode = (value) => {
7080
7163
  return (value == null ? void 0 : value.trim().toLowerCase()) === "high" ? "high" : "normal";
7081
7164
  };
7082
7165
  var readStoredExperienceSettings = () => {
7083
- var _a74, _b7, _c;
7166
+ var _a78, _b7, _c;
7084
7167
  const fallback = defaultExperienceSettings();
7085
7168
  if (typeof window === "undefined") return fallback;
7086
7169
  try {
7087
7170
  const raw = window.localStorage.getItem(EXPERIENCE_SETTINGS_STORAGE_KEY);
7088
7171
  const parsed = raw ? JSON.parse(raw) : null;
7089
7172
  const storedThemePreference = window.localStorage.getItem(THEME_PREFERENCE_STORAGE_KEY);
7090
- const legacyTheme = (_a74 = window.localStorage.getItem(THEME_STORAGE_KEY)) != null ? _a74 : window.localStorage.getItem(LEGACY_THEME_STORAGE_KEY);
7173
+ const legacyTheme = (_a78 = window.localStorage.getItem(THEME_STORAGE_KEY)) != null ? _a78 : window.localStorage.getItem(LEGACY_THEME_STORAGE_KEY);
7091
7174
  return {
7092
7175
  theme: normalizeThemePreference((_c = (_b7 = parsed == null ? void 0 : parsed.theme) != null ? _b7 : storedThemePreference) != null ? _c : legacyTheme),
7093
7176
  density: normalizeDensityMode(parsed == null ? void 0 : parsed.density),
@@ -7231,7 +7314,7 @@ var getNotificationTimestamp = (notification) => {
7231
7314
  return Number.isNaN(parsed) ? 0 : parsed;
7232
7315
  };
7233
7316
  var formatNotificationDateTime = (notification) => {
7234
- var _a74;
7317
+ var _a78;
7235
7318
  if (notification.createdAt) {
7236
7319
  const parsed = new Date(notification.createdAt);
7237
7320
  if (!Number.isNaN(parsed.getTime())) {
@@ -7243,7 +7326,7 @@ var formatNotificationDateTime = (notification) => {
7243
7326
  });
7244
7327
  }
7245
7328
  }
7246
- return ((_a74 = notification.timeLabel) == null ? void 0 : _a74.trim()) || "Agora";
7329
+ return ((_a78 = notification.timeLabel) == null ? void 0 : _a78.trim()) || "Agora";
7247
7330
  };
7248
7331
  var getNotificationDayKey = (notification) => {
7249
7332
  const timestamp = getNotificationTimestamp(notification);
@@ -7316,9 +7399,9 @@ var extractSharedFilesFromMessages = (messages) => {
7316
7399
  return files;
7317
7400
  };
7318
7401
  var resolveTelescupImageUrl = (value, options) => {
7319
- var _a74, _b7, _c;
7402
+ var _a78, _b7, _c;
7320
7403
  return resolveTelescupImageURL(value, {
7321
- width: (_a74 = options == null ? void 0 : options.width) != null ? _a74 : 96,
7404
+ width: (_a78 = options == null ? void 0 : options.width) != null ? _a78 : 96,
7322
7405
  height: (_b7 = options == null ? void 0 : options.height) != null ? _b7 : 96,
7323
7406
  fit: "cover",
7324
7407
  format: "avif",
@@ -7326,12 +7409,12 @@ var resolveTelescupImageUrl = (value, options) => {
7326
7409
  });
7327
7410
  };
7328
7411
  var resolveGroupAvatarFromTelescup = (asset, fallbackId) => {
7329
- var _a74, _b7;
7330
- return (_b7 = (_a74 = resolveTelescupImageUrl(asset == null ? void 0 : asset.url)) != null ? _a74 : resolveTelescupImageUrl(asset == null ? void 0 : asset.id)) != null ? _b7 : resolveTelescupImageUrl(fallbackId);
7412
+ var _a78, _b7;
7413
+ return (_b7 = (_a78 = resolveTelescupImageUrl(asset == null ? void 0 : asset.url)) != null ? _a78 : resolveTelescupImageUrl(asset == null ? void 0 : asset.id)) != null ? _b7 : resolveTelescupImageUrl(fallbackId);
7331
7414
  };
7332
7415
  var resolveProfileAvatarFromTelescup = (asset, fallbackId) => {
7333
- var _a74, _b7;
7334
- return (_b7 = (_a74 = resolveTelescupImageUrl(asset == null ? void 0 : asset.url, { width: 384, height: 384, quality: 80 })) != null ? _a74 : resolveTelescupImageUrl(asset == null ? void 0 : asset.id, { width: 384, height: 384, quality: 80 })) != null ? _b7 : resolveTelescupImageUrl(fallbackId, { width: 384, height: 384, quality: 80 });
7416
+ var _a78, _b7;
7417
+ return (_b7 = (_a78 = resolveTelescupImageUrl(asset == null ? void 0 : asset.url, { width: 384, height: 384, quality: 80 })) != null ? _a78 : resolveTelescupImageUrl(asset == null ? void 0 : asset.id, { width: 384, height: 384, quality: 80 })) != null ? _b7 : resolveTelescupImageUrl(fallbackId, { width: 384, height: 384, quality: 80 });
7335
7418
  };
7336
7419
  var playIncomingMessageSound = () => {
7337
7420
  if (typeof window === "undefined") return;
@@ -7470,7 +7553,7 @@ var UserMenuCupcode = ({
7470
7553
  panels,
7471
7554
  className
7472
7555
  }) => {
7473
- var _a74;
7556
+ var _a78;
7474
7557
  const [open, setOpen] = (0, import_react18.useState)(false);
7475
7558
  const [activeTab, setActiveTab] = (0, import_react18.useState)("profile");
7476
7559
  const [isLoggingOut, setIsLoggingOut] = (0, import_react18.useState)(false);
@@ -7574,12 +7657,12 @@ var UserMenuCupcode = ({
7574
7657
  );
7575
7658
  const normalizedNotificationFeed = (0, import_react18.useMemo)(
7576
7659
  () => resolvedNotificationFeed.map((notification) => {
7577
- var _a75;
7660
+ var _a79;
7578
7661
  const kind = normalizeNotificationKind(notification.kind);
7579
7662
  return {
7580
7663
  ...notification,
7581
7664
  kind,
7582
- topic: (_a75 = notification.topic) != null ? _a75 : NOTIFICATION_KIND_META[kind].topicFallback
7665
+ topic: (_a79 = notification.topic) != null ? _a79 : NOTIFICATION_KIND_META[kind].topicFallback
7583
7666
  };
7584
7667
  }),
7585
7668
  [resolvedNotificationFeed]
@@ -7614,9 +7697,9 @@ var UserMenuCupcode = ({
7614
7697
  const groupedNotifications = (0, import_react18.useMemo)(() => {
7615
7698
  const groups = /* @__PURE__ */ new Map();
7616
7699
  filteredNotifications.forEach((notification) => {
7617
- var _a75, _b7;
7700
+ var _a79, _b7;
7618
7701
  const kind = normalizeNotificationKind(notification.kind);
7619
- const key = notificationPreferences.grouping === "topic" ? (_a75 = notification.topic) != null ? _a75 : NOTIFICATION_KIND_META[kind].topicFallback : getNotificationDayKey(notification);
7702
+ const key = notificationPreferences.grouping === "topic" ? (_a79 = notification.topic) != null ? _a79 : NOTIFICATION_KIND_META[kind].topicFallback : getNotificationDayKey(notification);
7620
7703
  const current = (_b7 = groups.get(key)) != null ? _b7 : [];
7621
7704
  current.push(notification);
7622
7705
  groups.set(key, current);
@@ -7704,7 +7787,7 @@ var UserMenuCupcode = ({
7704
7787
  }).slice(0, 6);
7705
7788
  }, [recentActivity]);
7706
7789
  const isSendingChatMessage = isChatSending || isSendingInternalChatMessage;
7707
- const activeReactionPickerMessageId = (_a74 = activeReactionPicker == null ? void 0 : activeReactionPicker.messageId) != null ? _a74 : null;
7790
+ const activeReactionPickerMessageId = (_a78 = activeReactionPicker == null ? void 0 : activeReactionPicker.messageId) != null ? _a78 : null;
7708
7791
  const isChatSidebarOpen = isChatSidebarExpanded || isChatSidebarPinned;
7709
7792
  const hasTelescupAvatarSupport = Boolean(telescupBaseUrl && getTelescupAccessToken);
7710
7793
  const hasTelescupGroupAvatarSupport = hasTelescupAvatarSupport;
@@ -7718,8 +7801,8 @@ var UserMenuCupcode = ({
7718
7801
  meta.set(user.id, { lastMessage: null, lastTimestamp: 0, unreadCount: 0 });
7719
7802
  });
7720
7803
  resolvedAllChatMessages.forEach((message) => {
7721
- var _a75;
7722
- const current = (_a75 = meta.get(message.contactId)) != null ? _a75 : { lastMessage: null, lastTimestamp: 0, unreadCount: 0 };
7804
+ var _a79;
7805
+ const current = (_a79 = meta.get(message.contactId)) != null ? _a79 : { lastMessage: null, lastTimestamp: 0, unreadCount: 0 };
7723
7806
  const timestamp = getChatMessageTimestamp(message);
7724
7807
  if (timestamp >= current.lastTimestamp) {
7725
7808
  current.lastTimestamp = timestamp;
@@ -7739,10 +7822,10 @@ var UserMenuCupcode = ({
7739
7822
  return haystack.includes(query);
7740
7823
  });
7741
7824
  return filtered.sort((left, right) => {
7742
- var _a75, _b7, _c, _d;
7825
+ var _a79, _b7, _c, _d;
7743
7826
  const leftMeta = conversationMetaByUserId.get(left.id);
7744
7827
  const rightMeta = conversationMetaByUserId.get(right.id);
7745
- const leftUnread = (_a75 = leftMeta == null ? void 0 : leftMeta.unreadCount) != null ? _a75 : 0;
7828
+ const leftUnread = (_a79 = leftMeta == null ? void 0 : leftMeta.unreadCount) != null ? _a79 : 0;
7746
7829
  const rightUnread = (_b7 = rightMeta == null ? void 0 : rightMeta.unreadCount) != null ? _b7 : 0;
7747
7830
  if (leftUnread !== rightUnread) return rightUnread - leftUnread;
7748
7831
  const leftTimestamp = (_c = leftMeta == null ? void 0 : leftMeta.lastTimestamp) != null ? _c : 0;
@@ -7792,11 +7875,11 @@ var UserMenuCupcode = ({
7792
7875
  let changed = false;
7793
7876
  const next = { ...current };
7794
7877
  normalizedNotificationFeed.forEach((notification) => {
7795
- var _a75;
7878
+ var _a79;
7796
7879
  if (normalizeNotificationKind(notification.kind) !== "chat") return;
7797
7880
  const contactId = notification.actionChatUserId;
7798
7881
  if (!contactId) return;
7799
- if (((_a75 = resolvedChatUnreadByUser[contactId]) != null ? _a75 : 0) > 0) return;
7882
+ if (((_a79 = resolvedChatUnreadByUser[contactId]) != null ? _a79 : 0) > 0) return;
7800
7883
  if (next[notification.id] === true) return;
7801
7884
  next[notification.id] = true;
7802
7885
  changed = true;
@@ -7810,11 +7893,11 @@ var UserMenuCupcode = ({
7810
7893
  const visibleChatUnreadCount = resolvedChatUnreadCount;
7811
7894
  const firstUnreadChatUserId = (0, import_react18.useMemo)(
7812
7895
  () => {
7813
- var _a75, _b7;
7814
- return (_b7 = (_a75 = filteredAndSortedChatUsers.find((user) => {
7815
- var _a76;
7816
- return ((_a76 = resolvedChatUnreadByUser[user.id]) != null ? _a76 : 0) > 0;
7817
- })) == null ? void 0 : _a75.id) != null ? _b7 : null;
7896
+ var _a79, _b7;
7897
+ return (_b7 = (_a79 = filteredAndSortedChatUsers.find((user) => {
7898
+ var _a80;
7899
+ return ((_a80 = resolvedChatUnreadByUser[user.id]) != null ? _a80 : 0) > 0;
7900
+ })) == null ? void 0 : _a79.id) != null ? _b7 : null;
7818
7901
  },
7819
7902
  [filteredAndSortedChatUsers, resolvedChatUnreadByUser]
7820
7903
  );
@@ -7873,11 +7956,11 @@ var UserMenuCupcode = ({
7873
7956
  );
7874
7957
  const openChatPanel = (0, import_react18.useCallback)(
7875
7958
  (contactId) => {
7876
- var _a75, _b7, _c, _d, _e;
7959
+ var _a79, _b7, _c, _d, _e;
7877
7960
  setIsLogoutConfirmOpen(false);
7878
7961
  setOpen(true);
7879
7962
  setActiveTab("chat");
7880
- const targetContactId = (_e = (_d = (_b7 = contactId != null ? contactId : firstUnreadChatUserId) != null ? _b7 : (_a75 = filteredAndSortedChatUsers[0]) == null ? void 0 : _a75.id) != null ? _d : (_c = chatUsersList[0]) == null ? void 0 : _c.id) != null ? _e : "";
7963
+ const targetContactId = (_e = (_d = (_b7 = contactId != null ? contactId : firstUnreadChatUserId) != null ? _b7 : (_a79 = filteredAndSortedChatUsers[0]) == null ? void 0 : _a79.id) != null ? _d : (_c = chatUsersList[0]) == null ? void 0 : _c.id) != null ? _e : "";
7881
7964
  if (!targetContactId) return;
7882
7965
  setActiveChatUserId(targetContactId);
7883
7966
  markConversationRead(targetContactId);
@@ -7911,8 +7994,8 @@ var UserMenuCupcode = ({
7911
7994
  const reactionsByMessageId = (0, import_react18.useMemo)(() => {
7912
7995
  const grouped = /* @__PURE__ */ new Map();
7913
7996
  resolvedAllChatReactions.forEach((reaction) => {
7914
- var _a75, _b7;
7915
- const byEmoji = (_a75 = grouped.get(reaction.messageId)) != null ? _a75 : /* @__PURE__ */ new Map();
7997
+ var _a79, _b7;
7998
+ const byEmoji = (_a79 = grouped.get(reaction.messageId)) != null ? _a79 : /* @__PURE__ */ new Map();
7916
7999
  const current = (_b7 = byEmoji.get(reaction.emoji)) != null ? _b7 : { emoji: reaction.emoji, count: 0, reactedByMe: false };
7917
8000
  current.count += 1;
7918
8001
  if (resolvedCurrentChatUserId && reaction.userId === resolvedCurrentChatUserId) {
@@ -8110,9 +8193,9 @@ var UserMenuCupcode = ({
8110
8193
  const wasFocusModeActive = wasFocusModeActiveRef.current;
8111
8194
  if (wasFocusModeActive && !isFocusModeActive && suppressedFocusNotifications.length) {
8112
8195
  const byType = suppressedFocusNotifications.reduce((acc, notification) => {
8113
- var _a75;
8196
+ var _a79;
8114
8197
  const kind = normalizeNotificationKind(notification.kind);
8115
- acc[kind] = ((_a75 = acc[kind]) != null ? _a75 : 0) + 1;
8198
+ acc[kind] = ((_a79 = acc[kind]) != null ? _a79 : 0) + 1;
8116
8199
  return acc;
8117
8200
  }, { system: 0, comment: 0, access: 0, billing: 0, chat: 0, security: 0 });
8118
8201
  const summaryParts = NOTIFICATION_KIND_ORDER.filter((kind) => byType[kind] > 0).map(
@@ -8142,9 +8225,9 @@ var UserMenuCupcode = ({
8142
8225
  return;
8143
8226
  }
8144
8227
  setActiveChatUserId((current) => {
8145
- var _a75, _b7;
8228
+ var _a79, _b7;
8146
8229
  if (current && chatUsersList.some((user) => user.id === current)) return current;
8147
- return (_b7 = (_a75 = filteredAndSortedChatUsers[0]) == null ? void 0 : _a75.id) != null ? _b7 : chatUsersList[0].id;
8230
+ return (_b7 = (_a79 = filteredAndSortedChatUsers[0]) == null ? void 0 : _a79.id) != null ? _b7 : chatUsersList[0].id;
8148
8231
  });
8149
8232
  }, [chatUsersList, filteredAndSortedChatUsers]);
8150
8233
  (0, import_react18.useEffect)(() => {
@@ -8186,7 +8269,7 @@ var UserMenuCupcode = ({
8186
8269
  };
8187
8270
  }, [activeReactionPickerMessageId]);
8188
8271
  (0, import_react18.useEffect)(() => {
8189
- var _a75;
8272
+ var _a79;
8190
8273
  if (!hasBootstrappedIncomingMessagesRef.current && isChatLoading) return;
8191
8274
  const knownIncomingIds = seenIncomingMessageIdsRef.current;
8192
8275
  const incomingMessages = resolvedAllChatMessages.filter((message) => message.sender === "them" && !message.readAt);
@@ -8208,9 +8291,9 @@ var UserMenuCupcode = ({
8208
8291
  return;
8209
8292
  }
8210
8293
  const generatedNotifications = relevantIncomingMessages.map((message) => {
8211
- var _a76, _b7, _c;
8294
+ var _a80, _b7, _c;
8212
8295
  const contact = chatUsersList.find((user) => user.id === message.contactId);
8213
- const createdAt = (_a76 = message.createdAt) != null ? _a76 : (/* @__PURE__ */ new Date()).toISOString();
8296
+ const createdAt = (_a80 = message.createdAt) != null ? _a80 : (/* @__PURE__ */ new Date()).toISOString();
8214
8297
  const previewText = chatSettings.showMessagePreview ? summarizeChatText(message.text, 100) : "Nova mensagem no chat.";
8215
8298
  return {
8216
8299
  id: `chat-notification-${message.id}`,
@@ -8232,7 +8315,7 @@ var UserMenuCupcode = ({
8232
8315
  )[0];
8233
8316
  if (latestRelevantMessage) {
8234
8317
  const latestContact = chatUsersList.find((user) => user.id === latestRelevantMessage.contactId);
8235
- const senderName = (_a75 = latestContact == null ? void 0 : latestContact.name) != null ? _a75 : "usu\xE1rio";
8318
+ const senderName = (_a79 = latestContact == null ? void 0 : latestContact.name) != null ? _a79 : "usu\xE1rio";
8236
8319
  const latestPreview = chatSettings.showMessagePreview ? summarizeChatText(latestRelevantMessage.text, 96) : "Nova mensagem";
8237
8320
  const messageCount = relevantIncomingMessages.length;
8238
8321
  const messageCountLabel = messageCount > 99 ? "99+" : String(messageCount);
@@ -8281,10 +8364,10 @@ var UserMenuCupcode = ({
8281
8364
  return;
8282
8365
  }
8283
8366
  generatedNotifications.forEach((chatNotification) => {
8284
- var _a76;
8367
+ var _a80;
8285
8368
  const notification = new Notification(chatNotification.title, {
8286
8369
  body: chatSettings.showMessagePreview ? chatNotification.description : "Voc\xEA recebeu uma nova mensagem.",
8287
- tag: `cc-chat-${(_a76 = chatNotification.actionChatUserId) != null ? _a76 : chatNotification.id}`
8370
+ tag: `cc-chat-${(_a80 = chatNotification.actionChatUserId) != null ? _a80 : chatNotification.id}`
8288
8371
  });
8289
8372
  notification.onclick = () => {
8290
8373
  window.focus();
@@ -8311,14 +8394,14 @@ var UserMenuCupcode = ({
8311
8394
  ]);
8312
8395
  const activeChatUser = (0, import_react18.useMemo)(
8313
8396
  () => {
8314
- var _a75;
8315
- return (_a75 = chatUsersList.find((user) => user.id === activeChatUserId)) != null ? _a75 : null;
8397
+ var _a79;
8398
+ return (_a79 = chatUsersList.find((user) => user.id === activeChatUserId)) != null ? _a79 : null;
8316
8399
  },
8317
8400
  [activeChatUserId, chatUsersList]
8318
8401
  );
8319
8402
  const activeGroupMembers = (0, import_react18.useMemo)(() => {
8320
- var _a75;
8321
- if (!(activeChatUser == null ? void 0 : activeChatUser.isGroup) || !((_a75 = activeChatUser.memberIds) == null ? void 0 : _a75.length)) return [];
8403
+ var _a79;
8404
+ if (!(activeChatUser == null ? void 0 : activeChatUser.isGroup) || !((_a79 = activeChatUser.memberIds) == null ? void 0 : _a79.length)) return [];
8322
8405
  const members = activeChatUser.memberIds.map((memberId) => baseChatUsersList.find((user) => user.id === memberId)).filter((member) => Boolean(member));
8323
8406
  return members;
8324
8407
  }, [activeChatUser, baseChatUsersList]);
@@ -8357,8 +8440,8 @@ var UserMenuCupcode = ({
8357
8440
  return items;
8358
8441
  }, [activeChatMessages]);
8359
8442
  (0, import_react18.useEffect)(() => {
8360
- var _a75;
8361
- const conversationId = (_a75 = activeChatUser == null ? void 0 : activeChatUser.id) != null ? _a75 : null;
8443
+ var _a79;
8444
+ const conversationId = (_a79 = activeChatUser == null ? void 0 : activeChatUser.id) != null ? _a79 : null;
8362
8445
  if (!conversationId) {
8363
8446
  activeConversationIdRef.current = null;
8364
8447
  activeConversationMessageIdsRef.current = /* @__PURE__ */ new Set();
@@ -8411,9 +8494,9 @@ var UserMenuCupcode = ({
8411
8494
  });
8412
8495
  }, [activeChatUser, resolvedChatLogs]);
8413
8496
  const replyToMessage = (0, import_react18.useMemo)(() => {
8414
- var _a75;
8497
+ var _a79;
8415
8498
  if (!replyToMessageId) return null;
8416
- return (_a75 = activeChatMessagesMap.get(replyToMessageId)) != null ? _a75 : null;
8499
+ return (_a79 = activeChatMessagesMap.get(replyToMessageId)) != null ? _a79 : null;
8417
8500
  }, [activeChatMessagesMap, replyToMessageId]);
8418
8501
  (0, import_react18.useEffect)(() => {
8419
8502
  if (!replyToMessageId) return;
@@ -8440,9 +8523,9 @@ var UserMenuCupcode = ({
8440
8523
  }
8441
8524
  }, [activeChatUser]);
8442
8525
  (0, import_react18.useEffect)(() => {
8443
- var _a75;
8526
+ var _a79;
8444
8527
  if (!open || activeTab !== "chat" || !activeChatUser || activeChatUser.isGroup) return;
8445
- const unreadCount = (_a75 = resolvedChatUnreadByUser[activeChatUser.id]) != null ? _a75 : 0;
8528
+ const unreadCount = (_a79 = resolvedChatUnreadByUser[activeChatUser.id]) != null ? _a79 : 0;
8446
8529
  if (unreadCount <= 0) return;
8447
8530
  const contactId = activeChatUser.id;
8448
8531
  if (pendingReadRequestsRef.current.has(contactId)) return;
@@ -8518,13 +8601,13 @@ var UserMenuCupcode = ({
8518
8601
  openAccountsPath("/security#sessions");
8519
8602
  };
8520
8603
  const runOpenIntegrations = (provider) => {
8521
- var _a75;
8604
+ var _a79;
8522
8605
  if (!provider) {
8523
8606
  openAccountsPath("/integrations");
8524
8607
  return;
8525
8608
  }
8526
8609
  const option = INTEGRATION_OPTIONS.find((integration) => integration.id === provider);
8527
- openAccountsPath((_a75 = option == null ? void 0 : option.accountPath) != null ? _a75 : "/integrations");
8610
+ openAccountsPath((_a79 = option == null ? void 0 : option.accountPath) != null ? _a79 : "/integrations");
8528
8611
  };
8529
8612
  const changeStatus = (nextStatus) => {
8530
8613
  if (nextStatus === "offline") return;
@@ -8891,9 +8974,9 @@ var UserMenuCupcode = ({
8891
8974
  };
8892
8975
  const handleProfileAvatarChange = (0, import_react18.useCallback)(
8893
8976
  async (ids, assets) => {
8894
- var _a75, _b7, _c;
8977
+ var _a79, _b7, _c;
8895
8978
  const selectedAsset = assets == null ? void 0 : assets[0];
8896
- const selectedIdRaw = (_a75 = ids[0]) == null ? void 0 : _a75.trim();
8979
+ const selectedIdRaw = (_a79 = ids[0]) == null ? void 0 : _a79.trim();
8897
8980
  const selectedId = (_c = (_b7 = parseAssetId(selectedIdRaw)) != null ? _b7 : parseAssetId(selectedAsset == null ? void 0 : selectedAsset.id)) != null ? _c : parseAssetId(selectedAsset == null ? void 0 : selectedAsset.url);
8898
8981
  if (!selectedId) {
8899
8982
  toast({
@@ -8936,7 +9019,7 @@ var UserMenuCupcode = ({
8936
9019
  [isProfileAvatarSaving, onProfileAvatarChange, resolvedProfileAvatarUrl]
8937
9020
  );
8938
9021
  const sendChatMessage = async () => {
8939
- var _a75, _b7;
9022
+ var _a79, _b7;
8940
9023
  if (!activeChatUser) return;
8941
9024
  const text = chatDraft.trim();
8942
9025
  if (!text || isSendingChatMessage) return;
@@ -8948,7 +9031,7 @@ var UserMenuCupcode = ({
8948
9031
  await onChatSendMessage({
8949
9032
  recipientId: activeChatUser.id,
8950
9033
  text,
8951
- replyToMessageId: (_a75 = replyToMessage == null ? void 0 : replyToMessage.id) != null ? _a75 : null
9034
+ replyToMessageId: (_a79 = replyToMessage == null ? void 0 : replyToMessage.id) != null ? _a79 : null
8952
9035
  });
8953
9036
  setChatDraft("");
8954
9037
  setShowEmojiPicker(false);
@@ -8990,7 +9073,7 @@ var UserMenuCupcode = ({
8990
9073
  });
8991
9074
  };
8992
9075
  const renderDefaultPanel = () => {
8993
- var _a75, _b7, _c, _d;
9076
+ var _a79, _b7, _c, _d, _e;
8994
9077
  if (activeTab === "profile") {
8995
9078
  return /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)("div", { className: "space-y-4", children: [
8996
9079
  /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)("div", { className: "pt-1 text-center", children: [
@@ -9155,7 +9238,7 @@ var UserMenuCupcode = ({
9155
9238
  commitButtonLabel: "Salvar",
9156
9239
  closeOnCommit: true,
9157
9240
  multiple: false,
9158
- allowedTypes: ["image/*"],
9241
+ allowedTypes: ["image/*", "video/*"],
9159
9242
  maxSizeMB: 8,
9160
9243
  enableAI: false,
9161
9244
  enableMetaEditor: false,
@@ -9261,7 +9344,7 @@ var UserMenuCupcode = ({
9261
9344
  visibleGroupedNotifications.length ? visibleGroupedNotifications.map((group) => /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)("section", { className: "space-y-1.5", children: [
9262
9345
  /* @__PURE__ */ (0, import_jsx_runtime42.jsx)("p", { className: "px-0.5 text-[11px] font-semibold uppercase tracking-[0.08em] text-muted-foreground", children: group.label }),
9263
9346
  /* @__PURE__ */ (0, import_jsx_runtime42.jsx)("div", { className: "space-y-1.5", children: group.items.map((notification) => {
9264
- var _a76;
9347
+ var _a80;
9265
9348
  const kind = normalizeNotificationKind(notification.kind);
9266
9349
  const meta = NOTIFICATION_KIND_META[kind];
9267
9350
  const Icon3 = meta.icon;
@@ -9290,7 +9373,7 @@ var UserMenuCupcode = ({
9290
9373
  className: "inline-flex h-6 items-center gap-1 rounded-md border border-border/70 px-1.5 text-[11px] font-semibold text-foreground transition-all hover:bg-muted/45",
9291
9374
  children: [
9292
9375
  /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(import_lucide_react10.ExternalLink, { className: "h-3 w-3" }),
9293
- (_a76 = notification.actionLabel) != null ? _a76 : "Abrir"
9376
+ (_a80 = notification.actionLabel) != null ? _a80 : "Abrir"
9294
9377
  ]
9295
9378
  }
9296
9379
  ),
@@ -9518,7 +9601,7 @@ var UserMenuCupcode = ({
9518
9601
  }
9519
9602
  if (activeTab === "chat") {
9520
9603
  const canSendChatMessage = Boolean(activeChatUser) && chatDraft.trim() !== "" && !isSendingChatMessage && !isChatLoading;
9521
- const activeConversationUnreadCount = activeChatUser ? (_a75 = resolvedChatUnreadByUser[activeChatUser.id]) != null ? _a75 : 0 : 0;
9604
+ const activeConversationUnreadCount = activeChatUser ? (_a79 = resolvedChatUnreadByUser[activeChatUser.id]) != null ? _a79 : 0 : 0;
9522
9605
  return /* @__PURE__ */ (0, import_jsx_runtime42.jsx)("div", { className: "h-full", children: /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)(
9523
9606
  "div",
9524
9607
  {
@@ -9597,10 +9680,10 @@ var UserMenuCupcode = ({
9597
9680
  }
9598
9681
  ),
9599
9682
  /* @__PURE__ */ (0, import_jsx_runtime42.jsx)("div", { className: "space-y-1", children: users.map((user) => {
9600
- var _a76, _b8, _c2;
9683
+ var _a80, _b8, _c2, _d2;
9601
9684
  const userInitials = buildInitials(user.name, user.username);
9602
9685
  const isCurrent = user.id === activeChatUserId;
9603
- const unreadCount = (_a76 = resolvedChatUnreadByUser[user.id]) != null ? _a76 : 0;
9686
+ const unreadCount = (_a80 = resolvedChatUnreadByUser[user.id]) != null ? _a80 : 0;
9604
9687
  const hasUnread = unreadCount > 0;
9605
9688
  const lastMessage = (_b8 = conversationMetaByUserId.get(user.id)) == null ? void 0 : _b8.lastMessage;
9606
9689
  return /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)(
@@ -9647,7 +9730,7 @@ var UserMenuCupcode = ({
9647
9730
  summarizeChatText(lastMessage.text, 44)
9648
9731
  ] }) : "Nova mensagem"
9649
9732
  }
9650
- ) : /* @__PURE__ */ (0, import_jsx_runtime42.jsx)("p", { className: "mt-0.5 truncate text-[10px] text-muted-foreground", children: user.isGroup ? (_c2 = user.roleLabel) != null ? _c2 : "Grupo criado" : PRESENCE_META[user.status].label })
9733
+ ) : /* @__PURE__ */ (0, import_jsx_runtime42.jsx)("p", { className: "mt-0.5 truncate text-[10px] text-muted-foreground", children: user.isGroup ? (_c2 = user.roleLabel) != null ? _c2 : "Grupo criado" : (_d2 = user.statusLabel) != null ? _d2 : PRESENCE_META[user.status].label })
9651
9734
  ]
9652
9735
  }
9653
9736
  )
@@ -9731,7 +9814,7 @@ var UserMenuCupcode = ({
9731
9814
  /* @__PURE__ */ (0, import_jsx_runtime42.jsx)("p", { className: "truncate text-xs font-semibold text-foreground", children: activeChatUser.name }),
9732
9815
  !isBadgeSuppressedByFocus && activeConversationUnreadCount > 0 ? /* @__PURE__ */ (0, import_jsx_runtime42.jsx)("span", { className: "inline-flex h-4 min-w-[1rem] items-center justify-center rounded-full bg-destructive px-1 text-[10px] font-bold text-destructive-foreground", children: activeConversationUnreadCount > 99 ? "99+" : activeConversationUnreadCount }) : null
9733
9816
  ] }),
9734
- /* @__PURE__ */ (0, import_jsx_runtime42.jsx)("p", { className: "truncate text-[11px] text-muted-foreground", children: activeChatUser.isGroup ? "Grupo" : PRESENCE_META[activeChatUser.status].label }),
9817
+ /* @__PURE__ */ (0, import_jsx_runtime42.jsx)("p", { className: "truncate text-[11px] text-muted-foreground", children: activeChatUser.isGroup ? "Grupo" : (_b7 = activeChatUser.statusLabel) != null ? _b7 : PRESENCE_META[activeChatUser.status].label }),
9735
9818
  activeChatUser.roleLabel ? /* @__PURE__ */ (0, import_jsx_runtime42.jsx)("p", { className: "truncate text-[11px] text-primary", children: activeChatUser.roleLabel }) : null,
9736
9819
  activeChatUser.isGroup && activeGroupMembers.length ? /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)("p", { className: "truncate text-[11px] text-muted-foreground", children: [
9737
9820
  activeGroupMembers.length,
@@ -9817,12 +9900,12 @@ var UserMenuCupcode = ({
9817
9900
  className: "cc-scrollbar cc-scrollbar-purple relative flex-1 space-y-2 overflow-y-auto px-3 py-2.5",
9818
9901
  children: [
9819
9902
  isChatLoading ? /* @__PURE__ */ (0, import_jsx_runtime42.jsx)("p", { className: "rounded-xl border border-dashed border-border/70 bg-background/35 px-3 py-3 text-[11px] text-muted-foreground", children: "Carregando conversa..." }) : activeChatMessages.length ? activeChatTimeline.map((item) => {
9820
- var _a76, _b8;
9903
+ var _a80, _b8;
9821
9904
  if (item.type === "day") {
9822
9905
  return /* @__PURE__ */ (0, import_jsx_runtime42.jsx)("div", { className: "flex justify-center py-1", children: /* @__PURE__ */ (0, import_jsx_runtime42.jsx)("span", { className: "inline-flex items-center rounded-full border border-border/70 bg-background/85 px-2.5 py-0.5 text-[10px] font-medium text-muted-foreground shadow-[var(--elevation-2)]", children: item.label }) }, item.key);
9823
9906
  }
9824
9907
  const { message } = item;
9825
- const replyMessage = message.replyToMessageId ? (_a76 = activeChatMessagesMap.get(message.replyToMessageId)) != null ? _a76 : null : null;
9908
+ const replyMessage = message.replyToMessageId ? (_a80 = activeChatMessagesMap.get(message.replyToMessageId)) != null ? _a80 : null : null;
9826
9909
  const reactions = (_b8 = reactionsByMessageId.get(message.id)) != null ? _b8 : [];
9827
9910
  const hasReadReceipt = Boolean(message.readAt);
9828
9911
  const isEditing = editingMessageId === message.id;
@@ -9996,7 +10079,7 @@ var UserMenuCupcode = ({
9996
10079
  "div",
9997
10080
  {
9998
10081
  ref: reactionPickerRef,
9999
- style: { top: `${(_b7 = activeReactionPicker == null ? void 0 : activeReactionPicker.top) != null ? _b7 : 0}px`, left: `${(_c = activeReactionPicker == null ? void 0 : activeReactionPicker.left) != null ? _c : 0}px` },
10082
+ style: { top: `${(_c = activeReactionPicker == null ? void 0 : activeReactionPicker.top) != null ? _c : 0}px`, left: `${(_d = activeReactionPicker == null ? void 0 : activeReactionPicker.left) != null ? _d : 0}px` },
10000
10083
  className: "absolute z-[1900] flex w-[14.35rem] items-center gap-1 whitespace-nowrap rounded-xl border border-border/70 bg-background/95 p-1.5 shadow-[var(--elevation-4)]",
10001
10084
  children: MESSAGE_REACTION_OPTIONS.map((emoji) => /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(
10002
10085
  "button",
@@ -10152,8 +10235,8 @@ var UserMenuCupcode = ({
10152
10235
  ] })
10153
10236
  ] }),
10154
10237
  isChatSuperAdmin ? activeConversationLogs.length ? /* @__PURE__ */ (0, import_jsx_runtime42.jsx)("div", { className: "space-y-2", children: activeConversationLogs.map((entry) => {
10155
- var _a76;
10156
- const actorName = entry.actorId && entry.actorId === resolvedCurrentChatUserId ? "Voc\xEA" : (_a76 = entry.actorId) != null ? _a76 : "Usu\xE1rio";
10238
+ var _a80;
10239
+ const actorName = entry.actorId && entry.actorId === resolvedCurrentChatUserId ? "Voc\xEA" : (_a80 = entry.actorId) != null ? _a80 : "Usu\xE1rio";
10157
10240
  return /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)(
10158
10241
  "article",
10159
10242
  {
@@ -10319,7 +10402,7 @@ var UserMenuCupcode = ({
10319
10402
  baseUrl: telescupBaseUrl,
10320
10403
  getAccessToken: getTelescupAccessToken,
10321
10404
  multiple: false,
10322
- allowedTypes: ["image/*"],
10405
+ allowedTypes: ["image/*", "video/*"],
10323
10406
  maxSizeMB: 8,
10324
10407
  enableAI: false,
10325
10408
  enableMetaEditor: false,
@@ -10441,7 +10524,7 @@ var UserMenuCupcode = ({
10441
10524
  "Idioma"
10442
10525
  ] }),
10443
10526
  /* @__PURE__ */ (0, import_jsx_runtime42.jsx)("div", { className: "mt-2", children: /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)(Select, { value: resolvedLanguage, onValueChange: (value) => changeLanguage(value), children: [
10444
- /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(SelectTrigger, { className: "h-9 rounded-xl border-border/70 bg-background/55 text-[11px] text-foreground", children: /* @__PURE__ */ (0, import_jsx_runtime42.jsx)("span", { className: "truncate", children: (_d = LANGUAGE_OPTIONS.find((option) => option.value === resolvedLanguage)) == null ? void 0 : _d.label }) }),
10527
+ /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(SelectTrigger, { className: "h-9 rounded-xl border-border/70 bg-background/55 text-[11px] text-foreground", children: /* @__PURE__ */ (0, import_jsx_runtime42.jsx)("span", { className: "truncate", children: (_e = LANGUAGE_OPTIONS.find((option) => option.value === resolvedLanguage)) == null ? void 0 : _e.label }) }),
10445
10528
  /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(SelectContent, { className: "glass-strong z-[820] border-border/70 text-foreground", children: LANGUAGE_OPTIONS.map((option) => /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(SelectItem, { value: option.value, className: "text-xs", children: /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)("span", { className: "flex w-full items-center justify-between gap-3", children: [
10446
10529
  /* @__PURE__ */ (0, import_jsx_runtime42.jsx)("span", { children: option.label }),
10447
10530
  /* @__PURE__ */ (0, import_jsx_runtime42.jsx)("span", { className: "text-[10px] font-semibold text-muted-foreground", children: option.shortLabel })
@@ -11128,7 +11211,7 @@ var FunctionsClient = class {
11128
11211
  */
11129
11212
  invoke(functionName_1) {
11130
11213
  return __awaiter(this, arguments, void 0, function* (functionName, options = {}) {
11131
- var _a74;
11214
+ var _a78;
11132
11215
  let timeoutId;
11133
11216
  let timeoutController;
11134
11217
  try {
@@ -11194,7 +11277,7 @@ var FunctionsClient = class {
11194
11277
  if (!response.ok) {
11195
11278
  throw new FunctionsHttpError(response);
11196
11279
  }
11197
- let responseType = ((_a74 = response.headers.get("Content-Type")) !== null && _a74 !== void 0 ? _a74 : "text/plain").split(";")[0].trim();
11280
+ let responseType = ((_a78 = response.headers.get("Content-Type")) !== null && _a78 !== void 0 ? _a78 : "text/plain").split(";")[0].trim();
11198
11281
  let data;
11199
11282
  if (responseType === "application/json") {
11200
11283
  data = yield response.json();
@@ -12440,7 +12523,7 @@ var WebSocketFactory = class {
12440
12523
  constructor() {
12441
12524
  }
12442
12525
  static detectEnvironment() {
12443
- var _a74;
12526
+ var _a78;
12444
12527
  if (typeof WebSocket !== "undefined") {
12445
12528
  return { type: "native", constructor: WebSocket };
12446
12529
  }
@@ -12457,7 +12540,7 @@ var WebSocketFactory = class {
12457
12540
  workaround: "Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."
12458
12541
  };
12459
12542
  }
12460
- if (typeof globalThis !== "undefined" && globalThis.EdgeRuntime || typeof navigator !== "undefined" && ((_a74 = navigator.userAgent) === null || _a74 === void 0 ? void 0 : _a74.includes("Vercel-Edge"))) {
12543
+ if (typeof globalThis !== "undefined" && globalThis.EdgeRuntime || typeof navigator !== "undefined" && ((_a78 = navigator.userAgent) === null || _a78 === void 0 ? void 0 : _a78.includes("Vercel-Edge"))) {
12461
12544
  return {
12462
12545
  type: "unsupported",
12463
12546
  error: "Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",
@@ -12541,7 +12624,7 @@ Suggested solution: ${env.workaround}`;
12541
12624
  try {
12542
12625
  const env = this.detectEnvironment();
12543
12626
  return env.type === "native" || env.type === "ws";
12544
- } catch (_a74) {
12627
+ } catch (_a78) {
12545
12628
  return false;
12546
12629
  }
12547
12630
  }
@@ -12615,29 +12698,29 @@ var Serializer = class {
12615
12698
  return callback(JSON.stringify(payload));
12616
12699
  }
12617
12700
  _binaryEncodeUserBroadcastPush(message) {
12618
- var _a74;
12619
- if (this._isArrayBuffer((_a74 = message.payload) === null || _a74 === void 0 ? void 0 : _a74.payload)) {
12701
+ var _a78;
12702
+ if (this._isArrayBuffer((_a78 = message.payload) === null || _a78 === void 0 ? void 0 : _a78.payload)) {
12620
12703
  return this._encodeBinaryUserBroadcastPush(message);
12621
12704
  } else {
12622
12705
  return this._encodeJsonUserBroadcastPush(message);
12623
12706
  }
12624
12707
  }
12625
12708
  _encodeBinaryUserBroadcastPush(message) {
12626
- var _a74, _b7;
12627
- const userPayload = (_b7 = (_a74 = message.payload) === null || _a74 === void 0 ? void 0 : _a74.payload) !== null && _b7 !== void 0 ? _b7 : new ArrayBuffer(0);
12709
+ var _a78, _b7;
12710
+ const userPayload = (_b7 = (_a78 = message.payload) === null || _a78 === void 0 ? void 0 : _a78.payload) !== null && _b7 !== void 0 ? _b7 : new ArrayBuffer(0);
12628
12711
  return this._encodeUserBroadcastPush(message, this.BINARY_ENCODING, userPayload);
12629
12712
  }
12630
12713
  _encodeJsonUserBroadcastPush(message) {
12631
- var _a74, _b7;
12632
- const userPayload = (_b7 = (_a74 = message.payload) === null || _a74 === void 0 ? void 0 : _a74.payload) !== null && _b7 !== void 0 ? _b7 : {};
12714
+ var _a78, _b7;
12715
+ const userPayload = (_b7 = (_a78 = message.payload) === null || _a78 === void 0 ? void 0 : _a78.payload) !== null && _b7 !== void 0 ? _b7 : {};
12633
12716
  const encoder = new TextEncoder();
12634
12717
  const encodedUserPayload = encoder.encode(JSON.stringify(userPayload)).buffer;
12635
12718
  return this._encodeUserBroadcastPush(message, this.JSON_ENCODING, encodedUserPayload);
12636
12719
  }
12637
12720
  _encodeUserBroadcastPush(message, encodingType, encodedPayload) {
12638
- var _a74, _b7;
12721
+ var _a78, _b7;
12639
12722
  const topic = message.topic;
12640
- const ref = (_a74 = message.ref) !== null && _a74 !== void 0 ? _a74 : "";
12723
+ const ref = (_a78 = message.ref) !== null && _a78 !== void 0 ? _a78 : "";
12641
12724
  const joinRef = (_b7 = message.join_ref) !== null && _b7 !== void 0 ? _b7 : "";
12642
12725
  const userEvent = message.payload.event;
12643
12726
  const rest = this.allowedMetadataKeys ? this._pick(message.payload, this.allowedMetadataKeys) : {};
@@ -12724,8 +12807,8 @@ var Serializer = class {
12724
12807
  return { join_ref: null, ref: null, topic, event: this.BROADCAST_EVENT, payload: data };
12725
12808
  }
12726
12809
  _isArrayBuffer(buffer) {
12727
- var _a74;
12728
- return buffer instanceof ArrayBuffer || ((_a74 = buffer === null || buffer === void 0 ? void 0 : buffer.constructor) === null || _a74 === void 0 ? void 0 : _a74.name) === "ArrayBuffer";
12810
+ var _a78;
12811
+ return buffer instanceof ArrayBuffer || ((_a78 = buffer === null || buffer === void 0 ? void 0 : buffer.constructor) === null || _a78 === void 0 ? void 0 : _a78.name) === "ArrayBuffer";
12729
12812
  }
12730
12813
  _pick(obj, keys) {
12731
12814
  if (!obj || typeof obj !== "object") {
@@ -12789,8 +12872,8 @@ var PostgresTypes;
12789
12872
  PostgresTypes2["tstzrange"] = "tstzrange";
12790
12873
  })(PostgresTypes || (PostgresTypes = {}));
12791
12874
  var convertChangeData = (columns, record, options = {}) => {
12792
- var _a74;
12793
- const skipTypes = (_a74 = options.skipTypes) !== null && _a74 !== void 0 ? _a74 : [];
12875
+ var _a78;
12876
+ const skipTypes = (_a78 = options.skipTypes) !== null && _a78 !== void 0 ? _a78 : [];
12794
12877
  if (!record) {
12795
12878
  return {};
12796
12879
  }
@@ -12880,7 +12963,7 @@ var toJson = (value) => {
12880
12963
  if (typeof value === "string") {
12881
12964
  try {
12882
12965
  return JSON.parse(value);
12883
- } catch (_a74) {
12966
+ } catch (_a78) {
12884
12967
  return value;
12885
12968
  }
12886
12969
  }
@@ -12972,9 +13055,9 @@ var Push = class {
12972
13055
  this.payload = Object.assign(Object.assign({}, this.payload), payload);
12973
13056
  }
12974
13057
  receive(status, callback) {
12975
- var _a74;
13058
+ var _a78;
12976
13059
  if (this._hasReceived(status)) {
12977
- callback((_a74 = this.receivedResp) === null || _a74 === void 0 ? void 0 : _a74.response);
13060
+ callback((_a78 = this.receivedResp) === null || _a78 === void 0 ? void 0 : _a78.response);
12978
13061
  }
12979
13062
  this.recHooks.push({ status, callback });
12980
13063
  return this;
@@ -13165,8 +13248,8 @@ var RealtimePresence = class _RealtimePresence {
13165
13248
  };
13166
13249
  }
13167
13250
  this.map(joins, (key, newPresences) => {
13168
- var _a74;
13169
- const currentPresences = (_a74 = state[key]) !== null && _a74 !== void 0 ? _a74 : [];
13251
+ var _a78;
13252
+ const currentPresences = (_a78 = state[key]) !== null && _a78 !== void 0 ? _a78 : [];
13170
13253
  state[key] = this.cloneDeep(newPresences);
13171
13254
  if (currentPresences.length > 0) {
13172
13255
  const joinedPresenceRefs = state[key].map((m) => m.presence_ref);
@@ -13294,7 +13377,7 @@ var RealtimeChannel = class _RealtimeChannel {
13294
13377
  * ```
13295
13378
  */
13296
13379
  constructor(topic, params = { config: {} }, socket) {
13297
- var _a74, _b7;
13380
+ var _a78, _b7;
13298
13381
  this.topic = topic;
13299
13382
  this.params = params;
13300
13383
  this.socket = socket;
@@ -13353,19 +13436,19 @@ var RealtimeChannel = class _RealtimeChannel {
13353
13436
  this.presence = new RealtimePresence(this);
13354
13437
  this.broadcastEndpointURL = httpEndpointURL(this.socket.endPoint);
13355
13438
  this.private = this.params.config.private || false;
13356
- if (!this.private && ((_b7 = (_a74 = this.params.config) === null || _a74 === void 0 ? void 0 : _a74.broadcast) === null || _b7 === void 0 ? void 0 : _b7.replay)) {
13439
+ if (!this.private && ((_b7 = (_a78 = this.params.config) === null || _a78 === void 0 ? void 0 : _a78.broadcast) === null || _b7 === void 0 ? void 0 : _b7.replay)) {
13357
13440
  throw `tried to use replay on public channel '${this.topic}'. It must be a private channel.`;
13358
13441
  }
13359
13442
  }
13360
13443
  /** Subscribe registers your client with the server */
13361
13444
  subscribe(callback, timeout = this.timeout) {
13362
- var _a74, _b7, _c;
13445
+ var _a78, _b7, _c;
13363
13446
  if (!this.socket.isConnected()) {
13364
13447
  this.socket.connect();
13365
13448
  }
13366
13449
  if (this.state == CHANNEL_STATES.closed) {
13367
13450
  const { config: { broadcast, presence, private: isPrivate } } = this.params;
13368
- const postgres_changes = (_b7 = (_a74 = this.bindings.postgres_changes) === null || _a74 === void 0 ? void 0 : _a74.map((r) => r.filter)) !== null && _b7 !== void 0 ? _b7 : [];
13451
+ const postgres_changes = (_b7 = (_a78 = this.bindings.postgres_changes) === null || _a78 === void 0 ? void 0 : _a78.map((r) => r.filter)) !== null && _b7 !== void 0 ? _b7 : [];
13369
13452
  const presence_enabled = !!this.bindings[REALTIME_LISTEN_TYPES.PRESENCE] && this.bindings[REALTIME_LISTEN_TYPES.PRESENCE].length > 0 || ((_c = this.params.config.presence) === null || _c === void 0 ? void 0 : _c.enabled) === true;
13370
13453
  const accessTokenPayload = {};
13371
13454
  const config = {
@@ -13383,7 +13466,7 @@ var RealtimeChannel = class _RealtimeChannel {
13383
13466
  this.joinedOnce = true;
13384
13467
  this._rejoin(timeout);
13385
13468
  this.joinPush.receive("ok", async ({ postgres_changes: postgres_changes2 }) => {
13386
- var _a75;
13469
+ var _a79;
13387
13470
  if (!this.socket._isManualToken()) {
13388
13471
  this.socket.setAuth();
13389
13472
  }
@@ -13392,7 +13475,7 @@ var RealtimeChannel = class _RealtimeChannel {
13392
13475
  return;
13393
13476
  } else {
13394
13477
  const clientPostgresBindings = this.bindings.postgres_changes;
13395
- const bindingsLen = (_a75 = clientPostgresBindings === null || clientPostgresBindings === void 0 ? void 0 : clientPostgresBindings.length) !== null && _a75 !== void 0 ? _a75 : 0;
13478
+ const bindingsLen = (_a79 = clientPostgresBindings === null || clientPostgresBindings === void 0 ? void 0 : clientPostgresBindings.length) !== null && _a79 !== void 0 ? _a79 : 0;
13396
13479
  const newPostgresBindings = [];
13397
13480
  for (let i = 0; i < bindingsLen; i++) {
13398
13481
  const clientPostgresBinding = clientPostgresBindings[i];
@@ -13470,7 +13553,7 @@ var RealtimeChannel = class _RealtimeChannel {
13470
13553
  * @returns Promise resolving to object with success status, and error details if failed
13471
13554
  */
13472
13555
  async httpSend(event, payload, opts = {}) {
13473
- var _a74;
13556
+ var _a78;
13474
13557
  if (payload === void 0 || payload === null) {
13475
13558
  return Promise.reject("Payload is required for httpSend()");
13476
13559
  }
@@ -13495,7 +13578,7 @@ var RealtimeChannel = class _RealtimeChannel {
13495
13578
  ]
13496
13579
  })
13497
13580
  };
13498
- const response = await this._fetchWithTimeout(this.broadcastEndpointURL, options, (_a74 = opts.timeout) !== null && _a74 !== void 0 ? _a74 : this.timeout);
13581
+ const response = await this._fetchWithTimeout(this.broadcastEndpointURL, options, (_a78 = opts.timeout) !== null && _a78 !== void 0 ? _a78 : this.timeout);
13499
13582
  if (response.status === 202) {
13500
13583
  return { success: true };
13501
13584
  }
@@ -13517,7 +13600,7 @@ var RealtimeChannel = class _RealtimeChannel {
13517
13600
  * @param opts Options to be used during the send process
13518
13601
  */
13519
13602
  async send(args, opts = {}) {
13520
- var _a74, _b7;
13603
+ var _a78, _b7;
13521
13604
  if (!this._canPush() && args.type === "broadcast") {
13522
13605
  console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");
13523
13606
  const { event, payload: endpoint_payload } = args;
@@ -13543,7 +13626,7 @@ var RealtimeChannel = class _RealtimeChannel {
13543
13626
  })
13544
13627
  };
13545
13628
  try {
13546
- const response = await this._fetchWithTimeout(this.broadcastEndpointURL, options, (_a74 = opts.timeout) !== null && _a74 !== void 0 ? _a74 : this.timeout);
13629
+ const response = await this._fetchWithTimeout(this.broadcastEndpointURL, options, (_a78 = opts.timeout) !== null && _a78 !== void 0 ? _a78 : this.timeout);
13547
13630
  await ((_b7 = response.body) === null || _b7 === void 0 ? void 0 : _b7.cancel());
13548
13631
  return response.ok ? "ok" : "error";
13549
13632
  } catch (error) {
@@ -13555,9 +13638,9 @@ var RealtimeChannel = class _RealtimeChannel {
13555
13638
  }
13556
13639
  } else {
13557
13640
  return new Promise((resolve) => {
13558
- var _a75, _b8, _c;
13641
+ var _a79, _b8, _c;
13559
13642
  const push = this._push(args.type, args, opts.timeout || this.timeout);
13560
- if (args.type === "broadcast" && !((_c = (_b8 = (_a75 = this.params) === null || _a75 === void 0 ? void 0 : _a75.config) === null || _b8 === void 0 ? void 0 : _b8.broadcast) === null || _c === void 0 ? void 0 : _c.ack)) {
13643
+ if (args.type === "broadcast" && !((_c = (_b8 = (_a79 = this.params) === null || _a79 === void 0 ? void 0 : _a79.config) === null || _b8 === void 0 ? void 0 : _b8.broadcast) === null || _c === void 0 ? void 0 : _c.ack)) {
13561
13644
  resolve("ok");
13562
13645
  }
13563
13646
  push.receive("ok", () => resolve("ok"));
@@ -13676,7 +13759,7 @@ var RealtimeChannel = class _RealtimeChannel {
13676
13759
  }
13677
13760
  /** @internal */
13678
13761
  _trigger(type, payload, ref) {
13679
- var _a74, _b7;
13762
+ var _a78, _b7;
13680
13763
  const typeLower = type.toLocaleLowerCase();
13681
13764
  const { close, error, leave, join } = CHANNEL_EVENTS;
13682
13765
  const events = [close, error, leave, join];
@@ -13688,17 +13771,17 @@ var RealtimeChannel = class _RealtimeChannel {
13688
13771
  throw "channel onMessage callbacks must return the payload, modified or unmodified";
13689
13772
  }
13690
13773
  if (["insert", "update", "delete"].includes(typeLower)) {
13691
- (_a74 = this.bindings.postgres_changes) === null || _a74 === void 0 ? void 0 : _a74.filter((bind) => {
13692
- var _a75, _b8, _c;
13693
- return ((_a75 = bind.filter) === null || _a75 === void 0 ? void 0 : _a75.event) === "*" || ((_c = (_b8 = bind.filter) === null || _b8 === void 0 ? void 0 : _b8.event) === null || _c === void 0 ? void 0 : _c.toLocaleLowerCase()) === typeLower;
13774
+ (_a78 = this.bindings.postgres_changes) === null || _a78 === void 0 ? void 0 : _a78.filter((bind) => {
13775
+ var _a79, _b8, _c;
13776
+ return ((_a79 = bind.filter) === null || _a79 === void 0 ? void 0 : _a79.event) === "*" || ((_c = (_b8 = bind.filter) === null || _b8 === void 0 ? void 0 : _b8.event) === null || _c === void 0 ? void 0 : _c.toLocaleLowerCase()) === typeLower;
13694
13777
  }).map((bind) => bind.callback(handledPayload, ref));
13695
13778
  } else {
13696
13779
  (_b7 = this.bindings[typeLower]) === null || _b7 === void 0 ? void 0 : _b7.filter((bind) => {
13697
- var _a75, _b8, _c, _d, _e, _f, _g, _h;
13780
+ var _a79, _b8, _c, _d, _e, _f, _g, _h;
13698
13781
  if (["broadcast", "presence", "postgres_changes"].includes(typeLower)) {
13699
13782
  if ("id" in bind) {
13700
13783
  const bindId = bind.id;
13701
- const bindEvent = (_a75 = bind.filter) === null || _a75 === void 0 ? void 0 : _a75.event;
13784
+ const bindEvent = (_a79 = bind.filter) === null || _a79 === void 0 ? void 0 : _a79.event;
13702
13785
  return bindId && ((_b8 = payload.ids) === null || _b8 === void 0 ? void 0 : _b8.includes(bindId)) && (bindEvent === "*" || (bindEvent === null || bindEvent === void 0 ? void 0 : bindEvent.toLocaleLowerCase()) === ((_c = payload.data) === null || _c === void 0 ? void 0 : _c.type.toLocaleLowerCase())) && (!((_d = bind.filter) === null || _d === void 0 ? void 0 : _d.table) || bind.filter.table === ((_e = payload.data) === null || _e === void 0 ? void 0 : _e.table));
13703
13786
  } else {
13704
13787
  const bindEvent = (_g = (_f = bind === null || bind === void 0 ? void 0 : bind.filter) === null || _f === void 0 ? void 0 : _f.event) === null || _g === void 0 ? void 0 : _g.toLocaleLowerCase();
@@ -13766,8 +13849,8 @@ var RealtimeChannel = class _RealtimeChannel {
13766
13849
  const typeLower = type.toLocaleLowerCase();
13767
13850
  if (this.bindings[typeLower]) {
13768
13851
  this.bindings[typeLower] = this.bindings[typeLower].filter((bind) => {
13769
- var _a74;
13770
- return !(((_a74 = bind.type) === null || _a74 === void 0 ? void 0 : _a74.toLocaleLowerCase()) === typeLower && _RealtimeChannel.isEqual(bind.filter, filter));
13852
+ var _a78;
13853
+ return !(((_a78 = bind.type) === null || _a78 === void 0 ? void 0 : _a78.toLocaleLowerCase()) === typeLower && _RealtimeChannel.isEqual(bind.filter, filter));
13771
13854
  });
13772
13855
  }
13773
13856
  return this;
@@ -13897,7 +13980,7 @@ var RealtimeClient = class {
13897
13980
  * ```
13898
13981
  */
13899
13982
  constructor(endPoint, options) {
13900
- var _a74;
13983
+ var _a78;
13901
13984
  this.accessTokenValue = null;
13902
13985
  this.apiKey = null;
13903
13986
  this._manuallySetToken = false;
@@ -13936,7 +14019,7 @@ var RealtimeClient = class {
13936
14019
  }
13937
14020
  return (...args) => fetch(...args);
13938
14021
  };
13939
- if (!((_a74 = options === null || options === void 0 ? void 0 : options.params) === null || _a74 === void 0 ? void 0 : _a74.apikey)) {
14022
+ if (!((_a78 = options === null || options === void 0 ? void 0 : options.params) === null || _a78 === void 0 ? void 0 : _a78.apikey)) {
13940
14023
  throw new Error("API key is required to connect to Realtime");
13941
14024
  }
13942
14025
  this.apiKey = options.params.apikey;
@@ -14118,8 +14201,8 @@ Option 2: Install and provide the "ws" package:
14118
14201
  const { topic, event, payload, ref } = data;
14119
14202
  const callback = () => {
14120
14203
  this.encode(data, (result) => {
14121
- var _a74;
14122
- (_a74 = this.conn) === null || _a74 === void 0 ? void 0 : _a74.send(result);
14204
+ var _a78;
14205
+ (_a78 = this.conn) === null || _a78 === void 0 ? void 0 : _a78.send(result);
14123
14206
  });
14124
14207
  };
14125
14208
  this.log("push", `${topic} ${event} (${ref})`, payload);
@@ -14169,7 +14252,7 @@ Option 2: Install and provide the "ws" package:
14169
14252
  * Sends a heartbeat message if the socket is connected.
14170
14253
  */
14171
14254
  async sendHeartbeat() {
14172
- var _a74;
14255
+ var _a78;
14173
14256
  if (!this.isConnected()) {
14174
14257
  try {
14175
14258
  this.heartbeatCallback("disconnected");
@@ -14188,11 +14271,11 @@ Option 2: Install and provide the "ws" package:
14188
14271
  this.log("error", "error in heartbeat callback", e);
14189
14272
  }
14190
14273
  this._wasManualDisconnect = false;
14191
- (_a74 = this.conn) === null || _a74 === void 0 ? void 0 : _a74.close(WS_CLOSE_NORMAL, "heartbeat timeout");
14274
+ (_a78 = this.conn) === null || _a78 === void 0 ? void 0 : _a78.close(WS_CLOSE_NORMAL, "heartbeat timeout");
14192
14275
  setTimeout(() => {
14193
- var _a75;
14276
+ var _a79;
14194
14277
  if (!this.isConnected()) {
14195
- (_a75 = this.reconnectTimer) === null || _a75 === void 0 ? void 0 : _a75.scheduleTimeout();
14278
+ (_a79 = this.reconnectTimer) === null || _a79 === void 0 ? void 0 : _a79.scheduleTimeout();
14196
14279
  }
14197
14280
  }, CONNECTION_TIMEOUTS.HEARTBEAT_TIMEOUT_FALLBACK);
14198
14281
  return;
@@ -14290,12 +14373,12 @@ Option 2: Install and provide the "ws" package:
14290
14373
  * @internal
14291
14374
  */
14292
14375
  _clearTimer(timer) {
14293
- var _a74;
14376
+ var _a78;
14294
14377
  if (timer === "heartbeat" && this.heartbeatTimer) {
14295
14378
  clearInterval(this.heartbeatTimer);
14296
14379
  this.heartbeatTimer = void 0;
14297
14380
  } else if (timer === "reconnect") {
14298
- (_a74 = this.reconnectTimer) === null || _a74 === void 0 ? void 0 : _a74.reset();
14381
+ (_a78 = this.reconnectTimer) === null || _a78 === void 0 ? void 0 : _a78.reset();
14299
14382
  }
14300
14383
  }
14301
14384
  /**
@@ -14410,13 +14493,13 @@ Option 2: Install and provide the "ws" package:
14410
14493
  }
14411
14494
  /** @internal */
14412
14495
  _onConnClose(event) {
14413
- var _a74;
14496
+ var _a78;
14414
14497
  this._setConnectionState("disconnected");
14415
14498
  this.log("transport", "close", event);
14416
14499
  this._triggerChanError();
14417
14500
  this._clearTimer("heartbeat");
14418
14501
  if (!this._wasManualDisconnect) {
14419
- (_a74 = this.reconnectTimer) === null || _a74 === void 0 ? void 0 : _a74.scheduleTimeout();
14502
+ (_a78 = this.reconnectTimer) === null || _a78 === void 0 ? void 0 : _a78.scheduleTimeout();
14420
14503
  }
14421
14504
  this._triggerStateCallbacks("close", event);
14422
14505
  }
@@ -14559,8 +14642,8 @@ Option 2: Install and provide the "ws" package:
14559
14642
  * @internal
14560
14643
  */
14561
14644
  _initializeOptions(options) {
14562
- var _a74, _b7, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
14563
- this.transport = (_a74 = options === null || options === void 0 ? void 0 : options.transport) !== null && _a74 !== void 0 ? _a74 : null;
14645
+ var _a78, _b7, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
14646
+ this.transport = (_a78 = options === null || options === void 0 ? void 0 : options.transport) !== null && _a78 !== void 0 ? _a78 : null;
14564
14647
  this.timeout = (_b7 = options === null || options === void 0 ? void 0 : options.timeout) !== null && _b7 !== void 0 ? _b7 : DEFAULT_TIMEOUT;
14565
14648
  this.heartbeatIntervalMs = (_c = options === null || options === void 0 ? void 0 : options.heartbeatIntervalMs) !== null && _c !== void 0 ? _c : CONNECTION_TIMEOUTS.HEARTBEAT_INTERVAL;
14566
14649
  this.worker = (_d = options === null || options === void 0 ? void 0 : options.worker) !== null && _d !== void 0 ? _d : false;
@@ -14606,14 +14689,14 @@ Option 2: Install and provide the "ws" package:
14606
14689
  // node_modules/iceberg-js/dist/index.mjs
14607
14690
  var IcebergError = class extends Error {
14608
14691
  constructor(message, opts) {
14609
- var _a74;
14692
+ var _a78;
14610
14693
  super(message);
14611
14694
  this.name = "IcebergError";
14612
14695
  this.status = opts.status;
14613
14696
  this.icebergType = opts.icebergType;
14614
14697
  this.icebergCode = opts.icebergCode;
14615
14698
  this.details = opts.details;
14616
- this.isCommitStateUnknown = opts.icebergType === "CommitStateUnknownException" || [500, 502, 504].includes(opts.status) && ((_a74 = opts.icebergType) == null ? void 0 : _a74.includes("CommitState")) === true;
14699
+ this.isCommitStateUnknown = opts.icebergType === "CommitStateUnknownException" || [500, 502, 504].includes(opts.status) && ((_a78 = opts.icebergType) == null ? void 0 : _a78.includes("CommitState")) === true;
14617
14700
  }
14618
14701
  /**
14619
14702
  * Returns true if the error is a 404 Not Found error.
@@ -14661,8 +14744,8 @@ async function buildAuthHeaders(auth) {
14661
14744
  return {};
14662
14745
  }
14663
14746
  function createFetchClient(options) {
14664
- var _a74;
14665
- const fetchFn = (_a74 = options.fetchImpl) != null ? _a74 : globalThis.fetch;
14747
+ var _a78;
14748
+ const fetchFn = (_a78 = options.fetchImpl) != null ? _a78 : globalThis.fetch;
14666
14749
  return {
14667
14750
  async request({
14668
14751
  method,
@@ -14671,7 +14754,7 @@ function createFetchClient(options) {
14671
14754
  body,
14672
14755
  headers
14673
14756
  }) {
14674
- var _a75;
14757
+ var _a79;
14675
14758
  const url = buildUrl(options.baseUrl, path, query);
14676
14759
  const authHeaders = await buildAuthHeaders(options.auth);
14677
14760
  const res = await fetchFn(url, {
@@ -14690,7 +14773,7 @@ function createFetchClient(options) {
14690
14773
  const errBody = isJson ? data : void 0;
14691
14774
  const errorDetail = errBody == null ? void 0 : errBody.error;
14692
14775
  throw new IcebergError(
14693
- (_a75 = errorDetail == null ? void 0 : errorDetail.message) != null ? _a75 : `Request failed with status ${res.status}`,
14776
+ (_a79 = errorDetail == null ? void 0 : errorDetail.message) != null ? _a79 : `Request failed with status ${res.status}`,
14694
14777
  {
14695
14778
  status: res.status,
14696
14779
  icebergType: errorDetail == null ? void 0 : errorDetail.type,
@@ -14813,11 +14896,11 @@ var TableOperations = class {
14813
14896
  };
14814
14897
  }
14815
14898
  async dropTable(id, options) {
14816
- var _a74;
14899
+ var _a78;
14817
14900
  await this.client.request({
14818
14901
  method: "DELETE",
14819
14902
  path: `${this.prefix}/namespaces/${namespaceToPath2(id.namespace)}/tables/${id.name}`,
14820
- query: { purgeRequested: String((_a74 = options == null ? void 0 : options.purge) != null ? _a74 : false) }
14903
+ query: { purgeRequested: String((_a78 = options == null ? void 0 : options.purge) != null ? _a78 : false) }
14821
14904
  });
14822
14905
  }
14823
14906
  async loadTable(id) {
@@ -14869,7 +14952,7 @@ var IcebergRestCatalog = class {
14869
14952
  * @param options - Configuration options for the catalog client
14870
14953
  */
14871
14954
  constructor(options) {
14872
- var _a74;
14955
+ var _a78;
14873
14956
  let prefix = "v1";
14874
14957
  if (options.catalogName) {
14875
14958
  prefix += `/${options.catalogName}`;
@@ -14880,7 +14963,7 @@ var IcebergRestCatalog = class {
14880
14963
  auth: options.auth,
14881
14964
  fetchImpl: options.fetch
14882
14965
  });
14883
- this.accessDelegation = (_a74 = options.accessDelegation) == null ? void 0 : _a74.join(",");
14966
+ this.accessDelegation = (_a78 = options.accessDelegation) == null ? void 0 : _a78.join(",");
14884
14967
  this.namespaceOps = new NamespaceOperations(this.client, prefix);
14885
14968
  this.tableOps = new TableOperations(this.client, prefix, this.accessDelegation);
14886
14969
  }
@@ -18219,7 +18302,7 @@ var getItemAsync = async (storage, key) => {
18219
18302
  }
18220
18303
  try {
18221
18304
  return JSON.parse(value);
18222
- } catch (_a74) {
18305
+ } catch (_a78) {
18223
18306
  return value;
18224
18307
  }
18225
18308
  };
@@ -18430,7 +18513,7 @@ function deepClone(obj) {
18430
18513
  var _getErrorMessage2 = (err) => err.msg || err.message || err.error_description || err.error || JSON.stringify(err);
18431
18514
  var NETWORK_ERROR_CODES = [502, 503, 504];
18432
18515
  async function handleError2(error) {
18433
- var _a74;
18516
+ var _a78;
18434
18517
  if (!looksLikeFetchResponse(error)) {
18435
18518
  throw new AuthRetryableFetchError(_getErrorMessage2(error), 0);
18436
18519
  }
@@ -18455,7 +18538,7 @@ async function handleError2(error) {
18455
18538
  throw new AuthWeakPasswordError(_getErrorMessage2(data), error.status, data.weak_password.reasons);
18456
18539
  }
18457
18540
  } else if (errorCode === "weak_password") {
18458
- throw new AuthWeakPasswordError(_getErrorMessage2(data), error.status, ((_a74 = data.weak_password) === null || _a74 === void 0 ? void 0 : _a74.reasons) || []);
18541
+ throw new AuthWeakPasswordError(_getErrorMessage2(data), error.status, ((_a78 = data.weak_password) === null || _a78 === void 0 ? void 0 : _a78.reasons) || []);
18459
18542
  } else if (errorCode === "session_not_found") {
18460
18543
  throw new AuthSessionMissingError();
18461
18544
  }
@@ -18471,7 +18554,7 @@ var _getRequestParams2 = (method, options, parameters, body) => {
18471
18554
  return Object.assign(Object.assign({}, params), parameters);
18472
18555
  };
18473
18556
  async function _request(fetcher, method, url, options) {
18474
- var _a74;
18557
+ var _a78;
18475
18558
  const headers = Object.assign({}, options === null || options === void 0 ? void 0 : options.headers);
18476
18559
  if (!headers[API_VERSION_HEADER_NAME]) {
18477
18560
  headers[API_VERSION_HEADER_NAME] = API_VERSIONS["2024-01-01"].name;
@@ -18479,7 +18562,7 @@ async function _request(fetcher, method, url, options) {
18479
18562
  if (options === null || options === void 0 ? void 0 : options.jwt) {
18480
18563
  headers["Authorization"] = `Bearer ${options.jwt}`;
18481
18564
  }
18482
- const qs = (_a74 = options === null || options === void 0 ? void 0 : options.query) !== null && _a74 !== void 0 ? _a74 : {};
18565
+ const qs = (_a78 = options === null || options === void 0 ? void 0 : options.query) !== null && _a78 !== void 0 ? _a78 : {};
18483
18566
  if (options === null || options === void 0 ? void 0 : options.redirectTo) {
18484
18567
  qs["redirect_to"] = options.redirectTo;
18485
18568
  }
@@ -18512,7 +18595,7 @@ async function _handleRequest2(fetcher, method, url, options, parameters, body)
18512
18595
  }
18513
18596
  }
18514
18597
  function _sessionResponse(data) {
18515
- var _a74;
18598
+ var _a78;
18516
18599
  let session = null;
18517
18600
  if (hasSession(data)) {
18518
18601
  session = Object.assign({}, data);
@@ -18520,7 +18603,7 @@ function _sessionResponse(data) {
18520
18603
  session.expires_at = expiresAt(data.expires_in);
18521
18604
  }
18522
18605
  }
18523
- const user = (_a74 = data.user) !== null && _a74 !== void 0 ? _a74 : data;
18606
+ const user = (_a78 = data.user) !== null && _a78 !== void 0 ? _a78 : data;
18524
18607
  return { data: { session, user }, error: null };
18525
18608
  }
18526
18609
  function _sessionResponsePassword(data) {
@@ -18531,8 +18614,8 @@ function _sessionResponsePassword(data) {
18531
18614
  return response;
18532
18615
  }
18533
18616
  function _userResponse(data) {
18534
- var _a74;
18535
- const user = (_a74 = data.user) !== null && _a74 !== void 0 ? _a74 : data;
18617
+ var _a78;
18618
+ const user = (_a78 = data.user) !== null && _a78 !== void 0 ? _a78 : data;
18536
18619
  return { data: { user }, error: null };
18537
18620
  }
18538
18621
  function _ssoResponse(data) {
@@ -18701,14 +18784,14 @@ var GoTrueAdminApi = class {
18701
18784
  * @param params An object which supports `page` and `perPage` as numbers, to alter the paginated results.
18702
18785
  */
18703
18786
  async listUsers(params) {
18704
- var _a74, _b7, _c, _d, _e, _f, _g;
18787
+ var _a78, _b7, _c, _d, _e, _f, _g;
18705
18788
  try {
18706
18789
  const pagination = { nextPage: null, lastPage: 0, total: 0 };
18707
18790
  const response = await _request(this.fetch, "GET", `${this.url}/admin/users`, {
18708
18791
  headers: this.headers,
18709
18792
  noResolveJson: true,
18710
18793
  query: {
18711
- page: (_b7 = (_a74 = params === null || params === void 0 ? void 0 : params.page) === null || _a74 === void 0 ? void 0 : _a74.toString()) !== null && _b7 !== void 0 ? _b7 : "",
18794
+ page: (_b7 = (_a78 = params === null || params === void 0 ? void 0 : params.page) === null || _a78 === void 0 ? void 0 : _a78.toString()) !== null && _b7 !== void 0 ? _b7 : "",
18712
18795
  per_page: (_d = (_c = params === null || params === void 0 ? void 0 : params.perPage) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : ""
18713
18796
  },
18714
18797
  xform: _noResolveJsonResponse
@@ -18842,14 +18925,14 @@ var GoTrueAdminApi = class {
18842
18925
  * This function should only be called on a server. Never expose your `service_role` key in the browser.
18843
18926
  */
18844
18927
  async _listOAuthClients(params) {
18845
- var _a74, _b7, _c, _d, _e, _f, _g;
18928
+ var _a78, _b7, _c, _d, _e, _f, _g;
18846
18929
  try {
18847
18930
  const pagination = { nextPage: null, lastPage: 0, total: 0 };
18848
18931
  const response = await _request(this.fetch, "GET", `${this.url}/admin/oauth/clients`, {
18849
18932
  headers: this.headers,
18850
18933
  noResolveJson: true,
18851
18934
  query: {
18852
- page: (_b7 = (_a74 = params === null || params === void 0 ? void 0 : params.page) === null || _a74 === void 0 ? void 0 : _a74.toString()) !== null && _b7 !== void 0 ? _b7 : "",
18935
+ page: (_b7 = (_a78 = params === null || params === void 0 ? void 0 : params.page) === null || _a78 === void 0 ? void 0 : _a78.toString()) !== null && _b7 !== void 0 ? _b7 : "",
18853
18936
  per_page: (_d = (_c = params === null || params === void 0 ? void 0 : params.perPage) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : ""
18854
18937
  },
18855
18938
  xform: _noResolveJsonResponse
@@ -19102,7 +19185,7 @@ function toHex(value) {
19102
19185
  return "0x" + hex;
19103
19186
  }
19104
19187
  function createSiweMessage(parameters) {
19105
- var _a74;
19188
+ var _a78;
19106
19189
  const { chainId, domain, expirationTime, issuedAt = /* @__PURE__ */ new Date(), nonce, notBefore, requestId, resources, scheme, uri, version: version5 } = parameters;
19107
19190
  {
19108
19191
  if (!Number.isInteger(chainId))
@@ -19115,7 +19198,7 @@ function createSiweMessage(parameters) {
19115
19198
  throw new Error(`@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.`);
19116
19199
  if (version5 !== "1")
19117
19200
  throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${version5}`);
19118
- if ((_a74 = parameters.statement) === null || _a74 === void 0 ? void 0 : _a74.includes("\n"))
19201
+ if ((_a78 = parameters.statement) === null || _a78 === void 0 ? void 0 : _a78.includes("\n"))
19119
19202
  throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${parameters.statement}`);
19120
19203
  }
19121
19204
  const address = getAddress(parameters.address);
@@ -19157,10 +19240,10 @@ ${suffix}`;
19157
19240
  // node_modules/@supabase/auth-js/dist/module/lib/webauthn.errors.js
19158
19241
  var WebAuthnError = class extends Error {
19159
19242
  constructor({ message, code, cause, name }) {
19160
- var _a74;
19243
+ var _a78;
19161
19244
  super(message, { cause });
19162
19245
  this.__isWebAuthnError = true;
19163
- this.name = (_a74 = name !== null && name !== void 0 ? name : cause instanceof Error ? cause.name : void 0) !== null && _a74 !== void 0 ? _a74 : "Unknown Error";
19246
+ this.name = (_a78 = name !== null && name !== void 0 ? name : cause instanceof Error ? cause.name : void 0) !== null && _a78 !== void 0 ? _a78 : "Unknown Error";
19164
19247
  this.code = code;
19165
19248
  }
19166
19249
  };
@@ -19176,7 +19259,7 @@ var WebAuthnUnknownError = class extends WebAuthnError {
19176
19259
  }
19177
19260
  };
19178
19261
  function identifyRegistrationError({ error, options }) {
19179
- var _a74, _b7, _c;
19262
+ var _a78, _b7, _c;
19180
19263
  const { publicKey } = options;
19181
19264
  if (!publicKey) {
19182
19265
  throw Error("options was missing required publicKey property");
@@ -19190,7 +19273,7 @@ function identifyRegistrationError({ error, options }) {
19190
19273
  });
19191
19274
  }
19192
19275
  } else if (error.name === "ConstraintError") {
19193
- if (((_a74 = publicKey.authenticatorSelection) === null || _a74 === void 0 ? void 0 : _a74.requireResidentKey) === true) {
19276
+ if (((_a78 = publicKey.authenticatorSelection) === null || _a78 === void 0 ? void 0 : _a78.requireResidentKey) === true) {
19194
19277
  return new WebAuthnError({
19195
19278
  message: "Discoverable credentials were required but no available authenticator supported it",
19196
19279
  code: "ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",
@@ -19419,7 +19502,7 @@ function deserializeCredentialRequestOptions(options) {
19419
19502
  return result;
19420
19503
  }
19421
19504
  function serializeCredentialCreationResponse(credential) {
19422
- var _a74;
19505
+ var _a78;
19423
19506
  if ("toJSON" in credential && typeof credential.toJSON === "function") {
19424
19507
  return credential.toJSON();
19425
19508
  }
@@ -19434,11 +19517,11 @@ function serializeCredentialCreationResponse(credential) {
19434
19517
  type: "public-key",
19435
19518
  clientExtensionResults: credential.getClientExtensionResults(),
19436
19519
  // Convert null to undefined and cast to AuthenticatorAttachment type
19437
- authenticatorAttachment: (_a74 = credentialWithAttachment.authenticatorAttachment) !== null && _a74 !== void 0 ? _a74 : void 0
19520
+ authenticatorAttachment: (_a78 = credentialWithAttachment.authenticatorAttachment) !== null && _a78 !== void 0 ? _a78 : void 0
19438
19521
  };
19439
19522
  }
19440
19523
  function serializeCredentialRequestResponse(credential) {
19441
- var _a74;
19524
+ var _a78;
19442
19525
  if ("toJSON" in credential && typeof credential.toJSON === "function") {
19443
19526
  return credential.toJSON();
19444
19527
  }
@@ -19458,7 +19541,7 @@ function serializeCredentialRequestResponse(credential) {
19458
19541
  type: "public-key",
19459
19542
  clientExtensionResults,
19460
19543
  // Convert null to undefined and cast to AuthenticatorAttachment type
19461
- authenticatorAttachment: (_a74 = credentialWithAttachment.authenticatorAttachment) !== null && _a74 !== void 0 ? _a74 : void 0
19544
+ authenticatorAttachment: (_a78 = credentialWithAttachment.authenticatorAttachment) !== null && _a78 !== void 0 ? _a78 : void 0
19462
19545
  };
19463
19546
  }
19464
19547
  function isValidDomain(hostname) {
@@ -19468,8 +19551,8 @@ function isValidDomain(hostname) {
19468
19551
  );
19469
19552
  }
19470
19553
  function browserSupportsWebAuthn() {
19471
- var _a74, _b7;
19472
- return !!(isBrowser() && "PublicKeyCredential" in window && window.PublicKeyCredential && "credentials" in navigator && typeof ((_a74 = navigator === null || navigator === void 0 ? void 0 : navigator.credentials) === null || _a74 === void 0 ? void 0 : _a74.create) === "function" && typeof ((_b7 = navigator === null || navigator === void 0 ? void 0 : navigator.credentials) === null || _b7 === void 0 ? void 0 : _b7.get) === "function");
19554
+ var _a78, _b7;
19555
+ return !!(isBrowser() && "PublicKeyCredential" in window && window.PublicKeyCredential && "credentials" in navigator && typeof ((_a78 = navigator === null || navigator === void 0 ? void 0 : navigator.credentials) === null || _a78 === void 0 ? void 0 : _a78.create) === "function" && typeof ((_b7 = navigator === null || navigator === void 0 ? void 0 : navigator.credentials) === null || _b7 === void 0 ? void 0 : _b7.get) === "function");
19473
19556
  }
19474
19557
  async function createCredential(options) {
19475
19558
  try {
@@ -19798,8 +19881,8 @@ var WebAuthnApi = class {
19798
19881
  });
19799
19882
  if (!factor) {
19800
19883
  await this.client.mfa.listFactors().then((factors) => {
19801
- var _a74;
19802
- return (_a74 = factors.data) === null || _a74 === void 0 ? void 0 : _a74.all.find((v) => v.factor_type === "webauthn" && v.friendly_name === friendlyName && v.status !== "unverified");
19884
+ var _a78;
19885
+ return (_a78 = factors.data) === null || _a78 === void 0 ? void 0 : _a78.all.find((v) => v.factor_type === "webauthn" && v.friendly_name === friendlyName && v.status !== "unverified");
19803
19886
  }).then((factor2) => factor2 ? this.client.mfa.unenroll({ factorId: factor2 === null || factor2 === void 0 ? void 0 : factor2.id }) : void 0);
19804
19887
  return { data: null, error: enrollError };
19805
19888
  }
@@ -19861,15 +19944,15 @@ var GoTrueClient = class _GoTrueClient {
19861
19944
  * The JWKS used for verifying asymmetric JWTs
19862
19945
  */
19863
19946
  get jwks() {
19864
- var _a74, _b7;
19865
- return (_b7 = (_a74 = GLOBAL_JWKS[this.storageKey]) === null || _a74 === void 0 ? void 0 : _a74.jwks) !== null && _b7 !== void 0 ? _b7 : { keys: [] };
19947
+ var _a78, _b7;
19948
+ return (_b7 = (_a78 = GLOBAL_JWKS[this.storageKey]) === null || _a78 === void 0 ? void 0 : _a78.jwks) !== null && _b7 !== void 0 ? _b7 : { keys: [] };
19866
19949
  }
19867
19950
  set jwks(value) {
19868
19951
  GLOBAL_JWKS[this.storageKey] = Object.assign(Object.assign({}, GLOBAL_JWKS[this.storageKey]), { jwks: value });
19869
19952
  }
19870
19953
  get jwks_cached_at() {
19871
- var _a74, _b7;
19872
- return (_b7 = (_a74 = GLOBAL_JWKS[this.storageKey]) === null || _a74 === void 0 ? void 0 : _a74.cachedAt) !== null && _b7 !== void 0 ? _b7 : Number.MIN_SAFE_INTEGER;
19954
+ var _a78, _b7;
19955
+ return (_b7 = (_a78 = GLOBAL_JWKS[this.storageKey]) === null || _a78 === void 0 ? void 0 : _a78.cachedAt) !== null && _b7 !== void 0 ? _b7 : Number.MIN_SAFE_INTEGER;
19873
19956
  }
19874
19957
  set jwks_cached_at(value) {
19875
19958
  GLOBAL_JWKS[this.storageKey] = Object.assign(Object.assign({}, GLOBAL_JWKS[this.storageKey]), { cachedAt: value });
@@ -19889,7 +19972,7 @@ var GoTrueClient = class _GoTrueClient {
19889
19972
  * ```
19890
19973
  */
19891
19974
  constructor(options) {
19892
- var _a74, _b7, _c;
19975
+ var _a78, _b7, _c;
19893
19976
  this.userStorage = null;
19894
19977
  this.memoryStorage = null;
19895
19978
  this.stateChangeEmitters = /* @__PURE__ */ new Map();
@@ -19907,7 +19990,7 @@ var GoTrueClient = class _GoTrueClient {
19907
19990
  this.logger = console.log;
19908
19991
  const settings = Object.assign(Object.assign({}, DEFAULT_OPTIONS), options);
19909
19992
  this.storageKey = settings.storageKey;
19910
- this.instanceID = (_a74 = _GoTrueClient.nextInstanceID[this.storageKey]) !== null && _a74 !== void 0 ? _a74 : 0;
19993
+ this.instanceID = (_a78 = _GoTrueClient.nextInstanceID[this.storageKey]) !== null && _a78 !== void 0 ? _a78 : 0;
19911
19994
  _GoTrueClient.nextInstanceID[this.storageKey] = this.instanceID + 1;
19912
19995
  this.logDebugMessages = !!settings.debug;
19913
19996
  if (typeof settings.debug === "function") {
@@ -20044,7 +20127,7 @@ var GoTrueClient = class _GoTrueClient {
20044
20127
  * the whole lifetime of the client
20045
20128
  */
20046
20129
  async _initialize() {
20047
- var _a74;
20130
+ var _a78;
20048
20131
  try {
20049
20132
  let params = {};
20050
20133
  let callbackUrlType = "none";
@@ -20061,7 +20144,7 @@ var GoTrueClient = class _GoTrueClient {
20061
20144
  if (error) {
20062
20145
  this._debug("#_initialize()", "error detecting session from URL", error);
20063
20146
  if (isAuthImplicitGrantRedirectError(error)) {
20064
- const errorCode = (_a74 = error.details) === null || _a74 === void 0 ? void 0 : _a74.code;
20147
+ const errorCode = (_a78 = error.details) === null || _a78 === void 0 ? void 0 : _a78.code;
20065
20148
  if (errorCode === "identity_already_exists" || errorCode === "identity_not_found" || errorCode === "single_identity_not_deletable") {
20066
20149
  return { error };
20067
20150
  }
@@ -20100,12 +20183,12 @@ var GoTrueClient = class _GoTrueClient {
20100
20183
  * @returns A session where the is_anonymous claim in the access token JWT set to true
20101
20184
  */
20102
20185
  async signInAnonymously(credentials) {
20103
- var _a74, _b7, _c;
20186
+ var _a78, _b7, _c;
20104
20187
  try {
20105
20188
  const res = await _request(this.fetch, "POST", `${this.url}/signup`, {
20106
20189
  headers: this.headers,
20107
20190
  body: {
20108
- data: (_b7 = (_a74 = credentials === null || credentials === void 0 ? void 0 : credentials.options) === null || _a74 === void 0 ? void 0 : _a74.data) !== null && _b7 !== void 0 ? _b7 : {},
20191
+ data: (_b7 = (_a78 = credentials === null || credentials === void 0 ? void 0 : credentials.options) === null || _a78 === void 0 ? void 0 : _a78.data) !== null && _b7 !== void 0 ? _b7 : {},
20109
20192
  gotrue_meta_security: { captcha_token: (_c = credentials === null || credentials === void 0 ? void 0 : credentials.options) === null || _c === void 0 ? void 0 : _c.captchaToken }
20110
20193
  },
20111
20194
  xform: _sessionResponse
@@ -20139,7 +20222,7 @@ var GoTrueClient = class _GoTrueClient {
20139
20222
  * @returns A user if the server has "autoconfirm" OFF
20140
20223
  */
20141
20224
  async signUp(credentials) {
20142
- var _a74, _b7, _c;
20225
+ var _a78, _b7, _c;
20143
20226
  try {
20144
20227
  let res;
20145
20228
  if ("email" in credentials) {
@@ -20156,7 +20239,7 @@ var GoTrueClient = class _GoTrueClient {
20156
20239
  body: {
20157
20240
  email,
20158
20241
  password,
20159
- data: (_a74 = options === null || options === void 0 ? void 0 : options.data) !== null && _a74 !== void 0 ? _a74 : {},
20242
+ data: (_a78 = options === null || options === void 0 ? void 0 : options.data) !== null && _a78 !== void 0 ? _a78 : {},
20160
20243
  gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },
20161
20244
  code_challenge: codeChallenge,
20162
20245
  code_challenge_method: codeChallengeMethod
@@ -20262,9 +20345,9 @@ var GoTrueClient = class _GoTrueClient {
20262
20345
  * This method supports the PKCE flow.
20263
20346
  */
20264
20347
  async signInWithOAuth(credentials) {
20265
- var _a74, _b7, _c, _d;
20348
+ var _a78, _b7, _c, _d;
20266
20349
  return await this._handleProviderSignIn(credentials.provider, {
20267
- redirectTo: (_a74 = credentials.options) === null || _a74 === void 0 ? void 0 : _a74.redirectTo,
20350
+ redirectTo: (_a78 = credentials.options) === null || _a78 === void 0 ? void 0 : _a78.redirectTo,
20268
20351
  scopes: (_b7 = credentials.options) === null || _b7 === void 0 ? void 0 : _b7.scopes,
20269
20352
  queryParams: (_c = credentials.options) === null || _c === void 0 ? void 0 : _c.queryParams,
20270
20353
  skipBrowserRedirect: (_d = credentials.options) === null || _d === void 0 ? void 0 : _d.skipBrowserRedirect
@@ -20298,7 +20381,7 @@ var GoTrueClient = class _GoTrueClient {
20298
20381
  }
20299
20382
  }
20300
20383
  async signInWithEthereum(credentials) {
20301
- var _a74, _b7, _c, _d, _e, _f, _g, _h, _j, _k, _l;
20384
+ var _a78, _b7, _c, _d, _e, _f, _g, _h, _j, _k, _l;
20302
20385
  let message;
20303
20386
  let signature;
20304
20387
  if ("message" in credentials) {
@@ -20322,7 +20405,7 @@ var GoTrueClient = class _GoTrueClient {
20322
20405
  throw new Error(`@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.`);
20323
20406
  }
20324
20407
  }
20325
- const url = new URL((_a74 = options === null || options === void 0 ? void 0 : options.url) !== null && _a74 !== void 0 ? _a74 : window.location.href);
20408
+ const url = new URL((_a78 = options === null || options === void 0 ? void 0 : options.url) !== null && _a78 !== void 0 ? _a78 : window.location.href);
20326
20409
  const accounts = await resolvedWallet.request({
20327
20410
  method: "eth_requestAccounts"
20328
20411
  }).then((accs) => accs).catch(() => {
@@ -20389,7 +20472,7 @@ var GoTrueClient = class _GoTrueClient {
20389
20472
  }
20390
20473
  }
20391
20474
  async signInWithSolana(credentials) {
20392
- var _a74, _b7, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
20475
+ var _a78, _b7, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
20393
20476
  let message;
20394
20477
  let signature;
20395
20478
  if ("message" in credentials) {
@@ -20413,7 +20496,7 @@ var GoTrueClient = class _GoTrueClient {
20413
20496
  throw new Error(`@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.`);
20414
20497
  }
20415
20498
  }
20416
- const url = new URL((_a74 = options === null || options === void 0 ? void 0 : options.url) !== null && _a74 !== void 0 ? _a74 : window.location.href);
20499
+ const url = new URL((_a78 = options === null || options === void 0 ? void 0 : options.url) !== null && _a78 !== void 0 ? _a78 : window.location.href);
20417
20500
  if ("signIn" in resolvedWallet && resolvedWallet.signIn) {
20418
20501
  const output = await resolvedWallet.signIn(Object.assign(Object.assign(Object.assign({ issuedAt: (/* @__PURE__ */ new Date()).toISOString() }, options === null || options === void 0 ? void 0 : options.signInWithSolana), {
20419
20502
  // non-overridable properties
@@ -20587,7 +20670,7 @@ var GoTrueClient = class _GoTrueClient {
20587
20670
  * This method supports PKCE when an email is passed.
20588
20671
  */
20589
20672
  async signInWithOtp(credentials) {
20590
- var _a74, _b7, _c, _d, _e;
20673
+ var _a78, _b7, _c, _d, _e;
20591
20674
  try {
20592
20675
  if ("email" in credentials) {
20593
20676
  const { email, options } = credentials;
@@ -20601,7 +20684,7 @@ var GoTrueClient = class _GoTrueClient {
20601
20684
  headers: this.headers,
20602
20685
  body: {
20603
20686
  email,
20604
- data: (_a74 = options === null || options === void 0 ? void 0 : options.data) !== null && _a74 !== void 0 ? _a74 : {},
20687
+ data: (_a78 = options === null || options === void 0 ? void 0 : options.data) !== null && _a78 !== void 0 ? _a78 : {},
20605
20688
  create_user: (_b7 = options === null || options === void 0 ? void 0 : options.shouldCreateUser) !== null && _b7 !== void 0 ? _b7 : true,
20606
20689
  gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },
20607
20690
  code_challenge: codeChallenge,
@@ -20641,12 +20724,12 @@ var GoTrueClient = class _GoTrueClient {
20641
20724
  * Log in a user given a User supplied OTP or TokenHash received through mobile or email.
20642
20725
  */
20643
20726
  async verifyOtp(params) {
20644
- var _a74, _b7;
20727
+ var _a78, _b7;
20645
20728
  try {
20646
20729
  let redirectTo = void 0;
20647
20730
  let captchaToken = void 0;
20648
20731
  if ("options" in params) {
20649
- redirectTo = (_a74 = params.options) === null || _a74 === void 0 ? void 0 : _a74.redirectTo;
20732
+ redirectTo = (_a78 = params.options) === null || _a78 === void 0 ? void 0 : _a78.redirectTo;
20650
20733
  captchaToken = (_b7 = params.options) === null || _b7 === void 0 ? void 0 : _b7.captchaToken;
20651
20734
  }
20652
20735
  const { data, error } = await _request(this.fetch, "POST", `${this.url}/verify`, {
@@ -20691,7 +20774,7 @@ var GoTrueClient = class _GoTrueClient {
20691
20774
  * organization's SSO Identity Provider UUID directly instead.
20692
20775
  */
20693
20776
  async signInWithSSO(params) {
20694
- var _a74, _b7, _c, _d, _e;
20777
+ var _a78, _b7, _c, _d, _e;
20695
20778
  try {
20696
20779
  let codeChallenge = null;
20697
20780
  let codeChallengeMethod = null;
@@ -20700,7 +20783,7 @@ var GoTrueClient = class _GoTrueClient {
20700
20783
  [codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(this.storage, this.storageKey);
20701
20784
  }
20702
20785
  const result = await _request(this.fetch, "POST", `${this.url}/sso`, {
20703
- body: Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, "providerId" in params ? { provider_id: params.providerId } : null), "domain" in params ? { domain: params.domain } : null), { redirect_to: (_b7 = (_a74 = params.options) === null || _a74 === void 0 ? void 0 : _a74.redirectTo) !== null && _b7 !== void 0 ? _b7 : void 0 }), ((_c = params === null || params === void 0 ? void 0 : params.options) === null || _c === void 0 ? void 0 : _c.captchaToken) ? { gotrue_meta_security: { captcha_token: params.options.captchaToken } } : null), { skip_http_redirect: true, code_challenge: codeChallenge, code_challenge_method: codeChallengeMethod }),
20786
+ body: Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, "providerId" in params ? { provider_id: params.providerId } : null), "domain" in params ? { domain: params.domain } : null), { redirect_to: (_b7 = (_a78 = params.options) === null || _a78 === void 0 ? void 0 : _a78.redirectTo) !== null && _b7 !== void 0 ? _b7 : void 0 }), ((_c = params === null || params === void 0 ? void 0 : params.options) === null || _c === void 0 ? void 0 : _c.captchaToken) ? { gotrue_meta_security: { captcha_token: params.options.captchaToken } } : null), { skip_http_redirect: true, code_challenge: codeChallenge, code_challenge_method: codeChallengeMethod }),
20704
20787
  headers: this.headers,
20705
20788
  xform: _ssoResponse
20706
20789
  });
@@ -20954,12 +21037,12 @@ var GoTrueClient = class _GoTrueClient {
20954
21037
  });
20955
21038
  }
20956
21039
  return await this._useSession(async (result) => {
20957
- var _a74, _b7, _c;
21040
+ var _a78, _b7, _c;
20958
21041
  const { data, error } = result;
20959
21042
  if (error) {
20960
21043
  throw error;
20961
21044
  }
20962
- if (!((_a74 = data.session) === null || _a74 === void 0 ? void 0 : _a74.access_token) && !this.hasCustomAuthorizationHeader) {
21045
+ if (!((_a78 = data.session) === null || _a78 === void 0 ? void 0 : _a78.access_token) && !this.hasCustomAuthorizationHeader) {
20963
21046
  return { data: { user: null }, error: new AuthSessionMissingError() };
20964
21047
  }
20965
21048
  return await _request(this.fetch, "GET", `${this.url}/user`, {
@@ -21101,13 +21184,13 @@ var GoTrueClient = class _GoTrueClient {
21101
21184
  async _refreshSession(currentSession) {
21102
21185
  try {
21103
21186
  return await this._useSession(async (result) => {
21104
- var _a74;
21187
+ var _a78;
21105
21188
  if (!currentSession) {
21106
21189
  const { data, error: error2 } = result;
21107
21190
  if (error2) {
21108
21191
  throw error2;
21109
21192
  }
21110
- currentSession = (_a74 = data.session) !== null && _a74 !== void 0 ? _a74 : void 0;
21193
+ currentSession = (_a78 = data.session) !== null && _a78 !== void 0 ? _a78 : void 0;
21111
21194
  }
21112
21195
  if (!(currentSession === null || currentSession === void 0 ? void 0 : currentSession.refresh_token)) {
21113
21196
  throw new AuthSessionMissingError();
@@ -21245,12 +21328,12 @@ var GoTrueClient = class _GoTrueClient {
21245
21328
  }
21246
21329
  async _signOut({ scope } = { scope: "global" }) {
21247
21330
  return await this._useSession(async (result) => {
21248
- var _a74;
21331
+ var _a78;
21249
21332
  const { data, error: sessionError } = result;
21250
21333
  if (sessionError) {
21251
21334
  return this._returnResult({ error: sessionError });
21252
21335
  }
21253
- const accessToken = (_a74 = data.session) === null || _a74 === void 0 ? void 0 : _a74.access_token;
21336
+ const accessToken = (_a78 = data.session) === null || _a78 === void 0 ? void 0 : _a78.access_token;
21254
21337
  if (accessToken) {
21255
21338
  const { error } = await this.admin.signOut(accessToken, scope);
21256
21339
  if (error) {
@@ -21288,12 +21371,12 @@ var GoTrueClient = class _GoTrueClient {
21288
21371
  }
21289
21372
  async _emitInitialSession(id) {
21290
21373
  return await this._useSession(async (result) => {
21291
- var _a74, _b7;
21374
+ var _a78, _b7;
21292
21375
  try {
21293
21376
  const { data: { session }, error } = result;
21294
21377
  if (error)
21295
21378
  throw error;
21296
- await ((_a74 = this.stateChangeEmitters.get(id)) === null || _a74 === void 0 ? void 0 : _a74.callback("INITIAL_SESSION", session));
21379
+ await ((_a78 = this.stateChangeEmitters.get(id)) === null || _a78 === void 0 ? void 0 : _a78.callback("INITIAL_SESSION", session));
21297
21380
  this._debug("INITIAL_SESSION", "callback id", id, "session", session);
21298
21381
  } catch (err) {
21299
21382
  await ((_b7 = this.stateChangeEmitters.get(id)) === null || _b7 === void 0 ? void 0 : _b7.callback("INITIAL_SESSION", null));
@@ -21344,12 +21427,12 @@ var GoTrueClient = class _GoTrueClient {
21344
21427
  * Gets all the identities linked to a user.
21345
21428
  */
21346
21429
  async getUserIdentities() {
21347
- var _a74;
21430
+ var _a78;
21348
21431
  try {
21349
21432
  const { data, error } = await this.getUser();
21350
21433
  if (error)
21351
21434
  throw error;
21352
- return this._returnResult({ data: { identities: (_a74 = data.user.identities) !== null && _a74 !== void 0 ? _a74 : [] }, error: null });
21435
+ return this._returnResult({ data: { identities: (_a78 = data.user.identities) !== null && _a78 !== void 0 ? _a78 : [] }, error: null });
21353
21436
  } catch (error) {
21354
21437
  if (isAuthError(error)) {
21355
21438
  return this._returnResult({ data: null, error });
@@ -21364,15 +21447,15 @@ var GoTrueClient = class _GoTrueClient {
21364
21447
  return this.linkIdentityOAuth(credentials);
21365
21448
  }
21366
21449
  async linkIdentityOAuth(credentials) {
21367
- var _a74;
21450
+ var _a78;
21368
21451
  try {
21369
21452
  const { data, error } = await this._useSession(async (result) => {
21370
- var _a75, _b7, _c, _d, _e;
21453
+ var _a79, _b7, _c, _d, _e;
21371
21454
  const { data: data2, error: error2 } = result;
21372
21455
  if (error2)
21373
21456
  throw error2;
21374
21457
  const url = await this._getUrlForProvider(`${this.url}/user/identities/authorize`, credentials.provider, {
21375
- redirectTo: (_a75 = credentials.options) === null || _a75 === void 0 ? void 0 : _a75.redirectTo,
21458
+ redirectTo: (_a79 = credentials.options) === null || _a79 === void 0 ? void 0 : _a79.redirectTo,
21376
21459
  scopes: (_b7 = credentials.options) === null || _b7 === void 0 ? void 0 : _b7.scopes,
21377
21460
  queryParams: (_c = credentials.options) === null || _c === void 0 ? void 0 : _c.queryParams,
21378
21461
  skipBrowserRedirect: true
@@ -21384,7 +21467,7 @@ var GoTrueClient = class _GoTrueClient {
21384
21467
  });
21385
21468
  if (error)
21386
21469
  throw error;
21387
- if (isBrowser() && !((_a74 = credentials.options) === null || _a74 === void 0 ? void 0 : _a74.skipBrowserRedirect)) {
21470
+ if (isBrowser() && !((_a78 = credentials.options) === null || _a78 === void 0 ? void 0 : _a78.skipBrowserRedirect)) {
21388
21471
  window.location.assign(data === null || data === void 0 ? void 0 : data.url);
21389
21472
  }
21390
21473
  return this._returnResult({
@@ -21400,7 +21483,7 @@ var GoTrueClient = class _GoTrueClient {
21400
21483
  }
21401
21484
  async linkIdentityIdToken(credentials) {
21402
21485
  return await this._useSession(async (result) => {
21403
- var _a74;
21486
+ var _a78;
21404
21487
  try {
21405
21488
  const { error: sessionError, data: { session } } = result;
21406
21489
  if (sessionError)
@@ -21408,7 +21491,7 @@ var GoTrueClient = class _GoTrueClient {
21408
21491
  const { options, provider, token, access_token, nonce } = credentials;
21409
21492
  const res = await _request(this.fetch, "POST", `${this.url}/token?grant_type=id_token`, {
21410
21493
  headers: this.headers,
21411
- jwt: (_a74 = session === null || session === void 0 ? void 0 : session.access_token) !== null && _a74 !== void 0 ? _a74 : void 0,
21494
+ jwt: (_a78 = session === null || session === void 0 ? void 0 : session.access_token) !== null && _a78 !== void 0 ? _a78 : void 0,
21412
21495
  body: {
21413
21496
  provider,
21414
21497
  id_token: token,
@@ -21448,14 +21531,14 @@ var GoTrueClient = class _GoTrueClient {
21448
21531
  async unlinkIdentity(identity) {
21449
21532
  try {
21450
21533
  return await this._useSession(async (result) => {
21451
- var _a74, _b7;
21534
+ var _a78, _b7;
21452
21535
  const { data, error } = result;
21453
21536
  if (error) {
21454
21537
  throw error;
21455
21538
  }
21456
21539
  return await _request(this.fetch, "DELETE", `${this.url}/user/identities/${identity.identity_id}`, {
21457
21540
  headers: this.headers,
21458
- jwt: (_b7 = (_a74 = data.session) === null || _a74 === void 0 ? void 0 : _a74.access_token) !== null && _b7 !== void 0 ? _b7 : void 0
21541
+ jwt: (_b7 = (_a78 = data.session) === null || _a78 === void 0 ? void 0 : _a78.access_token) !== null && _b7 !== void 0 ? _b7 : void 0
21459
21542
  });
21460
21543
  });
21461
21544
  } catch (error) {
@@ -21520,7 +21603,7 @@ var GoTrueClient = class _GoTrueClient {
21520
21603
  * Note: this method is async to accommodate for AsyncStorage e.g. in React native.
21521
21604
  */
21522
21605
  async _recoverAndRefresh() {
21523
- var _a74, _b7;
21606
+ var _a78, _b7;
21524
21607
  const debugName = "#_recoverAndRefresh()";
21525
21608
  this._debug(debugName, "begin");
21526
21609
  try {
@@ -21531,7 +21614,7 @@ var GoTrueClient = class _GoTrueClient {
21531
21614
  maybeUser = { user: currentSession.user };
21532
21615
  await setItemAsync(this.userStorage, this.storageKey + "-user", maybeUser);
21533
21616
  }
21534
- currentSession.user = (_a74 = maybeUser === null || maybeUser === void 0 ? void 0 : maybeUser.user) !== null && _a74 !== void 0 ? _a74 : userNotAvailableProxy();
21617
+ currentSession.user = (_a78 = maybeUser === null || maybeUser === void 0 ? void 0 : maybeUser.user) !== null && _a78 !== void 0 ? _a78 : userNotAvailableProxy();
21535
21618
  } else if (currentSession && !currentSession.user) {
21536
21619
  if (!currentSession.user) {
21537
21620
  const separateUser = await getItemAsync(this.storage, this.storageKey + "-user");
@@ -21591,7 +21674,7 @@ var GoTrueClient = class _GoTrueClient {
21591
21674
  }
21592
21675
  }
21593
21676
  async _callRefreshToken(refreshToken) {
21594
- var _a74, _b7;
21677
+ var _a78, _b7;
21595
21678
  if (!refreshToken) {
21596
21679
  throw new AuthSessionMissingError();
21597
21680
  }
@@ -21619,7 +21702,7 @@ var GoTrueClient = class _GoTrueClient {
21619
21702
  if (!isAuthRetryableFetchError(error)) {
21620
21703
  await this._removeSession();
21621
21704
  }
21622
- (_a74 = this.refreshingDeferred) === null || _a74 === void 0 ? void 0 : _a74.resolve(result);
21705
+ (_a78 = this.refreshingDeferred) === null || _a78 === void 0 ? void 0 : _a78.resolve(result);
21623
21706
  return result;
21624
21707
  }
21625
21708
  (_b7 = this.refreshingDeferred) === null || _b7 === void 0 ? void 0 : _b7.reject(error);
@@ -21908,14 +21991,14 @@ var GoTrueClient = class _GoTrueClient {
21908
21991
  async _unenroll(params) {
21909
21992
  try {
21910
21993
  return await this._useSession(async (result) => {
21911
- var _a74;
21994
+ var _a78;
21912
21995
  const { data: sessionData, error: sessionError } = result;
21913
21996
  if (sessionError) {
21914
21997
  return this._returnResult({ data: null, error: sessionError });
21915
21998
  }
21916
21999
  return await _request(this.fetch, "DELETE", `${this.url}/factors/${params.factorId}`, {
21917
22000
  headers: this.headers,
21918
- jwt: (_a74 = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a74 === void 0 ? void 0 : _a74.access_token
22001
+ jwt: (_a78 = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a78 === void 0 ? void 0 : _a78.access_token
21919
22002
  });
21920
22003
  });
21921
22004
  } catch (error) {
@@ -21928,7 +22011,7 @@ var GoTrueClient = class _GoTrueClient {
21928
22011
  async _enroll(params) {
21929
22012
  try {
21930
22013
  return await this._useSession(async (result) => {
21931
- var _a74, _b7;
22014
+ var _a78, _b7;
21932
22015
  const { data: sessionData, error: sessionError } = result;
21933
22016
  if (sessionError) {
21934
22017
  return this._returnResult({ data: null, error: sessionError });
@@ -21937,7 +22020,7 @@ var GoTrueClient = class _GoTrueClient {
21937
22020
  const { data, error } = await _request(this.fetch, "POST", `${this.url}/factors`, {
21938
22021
  body,
21939
22022
  headers: this.headers,
21940
- jwt: (_a74 = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a74 === void 0 ? void 0 : _a74.access_token
22023
+ jwt: (_a78 = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a78 === void 0 ? void 0 : _a78.access_token
21941
22024
  });
21942
22025
  if (error) {
21943
22026
  return this._returnResult({ data: null, error });
@@ -21958,7 +22041,7 @@ var GoTrueClient = class _GoTrueClient {
21958
22041
  return this._acquireLock(this.lockAcquireTimeout, async () => {
21959
22042
  try {
21960
22043
  return await this._useSession(async (result) => {
21961
- var _a74;
22044
+ var _a78;
21962
22045
  const { data: sessionData, error: sessionError } = result;
21963
22046
  if (sessionError) {
21964
22047
  return this._returnResult({ data: null, error: sessionError });
@@ -21969,7 +22052,7 @@ var GoTrueClient = class _GoTrueClient {
21969
22052
  const { data, error } = await _request(this.fetch, "POST", `${this.url}/factors/${params.factorId}/verify`, {
21970
22053
  body,
21971
22054
  headers: this.headers,
21972
- jwt: (_a74 = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a74 === void 0 ? void 0 : _a74.access_token
22055
+ jwt: (_a78 = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a78 === void 0 ? void 0 : _a78.access_token
21973
22056
  });
21974
22057
  if (error) {
21975
22058
  return this._returnResult({ data: null, error });
@@ -21990,7 +22073,7 @@ var GoTrueClient = class _GoTrueClient {
21990
22073
  return this._acquireLock(this.lockAcquireTimeout, async () => {
21991
22074
  try {
21992
22075
  return await this._useSession(async (result) => {
21993
- var _a74;
22076
+ var _a78;
21994
22077
  const { data: sessionData, error: sessionError } = result;
21995
22078
  if (sessionError) {
21996
22079
  return this._returnResult({ data: null, error: sessionError });
@@ -21998,7 +22081,7 @@ var GoTrueClient = class _GoTrueClient {
21998
22081
  const response = await _request(this.fetch, "POST", `${this.url}/factors/${params.factorId}/challenge`, {
21999
22082
  body: params,
22000
22083
  headers: this.headers,
22001
- jwt: (_a74 = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a74 === void 0 ? void 0 : _a74.access_token
22084
+ jwt: (_a78 = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a78 === void 0 ? void 0 : _a78.access_token
22002
22085
  });
22003
22086
  if (response.error) {
22004
22087
  return response;
@@ -22048,7 +22131,7 @@ var GoTrueClient = class _GoTrueClient {
22048
22131
  * {@see GoTrueMFAApi#listFactors}
22049
22132
  */
22050
22133
  async _listFactors() {
22051
- var _a74;
22134
+ var _a78;
22052
22135
  const { data: { user }, error: userError } = await this.getUser();
22053
22136
  if (userError) {
22054
22137
  return { data: null, error: userError };
@@ -22059,7 +22142,7 @@ var GoTrueClient = class _GoTrueClient {
22059
22142
  totp: [],
22060
22143
  webauthn: []
22061
22144
  };
22062
- for (const factor of (_a74 = user === null || user === void 0 ? void 0 : user.factors) !== null && _a74 !== void 0 ? _a74 : []) {
22145
+ for (const factor of (_a78 = user === null || user === void 0 ? void 0 : user.factors) !== null && _a78 !== void 0 ? _a78 : []) {
22063
22146
  data.all.push(factor);
22064
22147
  if (factor.status === "verified") {
22065
22148
  ;
@@ -22075,7 +22158,7 @@ var GoTrueClient = class _GoTrueClient {
22075
22158
  * {@see GoTrueMFAApi#getAuthenticatorAssuranceLevel}
22076
22159
  */
22077
22160
  async _getAuthenticatorAssuranceLevel() {
22078
- var _a74, _b7;
22161
+ var _a78, _b7;
22079
22162
  const { data: { session }, error: sessionError } = await this.getSession();
22080
22163
  if (sessionError) {
22081
22164
  return this._returnResult({ data: null, error: sessionError });
@@ -22092,7 +22175,7 @@ var GoTrueClient = class _GoTrueClient {
22092
22175
  currentLevel = payload.aal;
22093
22176
  }
22094
22177
  let nextLevel = currentLevel;
22095
- const verifiedFactors = (_b7 = (_a74 = session.user.factors) === null || _a74 === void 0 ? void 0 : _a74.filter((factor) => factor.status === "verified")) !== null && _b7 !== void 0 ? _b7 : [];
22178
+ const verifiedFactors = (_b7 = (_a78 = session.user.factors) === null || _a78 === void 0 ? void 0 : _a78.filter((factor) => factor.status === "verified")) !== null && _b7 !== void 0 ? _b7 : [];
22096
22179
  if (verifiedFactors.length > 0) {
22097
22180
  nextLevel = "aal2";
22098
22181
  }
@@ -22698,10 +22781,10 @@ if (shouldShowDeprecationWarning()) console.warn("\u26A0\uFE0F Node.js 18 and b
22698
22781
  var cachedStargate = null;
22699
22782
  var cachedPublic = null;
22700
22783
  function getSupabase() {
22701
- var _a74;
22784
+ var _a78;
22702
22785
  if (cachedStargate) return cachedStargate;
22703
22786
  const url = getRuntimeEnv("VITE_SUPABASE_URL");
22704
- const anon = (_a74 = getRuntimeEnv("VITE_SUPABASE_ANON_KEY")) != null ? _a74 : getRuntimeEnv("VITE_SUPABASE_PUBLISHABLE_KEY");
22787
+ const anon = (_a78 = getRuntimeEnv("VITE_SUPABASE_ANON_KEY")) != null ? _a78 : getRuntimeEnv("VITE_SUPABASE_PUBLISHABLE_KEY");
22705
22788
  const schema = getRuntimeEnvOr("VITE_SUPABASE_SCHEMA", "public");
22706
22789
  if (!url || !anon) {
22707
22790
  if (isRuntimeDev()) {
@@ -22719,10 +22802,10 @@ function getSupabase() {
22719
22802
  return cachedStargate;
22720
22803
  }
22721
22804
  function getSupabasePublic() {
22722
- var _a74;
22805
+ var _a78;
22723
22806
  if (cachedPublic) return cachedPublic;
22724
22807
  const url = getRuntimeEnv("VITE_SUPABASE_URL");
22725
- const anon = (_a74 = getRuntimeEnv("VITE_SUPABASE_ANON_KEY")) != null ? _a74 : getRuntimeEnv("VITE_SUPABASE_PUBLISHABLE_KEY");
22808
+ const anon = (_a78 = getRuntimeEnv("VITE_SUPABASE_ANON_KEY")) != null ? _a78 : getRuntimeEnv("VITE_SUPABASE_PUBLISHABLE_KEY");
22726
22809
  if (!url || !anon) {
22727
22810
  if (isRuntimeDev()) {
22728
22811
  console.log("[supabase] getSupabasePublic: env faltando", { hasUrl: !!url, hasAnon: !!anon });
@@ -22797,9 +22880,9 @@ var Toaster = ({ theme, ...props }) => {
22797
22880
  // src/lib/accountsAuth.ts
22798
22881
  var normalizeBaseUrl2 = (value) => value.replace(/\/+$/, "");
22799
22882
  var getAccountsConfig = () => {
22800
- var _a74, _b7, _c;
22883
+ var _a78, _b7, _c;
22801
22884
  const baseUrl = normalizeBaseUrl2(
22802
- (_a74 = getRuntimeEnv("VITE_ACCOUNTS_BASE_URL")) != null ? _a74 : "https://accounts.cupcode.com.br"
22885
+ (_a78 = getRuntimeEnv("VITE_ACCOUNTS_BASE_URL")) != null ? _a78 : "https://accounts.cupcode.com.br"
22803
22886
  );
22804
22887
  const clientId = getRuntimeEnv("VITE_ACCOUNTS_CLIENT_ID");
22805
22888
  if (!clientId) {
@@ -22820,7 +22903,7 @@ var getAccountsConfig = () => {
22820
22903
  };
22821
22904
  var cachedDiscovery = null;
22822
22905
  var resolveOidcEndpoints = async (config) => {
22823
- var _a74, _b7, _c, _d, _e, _f;
22906
+ var _a78, _b7, _c, _d, _e, _f;
22824
22907
  if (config.authUrl && config.tokenUrl) {
22825
22908
  return {
22826
22909
  authUrl: config.authUrl,
@@ -22830,7 +22913,7 @@ var resolveOidcEndpoints = async (config) => {
22830
22913
  }
22831
22914
  if (cachedDiscovery) {
22832
22915
  return {
22833
- authUrl: (_a74 = cachedDiscovery.authorization_endpoint) != null ? _a74 : config.authUrl,
22916
+ authUrl: (_a78 = cachedDiscovery.authorization_endpoint) != null ? _a78 : config.authUrl,
22834
22917
  tokenUrl: (_b7 = cachedDiscovery.token_endpoint) != null ? _b7 : config.tokenUrl,
22835
22918
  logoutUrl: (_c = cachedDiscovery.end_session_endpoint) != null ? _c : config.logoutUrl
22836
22919
  };
@@ -22895,6 +22978,30 @@ var buildAuthorizeUrl = (config, authUrl, state, challenge, nonce, options) => {
22895
22978
  if (options == null ? void 0 : options.loginHint) params.set("login_hint", options.loginHint);
22896
22979
  return `${authUrl}?${params.toString()}`;
22897
22980
  };
22981
+ var readTokenField = (payload, keys) => {
22982
+ for (const key of keys) {
22983
+ const candidate = payload[key];
22984
+ if (typeof candidate !== "string") continue;
22985
+ const normalized = candidate.trim();
22986
+ if (normalized) return normalized;
22987
+ }
22988
+ return void 0;
22989
+ };
22990
+ var readNumericField = (payload, keys) => {
22991
+ for (const key of keys) {
22992
+ const candidate = payload[key];
22993
+ if (typeof candidate === "number" && Number.isFinite(candidate) && candidate > 0) {
22994
+ return candidate;
22995
+ }
22996
+ if (typeof candidate === "string") {
22997
+ const parsed = Number(candidate);
22998
+ if (Number.isFinite(parsed) && parsed > 0) {
22999
+ return parsed;
23000
+ }
23001
+ }
23002
+ }
23003
+ return void 0;
23004
+ };
22898
23005
  var exchangeCodeForToken = async (config, tokenUrl, code, verifier) => {
22899
23006
  const body = new URLSearchParams({
22900
23007
  grant_type: "authorization_code",
@@ -22912,7 +23019,22 @@ var exchangeCodeForToken = async (config, tokenUrl, code, verifier) => {
22912
23019
  const text = await response.text();
22913
23020
  throw new Error(text || "Falha ao obter token do accounts.");
22914
23021
  }
22915
- return await response.json();
23022
+ const payload = await response.json();
23023
+ const accessToken = readTokenField(payload, ["access_token", "accessToken", "token"]);
23024
+ if (!accessToken) {
23025
+ throw new Error("Token de acesso n\xE3o retornado pelo accounts.");
23026
+ }
23027
+ const idToken = readTokenField(payload, ["id_token", "idToken"]);
23028
+ const refreshToken = readTokenField(payload, ["refresh_token", "refreshToken"]);
23029
+ const tokenType = readTokenField(payload, ["token_type", "tokenType"]);
23030
+ const expiresIn = readNumericField(payload, ["expires_in", "expiresIn", "expires"]);
23031
+ return {
23032
+ access_token: accessToken,
23033
+ id_token: idToken,
23034
+ refresh_token: refreshToken,
23035
+ token_type: tokenType,
23036
+ expires_in: expiresIn
23037
+ };
22916
23038
  };
22917
23039
  var buildLogoutUrl = (config, logoutUrl, idTokenHint) => {
22918
23040
  if (!logoutUrl) return void 0;
@@ -22936,6 +23058,11 @@ var decodeJwt = (token) => {
22936
23058
 
22937
23059
  // src/components/cupcode/MainNavbar.tsx
22938
23060
  var import_jsx_runtime45 = require("react/jsx-runtime");
23061
+ var parsePositiveInteger = (rawValue, fallback) => {
23062
+ const parsed = Number(rawValue);
23063
+ if (!Number.isFinite(parsed) || parsed <= 0) return fallback;
23064
+ return Math.floor(parsed);
23065
+ };
22939
23066
  var _a18, _b5;
22940
23067
  var SUPABASE_SCHEMA = ((_b5 = (_a18 = getRuntimeEnv("VITE_CHAT_SCHEMA")) != null ? _a18 : getRuntimeEnv("VITE_SUPABASE_SCHEMA")) != null ? _b5 : "public").trim();
22941
23068
  var _a19;
@@ -22945,27 +23072,37 @@ var USER_PRESENCE_USER_ID_COLUMN = ((_a20 = getRuntimeEnv("VITE_USER_PRESENCE_US
22945
23072
  var _a21;
22946
23073
  var USER_PRESENCE_STATUS_COLUMN = ((_a21 = getRuntimeEnv("VITE_USER_PRESENCE_STATUS_COLUMN")) != null ? _a21 : "status").trim();
22947
23074
  var _a22;
22948
- var CHAT_USERS_TABLE = ((_a22 = getRuntimeEnv("VITE_CHAT_USERS_TABLE")) != null ? _a22 : "chat_users").trim();
23075
+ var USER_PRESENCE_SOURCE_COLUMN = ((_a22 = getRuntimeEnv("VITE_USER_PRESENCE_SOURCE_COLUMN")) != null ? _a22 : "status_source").trim();
22949
23076
  var _a23;
22950
- var CHAT_USERS_ID_COLUMN = ((_a23 = getRuntimeEnv("VITE_CHAT_USERS_ID_COLUMN")) != null ? _a23 : "id").trim();
23077
+ var USER_PRESENCE_LAST_ACTIVE_COLUMN = ((_a23 = getRuntimeEnv("VITE_USER_PRESENCE_LAST_ACTIVE_COLUMN")) != null ? _a23 : "last_active_at").trim();
23078
+ var PRESENCE_IDLE_TIMEOUT_MS = parsePositiveInteger(getRuntimeEnv("VITE_PRESENCE_IDLE_TIMEOUT_MS"), 10 * 60 * 1e3);
23079
+ var PRESENCE_OFFLINE_TIMEOUT_MS = Math.max(
23080
+ parsePositiveInteger(getRuntimeEnv("VITE_PRESENCE_OFFLINE_TIMEOUT_MS"), 10 * 60 * 1e3),
23081
+ PRESENCE_IDLE_TIMEOUT_MS
23082
+ );
23083
+ var PRESENCE_RECALC_INTERVAL_MS = 3e4;
22951
23084
  var _a24;
22952
- var CHAT_USERS_NAME_COLUMN = ((_a24 = getRuntimeEnv("VITE_CHAT_USERS_NAME_COLUMN")) != null ? _a24 : "name").trim();
23085
+ var CHAT_USERS_TABLE = ((_a24 = getRuntimeEnv("VITE_CHAT_USERS_TABLE")) != null ? _a24 : "chat_users").trim();
22953
23086
  var _a25;
22954
- var CHAT_USERS_USERNAME_COLUMN = ((_a25 = getRuntimeEnv("VITE_CHAT_USERS_USERNAME_COLUMN")) != null ? _a25 : "username").trim();
23087
+ var CHAT_USERS_ID_COLUMN = ((_a25 = getRuntimeEnv("VITE_CHAT_USERS_ID_COLUMN")) != null ? _a25 : "id").trim();
22955
23088
  var _a26;
22956
- var CHAT_USERS_EMAIL_COLUMN = ((_a26 = getRuntimeEnv("VITE_CHAT_USERS_EMAIL_COLUMN")) != null ? _a26 : "email").trim();
23089
+ var CHAT_USERS_NAME_COLUMN = ((_a26 = getRuntimeEnv("VITE_CHAT_USERS_NAME_COLUMN")) != null ? _a26 : "name").trim();
22957
23090
  var _a27;
22958
- var CHAT_USERS_AVATAR_COLUMN = ((_a27 = getRuntimeEnv("VITE_CHAT_USERS_AVATAR_COLUMN")) != null ? _a27 : "avatar_url").trim();
23091
+ var CHAT_USERS_USERNAME_COLUMN = ((_a27 = getRuntimeEnv("VITE_CHAT_USERS_USERNAME_COLUMN")) != null ? _a27 : "username").trim();
22959
23092
  var _a28;
22960
- var CHAT_USERS_ROLE_COLUMN = ((_a28 = getRuntimeEnv("VITE_CHAT_USERS_ROLE_COLUMN")) != null ? _a28 : "job_title").trim();
23093
+ var CHAT_USERS_EMAIL_COLUMN = ((_a28 = getRuntimeEnv("VITE_CHAT_USERS_EMAIL_COLUMN")) != null ? _a28 : "email").trim();
22961
23094
  var _a29;
22962
- var CHAT_USERS_UPDATE_TABLE = ((_a29 = getRuntimeEnv("VITE_CHAT_USERS_UPDATE_TABLE")) != null ? _a29 : "profiles").trim();
23095
+ var CHAT_USERS_AVATAR_COLUMN = ((_a29 = getRuntimeEnv("VITE_CHAT_USERS_AVATAR_COLUMN")) != null ? _a29 : "avatar_url").trim();
22963
23096
  var _a30;
22964
- var CHAT_USERS_UPDATE_ID_COLUMN = ((_a30 = getRuntimeEnv("VITE_CHAT_USERS_UPDATE_ID_COLUMN")) != null ? _a30 : "id").trim();
23097
+ var CHAT_USERS_ROLE_COLUMN = ((_a30 = getRuntimeEnv("VITE_CHAT_USERS_ROLE_COLUMN")) != null ? _a30 : "job_title").trim();
22965
23098
  var _a31;
22966
- var CHAT_USERS_UPDATE_EMAIL_COLUMN = ((_a31 = getRuntimeEnv("VITE_CHAT_USERS_UPDATE_EMAIL_COLUMN")) != null ? _a31 : "email").trim();
23099
+ var CHAT_USERS_UPDATE_TABLE = ((_a31 = getRuntimeEnv("VITE_CHAT_USERS_UPDATE_TABLE")) != null ? _a31 : "profiles").trim();
22967
23100
  var _a32;
22968
- var CHAT_USERS_UPDATE_AVATAR_COLUMN = ((_a32 = getRuntimeEnv("VITE_CHAT_USERS_UPDATE_AVATAR_COLUMN")) != null ? _a32 : "avatar_url").trim();
23101
+ var CHAT_USERS_UPDATE_ID_COLUMN = ((_a32 = getRuntimeEnv("VITE_CHAT_USERS_UPDATE_ID_COLUMN")) != null ? _a32 : "id").trim();
23102
+ var _a33;
23103
+ var CHAT_USERS_UPDATE_EMAIL_COLUMN = ((_a33 = getRuntimeEnv("VITE_CHAT_USERS_UPDATE_EMAIL_COLUMN")) != null ? _a33 : "email").trim();
23104
+ var _a34;
23105
+ var CHAT_USERS_UPDATE_AVATAR_COLUMN = ((_a34 = getRuntimeEnv("VITE_CHAT_USERS_UPDATE_AVATAR_COLUMN")) != null ? _a34 : "avatar_url").trim();
22969
23106
  var CHAT_USERS_LOOKUP_TABLES = Array.from(
22970
23107
  new Set(
22971
23108
  [CHAT_USERS_TABLE, "chat_users", CHAT_USERS_UPDATE_TABLE, "profiles", "users"].map((entry) => entry.trim()).filter((entry) => entry.length > 0)
@@ -22981,73 +23118,73 @@ var CHAT_USERS_LOOKUP_EMAIL_COLUMNS = Array.from(
22981
23118
  [CHAT_USERS_EMAIL_COLUMN, CHAT_USERS_UPDATE_EMAIL_COLUMN, "email"].map((entry) => entry.trim()).filter((entry) => entry.length > 0)
22982
23119
  )
22983
23120
  );
22984
- var _a33;
22985
- var CHAT_MESSAGES_TABLE = ((_a33 = getRuntimeEnv("VITE_CHAT_MESSAGES_TABLE")) != null ? _a33 : "chat_messages").trim();
22986
- var _a34;
22987
- var CHAT_MESSAGES_ID_COLUMN = ((_a34 = getRuntimeEnv("VITE_CHAT_MESSAGES_ID_COLUMN")) != null ? _a34 : "id").trim();
22988
23121
  var _a35;
22989
- var CHAT_MESSAGES_SENDER_COLUMN = ((_a35 = getRuntimeEnv("VITE_CHAT_MESSAGES_SENDER_COLUMN")) != null ? _a35 : "sender_id").trim();
23122
+ var CHAT_MESSAGES_TABLE = ((_a35 = getRuntimeEnv("VITE_CHAT_MESSAGES_TABLE")) != null ? _a35 : "chat_messages").trim();
22990
23123
  var _a36;
22991
- var CHAT_MESSAGES_RECIPIENT_COLUMN = ((_a36 = getRuntimeEnv("VITE_CHAT_MESSAGES_RECIPIENT_COLUMN")) != null ? _a36 : "recipient_id").trim();
23124
+ var CHAT_MESSAGES_ID_COLUMN = ((_a36 = getRuntimeEnv("VITE_CHAT_MESSAGES_ID_COLUMN")) != null ? _a36 : "id").trim();
22992
23125
  var _a37;
22993
- var CHAT_MESSAGES_TEXT_COLUMN = ((_a37 = getRuntimeEnv("VITE_CHAT_MESSAGES_TEXT_COLUMN")) != null ? _a37 : "text").trim();
23126
+ var CHAT_MESSAGES_SENDER_COLUMN = ((_a37 = getRuntimeEnv("VITE_CHAT_MESSAGES_SENDER_COLUMN")) != null ? _a37 : "sender_id").trim();
22994
23127
  var _a38;
22995
- var CHAT_MESSAGES_CREATED_AT_COLUMN = ((_a38 = getRuntimeEnv("VITE_CHAT_MESSAGES_CREATED_AT_COLUMN")) != null ? _a38 : "created_at").trim();
23128
+ var CHAT_MESSAGES_RECIPIENT_COLUMN = ((_a38 = getRuntimeEnv("VITE_CHAT_MESSAGES_RECIPIENT_COLUMN")) != null ? _a38 : "recipient_id").trim();
22996
23129
  var _a39;
22997
- var CHAT_MESSAGES_READ_AT_COLUMN = ((_a39 = getRuntimeEnv("VITE_CHAT_MESSAGES_READ_AT_COLUMN")) != null ? _a39 : "read_at").trim();
23130
+ var CHAT_MESSAGES_TEXT_COLUMN = ((_a39 = getRuntimeEnv("VITE_CHAT_MESSAGES_TEXT_COLUMN")) != null ? _a39 : "text").trim();
22998
23131
  var _a40;
22999
- var CHAT_MESSAGES_REPLY_TO_COLUMN = ((_a40 = getRuntimeEnv("VITE_CHAT_MESSAGES_REPLY_TO_COLUMN")) != null ? _a40 : "reply_to_message_id").trim();
23132
+ var CHAT_MESSAGES_CREATED_AT_COLUMN = ((_a40 = getRuntimeEnv("VITE_CHAT_MESSAGES_CREATED_AT_COLUMN")) != null ? _a40 : "created_at").trim();
23000
23133
  var _a41;
23001
- var CHAT_MESSAGES_EDITED_AT_COLUMN = ((_a41 = getRuntimeEnv("VITE_CHAT_MESSAGES_EDITED_AT_COLUMN")) != null ? _a41 : "edited_at").trim();
23134
+ var CHAT_MESSAGES_READ_AT_COLUMN = ((_a41 = getRuntimeEnv("VITE_CHAT_MESSAGES_READ_AT_COLUMN")) != null ? _a41 : "read_at").trim();
23002
23135
  var _a42;
23003
- var CHAT_MESSAGES_DELETED_AT_COLUMN = ((_a42 = getRuntimeEnv("VITE_CHAT_MESSAGES_DELETED_AT_COLUMN")) != null ? _a42 : "deleted_at").trim();
23136
+ var CHAT_MESSAGES_REPLY_TO_COLUMN = ((_a42 = getRuntimeEnv("VITE_CHAT_MESSAGES_REPLY_TO_COLUMN")) != null ? _a42 : "reply_to_message_id").trim();
23004
23137
  var _a43;
23005
- var CHAT_MESSAGES_DELETED_BY_COLUMN = ((_a43 = getRuntimeEnv("VITE_CHAT_MESSAGES_DELETED_BY_COLUMN")) != null ? _a43 : "deleted_by").trim();
23138
+ var CHAT_MESSAGES_EDITED_AT_COLUMN = ((_a43 = getRuntimeEnv("VITE_CHAT_MESSAGES_EDITED_AT_COLUMN")) != null ? _a43 : "edited_at").trim();
23006
23139
  var _a44;
23007
- var CHAT_REACTIONS_TABLE = ((_a44 = getRuntimeEnv("VITE_CHAT_REACTIONS_TABLE")) != null ? _a44 : "chat_message_reactions").trim();
23140
+ var CHAT_MESSAGES_DELETED_AT_COLUMN = ((_a44 = getRuntimeEnv("VITE_CHAT_MESSAGES_DELETED_AT_COLUMN")) != null ? _a44 : "deleted_at").trim();
23008
23141
  var _a45;
23009
- var CHAT_REACTIONS_ID_COLUMN = ((_a45 = getRuntimeEnv("VITE_CHAT_REACTIONS_ID_COLUMN")) != null ? _a45 : "id").trim();
23142
+ var CHAT_MESSAGES_DELETED_BY_COLUMN = ((_a45 = getRuntimeEnv("VITE_CHAT_MESSAGES_DELETED_BY_COLUMN")) != null ? _a45 : "deleted_by").trim();
23010
23143
  var _a46;
23011
- var CHAT_REACTIONS_MESSAGE_ID_COLUMN = ((_a46 = getRuntimeEnv("VITE_CHAT_REACTIONS_MESSAGE_ID_COLUMN")) != null ? _a46 : "message_id").trim();
23144
+ var CHAT_REACTIONS_TABLE = ((_a46 = getRuntimeEnv("VITE_CHAT_REACTIONS_TABLE")) != null ? _a46 : "chat_message_reactions").trim();
23012
23145
  var _a47;
23013
- var CHAT_REACTIONS_USER_ID_COLUMN = ((_a47 = getRuntimeEnv("VITE_CHAT_REACTIONS_USER_ID_COLUMN")) != null ? _a47 : "user_id").trim();
23146
+ var CHAT_REACTIONS_ID_COLUMN = ((_a47 = getRuntimeEnv("VITE_CHAT_REACTIONS_ID_COLUMN")) != null ? _a47 : "id").trim();
23014
23147
  var _a48;
23015
- var CHAT_REACTIONS_EMOJI_COLUMN = ((_a48 = getRuntimeEnv("VITE_CHAT_REACTIONS_EMOJI_COLUMN")) != null ? _a48 : "emoji").trim();
23148
+ var CHAT_REACTIONS_MESSAGE_ID_COLUMN = ((_a48 = getRuntimeEnv("VITE_CHAT_REACTIONS_MESSAGE_ID_COLUMN")) != null ? _a48 : "message_id").trim();
23016
23149
  var _a49;
23017
- var CHAT_REACTIONS_CREATED_AT_COLUMN = ((_a49 = getRuntimeEnv("VITE_CHAT_REACTIONS_CREATED_AT_COLUMN")) != null ? _a49 : "created_at").trim();
23150
+ var CHAT_REACTIONS_USER_ID_COLUMN = ((_a49 = getRuntimeEnv("VITE_CHAT_REACTIONS_USER_ID_COLUMN")) != null ? _a49 : "user_id").trim();
23018
23151
  var _a50;
23019
- var CHAT_LOGS_TABLE = ((_a50 = getRuntimeEnv("VITE_CHAT_LOGS_TABLE")) != null ? _a50 : "chat_message_logs").trim();
23152
+ var CHAT_REACTIONS_EMOJI_COLUMN = ((_a50 = getRuntimeEnv("VITE_CHAT_REACTIONS_EMOJI_COLUMN")) != null ? _a50 : "emoji").trim();
23020
23153
  var _a51;
23021
- var CHAT_LOGS_ID_COLUMN = ((_a51 = getRuntimeEnv("VITE_CHAT_LOGS_ID_COLUMN")) != null ? _a51 : "id").trim();
23154
+ var CHAT_REACTIONS_CREATED_AT_COLUMN = ((_a51 = getRuntimeEnv("VITE_CHAT_REACTIONS_CREATED_AT_COLUMN")) != null ? _a51 : "created_at").trim();
23022
23155
  var _a52;
23023
- var CHAT_LOGS_MESSAGE_ID_COLUMN = ((_a52 = getRuntimeEnv("VITE_CHAT_LOGS_MESSAGE_ID_COLUMN")) != null ? _a52 : "message_id").trim();
23156
+ var CHAT_LOGS_TABLE = ((_a52 = getRuntimeEnv("VITE_CHAT_LOGS_TABLE")) != null ? _a52 : "chat_message_logs").trim();
23024
23157
  var _a53;
23025
- var CHAT_LOGS_ACTOR_ID_COLUMN = ((_a53 = getRuntimeEnv("VITE_CHAT_LOGS_ACTOR_ID_COLUMN")) != null ? _a53 : "actor_id").trim();
23158
+ var CHAT_LOGS_ID_COLUMN = ((_a53 = getRuntimeEnv("VITE_CHAT_LOGS_ID_COLUMN")) != null ? _a53 : "id").trim();
23026
23159
  var _a54;
23027
- var CHAT_LOGS_ACTION_COLUMN = ((_a54 = getRuntimeEnv("VITE_CHAT_LOGS_ACTION_COLUMN")) != null ? _a54 : "action").trim();
23160
+ var CHAT_LOGS_MESSAGE_ID_COLUMN = ((_a54 = getRuntimeEnv("VITE_CHAT_LOGS_MESSAGE_ID_COLUMN")) != null ? _a54 : "message_id").trim();
23028
23161
  var _a55;
23029
- var CHAT_LOGS_PREVIOUS_TEXT_COLUMN = ((_a55 = getRuntimeEnv("VITE_CHAT_LOGS_PREVIOUS_TEXT_COLUMN")) != null ? _a55 : "previous_text").trim();
23162
+ var CHAT_LOGS_ACTOR_ID_COLUMN = ((_a55 = getRuntimeEnv("VITE_CHAT_LOGS_ACTOR_ID_COLUMN")) != null ? _a55 : "actor_id").trim();
23030
23163
  var _a56;
23031
- var CHAT_LOGS_NEXT_TEXT_COLUMN = ((_a56 = getRuntimeEnv("VITE_CHAT_LOGS_NEXT_TEXT_COLUMN")) != null ? _a56 : "next_text").trim();
23164
+ var CHAT_LOGS_ACTION_COLUMN = ((_a56 = getRuntimeEnv("VITE_CHAT_LOGS_ACTION_COLUMN")) != null ? _a56 : "action").trim();
23032
23165
  var _a57;
23033
- var CHAT_LOGS_CREATED_AT_COLUMN = ((_a57 = getRuntimeEnv("VITE_CHAT_LOGS_CREATED_AT_COLUMN")) != null ? _a57 : "created_at").trim();
23166
+ var CHAT_LOGS_PREVIOUS_TEXT_COLUMN = ((_a57 = getRuntimeEnv("VITE_CHAT_LOGS_PREVIOUS_TEXT_COLUMN")) != null ? _a57 : "previous_text").trim();
23167
+ var _a58;
23168
+ var CHAT_LOGS_NEXT_TEXT_COLUMN = ((_a58 = getRuntimeEnv("VITE_CHAT_LOGS_NEXT_TEXT_COLUMN")) != null ? _a58 : "next_text").trim();
23169
+ var _a59;
23170
+ var CHAT_LOGS_CREATED_AT_COLUMN = ((_a59 = getRuntimeEnv("VITE_CHAT_LOGS_CREATED_AT_COLUMN")) != null ? _a59 : "created_at").trim();
23034
23171
  var CHAT_MESSAGE_HISTORY_LIMIT = 200;
23035
23172
  var CHAT_EDIT_WINDOW_MINUTES2 = 15;
23036
23173
  var CHAT_DELETED_PLACEHOLDER_TEXT2 = "Mensagem deletada";
23037
- var _a58;
23038
- var TELESCUP_BASE_URL = (_a58 = getRuntimeEnv("VITE_TELESCUP_BASE_URL")) == null ? void 0 : _a58.trim();
23039
- var _a59;
23040
- var SUPABASE_URL2 = (_a59 = getRuntimeEnv("VITE_SUPABASE_URL")) == null ? void 0 : _a59.trim();
23041
- var TELESCUP_BASE_URL_FALLBACK = SUPABASE_URL2 ? `${SUPABASE_URL2.replace(/\/+$/, "")}/functions/v1` : void 0;
23042
- var ACCESS_TOKEN_STORAGE_KEY = "cc_access_token";
23043
23174
  var _a60;
23044
- var ACCOUNTS_BASE_URL2 = ((_a60 = getRuntimeEnv("VITE_ACCOUNTS_BASE_URL")) != null ? _a60 : "https://accounts.cupcode.com.br").trim().replace(/\/+$/, "");
23175
+ var TELESCUP_BASE_URL = (_a60 = getRuntimeEnv("VITE_TELESCUP_BASE_URL")) == null ? void 0 : _a60.trim();
23045
23176
  var _a61;
23046
- var MC_BASE_URL2 = ((_a61 = getRuntimeEnv("VITE_MC_BASE_URL")) != null ? _a61 : "https://mc.cupcode.com.br").trim().replace(/\/+$/, "");
23177
+ var SUPABASE_URL2 = (_a61 = getRuntimeEnv("VITE_SUPABASE_URL")) == null ? void 0 : _a61.trim();
23178
+ var TELESCUP_BASE_URL_FALLBACK = SUPABASE_URL2 ? `${SUPABASE_URL2.replace(/\/+$/, "")}/functions/v1` : void 0;
23179
+ var ACCESS_TOKEN_STORAGE_KEY = "cc_access_token";
23047
23180
  var _a62;
23048
- var ACCOUNTS_LANGUAGE_ENDPOINT = (_a62 = getRuntimeEnv("VITE_ACCOUNTS_LANGUAGE_ENDPOINT")) == null ? void 0 : _a62.trim();
23181
+ var ACCOUNTS_BASE_URL2 = ((_a62 = getRuntimeEnv("VITE_ACCOUNTS_BASE_URL")) != null ? _a62 : "https://accounts.cupcode.com.br").trim().replace(/\/+$/, "");
23049
23182
  var _a63;
23050
- var ACCOUNTS_ACTIVITY_ENDPOINT = (_a63 = getRuntimeEnv("VITE_ACCOUNTS_ACTIVITY_ENDPOINT")) == null ? void 0 : _a63.trim();
23183
+ var MC_BASE_URL2 = ((_a63 = getRuntimeEnv("VITE_MC_BASE_URL")) != null ? _a63 : "https://mc.cupcode.com.br").trim().replace(/\/+$/, "");
23184
+ var _a64;
23185
+ var ACCOUNTS_LANGUAGE_ENDPOINT = (_a64 = getRuntimeEnv("VITE_ACCOUNTS_LANGUAGE_ENDPOINT")) == null ? void 0 : _a64.trim();
23186
+ var _a65;
23187
+ var ACCOUNTS_ACTIVITY_ENDPOINT = (_a65 = getRuntimeEnv("VITE_ACCOUNTS_ACTIVITY_ENDPOINT")) == null ? void 0 : _a65.trim();
23051
23188
  var PRESENCE_STATUS_VALUES = [
23052
23189
  "online",
23053
23190
  "away",
@@ -23058,6 +23195,17 @@ var PRESENCE_STATUS_VALUES = [
23058
23195
  "designing",
23059
23196
  "offline"
23060
23197
  ];
23198
+ var PRESENCE_SOURCE_VALUES = ["auto", "manual", "system"];
23199
+ var PRESENCE_STATUS_LABELS = {
23200
+ online: "On-line",
23201
+ away: "Ausente",
23202
+ busy: "Ocupado",
23203
+ lunch: "Almo\xE7o",
23204
+ call: "Em call",
23205
+ coding: "Coding",
23206
+ designing: "Designing",
23207
+ offline: "Off-line"
23208
+ };
23061
23209
  var CHAT_FEATURE_FLAGS_STORAGE_KEY = "cc_chat_feature_flags";
23062
23210
  var getDefaultChatFeatureFlags = () => ({
23063
23211
  hasReadAt: true,
@@ -23159,6 +23307,59 @@ var normalizePresenceStatus = (value) => {
23159
23307
  const normalized = value.trim().toLowerCase();
23160
23308
  return PRESENCE_STATUS_VALUES.includes(normalized) ? normalized : "offline";
23161
23309
  };
23310
+ var normalizePresenceSource = (value) => {
23311
+ if (typeof value !== "string") return "auto";
23312
+ const normalized = value.trim().toLowerCase();
23313
+ return PRESENCE_SOURCE_VALUES.includes(normalized) ? normalized : "auto";
23314
+ };
23315
+ var toTimestampMs = (value) => {
23316
+ if (typeof value === "number" && Number.isFinite(value)) {
23317
+ return value > 1e12 ? value : value * 1e3;
23318
+ }
23319
+ if (typeof value !== "string") return void 0;
23320
+ const trimmed = value.trim();
23321
+ if (!trimmed) return void 0;
23322
+ const parsed = new Date(trimmed).getTime();
23323
+ return Number.isNaN(parsed) ? void 0 : parsed;
23324
+ };
23325
+ var resolveEffectivePresenceStatus = (snapshot, now = Date.now()) => {
23326
+ if (snapshot.status === "offline") {
23327
+ return "offline";
23328
+ }
23329
+ if (typeof snapshot.lastActiveAtMs === "number" && Number.isFinite(snapshot.lastActiveAtMs)) {
23330
+ const inactiveMs = now - snapshot.lastActiveAtMs;
23331
+ if (inactiveMs >= PRESENCE_OFFLINE_TIMEOUT_MS) {
23332
+ return "offline";
23333
+ }
23334
+ if (snapshot.source === "auto") {
23335
+ return inactiveMs >= PRESENCE_IDLE_TIMEOUT_MS ? "away" : "online";
23336
+ }
23337
+ return snapshot.status;
23338
+ }
23339
+ if (snapshot.source === "auto") {
23340
+ return snapshot.status === "away" ? "away" : "online";
23341
+ }
23342
+ return snapshot.status;
23343
+ };
23344
+ var resolvePresenceStatusLabel = (snapshot, effectiveStatus, now = Date.now()) => {
23345
+ if (effectiveStatus === "online") {
23346
+ return PRESENCE_STATUS_LABELS.online;
23347
+ }
23348
+ const lastActiveAtMs = snapshot.lastActiveAtMs;
23349
+ if ((effectiveStatus === "away" || effectiveStatus === "offline") && typeof lastActiveAtMs === "number" && Number.isFinite(lastActiveAtMs) && now >= lastActiveAtMs) {
23350
+ const diffMinutes = Math.max(1, Math.floor((now - lastActiveAtMs) / 6e4));
23351
+ return `On-line h\xE1 ${diffMinutes} min`;
23352
+ }
23353
+ return PRESENCE_STATUS_LABELS[effectiveStatus];
23354
+ };
23355
+ var readPresenceSnapshotFromRecord = (row) => {
23356
+ var _a78, _b7, _c, _d;
23357
+ if (!row) return null;
23358
+ const status = normalizePresenceStatus((_a78 = row[USER_PRESENCE_STATUS_COLUMN]) != null ? _a78 : row.status);
23359
+ const source = normalizePresenceSource((_b7 = row[USER_PRESENCE_SOURCE_COLUMN]) != null ? _b7 : row.status_source);
23360
+ const lastActiveAtMs = toTimestampMs((_d = (_c = row[USER_PRESENCE_LAST_ACTIVE_COLUMN]) != null ? _c : row.last_active_at) != null ? _d : row.updated_at);
23361
+ return { status, source, lastActiveAtMs };
23362
+ };
23162
23363
  var normalizeHandle2 = (value) => {
23163
23364
  if (!value) return void 0;
23164
23365
  return value.startsWith("@") ? value.slice(1) : value;
@@ -23188,12 +23389,12 @@ var resolveCurrentUserId = (user) => {
23188
23389
  return null;
23189
23390
  };
23190
23391
  var resolveUserIdFromClaims = (claims) => {
23191
- var _a74, _b7, _c, _d, _e;
23192
- return (_e = (_d = (_c = (_b7 = (_a74 = toStringOrUndefined(claims.sub)) != null ? _a74 : toStringOrUndefined(claims.user_id)) != null ? _b7 : toStringOrUndefined(claims.userId)) != null ? _c : toStringOrUndefined(claims.uid)) != null ? _d : toStringOrUndefined(claims.id)) != null ? _e : toStringOrUndefined(claims["https://cupcode.com/user_id"]);
23392
+ var _a78, _b7, _c, _d, _e;
23393
+ return (_e = (_d = (_c = (_b7 = (_a78 = toStringOrUndefined(claims.sub)) != null ? _a78 : toStringOrUndefined(claims.user_id)) != null ? _b7 : toStringOrUndefined(claims.userId)) != null ? _c : toStringOrUndefined(claims.uid)) != null ? _d : toStringOrUndefined(claims.id)) != null ? _e : toStringOrUndefined(claims["https://cupcode.com/user_id"]);
23193
23394
  };
23194
23395
  var resolveEmailFromClaims = (claims) => {
23195
- var _a74, _b7;
23196
- const candidate = (_b7 = (_a74 = toStringOrUndefined(claims.email)) != null ? _a74 : toStringOrUndefined(claims["https://cupcode.com/email"])) != null ? _b7 : toStringOrUndefined(claims.preferred_username);
23396
+ var _a78, _b7;
23397
+ const candidate = (_b7 = (_a78 = toStringOrUndefined(claims.email)) != null ? _a78 : toStringOrUndefined(claims["https://cupcode.com/email"])) != null ? _b7 : toStringOrUndefined(claims.preferred_username);
23197
23398
  if (!candidate || !candidate.includes("@")) return void 0;
23198
23399
  return candidate.toLowerCase();
23199
23400
  };
@@ -23258,8 +23459,8 @@ var parseRecentActivityItems = (payload) => {
23258
23459
  return [];
23259
23460
  };
23260
23461
  return toRows(payload).map((item, index) => {
23261
- var _a74, _b7, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
23262
- const id = (_b7 = (_a74 = toStringOrUndefined(item.id)) != null ? _a74 : toStringOrUndefined(item.event_id)) != null ? _b7 : `accounts-activity-${index}`;
23462
+ var _a78, _b7, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
23463
+ const id = (_b7 = (_a78 = toStringOrUndefined(item.id)) != null ? _a78 : toStringOrUndefined(item.event_id)) != null ? _b7 : `accounts-activity-${index}`;
23263
23464
  const title = (_e = (_d = (_c = toStringOrUndefined(item.title)) != null ? _c : toStringOrUndefined(item.action)) != null ? _d : toStringOrUndefined(item.event)) != null ? _e : toStringOrUndefined(item.type);
23264
23465
  if (!title) return null;
23265
23466
  const description = (_h = (_g = (_f = toStringOrUndefined(item.description)) != null ? _f : toStringOrUndefined(item.details)) != null ? _g : toStringOrUndefined(item.message)) != null ? _h : toStringOrUndefined(item.summary);
@@ -23342,9 +23543,9 @@ var dedupeAndSortReactions = (reactions) => {
23342
23543
  });
23343
23544
  };
23344
23545
  var getErrorText = (error) => {
23345
- var _a74, _b7, _c;
23546
+ var _a78, _b7, _c;
23346
23547
  const typed = error;
23347
- return `${(_a74 = typed == null ? void 0 : typed.message) != null ? _a74 : ""} ${(_b7 = typed == null ? void 0 : typed.details) != null ? _b7 : ""} ${(_c = typed == null ? void 0 : typed.hint) != null ? _c : ""}`.toLowerCase();
23548
+ return `${(_a78 = typed == null ? void 0 : typed.message) != null ? _a78 : ""} ${(_b7 = typed == null ? void 0 : typed.details) != null ? _b7 : ""} ${(_c = typed == null ? void 0 : typed.hint) != null ? _c : ""}`.toLowerCase();
23348
23549
  };
23349
23550
  var isMissingColumnError = (error, column) => {
23350
23551
  const normalized = getErrorText(error);
@@ -23370,8 +23571,8 @@ var isRecoverableLookupError = (error, relationName) => {
23370
23571
  return normalized.includes("schema cache") || normalized.includes("permission denied") || normalized.includes("does not exist") || normalized.includes("could not find");
23371
23572
  };
23372
23573
  var toChatMessage = (row, currentUserId) => {
23373
- var _a74, _b7, _c, _d, _e, _f;
23374
- const id = (_a74 = toStringOrUndefined(row[CHAT_MESSAGES_ID_COLUMN])) != null ? _a74 : `${toStringOrUndefined(row[CHAT_MESSAGES_SENDER_COLUMN])}-${toStringOrUndefined(row[CHAT_MESSAGES_RECIPIENT_COLUMN])}-${toStringOrUndefined(row[CHAT_MESSAGES_CREATED_AT_COLUMN])}`;
23574
+ var _a78, _b7, _c, _d, _e, _f;
23575
+ const id = (_a78 = toStringOrUndefined(row[CHAT_MESSAGES_ID_COLUMN])) != null ? _a78 : `${toStringOrUndefined(row[CHAT_MESSAGES_SENDER_COLUMN])}-${toStringOrUndefined(row[CHAT_MESSAGES_RECIPIENT_COLUMN])}-${toStringOrUndefined(row[CHAT_MESSAGES_CREATED_AT_COLUMN])}`;
23375
23576
  const senderId = toStringOrUndefined(row[CHAT_MESSAGES_SENDER_COLUMN]);
23376
23577
  const recipientId = toStringOrUndefined(row[CHAT_MESSAGES_RECIPIENT_COLUMN]);
23377
23578
  const text = toStringOrUndefined(row[CHAT_MESSAGES_TEXT_COLUMN]);
@@ -23411,12 +23612,12 @@ var toChatReaction = (row) => {
23411
23612
  return { id, messageId, userId, emoji, createdAt };
23412
23613
  };
23413
23614
  var toChatMessageLog = (row, messagesById) => {
23414
- var _a74, _b7;
23615
+ var _a78, _b7;
23415
23616
  const id = toStringOrUndefined(row[CHAT_LOGS_ID_COLUMN]);
23416
23617
  const messageId = toStringOrUndefined(row[CHAT_LOGS_MESSAGE_ID_COLUMN]);
23417
23618
  const actorId = toStringOrUndefined(row[CHAT_LOGS_ACTOR_ID_COLUMN]);
23418
23619
  const action = toStringOrUndefined(row[CHAT_LOGS_ACTION_COLUMN]);
23419
- const previousText = (_a74 = toStringOrUndefined(row[CHAT_LOGS_PREVIOUS_TEXT_COLUMN])) != null ? _a74 : null;
23620
+ const previousText = (_a78 = toStringOrUndefined(row[CHAT_LOGS_PREVIOUS_TEXT_COLUMN])) != null ? _a78 : null;
23420
23621
  const nextText = (_b7 = toStringOrUndefined(row[CHAT_LOGS_NEXT_TEXT_COLUMN])) != null ? _b7 : null;
23421
23622
  const createdAt = toStringOrUndefined(row[CHAT_LOGS_CREATED_AT_COLUMN]);
23422
23623
  if (!id || !messageId || !action || action !== "edit" && action !== "delete") return null;
@@ -23459,7 +23660,7 @@ var MainNavbar = ({
23459
23660
  getAccessToken,
23460
23661
  appVersion
23461
23662
  }) => {
23462
- var _a74, _b7, _c;
23663
+ var _a78, _b7, _c;
23463
23664
  const [chatUsers, setChatUsers] = (0, import_react19.useState)([]);
23464
23665
  const [chatMessages, setChatMessages] = (0, import_react19.useState)([]);
23465
23666
  const [chatMessageLogs, setChatMessageLogs] = (0, import_react19.useState)([]);
@@ -23476,6 +23677,7 @@ var MainNavbar = ({
23476
23677
  const [isAccountsActivityLoading, setIsAccountsActivityLoading] = (0, import_react19.useState)(false);
23477
23678
  const chatMessagesRef = (0, import_react19.useRef)([]);
23478
23679
  const chatFeatureFlagsRef = (0, import_react19.useRef)(readStoredChatFeatureFlags());
23680
+ const presenceSnapshotsRef = (0, import_react19.useRef)(/* @__PURE__ */ new Map());
23479
23681
  const updateChatFeatureFlags = (0, import_react19.useCallback)((partial) => {
23480
23682
  const nextFlags = {
23481
23683
  ...chatFeatureFlagsRef.current,
@@ -23490,19 +23692,19 @@ var MainNavbar = ({
23490
23692
  return "/";
23491
23693
  }, [pathname]);
23492
23694
  const currentUserId = (0, import_react19.useMemo)(() => {
23493
- var _a75;
23494
- return (_a75 = resolveCurrentUserId(authUser)) != null ? _a75 : tokenDerivedUserId;
23695
+ var _a79;
23696
+ return (_a79 = resolveCurrentUserId(authUser)) != null ? _a79 : tokenDerivedUserId;
23495
23697
  }, [authUser, tokenDerivedUserId]);
23496
23698
  const authEmail = (0, import_react19.useMemo)(
23497
23699
  () => {
23498
- var _a75, _b8;
23499
- return (_b8 = (_a75 = toStringOrUndefined(authUser == null ? void 0 : authUser.email)) == null ? void 0 : _a75.toLowerCase()) != null ? _b8 : tokenDerivedEmail;
23700
+ var _a79, _b8;
23701
+ return (_b8 = (_a79 = toStringOrUndefined(authUser == null ? void 0 : authUser.email)) == null ? void 0 : _a79.toLowerCase()) != null ? _b8 : tokenDerivedEmail;
23500
23702
  },
23501
23703
  [authUser == null ? void 0 : authUser.email, tokenDerivedEmail]
23502
23704
  );
23503
23705
  const isChatSuperAdmin = (0, import_react19.useMemo)(() => {
23504
- var _a75, _b8;
23505
- const roleTokens = `${(_a75 = authUser == null ? void 0 : authUser.role) != null ? _a75 : ""} ${(_b8 = authUser == null ? void 0 : authUser.jobTitle) != null ? _b8 : ""}`.toLowerCase();
23706
+ var _a79, _b8;
23707
+ const roleTokens = `${(_a79 = authUser == null ? void 0 : authUser.role) != null ? _a79 : ""} ${(_b8 = authUser == null ? void 0 : authUser.jobTitle) != null ? _b8 : ""}`.toLowerCase();
23506
23708
  return roleTokens.includes("superadmin") || roleTokens.includes("super admin");
23507
23709
  }, [authUser == null ? void 0 : authUser.jobTitle, authUser == null ? void 0 : authUser.role]);
23508
23710
  const resolvedTelescupBaseUrl = (0, import_react19.useMemo)(() => {
@@ -23511,7 +23713,7 @@ var MainNavbar = ({
23511
23713
  }
23512
23714
  return TELESCUP_BASE_URL_FALLBACK;
23513
23715
  }, []);
23514
- const resolvedProfileAvatarUrl = (_b7 = (_a74 = resolveChatAvatarUrl(persistedProfileAvatarValue)) != null ? _a74 : authUser == null ? void 0 : authUser.picture) != null ? _b7 : void 0;
23716
+ const resolvedProfileAvatarUrl = (_b7 = (_a78 = resolveChatAvatarUrl(persistedProfileAvatarValue)) != null ? _a78 : authUser == null ? void 0 : authUser.picture) != null ? _b7 : void 0;
23515
23717
  const effectiveCurrentUserId = resolvedSenderId != null ? resolvedSenderId : currentUserId;
23516
23718
  const hasStoredAccessToken = (() => {
23517
23719
  if (typeof window === "undefined") return false;
@@ -23549,7 +23751,7 @@ var MainNavbar = ({
23549
23751
  }
23550
23752
  let canceled = false;
23551
23753
  const resolveIdentityFromToken = async () => {
23552
- var _a75, _b8;
23754
+ var _a79, _b8;
23553
23755
  try {
23554
23756
  let token = null;
23555
23757
  if (typeof window !== "undefined") {
@@ -23569,7 +23771,7 @@ var MainNavbar = ({
23569
23771
  }
23570
23772
  return;
23571
23773
  }
23572
- const claims = (_a75 = decodeJwt(token)) != null ? _a75 : {};
23774
+ const claims = (_a79 = decodeJwt(token)) != null ? _a79 : {};
23573
23775
  if (canceled) return;
23574
23776
  setTokenDerivedUserId((_b8 = resolveUserIdFromClaims(claims)) != null ? _b8 : null);
23575
23777
  setTokenDerivedEmail(resolveEmailFromClaims(claims));
@@ -23614,7 +23816,7 @@ var MainNavbar = ({
23614
23816
  );
23615
23817
  const warnings = [];
23616
23818
  const runLookup = async (kind, value, columns) => {
23617
- var _a75, _b8, _c2;
23819
+ var _a79, _b8, _c2;
23618
23820
  for (const tableName of CHAT_USERS_LOOKUP_TABLES) {
23619
23821
  for (const columnName of columns) {
23620
23822
  if (!columnName) continue;
@@ -23623,7 +23825,7 @@ var MainNavbar = ({
23623
23825
  const lookupError = response.error;
23624
23826
  if (lookupError) {
23625
23827
  if (isRecoverableLookupError(lookupError, tableName)) {
23626
- warnings.push(`${tableName}.${columnName}: ${(_a75 = lookupError.message) != null ? _a75 : "falha de lookup"}`);
23828
+ warnings.push(`${tableName}.${columnName}: ${(_a79 = lookupError.message) != null ? _a79 : "falha de lookup"}`);
23627
23829
  continue;
23628
23830
  }
23629
23831
  warnings.push(`${tableName}.${columnName}: ${(_b8 = lookupError.message) != null ? _b8 : "falha de lookup"}`);
@@ -23675,7 +23877,7 @@ var MainNavbar = ({
23675
23877
  return sessionStorage.getItem(ACCESS_TOKEN_STORAGE_KEY);
23676
23878
  };
23677
23879
  const loadAccountsContext = async () => {
23678
- var _a75, _b8, _c2, _d, _e, _f, _g;
23880
+ var _a79, _b8, _c2, _d, _e, _f, _g;
23679
23881
  setIsAccountsActivityLoading(true);
23680
23882
  try {
23681
23883
  const token = await resolveAccountsToken();
@@ -23685,7 +23887,7 @@ var MainNavbar = ({
23685
23887
  }
23686
23888
  return;
23687
23889
  }
23688
- const claims = (_a75 = decodeJwt(token)) != null ? _a75 : {};
23890
+ const claims = (_a79 = decodeJwt(token)) != null ? _a79 : {};
23689
23891
  const languageFromToken = normalizeMenuLanguage(
23690
23892
  (_d = (_c2 = (_b8 = claims.locale) != null ? _b8 : claims.lang) != null ? _c2 : claims.language) != null ? _d : claims["https://cupcode.com/locale"]
23691
23893
  );
@@ -23744,6 +23946,7 @@ var MainNavbar = ({
23744
23946
  }, [chatMessages]);
23745
23947
  (0, import_react19.useEffect)(() => {
23746
23948
  if (!isAuthenticated) {
23949
+ presenceSnapshotsRef.current.clear();
23747
23950
  setChatUsers([]);
23748
23951
  setChatMessages([]);
23749
23952
  setChatMessageLogs([]);
@@ -23753,6 +23956,7 @@ var MainNavbar = ({
23753
23956
  return;
23754
23957
  }
23755
23958
  if (!effectiveCurrentUserId) {
23959
+ presenceSnapshotsRef.current.clear();
23756
23960
  setChatUsers([]);
23757
23961
  setChatMessages([]);
23758
23962
  setChatMessageLogs([]);
@@ -23763,6 +23967,7 @@ var MainNavbar = ({
23763
23967
  }
23764
23968
  const supabase = getSupabase();
23765
23969
  if (!supabase) {
23970
+ presenceSnapshotsRef.current.clear();
23766
23971
  setChatUsers([]);
23767
23972
  setChatMessages([]);
23768
23973
  setChatMessageLogs([]);
@@ -23773,11 +23978,11 @@ var MainNavbar = ({
23773
23978
  }
23774
23979
  let canceled = false;
23775
23980
  const loadChatData = async () => {
23776
- var _a75, _b8, _c2, _d, _e, _f, _g, _h, _i;
23981
+ var _a79, _b8, _c2, _d, _e, _f, _g, _h, _i;
23777
23982
  setIsChatLoading(true);
23778
23983
  setChatError(null);
23779
23984
  const fetchFirstAvailableTable = async (tableNames) => {
23780
- var _a76;
23985
+ var _a80;
23781
23986
  let lastError = null;
23782
23987
  for (const tableName of tableNames) {
23783
23988
  const response = await supabase.from(tableName).select("*");
@@ -23799,7 +24004,7 @@ var MainNavbar = ({
23799
24004
  }
23800
24005
  }
23801
24006
  return {
23802
- tableName: (_a76 = tableNames[0]) != null ? _a76 : null,
24007
+ tableName: (_a80 = tableNames[0]) != null ? _a80 : null,
23803
24008
  data: null,
23804
24009
  error: lastError
23805
24010
  };
@@ -23850,7 +24055,16 @@ var MainNavbar = ({
23850
24055
  ]);
23851
24056
  };
23852
24057
  const [presenceResponse, usersResponse, profilesResponse] = await Promise.all([
23853
- supabase.from(USER_PRESENCE_TABLE).select(`${USER_PRESENCE_USER_ID_COLUMN},${USER_PRESENCE_STATUS_COLUMN}`),
24058
+ supabase.from(USER_PRESENCE_TABLE).select(
24059
+ Array.from(
24060
+ /* @__PURE__ */ new Set([
24061
+ USER_PRESENCE_USER_ID_COLUMN,
24062
+ USER_PRESENCE_STATUS_COLUMN,
24063
+ USER_PRESENCE_SOURCE_COLUMN,
24064
+ USER_PRESENCE_LAST_ACTIVE_COLUMN
24065
+ ])
24066
+ ).join(",")
24067
+ ),
23854
24068
  fetchFirstAvailableTable(CHAT_USERS_LOOKUP_TABLES),
23855
24069
  fetchFirstAvailableTable(profileLookupTables)
23856
24070
  ]);
@@ -23896,18 +24110,26 @@ var MainNavbar = ({
23896
24110
  }
23897
24111
  if (canceled) return;
23898
24112
  const presenceMap = /* @__PURE__ */ new Map();
24113
+ const presenceStatusLabelMap = /* @__PURE__ */ new Map();
24114
+ const presenceSnapshots = /* @__PURE__ */ new Map();
24115
+ const now = Date.now();
23899
24116
  if (presenceResponse.error) {
23900
24117
  if (isRuntimeDev()) {
23901
24118
  console.warn("[chat] Falha ao carregar presen\xE7a:", presenceResponse.error.message);
23902
24119
  }
23903
24120
  } else {
23904
- (_a75 = presenceResponse.data) == null ? void 0 : _a75.forEach((row) => {
24121
+ (_a79 = presenceResponse.data) == null ? void 0 : _a79.forEach((row) => {
23905
24122
  const userId = readFirstRecordString(row, [USER_PRESENCE_USER_ID_COLUMN, "user_id", "id"]);
23906
24123
  if (!userId) return;
23907
- const statusValue = readFirstRecordString(row, [USER_PRESENCE_STATUS_COLUMN, "status", "presence_status"]);
23908
- presenceMap.set(userId, normalizePresenceStatus(statusValue));
24124
+ const snapshot = readPresenceSnapshotFromRecord(row);
24125
+ if (!snapshot) return;
24126
+ presenceSnapshots.set(userId, snapshot);
24127
+ const effectiveStatus = resolveEffectivePresenceStatus(snapshot, now);
24128
+ presenceMap.set(userId, effectiveStatus);
24129
+ presenceStatusLabelMap.set(userId, resolvePresenceStatusLabel(snapshot, effectiveStatus, now));
23909
24130
  });
23910
24131
  }
24132
+ presenceSnapshotsRef.current = presenceSnapshots;
23911
24133
  const profileById = /* @__PURE__ */ new Map();
23912
24134
  const profileByEmail = /* @__PURE__ */ new Map();
23913
24135
  if (profilesResponse.error) {
@@ -23943,11 +24165,11 @@ var MainNavbar = ({
23943
24165
  }
23944
24166
  } else {
23945
24167
  (_e = usersResponse.data) == null ? void 0 : _e.forEach((row) => {
23946
- var _a76, _b9, _c3, _d2, _e2, _f2, _g2, _h2;
24168
+ var _a80, _b9, _c3, _d2, _e2, _f2, _g2, _h2, _i2;
23947
24169
  const id = readFirstRecordString(row, [...CHAT_USERS_LOOKUP_ID_COLUMNS, "id", "user_id"]);
23948
24170
  if (!id || id === effectiveCurrentUserId) return;
23949
24171
  const rowEmail = readFirstRecordString(row, [...CHAT_USERS_LOOKUP_EMAIL_COLUMNS, "email"]);
23950
- const profile = (_a76 = profileById.get(id)) != null ? _a76 : rowEmail ? profileByEmail.get(rowEmail.toLowerCase()) : void 0;
24172
+ const profile = (_a80 = profileById.get(id)) != null ? _a80 : rowEmail ? profileByEmail.get(rowEmail.toLowerCase()) : void 0;
23951
24173
  const email = rowEmail != null ? rowEmail : readFirstRecordString(profile, [CHAT_USERS_UPDATE_EMAIL_COLUMN, CHAT_USERS_EMAIL_COLUMN, "email"]);
23952
24174
  const rawUsername = (_b9 = readFirstRecordString(row, [CHAT_USERS_USERNAME_COLUMN, "username", "user_name"])) != null ? _b9 : readFirstRecordString(profile, [CHAT_USERS_USERNAME_COLUMN, "username", "user_name"]);
23953
24175
  const username = buildHandle2(rawUsername, email);
@@ -23955,6 +24177,7 @@ var MainNavbar = ({
23955
24177
  const name = resolveReadableUserLabel(rawName, rawUsername, email, id);
23956
24178
  const avatarValue = (_d2 = readFirstRecordString(row, [CHAT_USERS_AVATAR_COLUMN, CHAT_USERS_UPDATE_AVATAR_COLUMN, "avatar_url", "picture"])) != null ? _d2 : readFirstRecordString(profile, [CHAT_USERS_UPDATE_AVATAR_COLUMN, CHAT_USERS_AVATAR_COLUMN, "picture", "photo_url", "avatar"]);
23957
24179
  const roleLabel = (_e2 = readFirstRecordString(row, [CHAT_USERS_ROLE_COLUMN, "job_title", "role"])) != null ? _e2 : readFirstRecordString(profile, [CHAT_USERS_ROLE_COLUMN, "job_title", "role"]);
24180
+ const resolvedStatus = (_h2 = (_g2 = (_f2 = presenceMap.get(id)) != null ? _f2 : readPresenceStatusFromRecord(profile)) != null ? _g2 : readPresenceStatusFromRecord(row)) != null ? _h2 : "offline";
23958
24181
  usersMap.set(id, {
23959
24182
  id,
23960
24183
  name,
@@ -23962,12 +24185,13 @@ var MainNavbar = ({
23962
24185
  email,
23963
24186
  avatarUrl: resolveChatAvatarUrl(avatarValue),
23964
24187
  roleLabel,
23965
- status: (_h2 = (_g2 = (_f2 = presenceMap.get(id)) != null ? _f2 : readPresenceStatusFromRecord(profile)) != null ? _g2 : readPresenceStatusFromRecord(row)) != null ? _h2 : "offline"
24188
+ status: resolvedStatus,
24189
+ statusLabel: (_i2 = presenceStatusLabelMap.get(id)) != null ? _i2 : PRESENCE_STATUS_LABELS[resolvedStatus]
23966
24190
  });
23967
24191
  });
23968
24192
  }
23969
24193
  profileById.forEach((profile, id) => {
23970
- var _a76, _b9;
24194
+ var _a80, _b9, _c3;
23971
24195
  if (!id || id === effectiveCurrentUserId || usersMap.has(id)) return;
23972
24196
  const email = readFirstRecordString(profile, [CHAT_USERS_UPDATE_EMAIL_COLUMN, CHAT_USERS_EMAIL_COLUMN, "email"]);
23973
24197
  const rawUsername = readFirstRecordString(profile, [CHAT_USERS_USERNAME_COLUMN, "username", "user_name"]);
@@ -23981,6 +24205,7 @@ var MainNavbar = ({
23981
24205
  "avatar"
23982
24206
  ]);
23983
24207
  const roleLabel = readFirstRecordString(profile, [CHAT_USERS_ROLE_COLUMN, "job_title", "role"]);
24208
+ const resolvedStatus = (_b9 = (_a80 = presenceMap.get(id)) != null ? _a80 : readPresenceStatusFromRecord(profile)) != null ? _b9 : "offline";
23984
24209
  usersMap.set(id, {
23985
24210
  id,
23986
24211
  name: resolveReadableUserLabel(rawName, rawUsername, email, id),
@@ -23988,10 +24213,12 @@ var MainNavbar = ({
23988
24213
  email,
23989
24214
  avatarUrl: resolveChatAvatarUrl(avatarValue),
23990
24215
  roleLabel,
23991
- status: (_b9 = (_a76 = presenceMap.get(id)) != null ? _a76 : readPresenceStatusFromRecord(profile)) != null ? _b9 : "offline"
24216
+ status: resolvedStatus,
24217
+ statusLabel: (_c3 = presenceStatusLabelMap.get(id)) != null ? _c3 : PRESENCE_STATUS_LABELS[resolvedStatus]
23992
24218
  });
23993
24219
  });
23994
24220
  presenceMap.forEach((statusValue, id) => {
24221
+ var _a80;
23995
24222
  if (id === effectiveCurrentUserId || usersMap.has(id)) return;
23996
24223
  const profile = profileById.get(id);
23997
24224
  const email = readFirstRecordString(profile, [CHAT_USERS_UPDATE_EMAIL_COLUMN, CHAT_USERS_EMAIL_COLUMN, "email"]);
@@ -24013,7 +24240,8 @@ var MainNavbar = ({
24013
24240
  email,
24014
24241
  avatarUrl: resolveChatAvatarUrl(avatarValue),
24015
24242
  roleLabel,
24016
- status: statusValue
24243
+ status: statusValue,
24244
+ statusLabel: (_a80 = presenceStatusLabelMap.get(id)) != null ? _a80 : PRESENCE_STATUS_LABELS[statusValue]
24017
24245
  });
24018
24246
  });
24019
24247
  if (messageErrors.length > 0) {
@@ -24030,7 +24258,7 @@ var MainNavbar = ({
24030
24258
  );
24031
24259
  setChatMessages(resolvedMessages);
24032
24260
  resolvedMessages.forEach((message) => {
24033
- var _a76, _b9;
24261
+ var _a80, _b9, _c3;
24034
24262
  const contactId = message.contactId;
24035
24263
  if (!contactId || contactId === effectiveCurrentUserId || usersMap.has(contactId)) return;
24036
24264
  const profile = profileById.get(contactId);
@@ -24046,6 +24274,7 @@ var MainNavbar = ({
24046
24274
  "avatar"
24047
24275
  ]);
24048
24276
  const roleLabel = readFirstRecordString(profile, [CHAT_USERS_ROLE_COLUMN, "job_title", "role"]);
24277
+ const resolvedStatus = (_b9 = (_a80 = presenceMap.get(contactId)) != null ? _a80 : readPresenceStatusFromRecord(profile)) != null ? _b9 : "offline";
24049
24278
  usersMap.set(contactId, {
24050
24279
  id: contactId,
24051
24280
  name: resolveReadableUserLabel(rawName, rawUsername, email, contactId),
@@ -24053,7 +24282,8 @@ var MainNavbar = ({
24053
24282
  email,
24054
24283
  avatarUrl: resolveChatAvatarUrl(avatarValue),
24055
24284
  roleLabel,
24056
- status: (_b9 = (_a76 = presenceMap.get(contactId)) != null ? _a76 : readPresenceStatusFromRecord(profile)) != null ? _b9 : "offline"
24285
+ status: resolvedStatus,
24286
+ statusLabel: (_c3 = presenceStatusLabelMap.get(contactId)) != null ? _c3 : PRESENCE_STATUS_LABELS[resolvedStatus]
24057
24287
  });
24058
24288
  });
24059
24289
  const resolvedUsers = [...usersMap.values()].sort((left, right) => left.name.localeCompare(right.name, "pt-BR"));
@@ -24200,10 +24430,21 @@ var MainNavbar = ({
24200
24430
  table: USER_PRESENCE_TABLE
24201
24431
  },
24202
24432
  (payload) => {
24433
+ var _a79, _b8;
24203
24434
  const row = payload.new || payload.old;
24204
- const userId = toStringOrUndefined(row[USER_PRESENCE_USER_ID_COLUMN]);
24435
+ const userId = toStringOrUndefined((_b8 = (_a79 = row[USER_PRESENCE_USER_ID_COLUMN]) != null ? _a79 : row.user_id) != null ? _b8 : row.id);
24205
24436
  if (!userId || userId === effectiveCurrentUserId) return;
24206
- const nextStatus = payload.eventType === "DELETE" ? "offline" : normalizePresenceStatus(row[USER_PRESENCE_STATUS_COLUMN]);
24437
+ let nextStatus = "offline";
24438
+ let nextStatusLabel = PRESENCE_STATUS_LABELS.offline;
24439
+ if (payload.eventType === "DELETE") {
24440
+ presenceSnapshotsRef.current.delete(userId);
24441
+ } else {
24442
+ const snapshot = readPresenceSnapshotFromRecord(row);
24443
+ if (!snapshot) return;
24444
+ presenceSnapshotsRef.current.set(userId, snapshot);
24445
+ nextStatus = resolveEffectivePresenceStatus(snapshot);
24446
+ nextStatusLabel = resolvePresenceStatusLabel(snapshot, nextStatus);
24447
+ }
24207
24448
  setChatUsers((current) => {
24208
24449
  const index = current.findIndex((user) => user.id === userId);
24209
24450
  if (index === -1) {
@@ -24214,12 +24455,13 @@ var MainNavbar = ({
24214
24455
  id: userId,
24215
24456
  name: resolveReadableUserLabel(void 0, void 0, void 0, userId),
24216
24457
  username,
24217
- status: nextStatus
24458
+ status: nextStatus,
24459
+ statusLabel: nextStatusLabel
24218
24460
  }
24219
24461
  ].sort((left, right) => left.name.localeCompare(right.name, "pt-BR"));
24220
24462
  }
24221
24463
  const updated = [...current];
24222
- updated[index] = { ...updated[index], status: nextStatus };
24464
+ updated[index] = { ...updated[index], status: nextStatus, statusLabel: nextStatusLabel };
24223
24465
  return updated;
24224
24466
  });
24225
24467
  }
@@ -24235,13 +24477,39 @@ var MainNavbar = ({
24235
24477
  void supabase.removeChannel(presenceChannel);
24236
24478
  };
24237
24479
  }, [effectiveCurrentUserId, isAuthenticated, isChatSuperAdmin]);
24480
+ (0, import_react19.useEffect)(() => {
24481
+ if (!isAuthenticated) return;
24482
+ const intervalId = window.setInterval(() => {
24483
+ const now = Date.now();
24484
+ setChatUsers((current) => {
24485
+ let hasChanges = false;
24486
+ const nextUsers = current.map((entry) => {
24487
+ const snapshot = presenceSnapshotsRef.current.get(entry.id);
24488
+ if (!snapshot) return entry;
24489
+ const effectiveStatus = resolveEffectivePresenceStatus(snapshot, now);
24490
+ const effectiveStatusLabel = resolvePresenceStatusLabel(snapshot, effectiveStatus, now);
24491
+ if (entry.status === effectiveStatus && entry.statusLabel === effectiveStatusLabel) return entry;
24492
+ hasChanges = true;
24493
+ return {
24494
+ ...entry,
24495
+ status: effectiveStatus,
24496
+ statusLabel: effectiveStatusLabel
24497
+ };
24498
+ });
24499
+ return hasChanges ? nextUsers : current;
24500
+ });
24501
+ }, PRESENCE_RECALC_INTERVAL_MS);
24502
+ return () => {
24503
+ window.clearInterval(intervalId);
24504
+ };
24505
+ }, [isAuthenticated]);
24238
24506
  const chatUnreadByUser = (0, import_react19.useMemo)(() => {
24239
24507
  const counters = {};
24240
24508
  chatMessages.forEach((message) => {
24241
- var _a75;
24509
+ var _a79;
24242
24510
  if (message.sender !== "them") return;
24243
24511
  if (message.readAt) return;
24244
- counters[message.contactId] = ((_a75 = counters[message.contactId]) != null ? _a75 : 0) + 1;
24512
+ counters[message.contactId] = ((_a79 = counters[message.contactId]) != null ? _a79 : 0) + 1;
24245
24513
  });
24246
24514
  return counters;
24247
24515
  }, [chatMessages]);
@@ -24289,9 +24557,9 @@ var MainNavbar = ({
24289
24557
  }
24290
24558
  const persistedReadAtByMessageId = /* @__PURE__ */ new Map();
24291
24559
  (data != null ? data : []).forEach((row) => {
24292
- var _a75;
24560
+ var _a79;
24293
24561
  const messageId = toStringOrUndefined(row[CHAT_MESSAGES_ID_COLUMN]);
24294
- const persistedReadAt = (_a75 = toStringOrUndefined(row[CHAT_MESSAGES_READ_AT_COLUMN])) != null ? _a75 : readAt;
24562
+ const persistedReadAt = (_a79 = toStringOrUndefined(row[CHAT_MESSAGES_READ_AT_COLUMN])) != null ? _a79 : readAt;
24295
24563
  if (!messageId) return;
24296
24564
  persistedReadAtByMessageId.set(messageId, persistedReadAt);
24297
24565
  });
@@ -24460,8 +24728,8 @@ var MainNavbar = ({
24460
24728
  (current) => dedupeAndSortMessages(
24461
24729
  current.map(
24462
24730
  (message) => {
24463
- var _a75;
24464
- return message.id === messageId ? { ...message, text: previousText, editedAt: (_a75 = targetMessage.editedAt) != null ? _a75 : null } : message;
24731
+ var _a79;
24732
+ return message.id === messageId ? { ...message, text: previousText, editedAt: (_a79 = targetMessage.editedAt) != null ? _a79 : null } : message;
24465
24733
  }
24466
24734
  )
24467
24735
  )
@@ -24492,13 +24760,13 @@ var MainNavbar = ({
24492
24760
  (current) => dedupeAndSortMessages(
24493
24761
  current.map(
24494
24762
  (message) => {
24495
- var _a75;
24763
+ var _a79;
24496
24764
  return message.id === messageId ? {
24497
24765
  ...message,
24498
24766
  text: CHAT_DELETED_PLACEHOLDER_TEXT2,
24499
24767
  deletedAt,
24500
24768
  deletedBy: effectiveCurrentUserId,
24501
- editedAt: (_a75 = message.editedAt) != null ? _a75 : deletedAt
24769
+ editedAt: (_a79 = message.editedAt) != null ? _a79 : deletedAt
24502
24770
  } : message;
24503
24771
  }
24504
24772
  )
@@ -24682,8 +24950,8 @@ var MainNavbar = ({
24682
24950
  ...item,
24683
24951
  isActive,
24684
24952
  onClick: isAnchor ? item.onClick : (event) => {
24685
- var _a75;
24686
- (_a75 = item.onClick) == null ? void 0 : _a75.call(item, event);
24953
+ var _a79;
24954
+ (_a79 = item.onClick) == null ? void 0 : _a79.call(item, event);
24687
24955
  if (!onNavigate || event.defaultPrevented) return;
24688
24956
  event.preventDefault();
24689
24957
  onNavigate(item.href);
@@ -24725,9 +24993,9 @@ var MainNavbar = ({
24725
24993
  window.open(`${MC_BASE_URL2}/tasks`, "_blank", "noopener,noreferrer");
24726
24994
  };
24727
24995
  const handleChatOpenUserProfile = (0, import_react19.useCallback)(({ userId }) => {
24728
- var _a75;
24996
+ var _a79;
24729
24997
  if (!userId || typeof window === "undefined") return;
24730
- const baseUrl = ((_a75 = getRuntimeEnv("VITE_ACCOUNTS_BASE_URL")) != null ? _a75 : "https://accounts.cupcode.com.br").replace(
24998
+ const baseUrl = ((_a79 = getRuntimeEnv("VITE_ACCOUNTS_BASE_URL")) != null ? _a79 : "https://accounts.cupcode.com.br").replace(
24731
24999
  /\/+$/,
24732
25000
  ""
24733
25001
  );
@@ -24797,8 +25065,8 @@ var MainNavbar = ({
24797
25065
  );
24798
25066
  const handleProfileAvatarChange = (0, import_react19.useCallback)(
24799
25067
  async ({ avatarId, avatarUrl }) => {
24800
- var _a75;
24801
- const normalizedAvatarId = (_a75 = parseAssetId(avatarId)) != null ? _a75 : parseAssetId(avatarUrl);
25068
+ var _a79;
25069
+ const normalizedAvatarId = (_a79 = parseAssetId(avatarId)) != null ? _a79 : parseAssetId(avatarUrl);
24802
25070
  if (!normalizedAvatarId) {
24803
25071
  throw new Error("ID da imagem inv\xE1lido.");
24804
25072
  }
@@ -24814,27 +25082,27 @@ var MainNavbar = ({
24814
25082
  );
24815
25083
  const updateErrors = [];
24816
25084
  const isRecoverableUpdateError = (error) => {
24817
- var _a76;
24818
- const message = ((_a76 = error.message) != null ? _a76 : "").toLowerCase();
25085
+ var _a80;
25086
+ const message = ((_a80 = error.message) != null ? _a80 : "").toLowerCase();
24819
25087
  return error.code === "55000" || error.code === "42P01" || error.code === "42703" || error.code === "42501" || error.code === "22P02" || message.includes("cannot update view") || message.includes("not automatically updatable") || message.includes("permission denied") || message.includes("invalid input syntax") || message.includes("relation") && message.includes("does not exist") || message.includes("column") && message.includes("does not exist");
24820
25088
  };
24821
25089
  const isRecoverableLookupError2 = (error) => {
24822
- var _a76;
24823
- const message = ((_a76 = error.message) != null ? _a76 : "").toLowerCase();
25090
+ var _a80;
25091
+ const message = ((_a80 = error.message) != null ? _a80 : "").toLowerCase();
24824
25092
  return error.code === "42P01" || error.code === "42703" || error.code === "42501" || message.includes("relation") && message.includes("does not exist") || message.includes("column") && message.includes("does not exist") || message.includes("permission denied");
24825
25093
  };
24826
25094
  const isPermissionDeniedError2 = (error) => {
24827
- var _a76;
24828
- const message = ((_a76 = error.message) != null ? _a76 : "").toLowerCase();
25095
+ var _a80;
25096
+ const message = ((_a80 = error.message) != null ? _a80 : "").toLowerCase();
24829
25097
  return error.code === "42501" || message.includes("permission denied");
24830
25098
  };
24831
25099
  const updateAvatarByUserId = async (userId) => {
24832
- var _a76, _b8, _c2, _d, _e;
25100
+ var _a80, _b8, _c2, _d, _e;
24833
25101
  for (const tableName of updateTargets) {
24834
25102
  const updateWithSelect = await supabase.from(tableName).update({ [CHAT_USERS_UPDATE_AVATAR_COLUMN]: normalizedAvatarId }).eq(CHAT_USERS_UPDATE_ID_COLUMN, userId).select(CHAT_USERS_UPDATE_ID_COLUMN).limit(1);
24835
25103
  if (!updateWithSelect.error) {
24836
25104
  const rows = updateWithSelect.data;
24837
- const row = (_a76 = rows == null ? void 0 : rows[0]) != null ? _a76 : null;
25105
+ const row = (_a80 = rows == null ? void 0 : rows[0]) != null ? _a80 : null;
24838
25106
  if (row) {
24839
25107
  return row;
24840
25108
  }
@@ -24866,13 +25134,13 @@ var MainNavbar = ({
24866
25134
  return null;
24867
25135
  };
24868
25136
  const resolveUserIdByEmail = async (emailValue) => {
24869
- var _a76;
25137
+ var _a80;
24870
25138
  let lastRecoverableError = null;
24871
25139
  for (const tableName of lookupTargets) {
24872
25140
  const { data, error } = await supabase.from(tableName).select(CHAT_USERS_UPDATE_ID_COLUMN).ilike(CHAT_USERS_UPDATE_EMAIL_COLUMN, emailValue).limit(1);
24873
25141
  if (!error) {
24874
25142
  const rows = data;
24875
- const resolvedId = toStringOrUndefined((_a76 = rows == null ? void 0 : rows[0]) == null ? void 0 : _a76[CHAT_USERS_UPDATE_ID_COLUMN]);
25143
+ const resolvedId = toStringOrUndefined((_a80 = rows == null ? void 0 : rows[0]) == null ? void 0 : _a80[CHAT_USERS_UPDATE_ID_COLUMN]);
24876
25144
  if (resolvedId) {
24877
25145
  return resolvedId;
24878
25146
  }
@@ -25494,10 +25762,10 @@ function isThemeMode(value) {
25494
25762
  return value === "light" || value === "dark";
25495
25763
  }
25496
25764
  function readStoredTheme() {
25497
- var _a74;
25765
+ var _a78;
25498
25766
  if (typeof window === "undefined") return null;
25499
25767
  try {
25500
- const storedTheme = (_a74 = window.localStorage.getItem(THEME_STORAGE_KEY2)) != null ? _a74 : window.localStorage.getItem("theme");
25768
+ const storedTheme = (_a78 = window.localStorage.getItem(THEME_STORAGE_KEY2)) != null ? _a78 : window.localStorage.getItem("theme");
25501
25769
  return isThemeMode(storedTheme) ? storedTheme : null;
25502
25770
  } catch (e) {
25503
25771
  return null;
@@ -25534,11 +25802,11 @@ var ThemeToggle = ({
25534
25802
  defaultTheme = "light",
25535
25803
  onThemeChange
25536
25804
  }) => {
25537
- var _a74;
25805
+ var _a78;
25538
25806
  const [mounted, setMounted] = React34.useState(false);
25539
25807
  const [internalTheme, setInternalTheme] = React34.useState(defaultTheme);
25540
25808
  const isControlled = typeof theme !== "undefined";
25541
- const activeTheme = (_a74 = isControlled ? theme : internalTheme) != null ? _a74 : defaultTheme;
25809
+ const activeTheme = (_a78 = isControlled ? theme : internalTheme) != null ? _a78 : defaultTheme;
25542
25810
  React34.useEffect(() => {
25543
25811
  if (!isControlled) {
25544
25812
  setInternalTheme(resolveTheme(defaultTheme));
@@ -26176,8 +26444,8 @@ var ChartStyle = ({ id, config }) => {
26176
26444
  ([theme, prefix]) => `
26177
26445
  ${prefix} [data-chart=${id}] {
26178
26446
  ${colorConfig.map(([key, itemConfig]) => {
26179
- var _a74;
26180
- const color = ((_a74 = itemConfig.theme) == null ? void 0 : _a74[theme]) || itemConfig.color;
26447
+ var _a78;
26448
+ const color = ((_a78 = itemConfig.theme) == null ? void 0 : _a78[theme]) || itemConfig.color;
26181
26449
  return color ? ` --color-${key}: ${color};` : null;
26182
26450
  }).join("\n")}
26183
26451
  }
@@ -26206,14 +26474,14 @@ var ChartTooltipContent = React41.forwardRef(
26206
26474
  }, ref) => {
26207
26475
  const { config } = useChart();
26208
26476
  const tooltipLabel = React41.useMemo(() => {
26209
- var _a74;
26477
+ var _a78;
26210
26478
  if (hideLabel || !(payload == null ? void 0 : payload.length)) {
26211
26479
  return null;
26212
26480
  }
26213
26481
  const [item] = payload;
26214
26482
  const key = `${labelKey || item.dataKey || item.name || "value"}`;
26215
26483
  const itemConfig = getPayloadConfigFromPayload(config, item, key);
26216
- const value = !labelKey && typeof label === "string" ? ((_a74 = config[label]) == null ? void 0 : _a74.label) || label : itemConfig == null ? void 0 : itemConfig.label;
26484
+ const value = !labelKey && typeof label === "string" ? ((_a78 = config[label]) == null ? void 0 : _a78.label) || label : itemConfig == null ? void 0 : itemConfig.label;
26217
26485
  if (labelFormatter) {
26218
26486
  return /* @__PURE__ */ (0, import_jsx_runtime64.jsx)("div", { className: cn("font-medium", labelClassName), children: labelFormatter(value, payload) });
26219
26487
  }
@@ -27898,8 +28166,8 @@ ToggleGroupItem.displayName = ToggleGroupPrimitive.Item.displayName;
27898
28166
  // src/hooks/useActiveSection.ts
27899
28167
  var import_react21 = require("react");
27900
28168
  var useActiveSection = (sectionIds, offset = 180) => {
27901
- var _a74;
27902
- const [activeId, setActiveId] = (0, import_react21.useState)((_a74 = sectionIds[0]) != null ? _a74 : "");
28169
+ var _a78;
28170
+ const [activeId, setActiveId] = (0, import_react21.useState)((_a78 = sectionIds[0]) != null ? _a78 : "");
27903
28171
  (0, import_react21.useEffect)(() => {
27904
28172
  if (!sectionIds.length || typeof window === "undefined") return;
27905
28173
  const update = () => {
@@ -27944,29 +28212,40 @@ var STORAGE_KEYS = {
27944
28212
  presenceSource: "cc_user_presence_source"
27945
28213
  };
27946
28214
  var LOCAL_STORAGE_KEYS = {
27947
- lastActivityAt: "cc_last_activity_at",
27948
28215
  presenceSource: "cc_user_presence_source"
27949
28216
  };
27950
- var _a64;
27951
- var USER_PRESENCE_TABLE2 = ((_a64 = getRuntimeEnv("VITE_USER_PRESENCE_TABLE")) != null ? _a64 : "user_presence").trim();
27952
- var _a65;
27953
- var USER_PRESENCE_USER_ID_COLUMN2 = ((_a65 = getRuntimeEnv("VITE_USER_PRESENCE_USER_ID_COLUMN")) != null ? _a65 : "user_id").trim();
27954
28217
  var _a66;
27955
- var USER_PRESENCE_STATUS_COLUMN2 = ((_a66 = getRuntimeEnv("VITE_USER_PRESENCE_STATUS_COLUMN")) != null ? _a66 : "status").trim();
27956
- var _a67, _b6;
27957
- var SUPABASE_CHAT_SCHEMA = ((_b6 = (_a67 = getRuntimeEnv("VITE_CHAT_SCHEMA")) != null ? _a67 : getRuntimeEnv("VITE_SUPABASE_SCHEMA")) != null ? _b6 : "public").trim();
28218
+ var USER_PRESENCE_TABLE2 = ((_a66 = getRuntimeEnv("VITE_USER_PRESENCE_TABLE")) != null ? _a66 : "user_presence").trim();
28219
+ var _a67;
28220
+ var USER_PRESENCE_USER_ID_COLUMN2 = ((_a67 = getRuntimeEnv("VITE_USER_PRESENCE_USER_ID_COLUMN")) != null ? _a67 : "user_id").trim();
27958
28221
  var _a68;
27959
- var CHAT_USERS_TABLE2 = ((_a68 = getRuntimeEnv("VITE_CHAT_USERS_TABLE")) != null ? _a68 : "chat_users").trim();
28222
+ var USER_PRESENCE_STATUS_COLUMN2 = ((_a68 = getRuntimeEnv("VITE_USER_PRESENCE_STATUS_COLUMN")) != null ? _a68 : "status").trim();
27960
28223
  var _a69;
27961
- var CHAT_USERS_ID_COLUMN2 = ((_a69 = getRuntimeEnv("VITE_CHAT_USERS_ID_COLUMN")) != null ? _a69 : "id").trim();
28224
+ var USER_PRESENCE_SOURCE_COLUMN2 = ((_a69 = getRuntimeEnv("VITE_USER_PRESENCE_SOURCE_COLUMN")) != null ? _a69 : "status_source").trim();
27962
28225
  var _a70;
27963
- var CHAT_USERS_EMAIL_COLUMN2 = ((_a70 = getRuntimeEnv("VITE_CHAT_USERS_EMAIL_COLUMN")) != null ? _a70 : "email").trim();
27964
- var _a71;
27965
- var CHAT_USERS_UPDATE_TABLE2 = ((_a71 = getRuntimeEnv("VITE_CHAT_USERS_UPDATE_TABLE")) != null ? _a71 : "profiles").trim();
28226
+ var USER_PRESENCE_LAST_ACTIVE_COLUMN2 = ((_a70 = getRuntimeEnv("VITE_USER_PRESENCE_LAST_ACTIVE_COLUMN")) != null ? _a70 : "last_active_at").trim();
28227
+ var _a71, _b6;
28228
+ var SUPABASE_CHAT_SCHEMA = ((_b6 = (_a71 = getRuntimeEnv("VITE_CHAT_SCHEMA")) != null ? _a71 : getRuntimeEnv("VITE_SUPABASE_SCHEMA")) != null ? _b6 : "public").trim();
28229
+ var PRESENCE_TOUCH_RPC = "cc_presence_touch";
28230
+ var PRESENCE_MARK_IDLE_RPC = "cc_presence_mark_idle";
28231
+ var PRESENCE_SET_STATUS_RPC = "cc_presence_set_status";
28232
+ var parsePositiveInteger2 = (rawValue, fallback) => {
28233
+ const parsed = Number(rawValue);
28234
+ if (!Number.isFinite(parsed) || parsed <= 0) return fallback;
28235
+ return Math.floor(parsed);
28236
+ };
27966
28237
  var _a72;
27967
- var CHAT_USERS_UPDATE_ID_COLUMN2 = ((_a72 = getRuntimeEnv("VITE_CHAT_USERS_UPDATE_ID_COLUMN")) != null ? _a72 : "id").trim();
28238
+ var CHAT_USERS_TABLE2 = ((_a72 = getRuntimeEnv("VITE_CHAT_USERS_TABLE")) != null ? _a72 : "chat_users").trim();
27968
28239
  var _a73;
27969
- var CHAT_USERS_UPDATE_EMAIL_COLUMN2 = ((_a73 = getRuntimeEnv("VITE_CHAT_USERS_UPDATE_EMAIL_COLUMN")) != null ? _a73 : "email").trim();
28240
+ var CHAT_USERS_ID_COLUMN2 = ((_a73 = getRuntimeEnv("VITE_CHAT_USERS_ID_COLUMN")) != null ? _a73 : "id").trim();
28241
+ var _a74;
28242
+ var CHAT_USERS_EMAIL_COLUMN2 = ((_a74 = getRuntimeEnv("VITE_CHAT_USERS_EMAIL_COLUMN")) != null ? _a74 : "email").trim();
28243
+ var _a75;
28244
+ var CHAT_USERS_UPDATE_TABLE2 = ((_a75 = getRuntimeEnv("VITE_CHAT_USERS_UPDATE_TABLE")) != null ? _a75 : "profiles").trim();
28245
+ var _a76;
28246
+ var CHAT_USERS_UPDATE_ID_COLUMN2 = ((_a76 = getRuntimeEnv("VITE_CHAT_USERS_UPDATE_ID_COLUMN")) != null ? _a76 : "id").trim();
28247
+ var _a77;
28248
+ var CHAT_USERS_UPDATE_EMAIL_COLUMN2 = ((_a77 = getRuntimeEnv("VITE_CHAT_USERS_UPDATE_EMAIL_COLUMN")) != null ? _a77 : "email").trim();
27970
28249
  var PRESENCE_USER_LOOKUP_TABLES = Array.from(
27971
28250
  new Set(
27972
28251
  [CHAT_USERS_UPDATE_TABLE2, CHAT_USERS_TABLE2, "profiles", "chat_users"].map((entry) => entry.trim()).filter((entry) => entry.length > 0)
@@ -27982,8 +28261,19 @@ var PRESENCE_USER_LOOKUP_EMAIL_COLUMNS = Array.from(
27982
28261
  [CHAT_USERS_UPDATE_EMAIL_COLUMN2, CHAT_USERS_EMAIL_COLUMN2, "email"].map((entry) => entry.trim()).filter((entry) => entry.length > 0)
27983
28262
  )
27984
28263
  );
27985
- var AWAY_AFTER_MS = 10 * 60 * 1e3;
27986
- var ACTIVITY_BROADCAST_THROTTLE_MS = 5e3;
28264
+ var AWAY_AFTER_MS = parsePositiveInteger2(getRuntimeEnv("VITE_PRESENCE_IDLE_TIMEOUT_MS"), 10 * 60 * 1e3);
28265
+ var OFFLINE_AFTER_MS = Math.max(
28266
+ parsePositiveInteger2(getRuntimeEnv("VITE_PRESENCE_OFFLINE_TIMEOUT_MS"), 10 * 60 * 1e3),
28267
+ AWAY_AFTER_MS
28268
+ );
28269
+ var ACTIVITY_BROADCAST_THROTTLE_MS = parsePositiveInteger2(
28270
+ getRuntimeEnv("VITE_PRESENCE_ACTIVITY_THROTTLE_MS"),
28271
+ 15e3
28272
+ );
28273
+ var PRESENCE_HEARTBEAT_INTERVAL_MS = parsePositiveInteger2(
28274
+ getRuntimeEnv("VITE_PRESENCE_HEARTBEAT_INTERVAL_MS"),
28275
+ 3e4
28276
+ );
27987
28277
  var INACTIVITY_CHECK_INTERVAL_MS = 3e4;
27988
28278
  var SILENT_AUTH_ERRORS = /* @__PURE__ */ new Set(["login_required", "interaction_required", "consent_required", "account_selection_required"]);
27989
28279
  var DEFAULT_PRESENCE_STATUS = "online";
@@ -27997,14 +28287,55 @@ var PRESENCE_STATUS_VALUES2 = [
27997
28287
  "designing",
27998
28288
  "offline"
27999
28289
  ];
28290
+ var PRESENCE_SOURCES = ["auto", "manual", "system"];
28000
28291
  var isUserPresenceStatus = (value) => {
28001
28292
  return typeof value === "string" && PRESENCE_STATUS_VALUES2.includes(value);
28002
28293
  };
28294
+ var isPresenceSource = (value) => {
28295
+ return typeof value === "string" && PRESENCE_SOURCES.includes(value);
28296
+ };
28003
28297
  var toNonEmptyString = (value) => {
28004
28298
  if (typeof value !== "string") return void 0;
28005
28299
  const trimmed = value.trim();
28006
28300
  return trimmed === "" ? void 0 : trimmed;
28007
28301
  };
28302
+ var normalizePresenceSource2 = (value) => {
28303
+ if (typeof value !== "string") return "auto";
28304
+ const normalized = value.trim().toLowerCase();
28305
+ return isPresenceSource(normalized) ? normalized : "auto";
28306
+ };
28307
+ var toTimestampMs2 = (value) => {
28308
+ if (typeof value === "number" && Number.isFinite(value)) {
28309
+ const epochMs = value > 1e12 ? value : value * 1e3;
28310
+ return epochMs;
28311
+ }
28312
+ if (typeof value !== "string") return void 0;
28313
+ const trimmed = value.trim();
28314
+ if (!trimmed) return void 0;
28315
+ const parsed = new Date(trimmed).getTime();
28316
+ return Number.isNaN(parsed) ? void 0 : parsed;
28317
+ };
28318
+ var readPresenceRow = (payload) => {
28319
+ if (!payload) return null;
28320
+ if (Array.isArray(payload)) {
28321
+ const first = payload.find((entry) => typeof entry === "object" && entry !== null);
28322
+ return first != null ? first : null;
28323
+ }
28324
+ if (typeof payload === "object") {
28325
+ return payload;
28326
+ }
28327
+ return null;
28328
+ };
28329
+ var isMissingColumnError2 = (error, column) => {
28330
+ var _a78;
28331
+ const message = ((_a78 = error == null ? void 0 : error.message) != null ? _a78 : "").toLowerCase();
28332
+ const code = error == null ? void 0 : error.code;
28333
+ const token = column.trim().toLowerCase();
28334
+ if (!token) return false;
28335
+ if (!message.includes(token)) return false;
28336
+ if (code === "42703" || code === "PGRST204") return true;
28337
+ return message.includes("column") && (message.includes("does not exist") || message.includes("could not find"));
28338
+ };
28008
28339
  var readFirstRecordString2 = (row, keys) => {
28009
28340
  if (!row) return void 0;
28010
28341
  for (const key of keys) {
@@ -28019,9 +28350,10 @@ var readStoredPresence = () => {
28019
28350
  return isUserPresenceStatus(stored) ? stored : DEFAULT_PRESENCE_STATUS;
28020
28351
  };
28021
28352
  var readStoredPresenceSource = () => {
28022
- var _a74;
28023
- const stored = (_a74 = sessionStorage.getItem(STORAGE_KEYS.presenceSource)) != null ? _a74 : localStorage.getItem(LOCAL_STORAGE_KEYS.presenceSource);
28024
- return stored === "system" ? "system" : "manual";
28353
+ var _a78;
28354
+ const stored = (_a78 = sessionStorage.getItem(STORAGE_KEYS.presenceSource)) != null ? _a78 : localStorage.getItem(LOCAL_STORAGE_KEYS.presenceSource);
28355
+ if (isPresenceSource(stored)) return stored;
28356
+ return "auto";
28025
28357
  };
28026
28358
  var AuthContext = (0, import_react22.createContext)(void 0);
28027
28359
  var readStoredToken = () => {
@@ -28038,36 +28370,107 @@ var readStoredToken = () => {
28038
28370
  return { accessToken, idToken };
28039
28371
  };
28040
28372
  var storeTokens = (tokens) => {
28041
- var _a74;
28042
28373
  sessionStorage.setItem(STORAGE_KEYS.accessToken, tokens.accessToken);
28043
- if (tokens.idToken) sessionStorage.setItem(STORAGE_KEYS.idToken, tokens.idToken);
28044
- if (tokens.refreshToken) sessionStorage.setItem(STORAGE_KEYS.refreshToken, tokens.refreshToken);
28045
- const expiresAt2 = Date.now() + ((_a74 = tokens.expiresIn) != null ? _a74 : 3600) * 1e3;
28374
+ if (tokens.idToken) {
28375
+ sessionStorage.setItem(STORAGE_KEYS.idToken, tokens.idToken);
28376
+ } else {
28377
+ sessionStorage.removeItem(STORAGE_KEYS.idToken);
28378
+ }
28379
+ if (tokens.refreshToken) {
28380
+ sessionStorage.setItem(STORAGE_KEYS.refreshToken, tokens.refreshToken);
28381
+ } else {
28382
+ sessionStorage.removeItem(STORAGE_KEYS.refreshToken);
28383
+ }
28384
+ const expiresInSeconds = Number(tokens.expiresIn);
28385
+ const validExpiresInSeconds = Number.isFinite(expiresInSeconds) && expiresInSeconds > 0 ? expiresInSeconds : 3600;
28386
+ const expiresAt2 = Date.now() + validExpiresInSeconds * 1e3;
28046
28387
  sessionStorage.setItem(STORAGE_KEYS.expiresAt, String(expiresAt2));
28047
28388
  };
28048
28389
  var clearTokens = () => {
28049
28390
  Object.values(STORAGE_KEYS).forEach((key) => sessionStorage.removeItem(key));
28050
28391
  };
28051
- var buildUserFromToken = (idToken) => {
28052
- var _a74, _b7, _c, _d, _e, _f, _g, _h;
28053
- const payload = decodeJwt(idToken);
28054
- if (!payload) return null;
28055
- const resolvedId = (_d = (_c = (_b7 = (_a74 = toNonEmptyString(payload["https://cupcode.com/user_id"])) != null ? _a74 : toNonEmptyString(payload.user_id)) != null ? _b7 : toNonEmptyString(payload.userId)) != null ? _c : toNonEmptyString(payload.uid)) != null ? _d : toNonEmptyString(payload.id);
28056
- const roleClaim = (_e = payload.role) != null ? _e : payload.roles;
28057
- const resolvedRole = typeof roleClaim === "string" ? roleClaim : Array.isArray(roleClaim) ? roleClaim.find((entry) => typeof entry === "string") : void 0;
28058
- const jobTitleClaim = (_g = (_f = payload.job_title) != null ? _f : payload.jobTitle) != null ? _g : payload.title;
28059
- const resolvedJobTitle = typeof jobTitleClaim === "string" ? jobTitleClaim : void 0;
28392
+ var readClaimValue = (claims, keys) => {
28393
+ if (!claims) return void 0;
28394
+ for (const key of keys) {
28395
+ const value = toNonEmptyString(claims[key]);
28396
+ if (value) return value;
28397
+ }
28398
+ return void 0;
28399
+ };
28400
+ var readClaimRole = (claims) => {
28401
+ var _a78, _b7, _c;
28402
+ if (!claims) return void 0;
28403
+ const roleClaim = (_c = (_b7 = (_a78 = claims.role) != null ? _a78 : claims.roles) != null ? _b7 : claims["https://cupcode.com/role"]) != null ? _c : claims["https://cupcode.com/roles"];
28404
+ if (typeof roleClaim === "string") return toNonEmptyString(roleClaim);
28405
+ if (Array.isArray(roleClaim)) {
28406
+ return roleClaim.find((entry) => typeof entry === "string" && entry.trim() !== "");
28407
+ }
28408
+ return void 0;
28409
+ };
28410
+ var buildUserFromTokens = ({
28411
+ idToken,
28412
+ accessToken
28413
+ }) => {
28414
+ var _a78;
28415
+ const idClaims = decodeJwt(idToken != null ? idToken : void 0);
28416
+ const accessClaims = decodeJwt(accessToken != null ? accessToken : void 0);
28417
+ if (!idClaims && !accessClaims) return null;
28418
+ const claimSources = [idClaims, accessClaims];
28419
+ const readFromClaims = (keys) => {
28420
+ for (const claims of claimSources) {
28421
+ const value = readClaimValue(claims, keys);
28422
+ if (value) return value;
28423
+ }
28424
+ return void 0;
28425
+ };
28426
+ const readRole = () => {
28427
+ for (const claims of claimSources) {
28428
+ const value = readClaimRole(claims);
28429
+ if (value) return value;
28430
+ }
28431
+ return void 0;
28432
+ };
28433
+ const resolvedId = readFromClaims([
28434
+ "https://cupcode.com/user_id",
28435
+ "user_id",
28436
+ "userId",
28437
+ "uid",
28438
+ "id",
28439
+ "sub"
28440
+ ]);
28441
+ const resolvedSub = (_a78 = readFromClaims(["sub"])) != null ? _a78 : resolvedId;
28442
+ const preferredUsername = readFromClaims([
28443
+ "preferred_username",
28444
+ "preferredUsername",
28445
+ "username",
28446
+ "user_name",
28447
+ "https://cupcode.com/username"
28448
+ ]);
28449
+ const nickname = readFromClaims(["nickname", "nick", "https://cupcode.com/nickname"]);
28450
+ const email = readFromClaims(["email", "https://cupcode.com/email", "upn", "preferred_username", "preferredUsername"]);
28451
+ const givenName = readFromClaims(["given_name", "givenName", "first_name", "firstName"]);
28452
+ const familyName = readFromClaims(["family_name", "familyName", "last_name", "lastName"]);
28453
+ const fullNameFromClaims = readFromClaims(["name", "full_name", "fullName", "https://cupcode.com/name"]);
28454
+ const derivedName = fullNameFromClaims != null ? fullNameFromClaims : [givenName, familyName].filter(Boolean).join(" ").trim() || void 0;
28455
+ const resolvedPicture = readFromClaims([
28456
+ "picture",
28457
+ "avatar_url",
28458
+ "avatarUrl",
28459
+ "photo_url",
28460
+ "photoURL",
28461
+ "https://cupcode.com/picture"
28462
+ ]);
28060
28463
  return {
28061
- sub: payload.sub,
28464
+ sub: resolvedSub,
28062
28465
  id: resolvedId,
28063
28466
  userId: resolvedId,
28064
- name: payload.name,
28065
- email: payload.email,
28066
- picture: payload.picture,
28067
- preferredUsername: (_h = payload.preferred_username) != null ? _h : payload.preferredUsername,
28068
- nickname: payload.nickname,
28069
- role: resolvedRole,
28070
- jobTitle: resolvedJobTitle
28467
+ name: derivedName,
28468
+ email: (email == null ? void 0 : email.includes("@")) ? email.toLowerCase() : email,
28469
+ picture: resolvedPicture,
28470
+ preferredUsername,
28471
+ nickname,
28472
+ role: readRole(),
28473
+ jobTitle: readFromClaims(["job_title", "jobTitle", "title", "position", "https://cupcode.com/job_title"])
28071
28474
  };
28072
28475
  };
28073
28476
  var AuthProvider = ({ children }) => {
@@ -28077,24 +28480,26 @@ var AuthProvider = ({ children }) => {
28077
28480
  const [presenceStatus, setPresenceStatusState] = (0, import_react22.useState)(() => readStoredPresence());
28078
28481
  const presenceStatusRef = (0, import_react22.useRef)(readStoredPresence());
28079
28482
  const presenceSourceRef = (0, import_react22.useRef)(readStoredPresenceSource());
28080
- const lastManualPresenceRef = (0, import_react22.useRef)(
28081
- readStoredPresence() === "offline" ? DEFAULT_PRESENCE_STATUS : readStoredPresence()
28082
- );
28083
28483
  const lastActivityAtRef = (0, import_react22.useRef)(Date.now());
28084
28484
  const lastActivityBroadcastAtRef = (0, import_react22.useRef)(0);
28085
28485
  const resolvedPresenceIdentityKeyRef = (0, import_react22.useRef)(null);
28086
28486
  const resolvedPresenceUserIdRef = (0, import_react22.useRef)(null);
28087
- const storePresenceStatus = (0, import_react22.useCallback)((nextStatus) => {
28487
+ const storePresenceStatus = (0, import_react22.useCallback)((nextStatus, source) => {
28088
28488
  setPresenceStatusState(nextStatus);
28089
28489
  presenceStatusRef.current = nextStatus;
28090
28490
  sessionStorage.setItem(STORAGE_KEYS.presence, nextStatus);
28491
+ if (source) {
28492
+ presenceSourceRef.current = source;
28493
+ sessionStorage.setItem(STORAGE_KEYS.presenceSource, source);
28494
+ localStorage.setItem(LOCAL_STORAGE_KEYS.presenceSource, source);
28495
+ }
28091
28496
  }, []);
28092
28497
  const resolvePresenceUserId = (0, import_react22.useCallback)(async (targetUser) => {
28093
- var _a74, _b7, _c, _d;
28498
+ var _a78, _b7, _c, _d;
28094
28499
  const sub = toNonEmptyString(targetUser == null ? void 0 : targetUser.sub);
28095
28500
  const id = toNonEmptyString(targetUser == null ? void 0 : targetUser.id);
28096
28501
  const userId = toNonEmptyString(targetUser == null ? void 0 : targetUser.userId);
28097
- const email = (_a74 = toNonEmptyString(targetUser == null ? void 0 : targetUser.email)) == null ? void 0 : _a74.toLowerCase();
28502
+ const email = (_a78 = toNonEmptyString(targetUser == null ? void 0 : targetUser.email)) == null ? void 0 : _a78.toLowerCase();
28098
28503
  const identityKey = [sub != null ? sub : "", id != null ? id : "", userId != null ? userId : "", email != null ? email : ""].join("|");
28099
28504
  if (resolvedPresenceIdentityKeyRef.current === identityKey && resolvedPresenceUserIdRef.current) {
28100
28505
  return resolvedPresenceUserIdRef.current;
@@ -28127,50 +28532,165 @@ var AuthProvider = ({ children }) => {
28127
28532
  resolvedPresenceUserIdRef.current = fallbackUserId;
28128
28533
  return fallbackUserId;
28129
28534
  }, []);
28130
- const persistPresenceStatus = (0, import_react22.useCallback)(
28131
- async (nextStatus, targetUser) => {
28535
+ const syncPresenceFromRecord = (0, import_react22.useCallback)(
28536
+ (rawRow) => {
28537
+ var _a78, _b7, _c;
28538
+ if (!rawRow) return;
28539
+ const statusValue = toNonEmptyString((_a78 = rawRow[USER_PRESENCE_STATUS_COLUMN2]) != null ? _a78 : rawRow.status);
28540
+ if (!isUserPresenceStatus(statusValue)) return;
28541
+ const sourceValue = normalizePresenceSource2((_b7 = rawRow[USER_PRESENCE_SOURCE_COLUMN2]) != null ? _b7 : rawRow.status_source);
28542
+ const lastActiveTimestamp = toTimestampMs2((_c = rawRow[USER_PRESENCE_LAST_ACTIVE_COLUMN2]) != null ? _c : rawRow.last_active_at);
28543
+ if (typeof lastActiveTimestamp === "number" && Number.isFinite(lastActiveTimestamp)) {
28544
+ lastActivityAtRef.current = Math.max(lastActivityAtRef.current, lastActiveTimestamp);
28545
+ }
28546
+ storePresenceStatus(statusValue, sourceValue);
28547
+ },
28548
+ [storePresenceStatus]
28549
+ );
28550
+ const persistPresenceLegacy = (0, import_react22.useCallback)(
28551
+ async (nextStatus, source, targetUser, options) => {
28132
28552
  const userId = await resolvePresenceUserId(targetUser != null ? targetUser : user);
28133
- if (!userId) return;
28553
+ if (!userId) return false;
28134
28554
  const supabase = getSupabase();
28135
- if (!supabase) return;
28555
+ if (!supabase) return false;
28136
28556
  const payload = {
28137
28557
  [USER_PRESENCE_USER_ID_COLUMN2]: userId,
28138
- [USER_PRESENCE_STATUS_COLUMN2]: nextStatus
28558
+ [USER_PRESENCE_STATUS_COLUMN2]: nextStatus,
28559
+ [USER_PRESENCE_SOURCE_COLUMN2]: source
28139
28560
  };
28140
- const { error } = await supabase.from(USER_PRESENCE_TABLE2).upsert(payload, { onConflict: USER_PRESENCE_USER_ID_COLUMN2 });
28141
- if (error && isRuntimeDev()) {
28142
- console.warn("[auth] Falha ao salvar status de presen\xE7a:", error.message);
28561
+ if (options == null ? void 0 : options.updateLastActiveAt) {
28562
+ payload[USER_PRESENCE_LAST_ACTIVE_COLUMN2] = (/* @__PURE__ */ new Date()).toISOString();
28563
+ }
28564
+ let response = await supabase.from(USER_PRESENCE_TABLE2).upsert(payload, { onConflict: USER_PRESENCE_USER_ID_COLUMN2 }).select("*").maybeSingle();
28565
+ if (response.error && (isMissingColumnError2(response.error, USER_PRESENCE_SOURCE_COLUMN2) || isMissingColumnError2(response.error, USER_PRESENCE_LAST_ACTIVE_COLUMN2))) {
28566
+ response = await supabase.from(USER_PRESENCE_TABLE2).upsert(
28567
+ {
28568
+ [USER_PRESENCE_USER_ID_COLUMN2]: userId,
28569
+ [USER_PRESENCE_STATUS_COLUMN2]: nextStatus
28570
+ },
28571
+ { onConflict: USER_PRESENCE_USER_ID_COLUMN2 }
28572
+ ).select("*").maybeSingle();
28573
+ }
28574
+ if (response.error) {
28575
+ if (isRuntimeDev()) {
28576
+ console.warn("[auth] Falha no fallback de presen\xE7a:", response.error.message);
28577
+ }
28578
+ return false;
28143
28579
  }
28580
+ syncPresenceFromRecord(response.data);
28581
+ return true;
28144
28582
  },
28145
- [resolvePresenceUserId, user]
28583
+ [resolvePresenceUserId, syncPresenceFromRecord, user]
28146
28584
  );
28147
- const applyPresenceStatus = (0, import_react22.useCallback)(
28148
- async (nextStatus, source, targetUser) => {
28149
- if (!isUserPresenceStatus(nextStatus)) return;
28150
- storePresenceStatus(nextStatus);
28151
- presenceSourceRef.current = source;
28152
- sessionStorage.setItem(STORAGE_KEYS.presenceSource, source);
28153
- localStorage.setItem(LOCAL_STORAGE_KEYS.presenceSource, source);
28154
- if (source === "manual" && nextStatus !== "offline") {
28155
- lastManualPresenceRef.current = nextStatus;
28585
+ const executePresenceRpc = (0, import_react22.useCallback)(
28586
+ async (fnName, payload, options) => {
28587
+ const supabase = getSupabase();
28588
+ if (!supabase) {
28589
+ if ((options == null ? void 0 : options.fallbackStatus) && options.fallbackSource) {
28590
+ await persistPresenceLegacy(options.fallbackStatus, options.fallbackSource, options.fallbackTargetUser, {
28591
+ updateLastActiveAt: options.updateLastActiveAt
28592
+ });
28593
+ }
28594
+ return false;
28595
+ }
28596
+ const { data, error } = await supabase.rpc(fnName, payload);
28597
+ if (error) {
28598
+ if (isRuntimeDev()) {
28599
+ console.warn(`[auth] Falha ao executar RPC de presen\xE7a (${fnName}):`, error.message);
28600
+ }
28601
+ if ((options == null ? void 0 : options.fallbackStatus) && options.fallbackSource) {
28602
+ await persistPresenceLegacy(options.fallbackStatus, options.fallbackSource, options.fallbackTargetUser, {
28603
+ updateLastActiveAt: options.updateLastActiveAt
28604
+ });
28605
+ }
28606
+ return false;
28156
28607
  }
28157
- await persistPresenceStatus(nextStatus, targetUser);
28608
+ syncPresenceFromRecord(readPresenceRow(data));
28609
+ return true;
28158
28610
  },
28159
- [persistPresenceStatus, storePresenceStatus]
28611
+ [persistPresenceLegacy, syncPresenceFromRecord]
28160
28612
  );
28161
- const syncPresenceFromDatabase = (0, import_react22.useCallback)(
28162
- (nextStatus) => {
28163
- storePresenceStatus(nextStatus);
28164
- const storedSource = readStoredPresenceSource();
28165
- const sourceFromDatabase = nextStatus === "away" ? storedSource : nextStatus === "offline" ? "system" : "manual";
28166
- presenceSourceRef.current = sourceFromDatabase;
28167
- sessionStorage.setItem(STORAGE_KEYS.presenceSource, sourceFromDatabase);
28168
- localStorage.setItem(LOCAL_STORAGE_KEYS.presenceSource, sourceFromDatabase);
28169
- if (nextStatus !== "offline") {
28170
- lastManualPresenceRef.current = nextStatus;
28613
+ const touchPresence = (0, import_react22.useCallback)(
28614
+ async (options) => {
28615
+ var _a78;
28616
+ const targetUser = (_a78 = options == null ? void 0 : options.targetUser) != null ? _a78 : user;
28617
+ const userId = await resolvePresenceUserId(targetUser);
28618
+ if (!userId) return;
28619
+ const now = Date.now();
28620
+ lastActivityAtRef.current = now;
28621
+ if ((options == null ? void 0 : options.throttle) && now - lastActivityBroadcastAtRef.current < ACTIVITY_BROADCAST_THROTTLE_MS) {
28622
+ return;
28171
28623
  }
28624
+ lastActivityBroadcastAtRef.current = now;
28625
+ const fallbackStatus = presenceSourceRef.current === "manual" ? presenceStatusRef.current : "online";
28626
+ const fallbackSource = presenceSourceRef.current === "manual" ? "manual" : "auto";
28627
+ await executePresenceRpc(
28628
+ PRESENCE_TOUCH_RPC,
28629
+ {
28630
+ p_user_id: userId,
28631
+ p_idle_after_seconds: Math.floor(AWAY_AFTER_MS / 1e3),
28632
+ p_force_online: Boolean(options == null ? void 0 : options.forceOnline)
28633
+ },
28634
+ {
28635
+ fallbackStatus,
28636
+ fallbackSource,
28637
+ fallbackTargetUser: targetUser,
28638
+ updateLastActiveAt: true
28639
+ }
28640
+ );
28172
28641
  },
28173
- [storePresenceStatus]
28642
+ [executePresenceRpc, resolvePresenceUserId, user]
28643
+ );
28644
+ const markPresenceIdle = (0, import_react22.useCallback)(
28645
+ async (targetUser) => {
28646
+ const resolvedTargetUser = targetUser != null ? targetUser : user;
28647
+ const userId = await resolvePresenceUserId(resolvedTargetUser);
28648
+ if (!userId) return;
28649
+ const idleMs = Date.now() - lastActivityAtRef.current;
28650
+ const fallbackStatus = idleMs >= OFFLINE_AFTER_MS ? "offline" : "away";
28651
+ const fallbackSource = fallbackStatus === "offline" ? "system" : "auto";
28652
+ await executePresenceRpc(
28653
+ PRESENCE_MARK_IDLE_RPC,
28654
+ {
28655
+ p_user_id: userId,
28656
+ p_idle_after_seconds: Math.floor(AWAY_AFTER_MS / 1e3),
28657
+ p_offline_after_seconds: Math.floor(OFFLINE_AFTER_MS / 1e3)
28658
+ },
28659
+ {
28660
+ fallbackStatus,
28661
+ fallbackSource,
28662
+ fallbackTargetUser: resolvedTargetUser,
28663
+ updateLastActiveAt: false
28664
+ }
28665
+ );
28666
+ },
28667
+ [executePresenceRpc, resolvePresenceUserId, user]
28668
+ );
28669
+ const setPresenceNetworkStatus = (0, import_react22.useCallback)(
28670
+ async (nextStatus, source, targetUser) => {
28671
+ const resolvedTargetUser = targetUser != null ? targetUser : user;
28672
+ const userId = await resolvePresenceUserId(resolvedTargetUser);
28673
+ if (!userId) return;
28674
+ const shouldUpdateLastActiveAt = nextStatus !== "offline";
28675
+ if (shouldUpdateLastActiveAt) {
28676
+ lastActivityAtRef.current = Date.now();
28677
+ }
28678
+ await executePresenceRpc(
28679
+ PRESENCE_SET_STATUS_RPC,
28680
+ {
28681
+ p_user_id: userId,
28682
+ p_status: nextStatus,
28683
+ p_source: source
28684
+ },
28685
+ {
28686
+ fallbackStatus: nextStatus,
28687
+ fallbackSource: source,
28688
+ fallbackTargetUser: resolvedTargetUser,
28689
+ updateLastActiveAt: shouldUpdateLastActiveAt
28690
+ }
28691
+ );
28692
+ },
28693
+ [executePresenceRpc, resolvePresenceUserId, user]
28174
28694
  );
28175
28695
  const loadPresenceFromDatabase = (0, import_react22.useCallback)(
28176
28696
  async (targetUser) => {
@@ -28178,7 +28698,19 @@ var AuthProvider = ({ children }) => {
28178
28698
  if (!userId) return;
28179
28699
  const supabase = getSupabase();
28180
28700
  if (!supabase) return;
28181
- const { data, error } = await supabase.from(USER_PRESENCE_TABLE2).select(USER_PRESENCE_STATUS_COLUMN2).eq(USER_PRESENCE_USER_ID_COLUMN2, userId).maybeSingle();
28701
+ const columns = Array.from(
28702
+ /* @__PURE__ */ new Set([
28703
+ USER_PRESENCE_STATUS_COLUMN2,
28704
+ USER_PRESENCE_SOURCE_COLUMN2,
28705
+ USER_PRESENCE_LAST_ACTIVE_COLUMN2
28706
+ ])
28707
+ ).join(",");
28708
+ let { data, error } = await supabase.from(USER_PRESENCE_TABLE2).select(columns).eq(USER_PRESENCE_USER_ID_COLUMN2, userId).maybeSingle();
28709
+ if (error && (isMissingColumnError2(error, USER_PRESENCE_SOURCE_COLUMN2) || isMissingColumnError2(error, USER_PRESENCE_LAST_ACTIVE_COLUMN2))) {
28710
+ const fallbackResponse = await supabase.from(USER_PRESENCE_TABLE2).select(USER_PRESENCE_STATUS_COLUMN2).eq(USER_PRESENCE_USER_ID_COLUMN2, userId).maybeSingle();
28711
+ data = fallbackResponse.data;
28712
+ error = fallbackResponse.error;
28713
+ }
28182
28714
  if (error) {
28183
28715
  if (isRuntimeDev()) {
28184
28716
  console.warn("[auth] Falha ao carregar status de presen\xE7a:", error.message);
@@ -28186,14 +28718,13 @@ var AuthProvider = ({ children }) => {
28186
28718
  return;
28187
28719
  }
28188
28720
  const row = data;
28189
- const rawStatus = row == null ? void 0 : row[USER_PRESENCE_STATUS_COLUMN2];
28190
- if (!isUserPresenceStatus(rawStatus)) {
28191
- await persistPresenceStatus(presenceStatusRef.current, targetUser);
28721
+ if (!row) {
28722
+ await touchPresence({ targetUser, forceOnline: false, throttle: false });
28192
28723
  return;
28193
28724
  }
28194
- syncPresenceFromDatabase(rawStatus);
28725
+ syncPresenceFromRecord(row);
28195
28726
  },
28196
- [persistPresenceStatus, resolvePresenceUserId, syncPresenceFromDatabase]
28727
+ [resolvePresenceUserId, syncPresenceFromRecord, touchPresence]
28197
28728
  );
28198
28729
  const clearAuthFlowState = (0, import_react22.useCallback)((options) => {
28199
28730
  sessionStorage.removeItem(STORAGE_KEYS.state);
@@ -28207,7 +28738,7 @@ var AuthProvider = ({ children }) => {
28207
28738
  }, []);
28208
28739
  const startAuthorization = (0, import_react22.useCallback)(
28209
28740
  async (options) => {
28210
- var _a74, _b7;
28741
+ var _a78, _b7;
28211
28742
  const config = getAccountsConfig();
28212
28743
  const { authUrl } = await resolveOidcEndpoints(config);
28213
28744
  if (!authUrl) {
@@ -28217,7 +28748,7 @@ var AuthProvider = ({ children }) => {
28217
28748
  const challenge = await generateCodeChallenge(verifier);
28218
28749
  const state = generateState();
28219
28750
  const nonce = generateNonce();
28220
- const redirectTo = (_a74 = options == null ? void 0 : options.redirectTo) != null ? _a74 : window.location.pathname + window.location.search + window.location.hash;
28751
+ const redirectTo = (_a78 = options == null ? void 0 : options.redirectTo) != null ? _a78 : window.location.pathname + window.location.search + window.location.hash;
28221
28752
  const mode = (_b7 = options == null ? void 0 : options.mode) != null ? _b7 : "interactive";
28222
28753
  sessionStorage.setItem(STORAGE_KEYS.verifier, verifier);
28223
28754
  sessionStorage.setItem(STORAGE_KEYS.state, state);
@@ -28245,14 +28776,18 @@ var AuthProvider = ({ children }) => {
28245
28776
  (0, import_react22.useEffect)(() => {
28246
28777
  let cancelled = false;
28247
28778
  const initializeAuth = async () => {
28248
- var _a74;
28779
+ var _a78;
28249
28780
  const stored = readStoredToken();
28250
28781
  const storedPresence = readStoredPresence();
28251
28782
  setPresenceStatusState(storedPresence);
28252
28783
  if (stored == null ? void 0 : stored.accessToken) {
28253
28784
  if (cancelled) return;
28785
+ const hydratedUser = buildUserFromTokens({
28786
+ idToken: (_a78 = stored.idToken) != null ? _a78 : void 0,
28787
+ accessToken: stored.accessToken
28788
+ });
28254
28789
  setAccessToken(stored.accessToken);
28255
- setUser(buildUserFromToken((_a74 = stored.idToken) != null ? _a74 : void 0));
28790
+ setUser(hydratedUser);
28256
28791
  setStatus("authenticated");
28257
28792
  return;
28258
28793
  }
@@ -28279,6 +28814,19 @@ var AuthProvider = ({ children }) => {
28279
28814
  cancelled = true;
28280
28815
  };
28281
28816
  }, [attemptSilentLogin]);
28817
+ (0, import_react22.useEffect)(() => {
28818
+ var _a78;
28819
+ if (status !== "authenticated") return;
28820
+ if (user) return;
28821
+ const stored = readStoredToken();
28822
+ if (!(stored == null ? void 0 : stored.accessToken)) return;
28823
+ const hydratedUser = buildUserFromTokens({
28824
+ idToken: (_a78 = stored.idToken) != null ? _a78 : void 0,
28825
+ accessToken: stored.accessToken
28826
+ });
28827
+ if (!hydratedUser) return;
28828
+ setUser(hydratedUser);
28829
+ }, [status, user]);
28282
28830
  (0, import_react22.useEffect)(() => {
28283
28831
  resolvedPresenceIdentityKeyRef.current = null;
28284
28832
  resolvedPresenceUserIdRef.current = null;
@@ -28304,16 +28852,15 @@ var AuthProvider = ({ children }) => {
28304
28852
  table: USER_PRESENCE_TABLE2
28305
28853
  },
28306
28854
  (payload) => {
28855
+ var _a78, _b7;
28307
28856
  const row = payload.new || payload.old;
28308
- const rowUserId = toNonEmptyString(row == null ? void 0 : row[USER_PRESENCE_USER_ID_COLUMN2]);
28857
+ const rowUserId = toNonEmptyString((_b7 = (_a78 = row == null ? void 0 : row[USER_PRESENCE_USER_ID_COLUMN2]) != null ? _a78 : row == null ? void 0 : row.user_id) != null ? _b7 : row == null ? void 0 : row.id);
28309
28858
  if (!rowUserId || rowUserId !== currentUserId) return;
28310
28859
  if (payload.eventType === "DELETE") {
28311
- syncPresenceFromDatabase("offline");
28860
+ storePresenceStatus("offline", "system");
28312
28861
  return;
28313
28862
  }
28314
- const nextStatus = row == null ? void 0 : row[USER_PRESENCE_STATUS_COLUMN2];
28315
- if (!isUserPresenceStatus(nextStatus)) return;
28316
- syncPresenceFromDatabase(nextStatus);
28863
+ syncPresenceFromRecord(row);
28317
28864
  }
28318
28865
  ).subscribe();
28319
28866
  };
@@ -28324,55 +28871,34 @@ var AuthProvider = ({ children }) => {
28324
28871
  void supabase.removeChannel(presenceChannel);
28325
28872
  }
28326
28873
  };
28327
- }, [resolvePresenceUserId, status, syncPresenceFromDatabase, user]);
28874
+ }, [resolvePresenceUserId, status, storePresenceStatus, syncPresenceFromRecord, user]);
28328
28875
  (0, import_react22.useEffect)(() => {
28329
- var _a74;
28330
28876
  if (status !== "authenticated") return;
28331
- const initialFromStorage = Number((_a74 = localStorage.getItem(LOCAL_STORAGE_KEYS.lastActivityAt)) != null ? _a74 : "0");
28332
- if (Number.isFinite(initialFromStorage) && initialFromStorage > 0) {
28333
- lastActivityAtRef.current = Math.max(lastActivityAtRef.current, initialFromStorage);
28334
- } else {
28335
- const now = Date.now();
28336
- lastActivityAtRef.current = now;
28337
- localStorage.setItem(LOCAL_STORAGE_KEYS.lastActivityAt, String(now));
28338
- }
28339
- const registerActivity = (shouldBroadcast = true) => {
28340
- const now = Date.now();
28341
- lastActivityAtRef.current = now;
28342
- if (shouldBroadcast && now - lastActivityBroadcastAtRef.current >= ACTIVITY_BROADCAST_THROTTLE_MS) {
28343
- lastActivityBroadcastAtRef.current = now;
28344
- localStorage.setItem(LOCAL_STORAGE_KEYS.lastActivityAt, String(now));
28345
- }
28346
- const currentStatus = presenceStatusRef.current;
28347
- if (presenceSourceRef.current === "system" && (currentStatus === "away" || currentStatus === "offline")) {
28348
- void applyPresenceStatus(DEFAULT_PRESENCE_STATUS, "manual");
28349
- }
28877
+ const registerActivity = () => {
28878
+ lastActivityAtRef.current = Date.now();
28879
+ void touchPresence({ throttle: true });
28350
28880
  };
28351
- const onActivity = () => registerActivity(true);
28881
+ const onActivity = () => registerActivity();
28352
28882
  const onVisibility = () => {
28353
28883
  if (document.visibilityState === "visible") {
28354
- registerActivity(true);
28884
+ registerActivity();
28355
28885
  }
28356
28886
  };
28357
- const onStorage = (event) => {
28358
- if (event.key !== LOCAL_STORAGE_KEYS.lastActivityAt || !event.newValue) return;
28359
- const parsed = Number(event.newValue);
28360
- if (!Number.isFinite(parsed) || parsed <= 0) return;
28361
- if (parsed > lastActivityAtRef.current) {
28362
- lastActivityAtRef.current = parsed;
28363
- }
28364
- const elapsed = Date.now() - parsed;
28365
- if (presenceSourceRef.current === "system" && (presenceStatusRef.current === "away" || presenceStatusRef.current === "offline") && elapsed < AWAY_AFTER_MS) {
28366
- void applyPresenceStatus(DEFAULT_PRESENCE_STATUS, "manual");
28367
- }
28368
- };
28369
- const intervalId = window.setInterval(() => {
28887
+ const heartbeatIntervalId = window.setInterval(() => {
28888
+ if (document.visibilityState !== "visible") return;
28370
28889
  const idleMs = Date.now() - lastActivityAtRef.current;
28371
- const currentStatus = presenceStatusRef.current;
28372
- if (idleMs >= AWAY_AFTER_MS) {
28373
- if (currentStatus !== "away" && currentStatus !== "offline") {
28374
- void applyPresenceStatus("away", "system");
28375
- }
28890
+ if (idleMs >= AWAY_AFTER_MS) return;
28891
+ void touchPresence({ throttle: false });
28892
+ }, PRESENCE_HEARTBEAT_INTERVAL_MS);
28893
+ const idleIntervalId = window.setInterval(() => {
28894
+ if (presenceStatusRef.current === "offline") return;
28895
+ const idleMs = Date.now() - lastActivityAtRef.current;
28896
+ if (idleMs >= OFFLINE_AFTER_MS) {
28897
+ void markPresenceIdle();
28898
+ return;
28899
+ }
28900
+ if (presenceSourceRef.current === "auto" && idleMs >= AWAY_AFTER_MS) {
28901
+ void markPresenceIdle();
28376
28902
  }
28377
28903
  }, INACTIVITY_CHECK_INTERVAL_MS);
28378
28904
  window.addEventListener("mousemove", onActivity, { passive: true });
@@ -28382,10 +28908,10 @@ var AuthProvider = ({ children }) => {
28382
28908
  window.addEventListener("touchstart", onActivity, { passive: true });
28383
28909
  window.addEventListener("focus", onActivity);
28384
28910
  document.addEventListener("visibilitychange", onVisibility);
28385
- window.addEventListener("storage", onStorage);
28386
- registerActivity(true);
28911
+ registerActivity();
28387
28912
  return () => {
28388
- window.clearInterval(intervalId);
28913
+ window.clearInterval(heartbeatIntervalId);
28914
+ window.clearInterval(idleIntervalId);
28389
28915
  window.removeEventListener("mousemove", onActivity);
28390
28916
  window.removeEventListener("mousedown", onActivity);
28391
28917
  window.removeEventListener("keydown", onActivity);
@@ -28393,9 +28919,8 @@ var AuthProvider = ({ children }) => {
28393
28919
  window.removeEventListener("touchstart", onActivity);
28394
28920
  window.removeEventListener("focus", onActivity);
28395
28921
  document.removeEventListener("visibilitychange", onVisibility);
28396
- window.removeEventListener("storage", onStorage);
28397
28922
  };
28398
- }, [applyPresenceStatus, status]);
28923
+ }, [markPresenceIdle, status, touchPresence]);
28399
28924
  const login = (0, import_react22.useCallback)(async (redirectTo) => {
28400
28925
  await startAuthorization({
28401
28926
  mode: "interactive",
@@ -28403,9 +28928,9 @@ var AuthProvider = ({ children }) => {
28403
28928
  });
28404
28929
  }, [startAuthorization]);
28405
28930
  const completeLogin = (0, import_react22.useCallback)(async () => {
28406
- var _a74;
28931
+ var _a78;
28407
28932
  const params = new URLSearchParams(window.location.search);
28408
- const redirectTo = (_a74 = sessionStorage.getItem(STORAGE_KEYS.redirect)) != null ? _a74 : "/";
28933
+ const redirectTo = (_a78 = sessionStorage.getItem(STORAGE_KEYS.redirect)) != null ? _a78 : "/";
28409
28934
  const authMode = sessionStorage.getItem(STORAGE_KEYS.authMode);
28410
28935
  const isSilentAuth = authMode === "silent";
28411
28936
  const error = params.get("error");
@@ -28458,8 +28983,12 @@ var AuthProvider = ({ children }) => {
28458
28983
  refreshToken: tokens.refresh_token,
28459
28984
  expiresIn: tokens.expires_in
28460
28985
  });
28986
+ const nextUser = buildUserFromTokens({
28987
+ idToken: tokens.id_token,
28988
+ accessToken: tokens.access_token
28989
+ });
28461
28990
  setAccessToken(tokens.access_token);
28462
- setUser(buildUserFromToken(tokens.id_token));
28991
+ setUser(nextUser);
28463
28992
  setStatus("authenticated");
28464
28993
  clearAuthFlowState();
28465
28994
  return { ok: true, redirectTo };
@@ -28469,42 +28998,40 @@ var AuthProvider = ({ children }) => {
28469
28998
  }
28470
28999
  }, [clearAuthFlowState]);
28471
29000
  const logout = (0, import_react22.useCallback)(async () => {
28472
- var _a74;
29001
+ var _a78;
28473
29002
  const config = getAccountsConfig();
28474
29003
  const { logoutUrl } = await resolveOidcEndpoints(config);
28475
- const idToken = (_a74 = sessionStorage.getItem(STORAGE_KEYS.idToken)) != null ? _a74 : void 0;
29004
+ const idToken = (_a78 = sessionStorage.getItem(STORAGE_KEYS.idToken)) != null ? _a78 : void 0;
28476
29005
  const currentUser = user;
28477
- await persistPresenceStatus("offline", currentUser);
29006
+ await setPresenceNetworkStatus("offline", "system", currentUser);
28478
29007
  clearTokens();
28479
29008
  setAccessToken(null);
28480
29009
  setUser(null);
28481
29010
  setStatus("unauthenticated");
28482
- setPresenceStatusState("offline");
28483
- presenceStatusRef.current = "offline";
28484
- presenceSourceRef.current = "system";
29011
+ storePresenceStatus("offline", "system");
28485
29012
  sessionStorage.removeItem(STORAGE_KEYS.presenceSource);
28486
29013
  localStorage.removeItem(LOCAL_STORAGE_KEYS.presenceSource);
28487
- localStorage.removeItem(LOCAL_STORAGE_KEYS.lastActivityAt);
28488
29014
  const url = buildLogoutUrl(config, logoutUrl, idToken);
28489
29015
  if (url) {
28490
29016
  window.location.assign(url);
28491
29017
  }
28492
- }, [persistPresenceStatus, user]);
29018
+ }, [setPresenceNetworkStatus, storePresenceStatus, user]);
28493
29019
  const getAccessToken = (0, import_react22.useCallback)(async () => {
28494
29020
  const stored = readStoredToken();
28495
29021
  if (stored == null ? void 0 : stored.accessToken) return stored.accessToken;
29022
+ if (accessToken) return accessToken;
28496
29023
  throw new Error("Usu\xE1rio n\xE3o autenticado.");
28497
- }, []);
29024
+ }, [accessToken]);
28498
29025
  const setPresenceStatus = (0, import_react22.useCallback)(
28499
29026
  async (nextStatus) => {
28500
29027
  if (!isUserPresenceStatus(nextStatus) || nextStatus === "offline") return;
28501
29028
  const now = Date.now();
28502
29029
  lastActivityAtRef.current = now;
28503
29030
  lastActivityBroadcastAtRef.current = now;
28504
- localStorage.setItem(LOCAL_STORAGE_KEYS.lastActivityAt, String(now));
28505
- await applyPresenceStatus(nextStatus, "manual");
29031
+ const source = nextStatus === "online" ? "auto" : "manual";
29032
+ await setPresenceNetworkStatus(nextStatus, source);
28506
29033
  },
28507
- [applyPresenceStatus]
29034
+ [setPresenceNetworkStatus]
28508
29035
  );
28509
29036
  const value = (0, import_react22.useMemo)(
28510
29037
  () => ({
@@ -28736,6 +29263,11 @@ var useAuth = () => {
28736
29263
  NavigationMenuList,
28737
29264
  NavigationMenuTrigger,
28738
29265
  NavigationMenuViewport,
29266
+ PRESENCE_ACTIVITY_THROTTLE_MS_ENV_KEY,
29267
+ PRESENCE_HEARTBEAT_INTERVAL_MS_ENV_KEY,
29268
+ PRESENCE_IDLE_TIMEOUT_MS_ENV_KEY,
29269
+ PRESENCE_OFFLINE_TIMEOUT_MS_ENV_KEY,
29270
+ PRESENCE_RUNTIME_ENV_KEYS,
28739
29271
  Pagination,
28740
29272
  PaginationContent,
28741
29273
  PaginationEllipsis,
@@ -28849,6 +29381,8 @@ var useAuth = () => {
28849
29381
  TooltipCupcode,
28850
29382
  TooltipProvider,
28851
29383
  TooltipTrigger,
29384
+ USER_PRESENCE_LAST_ACTIVE_COLUMN_ENV_KEY,
29385
+ USER_PRESENCE_SOURCE_COLUMN_ENV_KEY,
28852
29386
  UserMenuCupcode,
28853
29387
  badgeVariants,
28854
29388
  buildAuthorizeUrl,