@cupcodev/ui 2.0.0 → 2.0.1

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.js CHANGED
@@ -965,10 +965,10 @@ var Dock = ({ items, className }) => {
965
965
  const itemsRef = useRef3([]);
966
966
  const OVERSHOOT = 5;
967
967
  useEffect3(() => {
968
- var _a74;
968
+ var _a78;
969
969
  const activeItem = itemsRef.current[activeIndex];
970
970
  if (!activeItem) return;
971
- const containerRect = (_a74 = activeItem.parentElement) == null ? void 0 : _a74.getBoundingClientRect();
971
+ const containerRect = (_a78 = activeItem.parentElement) == null ? void 0 : _a78.getBoundingClientRect();
972
972
  const itemRect = activeItem.getBoundingClientRect();
973
973
  if (!containerRect) return;
974
974
  const relativeLeft = itemRect.left - containerRect.left;
@@ -1030,9 +1030,9 @@ var Dock = ({ items, className }) => {
1030
1030
  "button",
1031
1031
  {
1032
1032
  onClick: () => {
1033
- var _a74;
1033
+ var _a78;
1034
1034
  setActiveIndex(index);
1035
- (_a74 = item.onClick) == null ? void 0 : _a74.call(item);
1035
+ (_a78 = item.onClick) == null ? void 0 : _a78.call(item);
1036
1036
  },
1037
1037
  className: cn(
1038
1038
  "flex items-center justify-center w-12 h-12 rounded-xl",
@@ -1076,6 +1076,20 @@ var CUPCODE_APP_VERSION_ENV_KEYS = [
1076
1076
  "NEXT_PUBLIC_APP_VERSION",
1077
1077
  "REACT_APP_VERSION"
1078
1078
  ];
1079
+ var USER_PRESENCE_SOURCE_COLUMN_ENV_KEY = "VITE_USER_PRESENCE_SOURCE_COLUMN";
1080
+ var USER_PRESENCE_LAST_ACTIVE_COLUMN_ENV_KEY = "VITE_USER_PRESENCE_LAST_ACTIVE_COLUMN";
1081
+ var PRESENCE_IDLE_TIMEOUT_MS_ENV_KEY = "VITE_PRESENCE_IDLE_TIMEOUT_MS";
1082
+ var PRESENCE_OFFLINE_TIMEOUT_MS_ENV_KEY = "VITE_PRESENCE_OFFLINE_TIMEOUT_MS";
1083
+ var PRESENCE_HEARTBEAT_INTERVAL_MS_ENV_KEY = "VITE_PRESENCE_HEARTBEAT_INTERVAL_MS";
1084
+ var PRESENCE_ACTIVITY_THROTTLE_MS_ENV_KEY = "VITE_PRESENCE_ACTIVITY_THROTTLE_MS";
1085
+ var PRESENCE_RUNTIME_ENV_KEYS = [
1086
+ USER_PRESENCE_SOURCE_COLUMN_ENV_KEY,
1087
+ USER_PRESENCE_LAST_ACTIVE_COLUMN_ENV_KEY,
1088
+ PRESENCE_IDLE_TIMEOUT_MS_ENV_KEY,
1089
+ PRESENCE_OFFLINE_TIMEOUT_MS_ENV_KEY,
1090
+ PRESENCE_HEARTBEAT_INTERVAL_MS_ENV_KEY,
1091
+ PRESENCE_ACTIVITY_THROTTLE_MS_ENV_KEY
1092
+ ];
1079
1093
  var runtimeStore = {};
1080
1094
  var normalizeValue = (value) => {
1081
1095
  if (value === null || typeof value === "undefined") return void 0;
@@ -1086,9 +1100,9 @@ var normalizeValue = (value) => {
1086
1100
  return String(value);
1087
1101
  };
1088
1102
  var setCupcodeRuntimeEnv = (values) => {
1089
- var _a74;
1103
+ var _a78;
1090
1104
  const globalRef = globalThis;
1091
- const nextGlobalEnv = { ...(_a74 = globalRef.__CUPCODE_ENV__) != null ? _a74 : {} };
1105
+ const nextGlobalEnv = { ...(_a78 = globalRef.__CUPCODE_ENV__) != null ? _a78 : {} };
1092
1106
  Object.entries(values).forEach(([key, value]) => {
1093
1107
  const normalized = normalizeValue(value);
1094
1108
  runtimeStore[key] = normalized;
@@ -1097,8 +1111,8 @@ var setCupcodeRuntimeEnv = (values) => {
1097
1111
  globalRef.__CUPCODE_ENV__ = nextGlobalEnv;
1098
1112
  };
1099
1113
  var readFromProcessEnv = (key) => {
1100
- var _a74;
1101
- const processEnv = (_a74 = globalThis.process) == null ? void 0 : _a74.env;
1114
+ var _a78;
1115
+ const processEnv = (_a78 = globalThis.process) == null ? void 0 : _a78.env;
1102
1116
  return normalizeValue(processEnv == null ? void 0 : processEnv[key]);
1103
1117
  };
1104
1118
  var readFromImportMetaEnv = (key) => {
@@ -1110,12 +1124,12 @@ var readFromImportMetaEnv = (key) => {
1110
1124
  }
1111
1125
  };
1112
1126
  var getRuntimeEnv = (key) => {
1113
- var _a74;
1127
+ var _a78;
1114
1128
  const normalizedKey = key.trim();
1115
1129
  if (!normalizedKey) return void 0;
1116
1130
  const fromRuntimeStore = runtimeStore[normalizedKey];
1117
1131
  if (fromRuntimeStore) return fromRuntimeStore;
1118
- const fromGlobalStore = normalizeValue((_a74 = globalThis.__CUPCODE_ENV__) == null ? void 0 : _a74[normalizedKey]);
1132
+ const fromGlobalStore = normalizeValue((_a78 = globalThis.__CUPCODE_ENV__) == null ? void 0 : _a78[normalizedKey]);
1119
1133
  if (fromGlobalStore) return fromGlobalStore;
1120
1134
  const fromGlobalKey = normalizeValue(globalThis[normalizedKey]);
1121
1135
  if (fromGlobalKey) return fromGlobalKey;
@@ -1124,12 +1138,12 @@ var getRuntimeEnv = (key) => {
1124
1138
  return readFromProcessEnv(normalizedKey);
1125
1139
  };
1126
1140
  var getRuntimeEnvOr = (key, fallback) => {
1127
- var _a74;
1128
- return (_a74 = getRuntimeEnv(key)) != null ? _a74 : fallback;
1141
+ var _a78;
1142
+ return (_a78 = getRuntimeEnv(key)) != null ? _a78 : fallback;
1129
1143
  };
1130
1144
  var isRuntimeDev = () => {
1131
- var _a74, _b7, _c;
1132
- const explicitDev = (_a74 = getRuntimeEnv("DEV")) != null ? _a74 : getRuntimeEnv("VITE_DEV");
1145
+ var _a78, _b7, _c;
1146
+ const explicitDev = (_a78 = getRuntimeEnv("DEV")) != null ? _a78 : getRuntimeEnv("VITE_DEV");
1133
1147
  if (explicitDev) {
1134
1148
  const normalized = explicitDev.toLowerCase();
1135
1149
  return normalized === "1" || normalized === "true";
@@ -1155,11 +1169,11 @@ var isUuid = (value) => {
1155
1169
  return UUID_REGEX.test(value.trim());
1156
1170
  };
1157
1171
  function parseAssetId(input) {
1158
- var _a74, _b7, _c, _d;
1172
+ var _a78, _b7, _c, _d;
1159
1173
  const raw = input == null ? void 0 : input.trim();
1160
1174
  if (!raw) return void 0;
1161
1175
  if (UUID_REGEX.test(raw)) return raw;
1162
- const matchFromRaw = (_a74 = raw.match(UUID_IN_TEXT_REGEX)) == null ? void 0 : _a74[0];
1176
+ const matchFromRaw = (_a78 = raw.match(UUID_IN_TEXT_REGEX)) == null ? void 0 : _a78[0];
1163
1177
  if (isUuid(matchFromRaw)) return matchFromRaw;
1164
1178
  try {
1165
1179
  const url = new URL(raw);
@@ -1295,7 +1309,7 @@ var DockWrapper = ({ categories, activeCategoryId }) => {
1295
1309
  return void 0;
1296
1310
  }, [sortedCategories]);
1297
1311
  useEffect5(() => {
1298
- var _a74;
1312
+ var _a78;
1299
1313
  const root = rootRef.current;
1300
1314
  if (!root) return;
1301
1315
  const $ = (sel) => root.querySelector(sel);
@@ -1307,7 +1321,7 @@ var DockWrapper = ({ categories, activeCategoryId }) => {
1307
1321
  const getDockItems = () => Array.from(root.querySelectorAll(INTERACTIVE_SELECTOR));
1308
1322
  const dockItems = getDockItems();
1309
1323
  if (!tabbar || !dock || !listMenuShow || !tabbarUl || dockItems.length === 0) return;
1310
- const persistentId = (_a74 = activeCategoryId != null ? activeCategoryId : lastInteractiveId) != null ? _a74 : null;
1324
+ const persistentId = (_a78 = activeCategoryId != null ? activeCategoryId : lastInteractiveId) != null ? _a78 : null;
1311
1325
  let openItem = null;
1312
1326
  let latestToggleToken = null;
1313
1327
  const persistentSelector = persistentId != null ? `${INTERACTIVE_SELECTOR}[data-cat-id="${persistentId}"]` : null;
@@ -1606,8 +1620,8 @@ var DockWrapper = ({ categories, activeCategoryId }) => {
1606
1620
  }, total);
1607
1621
  }
1608
1622
  const hideBootstrapTooltip = (el) => {
1609
- var _a75, _b7;
1610
- const tooltip = ((_b7 = (_a75 = window.bootstrap) == null ? void 0 : _a75.Tooltip) == null ? void 0 : _b7.getInstance) ? window.bootstrap.Tooltip.getInstance(el) : null;
1623
+ var _a79, _b7;
1624
+ const tooltip = ((_b7 = (_a79 = window.bootstrap) == null ? void 0 : _a79.Tooltip) == null ? void 0 : _b7.getInstance) ? window.bootstrap.Tooltip.getInstance(el) : null;
1611
1625
  tooltip == null ? void 0 : tooltip.hide();
1612
1626
  };
1613
1627
  const openMenuForItem = (item, menu) => {
@@ -1625,14 +1639,14 @@ var DockWrapper = ({ categories, activeCategoryId }) => {
1625
1639
  latestToggleToken = null;
1626
1640
  };
1627
1641
  const closeActiveMenu = (opts = {}) => {
1628
- var _a75;
1642
+ var _a79;
1629
1643
  if (!opts.onClosed) {
1630
1644
  latestToggleToken = null;
1631
1645
  }
1632
1646
  const itemToClose = openItem;
1633
1647
  if (!itemToClose) {
1634
1648
  if (!opts.preserveWrapper) ensurePersistentHighlight();
1635
- (_a75 = opts.onClosed) == null ? void 0 : _a75.call(opts);
1649
+ (_a79 = opts.onClosed) == null ? void 0 : _a79.call(opts);
1636
1650
  return;
1637
1651
  }
1638
1652
  const menu = getMenuFor(itemToClose);
@@ -1640,7 +1654,7 @@ var DockWrapper = ({ categories, activeCategoryId }) => {
1640
1654
  itemToClose.classList.remove("active");
1641
1655
  delete itemToClose.dataset.menuOpen;
1642
1656
  const finalize = () => {
1643
- var _a76;
1657
+ var _a80;
1644
1658
  if (!opts.preserveWrapper) {
1645
1659
  listMenuShow.classList.remove("show");
1646
1660
  tabbar.classList.remove("is-active-menu");
@@ -1648,7 +1662,7 @@ var DockWrapper = ({ categories, activeCategoryId }) => {
1648
1662
  setTabbarTheme(null);
1649
1663
  ensurePersistentHighlight();
1650
1664
  }
1651
- (_a76 = opts.onClosed) == null ? void 0 : _a76.call(opts);
1665
+ (_a80 = opts.onClosed) == null ? void 0 : _a80.call(opts);
1652
1666
  };
1653
1667
  closeMenu(menu, finalize);
1654
1668
  };
@@ -1751,7 +1765,7 @@ var DockWrapper = ({ categories, activeCategoryId }) => {
1751
1765
  /* @__PURE__ */ jsx10("div", { className: "glass-overlay" }),
1752
1766
  /* @__PURE__ */ jsx10("div", { className: "glass-specular" }),
1753
1767
  /* @__PURE__ */ jsx10("ul", { className: "flex-center", children: sortedCategories.map((cat) => {
1754
- var _a74;
1768
+ var _a78;
1755
1769
  if (cat.type === "divider") {
1756
1770
  return /* @__PURE__ */ jsx10(
1757
1771
  "li",
@@ -1763,7 +1777,7 @@ var DockWrapper = ({ categories, activeCategoryId }) => {
1763
1777
  cat.id
1764
1778
  );
1765
1779
  }
1766
- const hasCards = (((_a74 = cat.cards) == null ? void 0 : _a74.length) || 0) > 0;
1780
+ const hasCards = (((_a78 = cat.cards) == null ? void 0 : _a78.length) || 0) > 0;
1767
1781
  const link = cat.href;
1768
1782
  const isCurrent = cat.id === activeCategoryId;
1769
1783
  return /* @__PURE__ */ jsxs8(
@@ -1797,12 +1811,12 @@ var DockWrapper = ({ categories, activeCategoryId }) => {
1797
1811
  );
1798
1812
  }) }),
1799
1813
  /* @__PURE__ */ jsx10("div", { className: "list-menu-mob-show", children: sortedCategories.filter((cat) => {
1800
- var _a74;
1801
- return cat.type !== "divider" && (((_a74 = cat.cards) == null ? void 0 : _a74.length) || 0) > 0;
1814
+ var _a78;
1815
+ return cat.type !== "divider" && (((_a78 = cat.cards) == null ? void 0 : _a78.length) || 0) > 0;
1802
1816
  }).map((cat) => {
1803
- var _a74;
1804
- return /* @__PURE__ */ jsx10("div", { className: "mob-list-menu hide", "data-tagget": cat.slug, children: /* @__PURE__ */ jsx10("div", { className: `submenu-stack ${cat.slug}`, children: ((_a74 = cat.cards) != null ? _a74 : []).map((card, i) => {
1805
- var _a75;
1817
+ var _a78;
1818
+ return /* @__PURE__ */ jsx10("div", { className: "mob-list-menu hide", "data-tagget": cat.slug, children: /* @__PURE__ */ jsx10("div", { className: `submenu-stack ${cat.slug}`, children: ((_a78 = cat.cards) != null ? _a78 : []).map((card, i) => {
1819
+ var _a79;
1806
1820
  return /* @__PURE__ */ jsxs8(
1807
1821
  "div",
1808
1822
  {
@@ -1818,8 +1832,8 @@ var DockWrapper = ({ categories, activeCategoryId }) => {
1818
1832
  /* @__PURE__ */ jsx10("div", { className: "title", children: card.title }),
1819
1833
  card.description ? /* @__PURE__ */ jsx10("div", { className: "description", children: card.description }) : null
1820
1834
  ] }),
1821
- /* @__PURE__ */ jsx10("div", { className: "actions", children: ((_a75 = card.buttons) != null ? _a75 : []).slice(0, 2).map((btn, idx) => {
1822
- var _a76, _b7, _c, _d;
1835
+ /* @__PURE__ */ jsx10("div", { className: "actions", children: ((_a79 = card.buttons) != null ? _a79 : []).slice(0, 2).map((btn, idx) => {
1836
+ var _a80, _b7, _c, _d;
1823
1837
  const className = idx === 0 ? "saiba-mais" : "saiba-mais-1";
1824
1838
  if (btn.type === "popup") {
1825
1839
  return /* @__PURE__ */ jsx10(
@@ -1834,7 +1848,7 @@ var DockWrapper = ({ categories, activeCategoryId }) => {
1834
1848
  window.dispatchEvent(new Event(`qw:open:${btn.popupId}`));
1835
1849
  }
1836
1850
  },
1837
- children: (_a76 = btn.label) != null ? _a76 : "Abrir"
1851
+ children: (_a80 = btn.label) != null ? _a80 : "Abrir"
1838
1852
  },
1839
1853
  `${cat.id}-card-${i}-btn-${idx}`
1840
1854
  );
@@ -2593,10 +2607,10 @@ var NavbarCupcode = ({
2593
2607
  React9.useEffect(() => {
2594
2608
  if (!isOpen) return;
2595
2609
  const handlePointerDown = (event) => {
2596
- var _a74;
2610
+ var _a78;
2597
2611
  const target = event.target;
2598
2612
  if (!(target instanceof Node)) return;
2599
- if (!((_a74 = navRef.current) == null ? void 0 : _a74.contains(target))) {
2613
+ if (!((_a78 = navRef.current) == null ? void 0 : _a78.contains(target))) {
2600
2614
  setIsOpen(false);
2601
2615
  }
2602
2616
  };
@@ -2656,8 +2670,8 @@ var NavbarCupcode = ({
2656
2670
  isActive && "text-primary after:w-full"
2657
2671
  );
2658
2672
  const handleClick = (event) => {
2659
- var _a74;
2660
- (_a74 = item.onClick) == null ? void 0 : _a74.call(item, event);
2673
+ var _a78;
2674
+ (_a78 = item.onClick) == null ? void 0 : _a78.call(item, event);
2661
2675
  };
2662
2676
  if (item.href.startsWith("#")) {
2663
2677
  return /* @__PURE__ */ jsxs17(
@@ -2718,8 +2732,8 @@ var NavbarCupcode = ({
2718
2732
  isActive && "text-primary"
2719
2733
  );
2720
2734
  const handleClick = (event) => {
2721
- var _a74;
2722
- (_a74 = item.onClick) == null ? void 0 : _a74.call(item, event);
2735
+ var _a78;
2736
+ (_a78 = item.onClick) == null ? void 0 : _a78.call(item, event);
2723
2737
  setIsOpen(false);
2724
2738
  };
2725
2739
  if (item.href.startsWith("#")) {
@@ -3569,12 +3583,12 @@ var rpcPreferredSchema = TELESCUP_RPC_SCHEMA;
3569
3583
  var RPC_MISSING_SCHEMAS_BY_PATH = /* @__PURE__ */ new Map();
3570
3584
  var FUNCTION_NOT_FOUND_CACHE = /* @__PURE__ */ new Set();
3571
3585
  var buildRestHeaders = (token, options) => {
3572
- var _a74;
3586
+ var _a78;
3573
3587
  const headers = {};
3574
3588
  if (SUPABASE_ANON_KEY) {
3575
3589
  headers.apikey = SUPABASE_ANON_KEY;
3576
3590
  }
3577
- const authorizationToken = (_a74 = resolveRpcAuthorizationToken(token)) != null ? _a74 : token;
3591
+ const authorizationToken = (_a78 = resolveRpcAuthorizationToken(token)) != null ? _a78 : token;
3578
3592
  if (authorizationToken) {
3579
3593
  headers.Authorization = `Bearer ${authorizationToken}`;
3580
3594
  }
@@ -3709,22 +3723,22 @@ var parseAssetSize = (value) => {
3709
3723
  return Number.isFinite(parsed) ? parsed : void 0;
3710
3724
  };
3711
3725
  var getFileExtension = (filename) => {
3712
- var _a74;
3726
+ var _a78;
3713
3727
  if (!filename) return void 0;
3714
3728
  const parts = filename.split(".");
3715
3729
  if (parts.length < 2) return void 0;
3716
- const candidate = (_a74 = parts[parts.length - 1]) == null ? void 0 : _a74.trim().toLowerCase();
3730
+ const candidate = (_a78 = parts[parts.length - 1]) == null ? void 0 : _a78.trim().toLowerCase();
3717
3731
  return candidate || void 0;
3718
3732
  };
3719
3733
  var resolveCategory = (row, activeMeta) => {
3720
- var _a74;
3721
- return (_a74 = readString(row.category)) != null ? _a74 : readString(activeMeta.category);
3734
+ var _a78;
3735
+ return (_a78 = readString(row.category)) != null ? _a78 : readString(activeMeta.category);
3722
3736
  };
3723
3737
  var resolveFolderName = (row) => readString(row.folder_name);
3724
3738
  var toTelescupAsset = (row, selectedLanguage) => {
3725
- var _a74, _b7, _c, _d, _e;
3739
+ var _a78, _b7, _c, _d, _e;
3726
3740
  const metaByLang = normalizeMetaByLanguage(row.meta);
3727
- const activeMeta = (_b7 = (_a74 = metaByLang[selectedLanguage]) != null ? _a74 : metaByLang.pt) != null ? _b7 : {};
3741
+ const activeMeta = (_b7 = (_a78 = metaByLang[selectedLanguage]) != null ? _a78 : metaByLang.pt) != null ? _b7 : {};
3728
3742
  return {
3729
3743
  id: (_c = row.id) != null ? _c : "",
3730
3744
  name: row.filename,
@@ -3750,9 +3764,9 @@ var buildFacetsFromItems = (items) => {
3750
3764
  const extensions = /* @__PURE__ */ new Map();
3751
3765
  const tags = /* @__PURE__ */ new Map();
3752
3766
  items.forEach((item) => {
3753
- var _a74, _b7, _c, _d, _e, _f, _g;
3767
+ var _a78, _b7, _c, _d, _e, _f, _g;
3754
3768
  if (item.category) {
3755
- categories.set(item.category, ((_a74 = categories.get(item.category)) != null ? _a74 : 0) + 1);
3769
+ categories.set(item.category, ((_a78 = categories.get(item.category)) != null ? _a78 : 0) + 1);
3756
3770
  }
3757
3771
  if (item.folderId) {
3758
3772
  const current = folders.get(item.folderId);
@@ -3768,16 +3782,16 @@ var buildFacetsFromItems = (items) => {
3768
3782
  extensions.set(item.extension, ((_e = extensions.get(item.extension)) != null ? _e : 0) + 1);
3769
3783
  }
3770
3784
  (_g = (_f = item.meta) == null ? void 0 : _f.tags) == null ? void 0 : _g.forEach((tag) => {
3771
- var _a75;
3785
+ var _a79;
3772
3786
  const normalizedTag = tag.trim();
3773
3787
  if (!normalizedTag) return;
3774
- tags.set(normalizedTag, ((_a75 = tags.get(normalizedTag)) != null ? _a75 : 0) + 1);
3788
+ tags.set(normalizedTag, ((_a79 = tags.get(normalizedTag)) != null ? _a79 : 0) + 1);
3775
3789
  });
3776
3790
  });
3777
3791
  const toFacetValues = (map) => Array.from(map.entries()).map(([value, count2]) => ({ value, count: count2 })).sort((a, b) => a.value.localeCompare(b.value));
3778
3792
  const toFolderFacetValues = (map) => Array.from(map.entries()).map(([value, info]) => ({ value, label: info.label, count: info.count })).sort((a, b) => {
3779
- var _a74, _b7;
3780
- return ((_a74 = a.label) != null ? _a74 : a.value).localeCompare((_b7 = b.label) != null ? _b7 : b.value);
3793
+ var _a78, _b7;
3794
+ return ((_a78 = a.label) != null ? _a78 : a.value).localeCompare((_b7 = b.label) != null ? _b7 : b.value);
3781
3795
  });
3782
3796
  return {
3783
3797
  categories: toFacetValues(categories),
@@ -3795,7 +3809,7 @@ var isManagerScopeRetryable = (error) => {
3795
3809
  return /permission|not allowed|wrong key type|insufficient|unauthorized/i.test(detailsText);
3796
3810
  };
3797
3811
  async function listAssetsViaRpc(config, filters) {
3798
- var _a74, _b7, _c, _d, _e, _f, _g, _h, _i;
3812
+ var _a78, _b7, _c, _d, _e, _f, _g, _h, _i;
3799
3813
  if (!SUPABASE_ANON_KEY) {
3800
3814
  throw new TelescupClientError(
3801
3815
  "VITE_SUPABASE_ANON_KEY (ou VITE_SUPABASE_PUBLISHABLE_KEY) n\xE3o encontrado para fallback RPC do Telescup."
@@ -3814,7 +3828,7 @@ async function listAssetsViaRpc(config, filters) {
3814
3828
  );
3815
3829
  }
3816
3830
  const pageSize = Math.min(100, Math.max(1, toPositiveInt(filters.pageSize, 24)));
3817
- const page = toPositiveInt((_a74 = filters.cursor) != null ? _a74 : filters.page, 1);
3831
+ const page = toPositiveInt((_a78 = filters.cursor) != null ? _a78 : filters.page, 1);
3818
3832
  const selectedLanguage = normalizeLanguageKey(filters.language);
3819
3833
  const bodyBase = {
3820
3834
  p_user_id: userId,
@@ -3914,13 +3928,13 @@ var getRpcSchemaCandidates = (rpcPath) => {
3914
3928
  return filtered.length ? filtered : ordered;
3915
3929
  };
3916
3930
  var markRpcSchemaMissing = (rpcPath, schema) => {
3917
- var _a74;
3918
- const set = (_a74 = RPC_MISSING_SCHEMAS_BY_PATH.get(rpcPath)) != null ? _a74 : /* @__PURE__ */ new Set();
3931
+ var _a78;
3932
+ const set = (_a78 = RPC_MISSING_SCHEMAS_BY_PATH.get(rpcPath)) != null ? _a78 : /* @__PURE__ */ new Set();
3919
3933
  set.add(schema);
3920
3934
  RPC_MISSING_SCHEMAS_BY_PATH.set(rpcPath, set);
3921
3935
  };
3922
3936
  async function requestRpc(config, rpcPath, payload) {
3923
- var _a74, _b7;
3937
+ var _a78, _b7;
3924
3938
  if (!SUPABASE_ANON_KEY) {
3925
3939
  throw new TelescupClientError(
3926
3940
  "VITE_SUPABASE_ANON_KEY (ou VITE_SUPABASE_PUBLISHABLE_KEY) n\xE3o encontrado para fallback RPC do Telescup."
@@ -3963,7 +3977,7 @@ async function requestRpc(config, rpcPath, payload) {
3963
3977
  throw new TelescupClientError(`Falha de rede ao chamar RPC ${rpcPath}.`, { details: error });
3964
3978
  }
3965
3979
  if (response.ok) {
3966
- const contentType = (_a74 = response.headers.get("content-type")) != null ? _a74 : "";
3980
+ const contentType = (_a78 = response.headers.get("content-type")) != null ? _a78 : "";
3967
3981
  if (!contentType.includes("application/json")) {
3968
3982
  const text = await response.text();
3969
3983
  if (!text) return {};
@@ -4015,7 +4029,7 @@ async function requestRpc(config, rpcPath, payload) {
4015
4029
  throw new TelescupClientError(`Falha ao chamar RPC ${rpcPath}.`);
4016
4030
  }
4017
4031
  var toTelescupError = async (response, fallbackMessage) => {
4018
- var _a74;
4032
+ var _a78;
4019
4033
  let payload = void 0;
4020
4034
  try {
4021
4035
  payload = await response.json();
@@ -4023,7 +4037,7 @@ var toTelescupError = async (response, fallbackMessage) => {
4023
4037
  payload = await response.text();
4024
4038
  }
4025
4039
  const payloadObject = payload != null ? payload : {};
4026
- const message = typeof payload === "string" ? payload : (_a74 = payloadObject.message) != null ? _a74 : `${fallbackMessage} (${response.status}).`;
4040
+ const message = typeof payload === "string" ? payload : (_a78 = payloadObject.message) != null ? _a78 : `${fallbackMessage} (${response.status}).`;
4027
4041
  return new TelescupClientError(message, {
4028
4042
  status: response.status,
4029
4043
  code: payloadObject.code,
@@ -4071,11 +4085,11 @@ var mergeFacetEntries = (current, incoming) => {
4071
4085
  const map = /* @__PURE__ */ new Map();
4072
4086
  current == null ? void 0 : current.forEach((entry) => map.set(entry.value, entry));
4073
4087
  incoming == null ? void 0 : incoming.forEach((entry) => {
4074
- var _a74, _b7, _c;
4088
+ var _a78, _b7, _c;
4075
4089
  const previous = map.get(entry.value);
4076
4090
  map.set(entry.value, {
4077
4091
  value: entry.value,
4078
- label: (_b7 = (_a74 = entry.label) != null ? _a74 : previous == null ? void 0 : previous.label) != null ? _b7 : entry.value,
4092
+ label: (_b7 = (_a78 = entry.label) != null ? _a78 : previous == null ? void 0 : previous.label) != null ? _b7 : entry.value,
4079
4093
  count: (_c = entry.count) != null ? _c : previous == null ? void 0 : previous.count
4080
4094
  });
4081
4095
  });
@@ -4095,10 +4109,10 @@ var mergeFacets = (base, incoming) => {
4095
4109
  var toFacetEntriesFromRows = (rows, valueKeys, labelKeys) => {
4096
4110
  const result = /* @__PURE__ */ new Map();
4097
4111
  rows.forEach((row) => {
4098
- var _a74;
4112
+ var _a78;
4099
4113
  const value = readFirstString(row, valueKeys);
4100
4114
  if (!value) return;
4101
- const label = (_a74 = readFirstString(row, labelKeys)) != null ? _a74 : value;
4115
+ const label = (_a78 = readFirstString(row, labelKeys)) != null ? _a78 : value;
4102
4116
  result.set(value, { value, label });
4103
4117
  });
4104
4118
  return Array.from(result.values()).sort((a, b) => a.label.localeCompare(b.label));
@@ -4164,7 +4178,7 @@ async function loadFacetsFromTelescupTablesCached(config) {
4164
4178
  return facets;
4165
4179
  }
4166
4180
  async function request(config, path, options = {}) {
4167
- var _a74, _b7, _c;
4181
+ var _a78, _b7, _c;
4168
4182
  const token = await config.getAccessToken();
4169
4183
  if (!token) {
4170
4184
  throw new TelescupClientError("Token de acesso n\xE3o encontrado.");
@@ -4172,7 +4186,7 @@ async function request(config, path, options = {}) {
4172
4186
  const functionsBaseUrl = resolveFunctionsBaseUrl(config.baseUrl);
4173
4187
  const url = joinUrl(functionsBaseUrl, path);
4174
4188
  const isAssetApiRoute = path.startsWith("asset-api/");
4175
- const authorizationToken = isAssetApiRoute ? (_a74 = resolveRpcAuthorizationToken(token)) != null ? _a74 : token : token;
4189
+ const authorizationToken = isAssetApiRoute ? (_a78 = resolveRpcAuthorizationToken(token)) != null ? _a78 : token : token;
4176
4190
  const headers = {
4177
4191
  Authorization: `Bearer ${authorizationToken}`,
4178
4192
  ...options.headers
@@ -4222,8 +4236,8 @@ var normalizeFunctionLanguage = (value) => {
4222
4236
  return normalized;
4223
4237
  };
4224
4238
  var toFunctionListPayload = (filters) => {
4225
- var _a74, _b7, _c, _d, _e, _f;
4226
- const page = toPositiveInt((_a74 = filters.cursor) != null ? _a74 : filters.page, 1);
4239
+ var _a78, _b7, _c, _d, _e, _f;
4240
+ const page = toPositiveInt((_a78 = filters.cursor) != null ? _a78 : filters.page, 1);
4227
4241
  const pageSize = Math.min(500, Math.max(1, toPositiveInt(filters.pageSize, 24)));
4228
4242
  return {
4229
4243
  query: (_b7 = filters.query) != null ? _b7 : "",
@@ -4261,8 +4275,8 @@ var toFolderPath = (value) => {
4261
4275
  return normalized.slice(0, lastSlash);
4262
4276
  };
4263
4277
  var normalizeFilterText = (value) => {
4264
- var _a74;
4265
- return (_a74 = value == null ? void 0 : value.trim().toLowerCase()) != null ? _a74 : "";
4278
+ var _a78;
4279
+ return (_a78 = value == null ? void 0 : value.trim().toLowerCase()) != null ? _a78 : "";
4266
4280
  };
4267
4281
  var hasActiveFacetFilter = (filters) => Boolean(filters.type && filters.type !== "all") || Boolean(filters.extension) || Boolean(filters.category) || Boolean(filters.folderId) || Boolean(filters.usage) || filters.hasAlt === true;
4268
4282
  var normalizeExtensionFilter = (value) => {
@@ -4277,16 +4291,16 @@ var normalizeFolderFilter = (value) => {
4277
4291
  var sortAssets = (items, sort, order) => {
4278
4292
  const direction = order === "asc" ? 1 : -1;
4279
4293
  const byName = (a, b) => {
4280
- var _a74, _b7, _c, _d;
4281
- return ((_b7 = (_a74 = a.fileName) != null ? _a74 : a.name) != null ? _b7 : "").localeCompare((_d = (_c = b.fileName) != null ? _c : b.name) != null ? _d : "");
4294
+ var _a78, _b7, _c, _d;
4295
+ return ((_b7 = (_a78 = a.fileName) != null ? _a78 : a.name) != null ? _b7 : "").localeCompare((_d = (_c = b.fileName) != null ? _c : b.name) != null ? _d : "");
4282
4296
  };
4283
4297
  const byDate = (a, b, key) => {
4284
- var _a74, _b7;
4285
- return (Date.parse((_a74 = a[key]) != null ? _a74 : "") || 0) - (Date.parse((_b7 = b[key]) != null ? _b7 : "") || 0);
4298
+ var _a78, _b7;
4299
+ return (Date.parse((_a78 = a[key]) != null ? _a78 : "") || 0) - (Date.parse((_b7 = b[key]) != null ? _b7 : "") || 0);
4286
4300
  };
4287
4301
  const bySize = (a, b) => {
4288
- var _a74, _b7;
4289
- return ((_a74 = a.size) != null ? _a74 : 0) - ((_b7 = b.size) != null ? _b7 : 0);
4302
+ var _a78, _b7;
4303
+ return ((_a78 = a.size) != null ? _a78 : 0) - ((_b7 = b.size) != null ? _b7 : 0);
4290
4304
  };
4291
4305
  const sorted = [...items];
4292
4306
  sorted.sort((a, b) => {
@@ -4321,7 +4335,7 @@ var applyAssetApiSearchFilters = (items, filters) => {
4321
4335
  const folderFilter = normalizeFolderFilter(filters.folderId);
4322
4336
  const requireAlt = filters.hasAlt === true;
4323
4337
  return items.filter((asset) => {
4324
- var _a74, _b7, _c, _d, _e, _f, _g, _h, _i;
4338
+ var _a78, _b7, _c, _d, _e, _f, _g, _h, _i;
4325
4339
  const haystack = [
4326
4340
  asset.id,
4327
4341
  asset.name,
@@ -4330,7 +4344,7 @@ var applyAssetApiSearchFilters = (items, filters) => {
4330
4344
  asset.folderName,
4331
4345
  asset.category,
4332
4346
  asset.usage,
4333
- (_a74 = asset.meta) == null ? void 0 : _a74.title,
4347
+ (_a78 = asset.meta) == null ? void 0 : _a78.title,
4334
4348
  (_b7 = asset.meta) == null ? void 0 : _b7.description,
4335
4349
  (_c = asset.meta) == null ? void 0 : _c.alt,
4336
4350
  ...Array.isArray((_d = asset.meta) == null ? void 0 : _d.tags) ? asset.meta.tags : []
@@ -4350,10 +4364,10 @@ var applyAssetApiSearchFilters = (items, filters) => {
4350
4364
  });
4351
4365
  };
4352
4366
  var mapAssetApiSearchRowToAsset = (row) => {
4353
- var _a74, _b7, _c, _d;
4367
+ var _a78, _b7, _c, _d;
4354
4368
  const id = readFirstString(row, ["asset_id", "id"]);
4355
4369
  if (!id) return null;
4356
- const fileName = (_a74 = readFirstString(row, ["original_filename", "filename", "title"])) != null ? _a74 : readFirstString(row, ["file_path"]);
4370
+ const fileName = (_a78 = readFirstString(row, ["original_filename", "filename", "title"])) != null ? _a78 : readFirstString(row, ["file_path"]);
4357
4371
  const mimeType = readFirstString(row, ["mime_type", "mime"]);
4358
4372
  const extension = getFileExtension(readFirstString(row, ["file_path", "filename", "original_filename"]));
4359
4373
  const tags = Array.isArray(row.tags) ? row.tags.filter((item) => typeof item === "string") : void 0;
@@ -4401,9 +4415,9 @@ var mapAssetApiSearchRowToAsset = (row) => {
4401
4415
  };
4402
4416
  };
4403
4417
  async function listAssetsViaAssetApiSearch(config, filters) {
4404
- var _a74, _b7;
4418
+ var _a78, _b7;
4405
4419
  const pageSize = Math.min(500, Math.max(1, toPositiveInt(filters.pageSize, 24)));
4406
- const page = toPositiveInt((_a74 = filters.cursor) != null ? _a74 : filters.page, 1);
4420
+ const page = toPositiveInt((_a78 = filters.cursor) != null ? _a78 : filters.page, 1);
4407
4421
  const hasFilter = hasActiveFacetFilter(filters);
4408
4422
  const baseLimit = page * pageSize + 1;
4409
4423
  const seedLimit = hasFilter ? baseLimit : Math.max(baseLimit, TELESCUP_ASSET_API_FACET_SEED_LIMIT);
@@ -4440,8 +4454,8 @@ async function listAssetsViaAssetApiSearch(config, filters) {
4440
4454
  };
4441
4455
  }
4442
4456
  var mapGenericRowToAsset = (row) => {
4443
- var _a74, _b7;
4444
- const id = (_a74 = readFirstString(row, ["asset_id", "id", "file_id", "uuid"])) != null ? _a74 : typeof row.id === "number" ? String(row.id) : void 0;
4457
+ var _a78, _b7;
4458
+ const id = (_a78 = readFirstString(row, ["asset_id", "id", "file_id", "uuid"])) != null ? _a78 : typeof row.id === "number" ? String(row.id) : void 0;
4445
4459
  if (!id) return null;
4446
4460
  const fileName = readFirstString(row, ["filename", "file_name", "name", "title", "original_name"]);
4447
4461
  const mimeType = readFirstString(row, ["mime", "mime_type", "content_type", "file_mime"]);
@@ -4463,16 +4477,16 @@ var mapGenericRowToAsset = (row) => {
4463
4477
  };
4464
4478
  };
4465
4479
  var normalizeListResponseFromFunctions = (response, filters) => {
4466
- var _a74, _b7, _c, _d, _e, _f;
4480
+ var _a78, _b7, _c, _d, _e, _f;
4467
4481
  const payload = response != null ? response : {};
4468
4482
  const itemsRaw = Array.isArray(payload.items) ? payload.items : [];
4469
4483
  const selectedLanguage = normalizeLanguageKey(filters.language);
4470
4484
  const items = itemsRaw.map((row) => {
4471
- var _a75, _b8, _c2;
4485
+ var _a79, _b8, _c2;
4472
4486
  const mapped = mapGenericRowToAsset(row);
4473
4487
  if (!mapped) return null;
4474
4488
  const metaByLang = normalizeMetaByLanguage(row.meta);
4475
- const activeMeta = (_b8 = (_a75 = metaByLang[selectedLanguage]) != null ? _a75 : metaByLang.pt) != null ? _b8 : {};
4489
+ const activeMeta = (_b8 = (_a79 = metaByLang[selectedLanguage]) != null ? _a79 : metaByLang.pt) != null ? _b8 : {};
4476
4490
  const usageFromObject = readUsageContext(row.usage);
4477
4491
  const normalized = {
4478
4492
  ...mapped,
@@ -4484,7 +4498,7 @@ var normalizeListResponseFromFunctions = (response, filters) => {
4484
4498
  };
4485
4499
  return normalized;
4486
4500
  }).filter((item) => item !== null);
4487
- const total = (_c = (_b7 = (_a74 = readNumber(payload.total)) != null ? _a74 : readNumber(payload.totalCount)) != null ? _b7 : readNumber(payload.total_count)) != null ? _c : items.length;
4501
+ const total = (_c = (_b7 = (_a78 = readNumber(payload.total)) != null ? _a78 : readNumber(payload.totalCount)) != null ? _b7 : readNumber(payload.total_count)) != null ? _c : items.length;
4488
4502
  const page = toPositiveInt((_e = (_d = payload.page) != null ? _d : filters.cursor) != null ? _e : filters.page, 1);
4489
4503
  const pageSize = Math.min(100, Math.max(1, toPositiveInt((_f = payload.pageSize) != null ? _f : filters.pageSize, 24)));
4490
4504
  const nextCursor = total > page * pageSize ? String(page + 1) : void 0;
@@ -4504,12 +4518,12 @@ var mapConflictForQueue = (value) => {
4504
4518
  return "conflict";
4505
4519
  };
4506
4520
  var toInitPayloadForFunctions = (payload) => {
4507
- var _a74, _b7;
4521
+ var _a78, _b7;
4508
4522
  return {
4509
4523
  filename: payload.fileName,
4510
4524
  size: payload.size,
4511
4525
  mime: payload.mimeType,
4512
- folder_id: (_a74 = payload.folderId) != null ? _a74 : null,
4526
+ folder_id: (_a78 = payload.folderId) != null ? _a78 : null,
4513
4527
  overwritePolicy: (_b7 = payload.conflict) != null ? _b7 : "ask",
4514
4528
  fileName: payload.fileName,
4515
4529
  mimeType: payload.mimeType,
@@ -4518,9 +4532,9 @@ var toInitPayloadForFunctions = (payload) => {
4518
4532
  };
4519
4533
  };
4520
4534
  var normalizeInitResponseFromFunctions = (response) => {
4521
- var _a74, _b7, _c, _d, _e, _f, _g;
4535
+ var _a78, _b7, _c, _d, _e, _f, _g;
4522
4536
  const payload = response != null ? response : {};
4523
- const existingRaw = (_a74 = payload.existingAsset) != null ? _a74 : payload.existing_asset;
4537
+ const existingRaw = (_a78 = payload.existingAsset) != null ? _a78 : payload.existing_asset;
4524
4538
  const existingAsset = existingRaw ? (_b7 = mapGenericRowToAsset(existingRaw)) != null ? _b7 : void 0 : void 0;
4525
4539
  const assetRaw = payload.asset;
4526
4540
  const asset = assetRaw ? (_c = mapGenericRowToAsset(assetRaw)) != null ? _c : void 0 : void 0;
@@ -4542,10 +4556,10 @@ var normalizeInitResponseFromFunctions = (response) => {
4542
4556
  };
4543
4557
  };
4544
4558
  var toCompletePayloadForFunctions = (payload) => {
4545
- var _a74, _b7, _c;
4559
+ var _a78, _b7, _c;
4546
4560
  return {
4547
4561
  uploadId: payload.uploadId,
4548
- assetDraftId: (_a74 = payload.assetDraftId) != null ? _a74 : payload.assetId,
4562
+ assetDraftId: (_a78 = payload.assetDraftId) != null ? _a78 : payload.assetId,
4549
4563
  storageKey: payload.storageKey,
4550
4564
  finalFilename: (_b7 = payload.finalFilename) != null ? _b7 : payload.fileName,
4551
4565
  folder_id: (_c = payload.folderId) != null ? _c : null,
@@ -4555,9 +4569,9 @@ var toCompletePayloadForFunctions = (payload) => {
4555
4569
  };
4556
4570
  };
4557
4571
  var normalizeCompleteResponseFromFunctions = (response) => {
4558
- var _a74, _b7;
4572
+ var _a78, _b7;
4559
4573
  const payload = response != null ? response : {};
4560
- const assetRaw = (_a74 = payload.asset) != null ? _a74 : payload;
4574
+ const assetRaw = (_a78 = payload.asset) != null ? _a78 : payload;
4561
4575
  const mapped = mapGenericRowToAsset(assetRaw);
4562
4576
  if (mapped) return { asset: mapped };
4563
4577
  const assetId = (_b7 = readFirstString(assetRaw, ["id", "asset_id"])) != null ? _b7 : readFirstString(payload, ["assetId", "asset_id"]);
@@ -4567,9 +4581,9 @@ var normalizeCompleteResponseFromFunctions = (response) => {
4567
4581
  return { asset: { id: assetId } };
4568
4582
  };
4569
4583
  var toMetaPayloadForFunctions = (payload) => {
4570
- var _a74, _b7;
4584
+ var _a78, _b7;
4571
4585
  if (TELESCUP_UPDATE_META_FUNCTION === "update-asset-meta") {
4572
- const categories = ((_a74 = payload.meta) == null ? void 0 : _a74.category) ? [payload.meta.category] : [];
4586
+ const categories = ((_a78 = payload.meta) == null ? void 0 : _a78.category) ? [payload.meta.category] : [];
4573
4587
  return {
4574
4588
  asset_id: payload.assetId,
4575
4589
  categories
@@ -4683,7 +4697,7 @@ var createTelescupClient = (config) => ({
4683
4697
  body: toMetaPayloadForFunctions(payload)
4684
4698
  }),
4685
4699
  uploadDirect: async (file) => {
4686
- var _a74;
4700
+ var _a78;
4687
4701
  const token = await config.getAccessToken();
4688
4702
  const userId = resolveUserIdFromToken(token);
4689
4703
  if (!userId) {
@@ -4711,7 +4725,7 @@ var createTelescupClient = (config) => ({
4711
4725
  }
4712
4726
  });
4713
4727
  const payload = response != null ? response : {};
4714
- const asset = mapAssetApiSearchRowToAsset((_a74 = payload.asset) != null ? _a74 : {});
4728
+ const asset = mapAssetApiSearchRowToAsset((_a78 = payload.asset) != null ? _a78 : {});
4715
4729
  if (!asset) {
4716
4730
  throw new TelescupClientError("Resposta inv\xE1lida do upload direto (asset-api).");
4717
4731
  }
@@ -4732,17 +4746,17 @@ var mergeFacetValues = (current, incoming) => {
4732
4746
  const map = /* @__PURE__ */ new Map();
4733
4747
  current == null ? void 0 : current.forEach((entry) => map.set(entry.value, entry));
4734
4748
  incoming == null ? void 0 : incoming.forEach((entry) => {
4735
- var _a74, _b7, _c;
4749
+ var _a78, _b7, _c;
4736
4750
  const previous = map.get(entry.value);
4737
4751
  map.set(entry.value, {
4738
4752
  value: entry.value,
4739
- label: (_b7 = (_a74 = entry.label) != null ? _a74 : previous == null ? void 0 : previous.label) != null ? _b7 : entry.value,
4753
+ label: (_b7 = (_a78 = entry.label) != null ? _a78 : previous == null ? void 0 : previous.label) != null ? _b7 : entry.value,
4740
4754
  count: (_c = entry.count) != null ? _c : previous == null ? void 0 : previous.count
4741
4755
  });
4742
4756
  });
4743
4757
  return Array.from(map.values()).sort((a, b) => {
4744
- var _a74, _b7;
4745
- return ((_a74 = a.label) != null ? _a74 : a.value).localeCompare((_b7 = b.label) != null ? _b7 : b.value);
4758
+ var _a78, _b7;
4759
+ return ((_a78 = a.label) != null ? _a78 : a.value).localeCompare((_b7 = b.label) != null ? _b7 : b.value);
4746
4760
  });
4747
4761
  };
4748
4762
  var DEFAULT_CACHE_MS = 3e5;
@@ -4836,9 +4850,9 @@ function useTelescupAssets(options) {
4836
4850
  ...sanitizeFilters(filters),
4837
4851
  pageSize
4838
4852
  }).then((data) => {
4839
- var _a74;
4853
+ var _a78;
4840
4854
  return {
4841
- items: (_a74 = data.items) != null ? _a74 : [],
4855
+ items: (_a78 = data.items) != null ? _a78 : [],
4842
4856
  nextCursor: data.nextCursor,
4843
4857
  total: data.total,
4844
4858
  facets: data.facets
@@ -4862,7 +4876,7 @@ function useTelescupAssets(options) {
4862
4876
  [cacheKey, cacheTimeMs, enabled, filters, pageSize, resolvedClient]
4863
4877
  );
4864
4878
  const loadMore = useCallback(async () => {
4865
- var _a74, _b7, _c, _d, _e, _f, _g;
4879
+ var _a78, _b7, _c, _d, _e, _f, _g;
4866
4880
  if (!state.nextCursor || isLoadingMore || isLoading) return;
4867
4881
  const requestSeq = requestSeqRef.current;
4868
4882
  setIsLoadingMore(true);
@@ -4876,7 +4890,7 @@ function useTelescupAssets(options) {
4876
4890
  });
4877
4891
  if (!aliveRef.current || requestSeq !== requestSeqRef.current) return;
4878
4892
  const merged = {
4879
- items: [...state.items, ...(_a74 = data.items) != null ? _a74 : []],
4893
+ items: [...state.items, ...(_a78 = data.items) != null ? _a78 : []],
4880
4894
  nextCursor: data.nextCursor,
4881
4895
  total: (_b7 = data.total) != null ? _b7 : state.total,
4882
4896
  facets: {
@@ -5034,13 +5048,14 @@ ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName;
5034
5048
 
5035
5049
  // src/components/cupcode/TelescupAssetPicker.tsx
5036
5050
  import { Expand } from "lucide-react";
5051
+ var import_meta2 = {};
5037
5052
  import { jsx as jsx35, jsxs as jsxs23 } from "react/jsx-runtime";
5038
5053
  var IMAGE_EXTENSIONS = /* @__PURE__ */ new Set(["jpg", "jpeg", "png", "gif", "webp", "avif", "svg", "bmp", "ico", "tif", "tiff"]);
5039
5054
  var VIDEO_EXTENSIONS = /* @__PURE__ */ new Set(["mp4", "mov", "webm", "mkv", "avi", "m4v", "wmv"]);
5040
5055
  var AUDIO_EXTENSIONS = /* @__PURE__ */ new Set(["mp3", "wav", "aac", "ogg", "flac", "m4a"]);
5041
5056
  var resolveAssetFamily = (asset) => {
5042
- var _a74, _b7, _c;
5043
- const explicitType = (_a74 = asset.type) == null ? void 0 : _a74.toLowerCase();
5057
+ var _a78, _b7, _c;
5058
+ const explicitType = (_a78 = asset.type) == null ? void 0 : _a78.toLowerCase();
5044
5059
  if (explicitType === "image" || explicitType === "video" || explicitType === "audio" || explicitType === "file") {
5045
5060
  return explicitType;
5046
5061
  }
@@ -5056,9 +5071,9 @@ var resolveAssetFamily = (asset) => {
5056
5071
  return "file";
5057
5072
  };
5058
5073
  var matchesAllowedAsset = (asset, allowed) => {
5059
- var _a74, _b7, _c, _d;
5074
+ var _a78, _b7, _c, _d;
5060
5075
  if (!allowed || allowed.length === 0) return true;
5061
- const mime = (_b7 = (_a74 = asset.mimeType) == null ? void 0 : _a74.toLowerCase()) != null ? _b7 : "";
5076
+ const mime = (_b7 = (_a78 = asset.mimeType) == null ? void 0 : _a78.toLowerCase()) != null ? _b7 : "";
5062
5077
  const ext = asset.extension ? `.${asset.extension.toLowerCase()}` : "";
5063
5078
  const type = (_d = (_c = asset.type) == null ? void 0 : _c.toLowerCase()) != null ? _d : "";
5064
5079
  const family = resolveAssetFamily(asset);
@@ -5113,10 +5128,10 @@ var UUID_REGEX3 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[
5113
5128
  var ROOT_FOLDERS_TO_HIDE = /* @__PURE__ */ new Set(["images", "videos"]);
5114
5129
  var normalizeFolderToken = (value) => value.trim().replace(/^\/+|\/+$/g, "").toLowerCase();
5115
5130
  var getLeafName = (value) => {
5116
- var _a74;
5131
+ var _a78;
5117
5132
  const normalized = normalizeFolderToken(value);
5118
5133
  const parts = normalized.split("/").filter(Boolean);
5119
- return (_a74 = parts[parts.length - 1]) != null ? _a74 : normalized;
5134
+ return (_a78 = parts[parts.length - 1]) != null ? _a78 : normalized;
5120
5135
  };
5121
5136
  var scoreFolderValue = (value, label) => {
5122
5137
  const normalizedValue = normalizeFolderToken(value);
@@ -5132,8 +5147,8 @@ var normalizeFacetOptions = (entries) => {
5132
5147
  if (!entries || !entries.length) return [];
5133
5148
  const byLabel = /* @__PURE__ */ new Map();
5134
5149
  entries.forEach((entry) => {
5135
- var _a74, _b7, _c, _d;
5136
- const value = (_a74 = entry.value) == null ? void 0 : _a74.trim();
5150
+ var _a78, _b7, _c, _d;
5151
+ const value = (_a78 = entry.value) == null ? void 0 : _a78.trim();
5137
5152
  if (!value) return;
5138
5153
  const label = ((_b7 = entry.label) == null ? void 0 : _b7.trim()) || value;
5139
5154
  const key = normalizeFolderToken(label);
@@ -5163,16 +5178,16 @@ var normalizeFacetOptions = (entries) => {
5163
5178
  const options = Array.from(byLabel.values());
5164
5179
  const groups = /* @__PURE__ */ new Map();
5165
5180
  options.forEach((option) => {
5166
- var _a74;
5181
+ var _a78;
5167
5182
  const leaf = getLeafName(option.label || option.value);
5168
- const list = (_a74 = groups.get(leaf)) != null ? _a74 : [];
5183
+ const list = (_a78 = groups.get(leaf)) != null ? _a78 : [];
5169
5184
  list.push(option);
5170
5185
  groups.set(leaf, list);
5171
5186
  });
5172
5187
  const collapsed = options.filter((option) => {
5173
- var _a74;
5188
+ var _a78;
5174
5189
  const leaf = getLeafName(option.label || option.value);
5175
- const group = (_a74 = groups.get(leaf)) != null ? _a74 : [];
5190
+ const group = (_a78 = groups.get(leaf)) != null ? _a78 : [];
5176
5191
  const hasPathVariant = group.some((entry) => normalizeFolderToken(entry.label).includes("/"));
5177
5192
  if (!hasPathVariant) return true;
5178
5193
  return normalizeFolderToken(option.label).includes("/");
@@ -5183,8 +5198,8 @@ var normalizeFacetOptions = (entries) => {
5183
5198
  var collectFacetOptions = (items, pick, pickLabel) => {
5184
5199
  const options = /* @__PURE__ */ new Map();
5185
5200
  items.forEach((asset) => {
5186
- var _a74, _b7, _c, _d;
5187
- const value = (_a74 = pick(asset)) == null ? void 0 : _a74.trim();
5201
+ var _a78, _b7, _c, _d;
5202
+ const value = (_a78 = pick(asset)) == null ? void 0 : _a78.trim();
5188
5203
  if (!value) return;
5189
5204
  const current = options.get(value);
5190
5205
  options.set(value, {
@@ -5213,6 +5228,27 @@ var TelescupAssetPicker = ({
5213
5228
  const [typeFilter, setTypeFilter] = useState7("all");
5214
5229
  const [folderFilter, setFolderFilter] = useState7("all");
5215
5230
  const [previewAsset, setPreviewAsset] = useState7(null);
5231
+ const allowedFamilies = useMemo4(() => {
5232
+ if (!allowedTypes || allowedTypes.length === 0) {
5233
+ return { image: true, video: true };
5234
+ }
5235
+ const flags = { image: false, video: false };
5236
+ allowedTypes.forEach((rawRule) => {
5237
+ const rule = rawRule.toLowerCase();
5238
+ if (rule.includes("image") || rule.includes(".jpg") || rule.includes(".jpeg") || rule.includes(".png") || rule.includes(".webp")) {
5239
+ flags.image = true;
5240
+ }
5241
+ if (rule.includes("video") || rule.includes(".mp4") || rule.includes(".webm") || rule.includes(".mov")) {
5242
+ flags.video = true;
5243
+ }
5244
+ });
5245
+ return flags;
5246
+ }, [allowedTypes]);
5247
+ React20.useEffect(() => {
5248
+ if (typeFilter === "video" && !allowedFamilies.video) {
5249
+ setTypeFilter("all");
5250
+ }
5251
+ }, [allowedFamilies.video, typeFilter]);
5216
5252
  const baseFilters = useMemo4(
5217
5253
  () => ({
5218
5254
  query: query || void 0,
@@ -5242,21 +5278,21 @@ var TelescupAssetPicker = ({
5242
5278
  return folderOptions.find((option) => option.value === folderFilter);
5243
5279
  }, [folderFilter, folderOptions]);
5244
5280
  const filteredItems = useMemo4(() => {
5245
- var _a74;
5281
+ var _a78;
5246
5282
  const selectedFolderAliases = new Set(
5247
- ((_a74 = selectedFolderOption == null ? void 0 : selectedFolderOption.aliases) != null ? _a74 : folderFilter === "all" ? [] : [folderFilter]).map(
5283
+ ((_a78 = selectedFolderOption == null ? void 0 : selectedFolderOption.aliases) != null ? _a78 : folderFilter === "all" ? [] : [folderFilter]).map(
5248
5284
  (entry) => normalizeFolderToken(entry)
5249
5285
  )
5250
5286
  );
5251
5287
  return items.filter((asset) => {
5252
- var _a75, _b7;
5288
+ var _a79, _b7;
5253
5289
  if (!matchesAllowedAsset(asset, allowedTypes)) return false;
5254
5290
  if (typeFilter !== "all") {
5255
5291
  const family = resolveAssetFamily(asset);
5256
5292
  if (family !== typeFilter) return false;
5257
5293
  }
5258
5294
  if (folderFilter !== "all") {
5259
- const folderIdToken = normalizeFolderToken((_a75 = asset.folderId) != null ? _a75 : "");
5295
+ const folderIdToken = normalizeFolderToken((_a79 = asset.folderId) != null ? _a79 : "");
5260
5296
  const folderNameToken = normalizeFolderToken((_b7 = asset.folderName) != null ? _b7 : "");
5261
5297
  if (!selectedFolderAliases.has(folderIdToken) && !selectedFolderAliases.has(folderNameToken)) {
5262
5298
  return false;
@@ -5265,6 +5301,46 @@ var TelescupAssetPicker = ({
5265
5301
  return true;
5266
5302
  });
5267
5303
  }, [allowedTypes, folderFilter, items, selectedFolderOption == null ? void 0 : selectedFolderOption.aliases, typeFilter]);
5304
+ React20.useEffect(() => {
5305
+ if (!import_meta2.env.DEV) return;
5306
+ const familyCount = items.reduce((acc, asset) => {
5307
+ var _a78, _b7;
5308
+ const key = (_a78 = resolveAssetFamily(asset)) != null ? _a78 : "unknown";
5309
+ acc[key] = ((_b7 = acc[key]) != null ? _b7 : 0) + 1;
5310
+ return acc;
5311
+ }, {});
5312
+ console.log("[telescup][picker]", {
5313
+ query,
5314
+ typeFilter,
5315
+ folderFilter,
5316
+ allowedTypes,
5317
+ totalFromApi: total,
5318
+ itemsLoaded: items.length,
5319
+ filteredItems: filteredItems.length,
5320
+ hasMore,
5321
+ isLoading,
5322
+ isLoadingMore,
5323
+ familyCount,
5324
+ sampleItems: items.slice(0, 5).map((asset) => ({
5325
+ id: asset.id,
5326
+ type: asset.type,
5327
+ mimeType: asset.mimeType,
5328
+ extension: asset.extension,
5329
+ family: resolveAssetFamily(asset)
5330
+ }))
5331
+ });
5332
+ }, [
5333
+ filteredItems.length,
5334
+ folderFilter,
5335
+ hasMore,
5336
+ isLoading,
5337
+ isLoadingMore,
5338
+ items,
5339
+ query,
5340
+ allowedTypes,
5341
+ total,
5342
+ typeFilter
5343
+ ]);
5268
5344
  const handleSelect = useCallback2(
5269
5345
  (asset) => {
5270
5346
  let nextIds = [];
@@ -5305,8 +5381,8 @@ var TelescupAssetPicker = ({
5305
5381
  /* @__PURE__ */ jsx35(SelectTrigger, { className: "border-border/70 bg-background/60 dark:border-white/15", children: /* @__PURE__ */ jsx35(SelectValue, { placeholder: labels.filters.type }) }),
5306
5382
  /* @__PURE__ */ jsxs23(SelectContent, { children: [
5307
5383
  /* @__PURE__ */ jsx35(SelectItem, { value: "all", children: labels.filters.allTypes }),
5308
- /* @__PURE__ */ jsx35(SelectItem, { value: "image", children: "Imagem" }),
5309
- /* @__PURE__ */ jsx35(SelectItem, { value: "video", children: "V\xEDdeo" })
5384
+ allowedFamilies.image ? /* @__PURE__ */ jsx35(SelectItem, { value: "image", children: "Imagem" }) : null,
5385
+ allowedFamilies.video ? /* @__PURE__ */ jsx35(SelectItem, { value: "video", children: "V\xEDdeo" }) : null
5310
5386
  ] })
5311
5387
  ] }),
5312
5388
  /* @__PURE__ */ jsxs23(Select, { value: folderFilter, onValueChange: setFolderFilter, children: [
@@ -5480,7 +5556,7 @@ function useTelescupUploadQueue(options) {
5480
5556
  activeRef.current += 1;
5481
5557
  updateItem(next.id, { status: "uploading", progress: 0, error: void 0 });
5482
5558
  const run = async () => {
5483
- var _a74, _b7, _c;
5559
+ var _a78, _b7, _c;
5484
5560
  try {
5485
5561
  if (TELESCUP_UPLOAD_MODE === "direct") {
5486
5562
  const completed2 = await client.uploadDirect(next.file);
@@ -5499,7 +5575,7 @@ function useTelescupUploadQueue(options) {
5499
5575
  size: next.file.size,
5500
5576
  mimeType: next.file.type,
5501
5577
  folderId,
5502
- conflict: (_a74 = next.conflictPolicy) != null ? _a74 : conflictPolicy
5578
+ conflict: (_a78 = next.conflictPolicy) != null ? _a78 : conflictPolicy
5503
5579
  });
5504
5580
  const conflictDetected = init.conflict === "ask" || init.conflict === "conflict" || init.conflict === "exists" || init.existingAsset && !init.uploadUrl;
5505
5581
  if (conflictDetected) {
@@ -5637,7 +5713,7 @@ var TelescupUploader = ({
5637
5713
  className,
5638
5714
  onAssetUploaded
5639
5715
  }) => {
5640
- var _a74;
5716
+ var _a78;
5641
5717
  const inputRef = useRef10(null);
5642
5718
  const [dragActive, setDragActive] = useState9(false);
5643
5719
  const {
@@ -5704,8 +5780,8 @@ var TelescupUploader = ({
5704
5780
  size: "sm",
5705
5781
  variant: "secondary",
5706
5782
  onClick: () => {
5707
- var _a75;
5708
- return (_a75 = inputRef.current) == null ? void 0 : _a75.click();
5783
+ var _a79;
5784
+ return (_a79 = inputRef.current) == null ? void 0 : _a79.click();
5709
5785
  },
5710
5786
  children: labels.uploader.browse
5711
5787
  }
@@ -5719,8 +5795,8 @@ var TelescupUploader = ({
5719
5795
  accept,
5720
5796
  multiple,
5721
5797
  onChange: (event) => {
5722
- var _a75;
5723
- if ((_a75 = event.target.files) == null ? void 0 : _a75.length) {
5798
+ var _a79;
5799
+ if ((_a79 = event.target.files) == null ? void 0 : _a79.length) {
5724
5800
  handleFiles(event.target.files);
5725
5801
  event.currentTarget.value = "";
5726
5802
  }
@@ -5755,7 +5831,7 @@ var TelescupUploader = ({
5755
5831
  /* @__PURE__ */ jsx37(AlertDialogTitle, { children: labels.conflict.title }),
5756
5832
  /* @__PURE__ */ jsx37(AlertDialogDescription, { children: labels.conflict.description })
5757
5833
  ] }),
5758
- ((_a74 = conflictItem == null ? void 0 : conflictItem.existingAsset) == null ? void 0 : _a74.id) ? /* @__PURE__ */ jsxs24("div", { className: "mt-3 rounded-lg border border-border bg-muted/30 p-3", children: [
5834
+ ((_a78 = conflictItem == null ? void 0 : conflictItem.existingAsset) == null ? void 0 : _a78.id) ? /* @__PURE__ */ jsxs24("div", { className: "mt-3 rounded-lg border border-border bg-muted/30 p-3", children: [
5759
5835
  /* @__PURE__ */ jsx37("p", { className: "text-xs font-semibold text-muted-foreground", children: "Asset existente" }),
5760
5836
  /* @__PURE__ */ jsx37("div", { className: "mt-2 h-28 overflow-hidden rounded-md", children: /* @__PURE__ */ jsx37(
5761
5837
  TelescupImage,
@@ -5978,7 +6054,7 @@ var DEFAULT_LABELS = {
5978
6054
  }
5979
6055
  };
5980
6056
  var mergeLabels = (overrides) => {
5981
- var _a74;
6057
+ var _a78;
5982
6058
  if (!overrides) return DEFAULT_LABELS;
5983
6059
  return {
5984
6060
  ...DEFAULT_LABELS,
@@ -5992,16 +6068,16 @@ var mergeLabels = (overrides) => {
5992
6068
  meta: {
5993
6069
  ...DEFAULT_LABELS.meta,
5994
6070
  ...overrides.meta,
5995
- fields: { ...DEFAULT_LABELS.meta.fields, ...(_a74 = overrides.meta) == null ? void 0 : _a74.fields }
6071
+ fields: { ...DEFAULT_LABELS.meta.fields, ...(_a78 = overrides.meta) == null ? void 0 : _a78.fields }
5996
6072
  },
5997
6073
  toasts: { ...DEFAULT_LABELS.toasts, ...overrides.toasts }
5998
6074
  };
5999
6075
  };
6000
6076
  var LANGUAGES = ["pt", "en", "es"];
6001
6077
  var getAssetMeta = (asset, lang) => {
6002
- var _a74, _b7;
6078
+ var _a78, _b7;
6003
6079
  if (!asset) return {};
6004
- if ((_a74 = asset.metaByLang) == null ? void 0 : _a74[lang]) return asset.metaByLang[lang];
6080
+ if ((_a78 = asset.metaByLang) == null ? void 0 : _a78[lang]) return asset.metaByLang[lang];
6005
6081
  return (_b7 = asset.meta) != null ? _b7 : {};
6006
6082
  };
6007
6083
  var TelescupMetaEditor = ({
@@ -6012,8 +6088,8 @@ var TelescupMetaEditor = ({
6012
6088
  labels,
6013
6089
  onAssetUpdated
6014
6090
  }) => {
6015
- var _a74, _b7, _c, _d, _e, _f, _g, _h;
6016
- const [activeAssetId, setActiveAssetId] = useState10((_b7 = (_a74 = assets[0]) == null ? void 0 : _a74.id) != null ? _b7 : "");
6091
+ var _a78, _b7, _c, _d, _e, _f, _g, _h;
6092
+ const [activeAssetId, setActiveAssetId] = useState10((_b7 = (_a78 = assets[0]) == null ? void 0 : _a78.id) != null ? _b7 : "");
6017
6093
  const [activeLang, setActiveLang] = useState10(
6018
6094
  LANGUAGES.includes(defaultLanguage) ? defaultLanguage : "pt"
6019
6095
  );
@@ -6031,18 +6107,18 @@ var TelescupMetaEditor = ({
6031
6107
  }, [activeAssetId, assets]);
6032
6108
  const asset = assets.find((item) => item.id === activeAssetId);
6033
6109
  const currentDraft = useMemo7(() => {
6034
- var _a75;
6035
- const existing = (_a75 = drafts[activeAssetId]) == null ? void 0 : _a75[activeLang];
6110
+ var _a79;
6111
+ const existing = (_a79 = drafts[activeAssetId]) == null ? void 0 : _a79[activeLang];
6036
6112
  if (existing) return existing;
6037
6113
  return getAssetMeta(asset, activeLang);
6038
6114
  }, [activeAssetId, activeLang, asset, drafts]);
6039
6115
  const updateDraft = (field, value) => {
6040
6116
  setDrafts((prev) => {
6041
- var _a75;
6117
+ var _a79;
6042
6118
  return {
6043
6119
  ...prev,
6044
6120
  [activeAssetId]: {
6045
- ...(_a75 = prev[activeAssetId]) != null ? _a75 : {},
6121
+ ...(_a79 = prev[activeAssetId]) != null ? _a79 : {},
6046
6122
  [activeLang]: {
6047
6123
  ...currentDraft,
6048
6124
  [field]: value
@@ -6110,11 +6186,11 @@ var TelescupMetaEditor = ({
6110
6186
  onAssetUpdated == null ? void 0 : onAssetUpdated(updated);
6111
6187
  const updatedMeta = getAssetMeta(updated, activeLang);
6112
6188
  setDrafts((prev) => {
6113
- var _a75;
6189
+ var _a79;
6114
6190
  return {
6115
6191
  ...prev,
6116
6192
  [asset.id]: {
6117
- ...(_a75 = prev[asset.id]) != null ? _a75 : {},
6193
+ ...(_a79 = prev[asset.id]) != null ? _a79 : {},
6118
6194
  [activeLang]: updatedMeta
6119
6195
  }
6120
6196
  };
@@ -6735,14 +6811,14 @@ var normalizeContrastMode = (value) => {
6735
6811
  return (value == null ? void 0 : value.trim().toLowerCase()) === "high" ? "high" : "normal";
6736
6812
  };
6737
6813
  var readStoredExperienceSettings = () => {
6738
- var _a74, _b7, _c;
6814
+ var _a78, _b7, _c;
6739
6815
  const fallback = defaultExperienceSettings();
6740
6816
  if (typeof window === "undefined") return fallback;
6741
6817
  try {
6742
6818
  const raw = window.localStorage.getItem(EXPERIENCE_SETTINGS_STORAGE_KEY);
6743
6819
  const parsed = raw ? JSON.parse(raw) : null;
6744
6820
  const storedThemePreference = window.localStorage.getItem(THEME_PREFERENCE_STORAGE_KEY);
6745
- const legacyTheme = (_a74 = window.localStorage.getItem(THEME_STORAGE_KEY)) != null ? _a74 : window.localStorage.getItem(LEGACY_THEME_STORAGE_KEY);
6821
+ const legacyTheme = (_a78 = window.localStorage.getItem(THEME_STORAGE_KEY)) != null ? _a78 : window.localStorage.getItem(LEGACY_THEME_STORAGE_KEY);
6746
6822
  return {
6747
6823
  theme: normalizeThemePreference((_c = (_b7 = parsed == null ? void 0 : parsed.theme) != null ? _b7 : storedThemePreference) != null ? _c : legacyTheme),
6748
6824
  density: normalizeDensityMode(parsed == null ? void 0 : parsed.density),
@@ -6886,7 +6962,7 @@ var getNotificationTimestamp = (notification) => {
6886
6962
  return Number.isNaN(parsed) ? 0 : parsed;
6887
6963
  };
6888
6964
  var formatNotificationDateTime = (notification) => {
6889
- var _a74;
6965
+ var _a78;
6890
6966
  if (notification.createdAt) {
6891
6967
  const parsed = new Date(notification.createdAt);
6892
6968
  if (!Number.isNaN(parsed.getTime())) {
@@ -6898,7 +6974,7 @@ var formatNotificationDateTime = (notification) => {
6898
6974
  });
6899
6975
  }
6900
6976
  }
6901
- return ((_a74 = notification.timeLabel) == null ? void 0 : _a74.trim()) || "Agora";
6977
+ return ((_a78 = notification.timeLabel) == null ? void 0 : _a78.trim()) || "Agora";
6902
6978
  };
6903
6979
  var getNotificationDayKey = (notification) => {
6904
6980
  const timestamp = getNotificationTimestamp(notification);
@@ -6971,9 +7047,9 @@ var extractSharedFilesFromMessages = (messages) => {
6971
7047
  return files;
6972
7048
  };
6973
7049
  var resolveTelescupImageUrl = (value, options) => {
6974
- var _a74, _b7, _c;
7050
+ var _a78, _b7, _c;
6975
7051
  return resolveTelescupImageURL(value, {
6976
- width: (_a74 = options == null ? void 0 : options.width) != null ? _a74 : 96,
7052
+ width: (_a78 = options == null ? void 0 : options.width) != null ? _a78 : 96,
6977
7053
  height: (_b7 = options == null ? void 0 : options.height) != null ? _b7 : 96,
6978
7054
  fit: "cover",
6979
7055
  format: "avif",
@@ -6981,12 +7057,12 @@ var resolveTelescupImageUrl = (value, options) => {
6981
7057
  });
6982
7058
  };
6983
7059
  var resolveGroupAvatarFromTelescup = (asset, fallbackId) => {
6984
- var _a74, _b7;
6985
- return (_b7 = (_a74 = resolveTelescupImageUrl(asset == null ? void 0 : asset.url)) != null ? _a74 : resolveTelescupImageUrl(asset == null ? void 0 : asset.id)) != null ? _b7 : resolveTelescupImageUrl(fallbackId);
7060
+ var _a78, _b7;
7061
+ return (_b7 = (_a78 = resolveTelescupImageUrl(asset == null ? void 0 : asset.url)) != null ? _a78 : resolveTelescupImageUrl(asset == null ? void 0 : asset.id)) != null ? _b7 : resolveTelescupImageUrl(fallbackId);
6986
7062
  };
6987
7063
  var resolveProfileAvatarFromTelescup = (asset, fallbackId) => {
6988
- var _a74, _b7;
6989
- 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 });
7064
+ var _a78, _b7;
7065
+ 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 });
6990
7066
  };
6991
7067
  var playIncomingMessageSound = () => {
6992
7068
  if (typeof window === "undefined") return;
@@ -7125,7 +7201,7 @@ var UserMenuCupcode = ({
7125
7201
  panels,
7126
7202
  className
7127
7203
  }) => {
7128
- var _a74;
7204
+ var _a78;
7129
7205
  const [open, setOpen] = useState11(false);
7130
7206
  const [activeTab, setActiveTab] = useState11("profile");
7131
7207
  const [isLoggingOut, setIsLoggingOut] = useState11(false);
@@ -7229,12 +7305,12 @@ var UserMenuCupcode = ({
7229
7305
  );
7230
7306
  const normalizedNotificationFeed = useMemo8(
7231
7307
  () => resolvedNotificationFeed.map((notification) => {
7232
- var _a75;
7308
+ var _a79;
7233
7309
  const kind = normalizeNotificationKind(notification.kind);
7234
7310
  return {
7235
7311
  ...notification,
7236
7312
  kind,
7237
- topic: (_a75 = notification.topic) != null ? _a75 : NOTIFICATION_KIND_META[kind].topicFallback
7313
+ topic: (_a79 = notification.topic) != null ? _a79 : NOTIFICATION_KIND_META[kind].topicFallback
7238
7314
  };
7239
7315
  }),
7240
7316
  [resolvedNotificationFeed]
@@ -7269,9 +7345,9 @@ var UserMenuCupcode = ({
7269
7345
  const groupedNotifications = useMemo8(() => {
7270
7346
  const groups = /* @__PURE__ */ new Map();
7271
7347
  filteredNotifications.forEach((notification) => {
7272
- var _a75, _b7;
7348
+ var _a79, _b7;
7273
7349
  const kind = normalizeNotificationKind(notification.kind);
7274
- const key = notificationPreferences.grouping === "topic" ? (_a75 = notification.topic) != null ? _a75 : NOTIFICATION_KIND_META[kind].topicFallback : getNotificationDayKey(notification);
7350
+ const key = notificationPreferences.grouping === "topic" ? (_a79 = notification.topic) != null ? _a79 : NOTIFICATION_KIND_META[kind].topicFallback : getNotificationDayKey(notification);
7275
7351
  const current = (_b7 = groups.get(key)) != null ? _b7 : [];
7276
7352
  current.push(notification);
7277
7353
  groups.set(key, current);
@@ -7359,7 +7435,7 @@ var UserMenuCupcode = ({
7359
7435
  }).slice(0, 6);
7360
7436
  }, [recentActivity]);
7361
7437
  const isSendingChatMessage = isChatSending || isSendingInternalChatMessage;
7362
- const activeReactionPickerMessageId = (_a74 = activeReactionPicker == null ? void 0 : activeReactionPicker.messageId) != null ? _a74 : null;
7438
+ const activeReactionPickerMessageId = (_a78 = activeReactionPicker == null ? void 0 : activeReactionPicker.messageId) != null ? _a78 : null;
7363
7439
  const isChatSidebarOpen = isChatSidebarExpanded || isChatSidebarPinned;
7364
7440
  const hasTelescupAvatarSupport = Boolean(telescupBaseUrl && getTelescupAccessToken);
7365
7441
  const hasTelescupGroupAvatarSupport = hasTelescupAvatarSupport;
@@ -7373,8 +7449,8 @@ var UserMenuCupcode = ({
7373
7449
  meta.set(user.id, { lastMessage: null, lastTimestamp: 0, unreadCount: 0 });
7374
7450
  });
7375
7451
  resolvedAllChatMessages.forEach((message) => {
7376
- var _a75;
7377
- const current = (_a75 = meta.get(message.contactId)) != null ? _a75 : { lastMessage: null, lastTimestamp: 0, unreadCount: 0 };
7452
+ var _a79;
7453
+ const current = (_a79 = meta.get(message.contactId)) != null ? _a79 : { lastMessage: null, lastTimestamp: 0, unreadCount: 0 };
7378
7454
  const timestamp = getChatMessageTimestamp(message);
7379
7455
  if (timestamp >= current.lastTimestamp) {
7380
7456
  current.lastTimestamp = timestamp;
@@ -7394,10 +7470,10 @@ var UserMenuCupcode = ({
7394
7470
  return haystack.includes(query);
7395
7471
  });
7396
7472
  return filtered.sort((left, right) => {
7397
- var _a75, _b7, _c, _d;
7473
+ var _a79, _b7, _c, _d;
7398
7474
  const leftMeta = conversationMetaByUserId.get(left.id);
7399
7475
  const rightMeta = conversationMetaByUserId.get(right.id);
7400
- const leftUnread = (_a75 = leftMeta == null ? void 0 : leftMeta.unreadCount) != null ? _a75 : 0;
7476
+ const leftUnread = (_a79 = leftMeta == null ? void 0 : leftMeta.unreadCount) != null ? _a79 : 0;
7401
7477
  const rightUnread = (_b7 = rightMeta == null ? void 0 : rightMeta.unreadCount) != null ? _b7 : 0;
7402
7478
  if (leftUnread !== rightUnread) return rightUnread - leftUnread;
7403
7479
  const leftTimestamp = (_c = leftMeta == null ? void 0 : leftMeta.lastTimestamp) != null ? _c : 0;
@@ -7447,11 +7523,11 @@ var UserMenuCupcode = ({
7447
7523
  let changed = false;
7448
7524
  const next = { ...current };
7449
7525
  normalizedNotificationFeed.forEach((notification) => {
7450
- var _a75;
7526
+ var _a79;
7451
7527
  if (normalizeNotificationKind(notification.kind) !== "chat") return;
7452
7528
  const contactId = notification.actionChatUserId;
7453
7529
  if (!contactId) return;
7454
- if (((_a75 = resolvedChatUnreadByUser[contactId]) != null ? _a75 : 0) > 0) return;
7530
+ if (((_a79 = resolvedChatUnreadByUser[contactId]) != null ? _a79 : 0) > 0) return;
7455
7531
  if (next[notification.id] === true) return;
7456
7532
  next[notification.id] = true;
7457
7533
  changed = true;
@@ -7465,11 +7541,11 @@ var UserMenuCupcode = ({
7465
7541
  const visibleChatUnreadCount = resolvedChatUnreadCount;
7466
7542
  const firstUnreadChatUserId = useMemo8(
7467
7543
  () => {
7468
- var _a75, _b7;
7469
- return (_b7 = (_a75 = filteredAndSortedChatUsers.find((user) => {
7470
- var _a76;
7471
- return ((_a76 = resolvedChatUnreadByUser[user.id]) != null ? _a76 : 0) > 0;
7472
- })) == null ? void 0 : _a75.id) != null ? _b7 : null;
7544
+ var _a79, _b7;
7545
+ return (_b7 = (_a79 = filteredAndSortedChatUsers.find((user) => {
7546
+ var _a80;
7547
+ return ((_a80 = resolvedChatUnreadByUser[user.id]) != null ? _a80 : 0) > 0;
7548
+ })) == null ? void 0 : _a79.id) != null ? _b7 : null;
7473
7549
  },
7474
7550
  [filteredAndSortedChatUsers, resolvedChatUnreadByUser]
7475
7551
  );
@@ -7528,11 +7604,11 @@ var UserMenuCupcode = ({
7528
7604
  );
7529
7605
  const openChatPanel = useCallback5(
7530
7606
  (contactId) => {
7531
- var _a75, _b7, _c, _d, _e;
7607
+ var _a79, _b7, _c, _d, _e;
7532
7608
  setIsLogoutConfirmOpen(false);
7533
7609
  setOpen(true);
7534
7610
  setActiveTab("chat");
7535
- 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 : "";
7611
+ 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 : "";
7536
7612
  if (!targetContactId) return;
7537
7613
  setActiveChatUserId(targetContactId);
7538
7614
  markConversationRead(targetContactId);
@@ -7566,8 +7642,8 @@ var UserMenuCupcode = ({
7566
7642
  const reactionsByMessageId = useMemo8(() => {
7567
7643
  const grouped = /* @__PURE__ */ new Map();
7568
7644
  resolvedAllChatReactions.forEach((reaction) => {
7569
- var _a75, _b7;
7570
- const byEmoji = (_a75 = grouped.get(reaction.messageId)) != null ? _a75 : /* @__PURE__ */ new Map();
7645
+ var _a79, _b7;
7646
+ const byEmoji = (_a79 = grouped.get(reaction.messageId)) != null ? _a79 : /* @__PURE__ */ new Map();
7571
7647
  const current = (_b7 = byEmoji.get(reaction.emoji)) != null ? _b7 : { emoji: reaction.emoji, count: 0, reactedByMe: false };
7572
7648
  current.count += 1;
7573
7649
  if (resolvedCurrentChatUserId && reaction.userId === resolvedCurrentChatUserId) {
@@ -7765,9 +7841,9 @@ var UserMenuCupcode = ({
7765
7841
  const wasFocusModeActive = wasFocusModeActiveRef.current;
7766
7842
  if (wasFocusModeActive && !isFocusModeActive && suppressedFocusNotifications.length) {
7767
7843
  const byType = suppressedFocusNotifications.reduce((acc, notification) => {
7768
- var _a75;
7844
+ var _a79;
7769
7845
  const kind = normalizeNotificationKind(notification.kind);
7770
- acc[kind] = ((_a75 = acc[kind]) != null ? _a75 : 0) + 1;
7846
+ acc[kind] = ((_a79 = acc[kind]) != null ? _a79 : 0) + 1;
7771
7847
  return acc;
7772
7848
  }, { system: 0, comment: 0, access: 0, billing: 0, chat: 0, security: 0 });
7773
7849
  const summaryParts = NOTIFICATION_KIND_ORDER.filter((kind) => byType[kind] > 0).map(
@@ -7797,9 +7873,9 @@ var UserMenuCupcode = ({
7797
7873
  return;
7798
7874
  }
7799
7875
  setActiveChatUserId((current) => {
7800
- var _a75, _b7;
7876
+ var _a79, _b7;
7801
7877
  if (current && chatUsersList.some((user) => user.id === current)) return current;
7802
- return (_b7 = (_a75 = filteredAndSortedChatUsers[0]) == null ? void 0 : _a75.id) != null ? _b7 : chatUsersList[0].id;
7878
+ return (_b7 = (_a79 = filteredAndSortedChatUsers[0]) == null ? void 0 : _a79.id) != null ? _b7 : chatUsersList[0].id;
7803
7879
  });
7804
7880
  }, [chatUsersList, filteredAndSortedChatUsers]);
7805
7881
  useEffect14(() => {
@@ -7841,7 +7917,7 @@ var UserMenuCupcode = ({
7841
7917
  };
7842
7918
  }, [activeReactionPickerMessageId]);
7843
7919
  useEffect14(() => {
7844
- var _a75;
7920
+ var _a79;
7845
7921
  if (!hasBootstrappedIncomingMessagesRef.current && isChatLoading) return;
7846
7922
  const knownIncomingIds = seenIncomingMessageIdsRef.current;
7847
7923
  const incomingMessages = resolvedAllChatMessages.filter((message) => message.sender === "them" && !message.readAt);
@@ -7863,9 +7939,9 @@ var UserMenuCupcode = ({
7863
7939
  return;
7864
7940
  }
7865
7941
  const generatedNotifications = relevantIncomingMessages.map((message) => {
7866
- var _a76, _b7, _c;
7942
+ var _a80, _b7, _c;
7867
7943
  const contact = chatUsersList.find((user) => user.id === message.contactId);
7868
- const createdAt = (_a76 = message.createdAt) != null ? _a76 : (/* @__PURE__ */ new Date()).toISOString();
7944
+ const createdAt = (_a80 = message.createdAt) != null ? _a80 : (/* @__PURE__ */ new Date()).toISOString();
7869
7945
  const previewText = chatSettings.showMessagePreview ? summarizeChatText(message.text, 100) : "Nova mensagem no chat.";
7870
7946
  return {
7871
7947
  id: `chat-notification-${message.id}`,
@@ -7887,7 +7963,7 @@ var UserMenuCupcode = ({
7887
7963
  )[0];
7888
7964
  if (latestRelevantMessage) {
7889
7965
  const latestContact = chatUsersList.find((user) => user.id === latestRelevantMessage.contactId);
7890
- const senderName = (_a75 = latestContact == null ? void 0 : latestContact.name) != null ? _a75 : "usu\xE1rio";
7966
+ const senderName = (_a79 = latestContact == null ? void 0 : latestContact.name) != null ? _a79 : "usu\xE1rio";
7891
7967
  const latestPreview = chatSettings.showMessagePreview ? summarizeChatText(latestRelevantMessage.text, 96) : "Nova mensagem";
7892
7968
  const messageCount = relevantIncomingMessages.length;
7893
7969
  const messageCountLabel = messageCount > 99 ? "99+" : String(messageCount);
@@ -7936,10 +8012,10 @@ var UserMenuCupcode = ({
7936
8012
  return;
7937
8013
  }
7938
8014
  generatedNotifications.forEach((chatNotification) => {
7939
- var _a76;
8015
+ var _a80;
7940
8016
  const notification = new Notification(chatNotification.title, {
7941
8017
  body: chatSettings.showMessagePreview ? chatNotification.description : "Voc\xEA recebeu uma nova mensagem.",
7942
- tag: `cc-chat-${(_a76 = chatNotification.actionChatUserId) != null ? _a76 : chatNotification.id}`
8018
+ tag: `cc-chat-${(_a80 = chatNotification.actionChatUserId) != null ? _a80 : chatNotification.id}`
7943
8019
  });
7944
8020
  notification.onclick = () => {
7945
8021
  window.focus();
@@ -7966,14 +8042,14 @@ var UserMenuCupcode = ({
7966
8042
  ]);
7967
8043
  const activeChatUser = useMemo8(
7968
8044
  () => {
7969
- var _a75;
7970
- return (_a75 = chatUsersList.find((user) => user.id === activeChatUserId)) != null ? _a75 : null;
8045
+ var _a79;
8046
+ return (_a79 = chatUsersList.find((user) => user.id === activeChatUserId)) != null ? _a79 : null;
7971
8047
  },
7972
8048
  [activeChatUserId, chatUsersList]
7973
8049
  );
7974
8050
  const activeGroupMembers = useMemo8(() => {
7975
- var _a75;
7976
- if (!(activeChatUser == null ? void 0 : activeChatUser.isGroup) || !((_a75 = activeChatUser.memberIds) == null ? void 0 : _a75.length)) return [];
8051
+ var _a79;
8052
+ if (!(activeChatUser == null ? void 0 : activeChatUser.isGroup) || !((_a79 = activeChatUser.memberIds) == null ? void 0 : _a79.length)) return [];
7977
8053
  const members = activeChatUser.memberIds.map((memberId) => baseChatUsersList.find((user) => user.id === memberId)).filter((member) => Boolean(member));
7978
8054
  return members;
7979
8055
  }, [activeChatUser, baseChatUsersList]);
@@ -8012,8 +8088,8 @@ var UserMenuCupcode = ({
8012
8088
  return items;
8013
8089
  }, [activeChatMessages]);
8014
8090
  useEffect14(() => {
8015
- var _a75;
8016
- const conversationId = (_a75 = activeChatUser == null ? void 0 : activeChatUser.id) != null ? _a75 : null;
8091
+ var _a79;
8092
+ const conversationId = (_a79 = activeChatUser == null ? void 0 : activeChatUser.id) != null ? _a79 : null;
8017
8093
  if (!conversationId) {
8018
8094
  activeConversationIdRef.current = null;
8019
8095
  activeConversationMessageIdsRef.current = /* @__PURE__ */ new Set();
@@ -8066,9 +8142,9 @@ var UserMenuCupcode = ({
8066
8142
  });
8067
8143
  }, [activeChatUser, resolvedChatLogs]);
8068
8144
  const replyToMessage = useMemo8(() => {
8069
- var _a75;
8145
+ var _a79;
8070
8146
  if (!replyToMessageId) return null;
8071
- return (_a75 = activeChatMessagesMap.get(replyToMessageId)) != null ? _a75 : null;
8147
+ return (_a79 = activeChatMessagesMap.get(replyToMessageId)) != null ? _a79 : null;
8072
8148
  }, [activeChatMessagesMap, replyToMessageId]);
8073
8149
  useEffect14(() => {
8074
8150
  if (!replyToMessageId) return;
@@ -8095,9 +8171,9 @@ var UserMenuCupcode = ({
8095
8171
  }
8096
8172
  }, [activeChatUser]);
8097
8173
  useEffect14(() => {
8098
- var _a75;
8174
+ var _a79;
8099
8175
  if (!open || activeTab !== "chat" || !activeChatUser || activeChatUser.isGroup) return;
8100
- const unreadCount = (_a75 = resolvedChatUnreadByUser[activeChatUser.id]) != null ? _a75 : 0;
8176
+ const unreadCount = (_a79 = resolvedChatUnreadByUser[activeChatUser.id]) != null ? _a79 : 0;
8101
8177
  if (unreadCount <= 0) return;
8102
8178
  const contactId = activeChatUser.id;
8103
8179
  if (pendingReadRequestsRef.current.has(contactId)) return;
@@ -8173,13 +8249,13 @@ var UserMenuCupcode = ({
8173
8249
  openAccountsPath("/security#sessions");
8174
8250
  };
8175
8251
  const runOpenIntegrations = (provider) => {
8176
- var _a75;
8252
+ var _a79;
8177
8253
  if (!provider) {
8178
8254
  openAccountsPath("/integrations");
8179
8255
  return;
8180
8256
  }
8181
8257
  const option = INTEGRATION_OPTIONS.find((integration) => integration.id === provider);
8182
- openAccountsPath((_a75 = option == null ? void 0 : option.accountPath) != null ? _a75 : "/integrations");
8258
+ openAccountsPath((_a79 = option == null ? void 0 : option.accountPath) != null ? _a79 : "/integrations");
8183
8259
  };
8184
8260
  const changeStatus = (nextStatus) => {
8185
8261
  if (nextStatus === "offline") return;
@@ -8546,9 +8622,9 @@ var UserMenuCupcode = ({
8546
8622
  };
8547
8623
  const handleProfileAvatarChange = useCallback5(
8548
8624
  async (ids, assets) => {
8549
- var _a75, _b7, _c;
8625
+ var _a79, _b7, _c;
8550
8626
  const selectedAsset = assets == null ? void 0 : assets[0];
8551
- const selectedIdRaw = (_a75 = ids[0]) == null ? void 0 : _a75.trim();
8627
+ const selectedIdRaw = (_a79 = ids[0]) == null ? void 0 : _a79.trim();
8552
8628
  const selectedId = (_c = (_b7 = parseAssetId(selectedIdRaw)) != null ? _b7 : parseAssetId(selectedAsset == null ? void 0 : selectedAsset.id)) != null ? _c : parseAssetId(selectedAsset == null ? void 0 : selectedAsset.url);
8553
8629
  if (!selectedId) {
8554
8630
  toast({
@@ -8591,7 +8667,7 @@ var UserMenuCupcode = ({
8591
8667
  [isProfileAvatarSaving, onProfileAvatarChange, resolvedProfileAvatarUrl]
8592
8668
  );
8593
8669
  const sendChatMessage = async () => {
8594
- var _a75, _b7;
8670
+ var _a79, _b7;
8595
8671
  if (!activeChatUser) return;
8596
8672
  const text = chatDraft.trim();
8597
8673
  if (!text || isSendingChatMessage) return;
@@ -8603,7 +8679,7 @@ var UserMenuCupcode = ({
8603
8679
  await onChatSendMessage({
8604
8680
  recipientId: activeChatUser.id,
8605
8681
  text,
8606
- replyToMessageId: (_a75 = replyToMessage == null ? void 0 : replyToMessage.id) != null ? _a75 : null
8682
+ replyToMessageId: (_a79 = replyToMessage == null ? void 0 : replyToMessage.id) != null ? _a79 : null
8607
8683
  });
8608
8684
  setChatDraft("");
8609
8685
  setShowEmojiPicker(false);
@@ -8645,7 +8721,7 @@ var UserMenuCupcode = ({
8645
8721
  });
8646
8722
  };
8647
8723
  const renderDefaultPanel = () => {
8648
- var _a75, _b7, _c, _d;
8724
+ var _a79, _b7, _c, _d, _e;
8649
8725
  if (activeTab === "profile") {
8650
8726
  return /* @__PURE__ */ jsxs27("div", { className: "space-y-4", children: [
8651
8727
  /* @__PURE__ */ jsxs27("div", { className: "pt-1 text-center", children: [
@@ -8810,7 +8886,7 @@ var UserMenuCupcode = ({
8810
8886
  commitButtonLabel: "Salvar",
8811
8887
  closeOnCommit: true,
8812
8888
  multiple: false,
8813
- allowedTypes: ["image/*"],
8889
+ allowedTypes: ["image/*", "video/*"],
8814
8890
  maxSizeMB: 8,
8815
8891
  enableAI: false,
8816
8892
  enableMetaEditor: false,
@@ -8916,7 +8992,7 @@ var UserMenuCupcode = ({
8916
8992
  visibleGroupedNotifications.length ? visibleGroupedNotifications.map((group) => /* @__PURE__ */ jsxs27("section", { className: "space-y-1.5", children: [
8917
8993
  /* @__PURE__ */ jsx42("p", { className: "px-0.5 text-[11px] font-semibold uppercase tracking-[0.08em] text-muted-foreground", children: group.label }),
8918
8994
  /* @__PURE__ */ jsx42("div", { className: "space-y-1.5", children: group.items.map((notification) => {
8919
- var _a76;
8995
+ var _a80;
8920
8996
  const kind = normalizeNotificationKind(notification.kind);
8921
8997
  const meta = NOTIFICATION_KIND_META[kind];
8922
8998
  const Icon3 = meta.icon;
@@ -8945,7 +9021,7 @@ var UserMenuCupcode = ({
8945
9021
  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",
8946
9022
  children: [
8947
9023
  /* @__PURE__ */ jsx42(ExternalLink, { className: "h-3 w-3" }),
8948
- (_a76 = notification.actionLabel) != null ? _a76 : "Abrir"
9024
+ (_a80 = notification.actionLabel) != null ? _a80 : "Abrir"
8949
9025
  ]
8950
9026
  }
8951
9027
  ),
@@ -9173,7 +9249,7 @@ var UserMenuCupcode = ({
9173
9249
  }
9174
9250
  if (activeTab === "chat") {
9175
9251
  const canSendChatMessage = Boolean(activeChatUser) && chatDraft.trim() !== "" && !isSendingChatMessage && !isChatLoading;
9176
- const activeConversationUnreadCount = activeChatUser ? (_a75 = resolvedChatUnreadByUser[activeChatUser.id]) != null ? _a75 : 0 : 0;
9252
+ const activeConversationUnreadCount = activeChatUser ? (_a79 = resolvedChatUnreadByUser[activeChatUser.id]) != null ? _a79 : 0 : 0;
9177
9253
  return /* @__PURE__ */ jsx42("div", { className: "h-full", children: /* @__PURE__ */ jsxs27(
9178
9254
  "div",
9179
9255
  {
@@ -9252,10 +9328,10 @@ var UserMenuCupcode = ({
9252
9328
  }
9253
9329
  ),
9254
9330
  /* @__PURE__ */ jsx42("div", { className: "space-y-1", children: users.map((user) => {
9255
- var _a76, _b8, _c2;
9331
+ var _a80, _b8, _c2, _d2;
9256
9332
  const userInitials = buildInitials(user.name, user.username);
9257
9333
  const isCurrent = user.id === activeChatUserId;
9258
- const unreadCount = (_a76 = resolvedChatUnreadByUser[user.id]) != null ? _a76 : 0;
9334
+ const unreadCount = (_a80 = resolvedChatUnreadByUser[user.id]) != null ? _a80 : 0;
9259
9335
  const hasUnread = unreadCount > 0;
9260
9336
  const lastMessage = (_b8 = conversationMetaByUserId.get(user.id)) == null ? void 0 : _b8.lastMessage;
9261
9337
  return /* @__PURE__ */ jsxs27(
@@ -9302,7 +9378,7 @@ var UserMenuCupcode = ({
9302
9378
  summarizeChatText(lastMessage.text, 44)
9303
9379
  ] }) : "Nova mensagem"
9304
9380
  }
9305
- ) : /* @__PURE__ */ jsx42("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 })
9381
+ ) : /* @__PURE__ */ jsx42("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 })
9306
9382
  ]
9307
9383
  }
9308
9384
  )
@@ -9386,7 +9462,7 @@ var UserMenuCupcode = ({
9386
9462
  /* @__PURE__ */ jsx42("p", { className: "truncate text-xs font-semibold text-foreground", children: activeChatUser.name }),
9387
9463
  !isBadgeSuppressedByFocus && activeConversationUnreadCount > 0 ? /* @__PURE__ */ jsx42("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
9388
9464
  ] }),
9389
- /* @__PURE__ */ jsx42("p", { className: "truncate text-[11px] text-muted-foreground", children: activeChatUser.isGroup ? "Grupo" : PRESENCE_META[activeChatUser.status].label }),
9465
+ /* @__PURE__ */ jsx42("p", { className: "truncate text-[11px] text-muted-foreground", children: activeChatUser.isGroup ? "Grupo" : (_b7 = activeChatUser.statusLabel) != null ? _b7 : PRESENCE_META[activeChatUser.status].label }),
9390
9466
  activeChatUser.roleLabel ? /* @__PURE__ */ jsx42("p", { className: "truncate text-[11px] text-primary", children: activeChatUser.roleLabel }) : null,
9391
9467
  activeChatUser.isGroup && activeGroupMembers.length ? /* @__PURE__ */ jsxs27("p", { className: "truncate text-[11px] text-muted-foreground", children: [
9392
9468
  activeGroupMembers.length,
@@ -9472,12 +9548,12 @@ var UserMenuCupcode = ({
9472
9548
  className: "cc-scrollbar cc-scrollbar-purple relative flex-1 space-y-2 overflow-y-auto px-3 py-2.5",
9473
9549
  children: [
9474
9550
  isChatLoading ? /* @__PURE__ */ jsx42("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) => {
9475
- var _a76, _b8;
9551
+ var _a80, _b8;
9476
9552
  if (item.type === "day") {
9477
9553
  return /* @__PURE__ */ jsx42("div", { className: "flex justify-center py-1", children: /* @__PURE__ */ jsx42("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);
9478
9554
  }
9479
9555
  const { message } = item;
9480
- const replyMessage = message.replyToMessageId ? (_a76 = activeChatMessagesMap.get(message.replyToMessageId)) != null ? _a76 : null : null;
9556
+ const replyMessage = message.replyToMessageId ? (_a80 = activeChatMessagesMap.get(message.replyToMessageId)) != null ? _a80 : null : null;
9481
9557
  const reactions = (_b8 = reactionsByMessageId.get(message.id)) != null ? _b8 : [];
9482
9558
  const hasReadReceipt = Boolean(message.readAt);
9483
9559
  const isEditing = editingMessageId === message.id;
@@ -9651,7 +9727,7 @@ var UserMenuCupcode = ({
9651
9727
  "div",
9652
9728
  {
9653
9729
  ref: reactionPickerRef,
9654
- 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` },
9730
+ 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` },
9655
9731
  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)]",
9656
9732
  children: MESSAGE_REACTION_OPTIONS.map((emoji) => /* @__PURE__ */ jsx42(
9657
9733
  "button",
@@ -9807,8 +9883,8 @@ var UserMenuCupcode = ({
9807
9883
  ] })
9808
9884
  ] }),
9809
9885
  isChatSuperAdmin ? activeConversationLogs.length ? /* @__PURE__ */ jsx42("div", { className: "space-y-2", children: activeConversationLogs.map((entry) => {
9810
- var _a76;
9811
- const actorName = entry.actorId && entry.actorId === resolvedCurrentChatUserId ? "Voc\xEA" : (_a76 = entry.actorId) != null ? _a76 : "Usu\xE1rio";
9886
+ var _a80;
9887
+ const actorName = entry.actorId && entry.actorId === resolvedCurrentChatUserId ? "Voc\xEA" : (_a80 = entry.actorId) != null ? _a80 : "Usu\xE1rio";
9812
9888
  return /* @__PURE__ */ jsxs27(
9813
9889
  "article",
9814
9890
  {
@@ -9974,7 +10050,7 @@ var UserMenuCupcode = ({
9974
10050
  baseUrl: telescupBaseUrl,
9975
10051
  getAccessToken: getTelescupAccessToken,
9976
10052
  multiple: false,
9977
- allowedTypes: ["image/*"],
10053
+ allowedTypes: ["image/*", "video/*"],
9978
10054
  maxSizeMB: 8,
9979
10055
  enableAI: false,
9980
10056
  enableMetaEditor: false,
@@ -10096,7 +10172,7 @@ var UserMenuCupcode = ({
10096
10172
  "Idioma"
10097
10173
  ] }),
10098
10174
  /* @__PURE__ */ jsx42("div", { className: "mt-2", children: /* @__PURE__ */ jsxs27(Select, { value: resolvedLanguage, onValueChange: (value) => changeLanguage(value), children: [
10099
- /* @__PURE__ */ jsx42(SelectTrigger, { className: "h-9 rounded-xl border-border/70 bg-background/55 text-[11px] text-foreground", children: /* @__PURE__ */ jsx42("span", { className: "truncate", children: (_d = LANGUAGE_OPTIONS.find((option) => option.value === resolvedLanguage)) == null ? void 0 : _d.label }) }),
10175
+ /* @__PURE__ */ jsx42(SelectTrigger, { className: "h-9 rounded-xl border-border/70 bg-background/55 text-[11px] text-foreground", children: /* @__PURE__ */ jsx42("span", { className: "truncate", children: (_e = LANGUAGE_OPTIONS.find((option) => option.value === resolvedLanguage)) == null ? void 0 : _e.label }) }),
10100
10176
  /* @__PURE__ */ jsx42(SelectContent, { className: "glass-strong z-[820] border-border/70 text-foreground", children: LANGUAGE_OPTIONS.map((option) => /* @__PURE__ */ jsx42(SelectItem, { value: option.value, className: "text-xs", children: /* @__PURE__ */ jsxs27("span", { className: "flex w-full items-center justify-between gap-3", children: [
10101
10177
  /* @__PURE__ */ jsx42("span", { children: option.label }),
10102
10178
  /* @__PURE__ */ jsx42("span", { className: "text-[10px] font-semibold text-muted-foreground", children: option.shortLabel })
@@ -10783,7 +10859,7 @@ var FunctionsClient = class {
10783
10859
  */
10784
10860
  invoke(functionName_1) {
10785
10861
  return __awaiter(this, arguments, void 0, function* (functionName, options = {}) {
10786
- var _a74;
10862
+ var _a78;
10787
10863
  let timeoutId;
10788
10864
  let timeoutController;
10789
10865
  try {
@@ -10849,7 +10925,7 @@ var FunctionsClient = class {
10849
10925
  if (!response.ok) {
10850
10926
  throw new FunctionsHttpError(response);
10851
10927
  }
10852
- let responseType = ((_a74 = response.headers.get("Content-Type")) !== null && _a74 !== void 0 ? _a74 : "text/plain").split(";")[0].trim();
10928
+ let responseType = ((_a78 = response.headers.get("Content-Type")) !== null && _a78 !== void 0 ? _a78 : "text/plain").split(";")[0].trim();
10853
10929
  let data;
10854
10930
  if (responseType === "application/json") {
10855
10931
  data = yield response.json();
@@ -12095,7 +12171,7 @@ var WebSocketFactory = class {
12095
12171
  constructor() {
12096
12172
  }
12097
12173
  static detectEnvironment() {
12098
- var _a74;
12174
+ var _a78;
12099
12175
  if (typeof WebSocket !== "undefined") {
12100
12176
  return { type: "native", constructor: WebSocket };
12101
12177
  }
@@ -12112,7 +12188,7 @@ var WebSocketFactory = class {
12112
12188
  workaround: "Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."
12113
12189
  };
12114
12190
  }
12115
- if (typeof globalThis !== "undefined" && globalThis.EdgeRuntime || typeof navigator !== "undefined" && ((_a74 = navigator.userAgent) === null || _a74 === void 0 ? void 0 : _a74.includes("Vercel-Edge"))) {
12191
+ if (typeof globalThis !== "undefined" && globalThis.EdgeRuntime || typeof navigator !== "undefined" && ((_a78 = navigator.userAgent) === null || _a78 === void 0 ? void 0 : _a78.includes("Vercel-Edge"))) {
12116
12192
  return {
12117
12193
  type: "unsupported",
12118
12194
  error: "Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",
@@ -12196,7 +12272,7 @@ Suggested solution: ${env.workaround}`;
12196
12272
  try {
12197
12273
  const env = this.detectEnvironment();
12198
12274
  return env.type === "native" || env.type === "ws";
12199
- } catch (_a74) {
12275
+ } catch (_a78) {
12200
12276
  return false;
12201
12277
  }
12202
12278
  }
@@ -12270,29 +12346,29 @@ var Serializer = class {
12270
12346
  return callback(JSON.stringify(payload));
12271
12347
  }
12272
12348
  _binaryEncodeUserBroadcastPush(message) {
12273
- var _a74;
12274
- if (this._isArrayBuffer((_a74 = message.payload) === null || _a74 === void 0 ? void 0 : _a74.payload)) {
12349
+ var _a78;
12350
+ if (this._isArrayBuffer((_a78 = message.payload) === null || _a78 === void 0 ? void 0 : _a78.payload)) {
12275
12351
  return this._encodeBinaryUserBroadcastPush(message);
12276
12352
  } else {
12277
12353
  return this._encodeJsonUserBroadcastPush(message);
12278
12354
  }
12279
12355
  }
12280
12356
  _encodeBinaryUserBroadcastPush(message) {
12281
- var _a74, _b7;
12282
- const userPayload = (_b7 = (_a74 = message.payload) === null || _a74 === void 0 ? void 0 : _a74.payload) !== null && _b7 !== void 0 ? _b7 : new ArrayBuffer(0);
12357
+ var _a78, _b7;
12358
+ const userPayload = (_b7 = (_a78 = message.payload) === null || _a78 === void 0 ? void 0 : _a78.payload) !== null && _b7 !== void 0 ? _b7 : new ArrayBuffer(0);
12283
12359
  return this._encodeUserBroadcastPush(message, this.BINARY_ENCODING, userPayload);
12284
12360
  }
12285
12361
  _encodeJsonUserBroadcastPush(message) {
12286
- var _a74, _b7;
12287
- const userPayload = (_b7 = (_a74 = message.payload) === null || _a74 === void 0 ? void 0 : _a74.payload) !== null && _b7 !== void 0 ? _b7 : {};
12362
+ var _a78, _b7;
12363
+ const userPayload = (_b7 = (_a78 = message.payload) === null || _a78 === void 0 ? void 0 : _a78.payload) !== null && _b7 !== void 0 ? _b7 : {};
12288
12364
  const encoder = new TextEncoder();
12289
12365
  const encodedUserPayload = encoder.encode(JSON.stringify(userPayload)).buffer;
12290
12366
  return this._encodeUserBroadcastPush(message, this.JSON_ENCODING, encodedUserPayload);
12291
12367
  }
12292
12368
  _encodeUserBroadcastPush(message, encodingType, encodedPayload) {
12293
- var _a74, _b7;
12369
+ var _a78, _b7;
12294
12370
  const topic = message.topic;
12295
- const ref = (_a74 = message.ref) !== null && _a74 !== void 0 ? _a74 : "";
12371
+ const ref = (_a78 = message.ref) !== null && _a78 !== void 0 ? _a78 : "";
12296
12372
  const joinRef = (_b7 = message.join_ref) !== null && _b7 !== void 0 ? _b7 : "";
12297
12373
  const userEvent = message.payload.event;
12298
12374
  const rest = this.allowedMetadataKeys ? this._pick(message.payload, this.allowedMetadataKeys) : {};
@@ -12379,8 +12455,8 @@ var Serializer = class {
12379
12455
  return { join_ref: null, ref: null, topic, event: this.BROADCAST_EVENT, payload: data };
12380
12456
  }
12381
12457
  _isArrayBuffer(buffer) {
12382
- var _a74;
12383
- return buffer instanceof ArrayBuffer || ((_a74 = buffer === null || buffer === void 0 ? void 0 : buffer.constructor) === null || _a74 === void 0 ? void 0 : _a74.name) === "ArrayBuffer";
12458
+ var _a78;
12459
+ return buffer instanceof ArrayBuffer || ((_a78 = buffer === null || buffer === void 0 ? void 0 : buffer.constructor) === null || _a78 === void 0 ? void 0 : _a78.name) === "ArrayBuffer";
12384
12460
  }
12385
12461
  _pick(obj, keys) {
12386
12462
  if (!obj || typeof obj !== "object") {
@@ -12444,8 +12520,8 @@ var PostgresTypes;
12444
12520
  PostgresTypes2["tstzrange"] = "tstzrange";
12445
12521
  })(PostgresTypes || (PostgresTypes = {}));
12446
12522
  var convertChangeData = (columns, record, options = {}) => {
12447
- var _a74;
12448
- const skipTypes = (_a74 = options.skipTypes) !== null && _a74 !== void 0 ? _a74 : [];
12523
+ var _a78;
12524
+ const skipTypes = (_a78 = options.skipTypes) !== null && _a78 !== void 0 ? _a78 : [];
12449
12525
  if (!record) {
12450
12526
  return {};
12451
12527
  }
@@ -12535,7 +12611,7 @@ var toJson = (value) => {
12535
12611
  if (typeof value === "string") {
12536
12612
  try {
12537
12613
  return JSON.parse(value);
12538
- } catch (_a74) {
12614
+ } catch (_a78) {
12539
12615
  return value;
12540
12616
  }
12541
12617
  }
@@ -12627,9 +12703,9 @@ var Push = class {
12627
12703
  this.payload = Object.assign(Object.assign({}, this.payload), payload);
12628
12704
  }
12629
12705
  receive(status, callback) {
12630
- var _a74;
12706
+ var _a78;
12631
12707
  if (this._hasReceived(status)) {
12632
- callback((_a74 = this.receivedResp) === null || _a74 === void 0 ? void 0 : _a74.response);
12708
+ callback((_a78 = this.receivedResp) === null || _a78 === void 0 ? void 0 : _a78.response);
12633
12709
  }
12634
12710
  this.recHooks.push({ status, callback });
12635
12711
  return this;
@@ -12820,8 +12896,8 @@ var RealtimePresence = class _RealtimePresence {
12820
12896
  };
12821
12897
  }
12822
12898
  this.map(joins, (key, newPresences) => {
12823
- var _a74;
12824
- const currentPresences = (_a74 = state[key]) !== null && _a74 !== void 0 ? _a74 : [];
12899
+ var _a78;
12900
+ const currentPresences = (_a78 = state[key]) !== null && _a78 !== void 0 ? _a78 : [];
12825
12901
  state[key] = this.cloneDeep(newPresences);
12826
12902
  if (currentPresences.length > 0) {
12827
12903
  const joinedPresenceRefs = state[key].map((m) => m.presence_ref);
@@ -12949,7 +13025,7 @@ var RealtimeChannel = class _RealtimeChannel {
12949
13025
  * ```
12950
13026
  */
12951
13027
  constructor(topic, params = { config: {} }, socket) {
12952
- var _a74, _b7;
13028
+ var _a78, _b7;
12953
13029
  this.topic = topic;
12954
13030
  this.params = params;
12955
13031
  this.socket = socket;
@@ -13008,19 +13084,19 @@ var RealtimeChannel = class _RealtimeChannel {
13008
13084
  this.presence = new RealtimePresence(this);
13009
13085
  this.broadcastEndpointURL = httpEndpointURL(this.socket.endPoint);
13010
13086
  this.private = this.params.config.private || false;
13011
- if (!this.private && ((_b7 = (_a74 = this.params.config) === null || _a74 === void 0 ? void 0 : _a74.broadcast) === null || _b7 === void 0 ? void 0 : _b7.replay)) {
13087
+ if (!this.private && ((_b7 = (_a78 = this.params.config) === null || _a78 === void 0 ? void 0 : _a78.broadcast) === null || _b7 === void 0 ? void 0 : _b7.replay)) {
13012
13088
  throw `tried to use replay on public channel '${this.topic}'. It must be a private channel.`;
13013
13089
  }
13014
13090
  }
13015
13091
  /** Subscribe registers your client with the server */
13016
13092
  subscribe(callback, timeout = this.timeout) {
13017
- var _a74, _b7, _c;
13093
+ var _a78, _b7, _c;
13018
13094
  if (!this.socket.isConnected()) {
13019
13095
  this.socket.connect();
13020
13096
  }
13021
13097
  if (this.state == CHANNEL_STATES.closed) {
13022
13098
  const { config: { broadcast, presence, private: isPrivate } } = this.params;
13023
- 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 : [];
13099
+ 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 : [];
13024
13100
  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;
13025
13101
  const accessTokenPayload = {};
13026
13102
  const config = {
@@ -13038,7 +13114,7 @@ var RealtimeChannel = class _RealtimeChannel {
13038
13114
  this.joinedOnce = true;
13039
13115
  this._rejoin(timeout);
13040
13116
  this.joinPush.receive("ok", async ({ postgres_changes: postgres_changes2 }) => {
13041
- var _a75;
13117
+ var _a79;
13042
13118
  if (!this.socket._isManualToken()) {
13043
13119
  this.socket.setAuth();
13044
13120
  }
@@ -13047,7 +13123,7 @@ var RealtimeChannel = class _RealtimeChannel {
13047
13123
  return;
13048
13124
  } else {
13049
13125
  const clientPostgresBindings = this.bindings.postgres_changes;
13050
- const bindingsLen = (_a75 = clientPostgresBindings === null || clientPostgresBindings === void 0 ? void 0 : clientPostgresBindings.length) !== null && _a75 !== void 0 ? _a75 : 0;
13126
+ const bindingsLen = (_a79 = clientPostgresBindings === null || clientPostgresBindings === void 0 ? void 0 : clientPostgresBindings.length) !== null && _a79 !== void 0 ? _a79 : 0;
13051
13127
  const newPostgresBindings = [];
13052
13128
  for (let i = 0; i < bindingsLen; i++) {
13053
13129
  const clientPostgresBinding = clientPostgresBindings[i];
@@ -13125,7 +13201,7 @@ var RealtimeChannel = class _RealtimeChannel {
13125
13201
  * @returns Promise resolving to object with success status, and error details if failed
13126
13202
  */
13127
13203
  async httpSend(event, payload, opts = {}) {
13128
- var _a74;
13204
+ var _a78;
13129
13205
  if (payload === void 0 || payload === null) {
13130
13206
  return Promise.reject("Payload is required for httpSend()");
13131
13207
  }
@@ -13150,7 +13226,7 @@ var RealtimeChannel = class _RealtimeChannel {
13150
13226
  ]
13151
13227
  })
13152
13228
  };
13153
- const response = await this._fetchWithTimeout(this.broadcastEndpointURL, options, (_a74 = opts.timeout) !== null && _a74 !== void 0 ? _a74 : this.timeout);
13229
+ const response = await this._fetchWithTimeout(this.broadcastEndpointURL, options, (_a78 = opts.timeout) !== null && _a78 !== void 0 ? _a78 : this.timeout);
13154
13230
  if (response.status === 202) {
13155
13231
  return { success: true };
13156
13232
  }
@@ -13172,7 +13248,7 @@ var RealtimeChannel = class _RealtimeChannel {
13172
13248
  * @param opts Options to be used during the send process
13173
13249
  */
13174
13250
  async send(args, opts = {}) {
13175
- var _a74, _b7;
13251
+ var _a78, _b7;
13176
13252
  if (!this._canPush() && args.type === "broadcast") {
13177
13253
  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.");
13178
13254
  const { event, payload: endpoint_payload } = args;
@@ -13198,7 +13274,7 @@ var RealtimeChannel = class _RealtimeChannel {
13198
13274
  })
13199
13275
  };
13200
13276
  try {
13201
- const response = await this._fetchWithTimeout(this.broadcastEndpointURL, options, (_a74 = opts.timeout) !== null && _a74 !== void 0 ? _a74 : this.timeout);
13277
+ const response = await this._fetchWithTimeout(this.broadcastEndpointURL, options, (_a78 = opts.timeout) !== null && _a78 !== void 0 ? _a78 : this.timeout);
13202
13278
  await ((_b7 = response.body) === null || _b7 === void 0 ? void 0 : _b7.cancel());
13203
13279
  return response.ok ? "ok" : "error";
13204
13280
  } catch (error) {
@@ -13210,9 +13286,9 @@ var RealtimeChannel = class _RealtimeChannel {
13210
13286
  }
13211
13287
  } else {
13212
13288
  return new Promise((resolve) => {
13213
- var _a75, _b8, _c;
13289
+ var _a79, _b8, _c;
13214
13290
  const push = this._push(args.type, args, opts.timeout || this.timeout);
13215
- 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)) {
13291
+ 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)) {
13216
13292
  resolve("ok");
13217
13293
  }
13218
13294
  push.receive("ok", () => resolve("ok"));
@@ -13331,7 +13407,7 @@ var RealtimeChannel = class _RealtimeChannel {
13331
13407
  }
13332
13408
  /** @internal */
13333
13409
  _trigger(type, payload, ref) {
13334
- var _a74, _b7;
13410
+ var _a78, _b7;
13335
13411
  const typeLower = type.toLocaleLowerCase();
13336
13412
  const { close, error, leave, join } = CHANNEL_EVENTS;
13337
13413
  const events = [close, error, leave, join];
@@ -13343,17 +13419,17 @@ var RealtimeChannel = class _RealtimeChannel {
13343
13419
  throw "channel onMessage callbacks must return the payload, modified or unmodified";
13344
13420
  }
13345
13421
  if (["insert", "update", "delete"].includes(typeLower)) {
13346
- (_a74 = this.bindings.postgres_changes) === null || _a74 === void 0 ? void 0 : _a74.filter((bind) => {
13347
- var _a75, _b8, _c;
13348
- 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;
13422
+ (_a78 = this.bindings.postgres_changes) === null || _a78 === void 0 ? void 0 : _a78.filter((bind) => {
13423
+ var _a79, _b8, _c;
13424
+ 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;
13349
13425
  }).map((bind) => bind.callback(handledPayload, ref));
13350
13426
  } else {
13351
13427
  (_b7 = this.bindings[typeLower]) === null || _b7 === void 0 ? void 0 : _b7.filter((bind) => {
13352
- var _a75, _b8, _c, _d, _e, _f, _g, _h;
13428
+ var _a79, _b8, _c, _d, _e, _f, _g, _h;
13353
13429
  if (["broadcast", "presence", "postgres_changes"].includes(typeLower)) {
13354
13430
  if ("id" in bind) {
13355
13431
  const bindId = bind.id;
13356
- const bindEvent = (_a75 = bind.filter) === null || _a75 === void 0 ? void 0 : _a75.event;
13432
+ const bindEvent = (_a79 = bind.filter) === null || _a79 === void 0 ? void 0 : _a79.event;
13357
13433
  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));
13358
13434
  } else {
13359
13435
  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();
@@ -13421,8 +13497,8 @@ var RealtimeChannel = class _RealtimeChannel {
13421
13497
  const typeLower = type.toLocaleLowerCase();
13422
13498
  if (this.bindings[typeLower]) {
13423
13499
  this.bindings[typeLower] = this.bindings[typeLower].filter((bind) => {
13424
- var _a74;
13425
- return !(((_a74 = bind.type) === null || _a74 === void 0 ? void 0 : _a74.toLocaleLowerCase()) === typeLower && _RealtimeChannel.isEqual(bind.filter, filter));
13500
+ var _a78;
13501
+ return !(((_a78 = bind.type) === null || _a78 === void 0 ? void 0 : _a78.toLocaleLowerCase()) === typeLower && _RealtimeChannel.isEqual(bind.filter, filter));
13426
13502
  });
13427
13503
  }
13428
13504
  return this;
@@ -13552,7 +13628,7 @@ var RealtimeClient = class {
13552
13628
  * ```
13553
13629
  */
13554
13630
  constructor(endPoint, options) {
13555
- var _a74;
13631
+ var _a78;
13556
13632
  this.accessTokenValue = null;
13557
13633
  this.apiKey = null;
13558
13634
  this._manuallySetToken = false;
@@ -13591,7 +13667,7 @@ var RealtimeClient = class {
13591
13667
  }
13592
13668
  return (...args) => fetch(...args);
13593
13669
  };
13594
- if (!((_a74 = options === null || options === void 0 ? void 0 : options.params) === null || _a74 === void 0 ? void 0 : _a74.apikey)) {
13670
+ if (!((_a78 = options === null || options === void 0 ? void 0 : options.params) === null || _a78 === void 0 ? void 0 : _a78.apikey)) {
13595
13671
  throw new Error("API key is required to connect to Realtime");
13596
13672
  }
13597
13673
  this.apiKey = options.params.apikey;
@@ -13773,8 +13849,8 @@ Option 2: Install and provide the "ws" package:
13773
13849
  const { topic, event, payload, ref } = data;
13774
13850
  const callback = () => {
13775
13851
  this.encode(data, (result) => {
13776
- var _a74;
13777
- (_a74 = this.conn) === null || _a74 === void 0 ? void 0 : _a74.send(result);
13852
+ var _a78;
13853
+ (_a78 = this.conn) === null || _a78 === void 0 ? void 0 : _a78.send(result);
13778
13854
  });
13779
13855
  };
13780
13856
  this.log("push", `${topic} ${event} (${ref})`, payload);
@@ -13824,7 +13900,7 @@ Option 2: Install and provide the "ws" package:
13824
13900
  * Sends a heartbeat message if the socket is connected.
13825
13901
  */
13826
13902
  async sendHeartbeat() {
13827
- var _a74;
13903
+ var _a78;
13828
13904
  if (!this.isConnected()) {
13829
13905
  try {
13830
13906
  this.heartbeatCallback("disconnected");
@@ -13843,11 +13919,11 @@ Option 2: Install and provide the "ws" package:
13843
13919
  this.log("error", "error in heartbeat callback", e);
13844
13920
  }
13845
13921
  this._wasManualDisconnect = false;
13846
- (_a74 = this.conn) === null || _a74 === void 0 ? void 0 : _a74.close(WS_CLOSE_NORMAL, "heartbeat timeout");
13922
+ (_a78 = this.conn) === null || _a78 === void 0 ? void 0 : _a78.close(WS_CLOSE_NORMAL, "heartbeat timeout");
13847
13923
  setTimeout(() => {
13848
- var _a75;
13924
+ var _a79;
13849
13925
  if (!this.isConnected()) {
13850
- (_a75 = this.reconnectTimer) === null || _a75 === void 0 ? void 0 : _a75.scheduleTimeout();
13926
+ (_a79 = this.reconnectTimer) === null || _a79 === void 0 ? void 0 : _a79.scheduleTimeout();
13851
13927
  }
13852
13928
  }, CONNECTION_TIMEOUTS.HEARTBEAT_TIMEOUT_FALLBACK);
13853
13929
  return;
@@ -13945,12 +14021,12 @@ Option 2: Install and provide the "ws" package:
13945
14021
  * @internal
13946
14022
  */
13947
14023
  _clearTimer(timer) {
13948
- var _a74;
14024
+ var _a78;
13949
14025
  if (timer === "heartbeat" && this.heartbeatTimer) {
13950
14026
  clearInterval(this.heartbeatTimer);
13951
14027
  this.heartbeatTimer = void 0;
13952
14028
  } else if (timer === "reconnect") {
13953
- (_a74 = this.reconnectTimer) === null || _a74 === void 0 ? void 0 : _a74.reset();
14029
+ (_a78 = this.reconnectTimer) === null || _a78 === void 0 ? void 0 : _a78.reset();
13954
14030
  }
13955
14031
  }
13956
14032
  /**
@@ -14065,13 +14141,13 @@ Option 2: Install and provide the "ws" package:
14065
14141
  }
14066
14142
  /** @internal */
14067
14143
  _onConnClose(event) {
14068
- var _a74;
14144
+ var _a78;
14069
14145
  this._setConnectionState("disconnected");
14070
14146
  this.log("transport", "close", event);
14071
14147
  this._triggerChanError();
14072
14148
  this._clearTimer("heartbeat");
14073
14149
  if (!this._wasManualDisconnect) {
14074
- (_a74 = this.reconnectTimer) === null || _a74 === void 0 ? void 0 : _a74.scheduleTimeout();
14150
+ (_a78 = this.reconnectTimer) === null || _a78 === void 0 ? void 0 : _a78.scheduleTimeout();
14075
14151
  }
14076
14152
  this._triggerStateCallbacks("close", event);
14077
14153
  }
@@ -14214,8 +14290,8 @@ Option 2: Install and provide the "ws" package:
14214
14290
  * @internal
14215
14291
  */
14216
14292
  _initializeOptions(options) {
14217
- var _a74, _b7, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
14218
- this.transport = (_a74 = options === null || options === void 0 ? void 0 : options.transport) !== null && _a74 !== void 0 ? _a74 : null;
14293
+ var _a78, _b7, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
14294
+ this.transport = (_a78 = options === null || options === void 0 ? void 0 : options.transport) !== null && _a78 !== void 0 ? _a78 : null;
14219
14295
  this.timeout = (_b7 = options === null || options === void 0 ? void 0 : options.timeout) !== null && _b7 !== void 0 ? _b7 : DEFAULT_TIMEOUT;
14220
14296
  this.heartbeatIntervalMs = (_c = options === null || options === void 0 ? void 0 : options.heartbeatIntervalMs) !== null && _c !== void 0 ? _c : CONNECTION_TIMEOUTS.HEARTBEAT_INTERVAL;
14221
14297
  this.worker = (_d = options === null || options === void 0 ? void 0 : options.worker) !== null && _d !== void 0 ? _d : false;
@@ -14261,14 +14337,14 @@ Option 2: Install and provide the "ws" package:
14261
14337
  // node_modules/iceberg-js/dist/index.mjs
14262
14338
  var IcebergError = class extends Error {
14263
14339
  constructor(message, opts) {
14264
- var _a74;
14340
+ var _a78;
14265
14341
  super(message);
14266
14342
  this.name = "IcebergError";
14267
14343
  this.status = opts.status;
14268
14344
  this.icebergType = opts.icebergType;
14269
14345
  this.icebergCode = opts.icebergCode;
14270
14346
  this.details = opts.details;
14271
- this.isCommitStateUnknown = opts.icebergType === "CommitStateUnknownException" || [500, 502, 504].includes(opts.status) && ((_a74 = opts.icebergType) == null ? void 0 : _a74.includes("CommitState")) === true;
14347
+ this.isCommitStateUnknown = opts.icebergType === "CommitStateUnknownException" || [500, 502, 504].includes(opts.status) && ((_a78 = opts.icebergType) == null ? void 0 : _a78.includes("CommitState")) === true;
14272
14348
  }
14273
14349
  /**
14274
14350
  * Returns true if the error is a 404 Not Found error.
@@ -14316,8 +14392,8 @@ async function buildAuthHeaders(auth) {
14316
14392
  return {};
14317
14393
  }
14318
14394
  function createFetchClient(options) {
14319
- var _a74;
14320
- const fetchFn = (_a74 = options.fetchImpl) != null ? _a74 : globalThis.fetch;
14395
+ var _a78;
14396
+ const fetchFn = (_a78 = options.fetchImpl) != null ? _a78 : globalThis.fetch;
14321
14397
  return {
14322
14398
  async request({
14323
14399
  method,
@@ -14326,7 +14402,7 @@ function createFetchClient(options) {
14326
14402
  body,
14327
14403
  headers
14328
14404
  }) {
14329
- var _a75;
14405
+ var _a79;
14330
14406
  const url = buildUrl(options.baseUrl, path, query);
14331
14407
  const authHeaders = await buildAuthHeaders(options.auth);
14332
14408
  const res = await fetchFn(url, {
@@ -14345,7 +14421,7 @@ function createFetchClient(options) {
14345
14421
  const errBody = isJson ? data : void 0;
14346
14422
  const errorDetail = errBody == null ? void 0 : errBody.error;
14347
14423
  throw new IcebergError(
14348
- (_a75 = errorDetail == null ? void 0 : errorDetail.message) != null ? _a75 : `Request failed with status ${res.status}`,
14424
+ (_a79 = errorDetail == null ? void 0 : errorDetail.message) != null ? _a79 : `Request failed with status ${res.status}`,
14349
14425
  {
14350
14426
  status: res.status,
14351
14427
  icebergType: errorDetail == null ? void 0 : errorDetail.type,
@@ -14468,11 +14544,11 @@ var TableOperations = class {
14468
14544
  };
14469
14545
  }
14470
14546
  async dropTable(id, options) {
14471
- var _a74;
14547
+ var _a78;
14472
14548
  await this.client.request({
14473
14549
  method: "DELETE",
14474
14550
  path: `${this.prefix}/namespaces/${namespaceToPath2(id.namespace)}/tables/${id.name}`,
14475
- query: { purgeRequested: String((_a74 = options == null ? void 0 : options.purge) != null ? _a74 : false) }
14551
+ query: { purgeRequested: String((_a78 = options == null ? void 0 : options.purge) != null ? _a78 : false) }
14476
14552
  });
14477
14553
  }
14478
14554
  async loadTable(id) {
@@ -14524,7 +14600,7 @@ var IcebergRestCatalog = class {
14524
14600
  * @param options - Configuration options for the catalog client
14525
14601
  */
14526
14602
  constructor(options) {
14527
- var _a74;
14603
+ var _a78;
14528
14604
  let prefix = "v1";
14529
14605
  if (options.catalogName) {
14530
14606
  prefix += `/${options.catalogName}`;
@@ -14535,7 +14611,7 @@ var IcebergRestCatalog = class {
14535
14611
  auth: options.auth,
14536
14612
  fetchImpl: options.fetch
14537
14613
  });
14538
- this.accessDelegation = (_a74 = options.accessDelegation) == null ? void 0 : _a74.join(",");
14614
+ this.accessDelegation = (_a78 = options.accessDelegation) == null ? void 0 : _a78.join(",");
14539
14615
  this.namespaceOps = new NamespaceOperations(this.client, prefix);
14540
14616
  this.tableOps = new TableOperations(this.client, prefix, this.accessDelegation);
14541
14617
  }
@@ -17874,7 +17950,7 @@ var getItemAsync = async (storage, key) => {
17874
17950
  }
17875
17951
  try {
17876
17952
  return JSON.parse(value);
17877
- } catch (_a74) {
17953
+ } catch (_a78) {
17878
17954
  return value;
17879
17955
  }
17880
17956
  };
@@ -18085,7 +18161,7 @@ function deepClone(obj) {
18085
18161
  var _getErrorMessage2 = (err) => err.msg || err.message || err.error_description || err.error || JSON.stringify(err);
18086
18162
  var NETWORK_ERROR_CODES = [502, 503, 504];
18087
18163
  async function handleError2(error) {
18088
- var _a74;
18164
+ var _a78;
18089
18165
  if (!looksLikeFetchResponse(error)) {
18090
18166
  throw new AuthRetryableFetchError(_getErrorMessage2(error), 0);
18091
18167
  }
@@ -18110,7 +18186,7 @@ async function handleError2(error) {
18110
18186
  throw new AuthWeakPasswordError(_getErrorMessage2(data), error.status, data.weak_password.reasons);
18111
18187
  }
18112
18188
  } else if (errorCode === "weak_password") {
18113
- throw new AuthWeakPasswordError(_getErrorMessage2(data), error.status, ((_a74 = data.weak_password) === null || _a74 === void 0 ? void 0 : _a74.reasons) || []);
18189
+ throw new AuthWeakPasswordError(_getErrorMessage2(data), error.status, ((_a78 = data.weak_password) === null || _a78 === void 0 ? void 0 : _a78.reasons) || []);
18114
18190
  } else if (errorCode === "session_not_found") {
18115
18191
  throw new AuthSessionMissingError();
18116
18192
  }
@@ -18126,7 +18202,7 @@ var _getRequestParams2 = (method, options, parameters, body) => {
18126
18202
  return Object.assign(Object.assign({}, params), parameters);
18127
18203
  };
18128
18204
  async function _request(fetcher, method, url, options) {
18129
- var _a74;
18205
+ var _a78;
18130
18206
  const headers = Object.assign({}, options === null || options === void 0 ? void 0 : options.headers);
18131
18207
  if (!headers[API_VERSION_HEADER_NAME]) {
18132
18208
  headers[API_VERSION_HEADER_NAME] = API_VERSIONS["2024-01-01"].name;
@@ -18134,7 +18210,7 @@ async function _request(fetcher, method, url, options) {
18134
18210
  if (options === null || options === void 0 ? void 0 : options.jwt) {
18135
18211
  headers["Authorization"] = `Bearer ${options.jwt}`;
18136
18212
  }
18137
- const qs = (_a74 = options === null || options === void 0 ? void 0 : options.query) !== null && _a74 !== void 0 ? _a74 : {};
18213
+ const qs = (_a78 = options === null || options === void 0 ? void 0 : options.query) !== null && _a78 !== void 0 ? _a78 : {};
18138
18214
  if (options === null || options === void 0 ? void 0 : options.redirectTo) {
18139
18215
  qs["redirect_to"] = options.redirectTo;
18140
18216
  }
@@ -18167,7 +18243,7 @@ async function _handleRequest2(fetcher, method, url, options, parameters, body)
18167
18243
  }
18168
18244
  }
18169
18245
  function _sessionResponse(data) {
18170
- var _a74;
18246
+ var _a78;
18171
18247
  let session = null;
18172
18248
  if (hasSession(data)) {
18173
18249
  session = Object.assign({}, data);
@@ -18175,7 +18251,7 @@ function _sessionResponse(data) {
18175
18251
  session.expires_at = expiresAt(data.expires_in);
18176
18252
  }
18177
18253
  }
18178
- const user = (_a74 = data.user) !== null && _a74 !== void 0 ? _a74 : data;
18254
+ const user = (_a78 = data.user) !== null && _a78 !== void 0 ? _a78 : data;
18179
18255
  return { data: { session, user }, error: null };
18180
18256
  }
18181
18257
  function _sessionResponsePassword(data) {
@@ -18186,8 +18262,8 @@ function _sessionResponsePassword(data) {
18186
18262
  return response;
18187
18263
  }
18188
18264
  function _userResponse(data) {
18189
- var _a74;
18190
- const user = (_a74 = data.user) !== null && _a74 !== void 0 ? _a74 : data;
18265
+ var _a78;
18266
+ const user = (_a78 = data.user) !== null && _a78 !== void 0 ? _a78 : data;
18191
18267
  return { data: { user }, error: null };
18192
18268
  }
18193
18269
  function _ssoResponse(data) {
@@ -18356,14 +18432,14 @@ var GoTrueAdminApi = class {
18356
18432
  * @param params An object which supports `page` and `perPage` as numbers, to alter the paginated results.
18357
18433
  */
18358
18434
  async listUsers(params) {
18359
- var _a74, _b7, _c, _d, _e, _f, _g;
18435
+ var _a78, _b7, _c, _d, _e, _f, _g;
18360
18436
  try {
18361
18437
  const pagination = { nextPage: null, lastPage: 0, total: 0 };
18362
18438
  const response = await _request(this.fetch, "GET", `${this.url}/admin/users`, {
18363
18439
  headers: this.headers,
18364
18440
  noResolveJson: true,
18365
18441
  query: {
18366
- 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 : "",
18442
+ 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 : "",
18367
18443
  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 : ""
18368
18444
  },
18369
18445
  xform: _noResolveJsonResponse
@@ -18497,14 +18573,14 @@ var GoTrueAdminApi = class {
18497
18573
  * This function should only be called on a server. Never expose your `service_role` key in the browser.
18498
18574
  */
18499
18575
  async _listOAuthClients(params) {
18500
- var _a74, _b7, _c, _d, _e, _f, _g;
18576
+ var _a78, _b7, _c, _d, _e, _f, _g;
18501
18577
  try {
18502
18578
  const pagination = { nextPage: null, lastPage: 0, total: 0 };
18503
18579
  const response = await _request(this.fetch, "GET", `${this.url}/admin/oauth/clients`, {
18504
18580
  headers: this.headers,
18505
18581
  noResolveJson: true,
18506
18582
  query: {
18507
- 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 : "",
18583
+ 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 : "",
18508
18584
  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 : ""
18509
18585
  },
18510
18586
  xform: _noResolveJsonResponse
@@ -18757,7 +18833,7 @@ function toHex(value) {
18757
18833
  return "0x" + hex;
18758
18834
  }
18759
18835
  function createSiweMessage(parameters) {
18760
- var _a74;
18836
+ var _a78;
18761
18837
  const { chainId, domain, expirationTime, issuedAt = /* @__PURE__ */ new Date(), nonce, notBefore, requestId, resources, scheme, uri, version: version5 } = parameters;
18762
18838
  {
18763
18839
  if (!Number.isInteger(chainId))
@@ -18770,7 +18846,7 @@ function createSiweMessage(parameters) {
18770
18846
  throw new Error(`@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.`);
18771
18847
  if (version5 !== "1")
18772
18848
  throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${version5}`);
18773
- if ((_a74 = parameters.statement) === null || _a74 === void 0 ? void 0 : _a74.includes("\n"))
18849
+ if ((_a78 = parameters.statement) === null || _a78 === void 0 ? void 0 : _a78.includes("\n"))
18774
18850
  throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${parameters.statement}`);
18775
18851
  }
18776
18852
  const address = getAddress(parameters.address);
@@ -18812,10 +18888,10 @@ ${suffix}`;
18812
18888
  // node_modules/@supabase/auth-js/dist/module/lib/webauthn.errors.js
18813
18889
  var WebAuthnError = class extends Error {
18814
18890
  constructor({ message, code, cause, name }) {
18815
- var _a74;
18891
+ var _a78;
18816
18892
  super(message, { cause });
18817
18893
  this.__isWebAuthnError = true;
18818
- this.name = (_a74 = name !== null && name !== void 0 ? name : cause instanceof Error ? cause.name : void 0) !== null && _a74 !== void 0 ? _a74 : "Unknown Error";
18894
+ this.name = (_a78 = name !== null && name !== void 0 ? name : cause instanceof Error ? cause.name : void 0) !== null && _a78 !== void 0 ? _a78 : "Unknown Error";
18819
18895
  this.code = code;
18820
18896
  }
18821
18897
  };
@@ -18831,7 +18907,7 @@ var WebAuthnUnknownError = class extends WebAuthnError {
18831
18907
  }
18832
18908
  };
18833
18909
  function identifyRegistrationError({ error, options }) {
18834
- var _a74, _b7, _c;
18910
+ var _a78, _b7, _c;
18835
18911
  const { publicKey } = options;
18836
18912
  if (!publicKey) {
18837
18913
  throw Error("options was missing required publicKey property");
@@ -18845,7 +18921,7 @@ function identifyRegistrationError({ error, options }) {
18845
18921
  });
18846
18922
  }
18847
18923
  } else if (error.name === "ConstraintError") {
18848
- if (((_a74 = publicKey.authenticatorSelection) === null || _a74 === void 0 ? void 0 : _a74.requireResidentKey) === true) {
18924
+ if (((_a78 = publicKey.authenticatorSelection) === null || _a78 === void 0 ? void 0 : _a78.requireResidentKey) === true) {
18849
18925
  return new WebAuthnError({
18850
18926
  message: "Discoverable credentials were required but no available authenticator supported it",
18851
18927
  code: "ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",
@@ -19074,7 +19150,7 @@ function deserializeCredentialRequestOptions(options) {
19074
19150
  return result;
19075
19151
  }
19076
19152
  function serializeCredentialCreationResponse(credential) {
19077
- var _a74;
19153
+ var _a78;
19078
19154
  if ("toJSON" in credential && typeof credential.toJSON === "function") {
19079
19155
  return credential.toJSON();
19080
19156
  }
@@ -19089,11 +19165,11 @@ function serializeCredentialCreationResponse(credential) {
19089
19165
  type: "public-key",
19090
19166
  clientExtensionResults: credential.getClientExtensionResults(),
19091
19167
  // Convert null to undefined and cast to AuthenticatorAttachment type
19092
- authenticatorAttachment: (_a74 = credentialWithAttachment.authenticatorAttachment) !== null && _a74 !== void 0 ? _a74 : void 0
19168
+ authenticatorAttachment: (_a78 = credentialWithAttachment.authenticatorAttachment) !== null && _a78 !== void 0 ? _a78 : void 0
19093
19169
  };
19094
19170
  }
19095
19171
  function serializeCredentialRequestResponse(credential) {
19096
- var _a74;
19172
+ var _a78;
19097
19173
  if ("toJSON" in credential && typeof credential.toJSON === "function") {
19098
19174
  return credential.toJSON();
19099
19175
  }
@@ -19113,7 +19189,7 @@ function serializeCredentialRequestResponse(credential) {
19113
19189
  type: "public-key",
19114
19190
  clientExtensionResults,
19115
19191
  // Convert null to undefined and cast to AuthenticatorAttachment type
19116
- authenticatorAttachment: (_a74 = credentialWithAttachment.authenticatorAttachment) !== null && _a74 !== void 0 ? _a74 : void 0
19192
+ authenticatorAttachment: (_a78 = credentialWithAttachment.authenticatorAttachment) !== null && _a78 !== void 0 ? _a78 : void 0
19117
19193
  };
19118
19194
  }
19119
19195
  function isValidDomain(hostname) {
@@ -19123,8 +19199,8 @@ function isValidDomain(hostname) {
19123
19199
  );
19124
19200
  }
19125
19201
  function browserSupportsWebAuthn() {
19126
- var _a74, _b7;
19127
- 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");
19202
+ var _a78, _b7;
19203
+ 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");
19128
19204
  }
19129
19205
  async function createCredential(options) {
19130
19206
  try {
@@ -19453,8 +19529,8 @@ var WebAuthnApi = class {
19453
19529
  });
19454
19530
  if (!factor) {
19455
19531
  await this.client.mfa.listFactors().then((factors) => {
19456
- var _a74;
19457
- 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");
19532
+ var _a78;
19533
+ 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");
19458
19534
  }).then((factor2) => factor2 ? this.client.mfa.unenroll({ factorId: factor2 === null || factor2 === void 0 ? void 0 : factor2.id }) : void 0);
19459
19535
  return { data: null, error: enrollError };
19460
19536
  }
@@ -19516,15 +19592,15 @@ var GoTrueClient = class _GoTrueClient {
19516
19592
  * The JWKS used for verifying asymmetric JWTs
19517
19593
  */
19518
19594
  get jwks() {
19519
- var _a74, _b7;
19520
- return (_b7 = (_a74 = GLOBAL_JWKS[this.storageKey]) === null || _a74 === void 0 ? void 0 : _a74.jwks) !== null && _b7 !== void 0 ? _b7 : { keys: [] };
19595
+ var _a78, _b7;
19596
+ return (_b7 = (_a78 = GLOBAL_JWKS[this.storageKey]) === null || _a78 === void 0 ? void 0 : _a78.jwks) !== null && _b7 !== void 0 ? _b7 : { keys: [] };
19521
19597
  }
19522
19598
  set jwks(value) {
19523
19599
  GLOBAL_JWKS[this.storageKey] = Object.assign(Object.assign({}, GLOBAL_JWKS[this.storageKey]), { jwks: value });
19524
19600
  }
19525
19601
  get jwks_cached_at() {
19526
- var _a74, _b7;
19527
- return (_b7 = (_a74 = GLOBAL_JWKS[this.storageKey]) === null || _a74 === void 0 ? void 0 : _a74.cachedAt) !== null && _b7 !== void 0 ? _b7 : Number.MIN_SAFE_INTEGER;
19602
+ var _a78, _b7;
19603
+ return (_b7 = (_a78 = GLOBAL_JWKS[this.storageKey]) === null || _a78 === void 0 ? void 0 : _a78.cachedAt) !== null && _b7 !== void 0 ? _b7 : Number.MIN_SAFE_INTEGER;
19528
19604
  }
19529
19605
  set jwks_cached_at(value) {
19530
19606
  GLOBAL_JWKS[this.storageKey] = Object.assign(Object.assign({}, GLOBAL_JWKS[this.storageKey]), { cachedAt: value });
@@ -19544,7 +19620,7 @@ var GoTrueClient = class _GoTrueClient {
19544
19620
  * ```
19545
19621
  */
19546
19622
  constructor(options) {
19547
- var _a74, _b7, _c;
19623
+ var _a78, _b7, _c;
19548
19624
  this.userStorage = null;
19549
19625
  this.memoryStorage = null;
19550
19626
  this.stateChangeEmitters = /* @__PURE__ */ new Map();
@@ -19562,7 +19638,7 @@ var GoTrueClient = class _GoTrueClient {
19562
19638
  this.logger = console.log;
19563
19639
  const settings = Object.assign(Object.assign({}, DEFAULT_OPTIONS), options);
19564
19640
  this.storageKey = settings.storageKey;
19565
- this.instanceID = (_a74 = _GoTrueClient.nextInstanceID[this.storageKey]) !== null && _a74 !== void 0 ? _a74 : 0;
19641
+ this.instanceID = (_a78 = _GoTrueClient.nextInstanceID[this.storageKey]) !== null && _a78 !== void 0 ? _a78 : 0;
19566
19642
  _GoTrueClient.nextInstanceID[this.storageKey] = this.instanceID + 1;
19567
19643
  this.logDebugMessages = !!settings.debug;
19568
19644
  if (typeof settings.debug === "function") {
@@ -19699,7 +19775,7 @@ var GoTrueClient = class _GoTrueClient {
19699
19775
  * the whole lifetime of the client
19700
19776
  */
19701
19777
  async _initialize() {
19702
- var _a74;
19778
+ var _a78;
19703
19779
  try {
19704
19780
  let params = {};
19705
19781
  let callbackUrlType = "none";
@@ -19716,7 +19792,7 @@ var GoTrueClient = class _GoTrueClient {
19716
19792
  if (error) {
19717
19793
  this._debug("#_initialize()", "error detecting session from URL", error);
19718
19794
  if (isAuthImplicitGrantRedirectError(error)) {
19719
- const errorCode = (_a74 = error.details) === null || _a74 === void 0 ? void 0 : _a74.code;
19795
+ const errorCode = (_a78 = error.details) === null || _a78 === void 0 ? void 0 : _a78.code;
19720
19796
  if (errorCode === "identity_already_exists" || errorCode === "identity_not_found" || errorCode === "single_identity_not_deletable") {
19721
19797
  return { error };
19722
19798
  }
@@ -19755,12 +19831,12 @@ var GoTrueClient = class _GoTrueClient {
19755
19831
  * @returns A session where the is_anonymous claim in the access token JWT set to true
19756
19832
  */
19757
19833
  async signInAnonymously(credentials) {
19758
- var _a74, _b7, _c;
19834
+ var _a78, _b7, _c;
19759
19835
  try {
19760
19836
  const res = await _request(this.fetch, "POST", `${this.url}/signup`, {
19761
19837
  headers: this.headers,
19762
19838
  body: {
19763
- 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 : {},
19839
+ 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 : {},
19764
19840
  gotrue_meta_security: { captcha_token: (_c = credentials === null || credentials === void 0 ? void 0 : credentials.options) === null || _c === void 0 ? void 0 : _c.captchaToken }
19765
19841
  },
19766
19842
  xform: _sessionResponse
@@ -19794,7 +19870,7 @@ var GoTrueClient = class _GoTrueClient {
19794
19870
  * @returns A user if the server has "autoconfirm" OFF
19795
19871
  */
19796
19872
  async signUp(credentials) {
19797
- var _a74, _b7, _c;
19873
+ var _a78, _b7, _c;
19798
19874
  try {
19799
19875
  let res;
19800
19876
  if ("email" in credentials) {
@@ -19811,7 +19887,7 @@ var GoTrueClient = class _GoTrueClient {
19811
19887
  body: {
19812
19888
  email,
19813
19889
  password,
19814
- data: (_a74 = options === null || options === void 0 ? void 0 : options.data) !== null && _a74 !== void 0 ? _a74 : {},
19890
+ data: (_a78 = options === null || options === void 0 ? void 0 : options.data) !== null && _a78 !== void 0 ? _a78 : {},
19815
19891
  gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },
19816
19892
  code_challenge: codeChallenge,
19817
19893
  code_challenge_method: codeChallengeMethod
@@ -19917,9 +19993,9 @@ var GoTrueClient = class _GoTrueClient {
19917
19993
  * This method supports the PKCE flow.
19918
19994
  */
19919
19995
  async signInWithOAuth(credentials) {
19920
- var _a74, _b7, _c, _d;
19996
+ var _a78, _b7, _c, _d;
19921
19997
  return await this._handleProviderSignIn(credentials.provider, {
19922
- redirectTo: (_a74 = credentials.options) === null || _a74 === void 0 ? void 0 : _a74.redirectTo,
19998
+ redirectTo: (_a78 = credentials.options) === null || _a78 === void 0 ? void 0 : _a78.redirectTo,
19923
19999
  scopes: (_b7 = credentials.options) === null || _b7 === void 0 ? void 0 : _b7.scopes,
19924
20000
  queryParams: (_c = credentials.options) === null || _c === void 0 ? void 0 : _c.queryParams,
19925
20001
  skipBrowserRedirect: (_d = credentials.options) === null || _d === void 0 ? void 0 : _d.skipBrowserRedirect
@@ -19953,7 +20029,7 @@ var GoTrueClient = class _GoTrueClient {
19953
20029
  }
19954
20030
  }
19955
20031
  async signInWithEthereum(credentials) {
19956
- var _a74, _b7, _c, _d, _e, _f, _g, _h, _j, _k, _l;
20032
+ var _a78, _b7, _c, _d, _e, _f, _g, _h, _j, _k, _l;
19957
20033
  let message;
19958
20034
  let signature;
19959
20035
  if ("message" in credentials) {
@@ -19977,7 +20053,7 @@ var GoTrueClient = class _GoTrueClient {
19977
20053
  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.`);
19978
20054
  }
19979
20055
  }
19980
- const url = new URL((_a74 = options === null || options === void 0 ? void 0 : options.url) !== null && _a74 !== void 0 ? _a74 : window.location.href);
20056
+ const url = new URL((_a78 = options === null || options === void 0 ? void 0 : options.url) !== null && _a78 !== void 0 ? _a78 : window.location.href);
19981
20057
  const accounts = await resolvedWallet.request({
19982
20058
  method: "eth_requestAccounts"
19983
20059
  }).then((accs) => accs).catch(() => {
@@ -20044,7 +20120,7 @@ var GoTrueClient = class _GoTrueClient {
20044
20120
  }
20045
20121
  }
20046
20122
  async signInWithSolana(credentials) {
20047
- var _a74, _b7, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
20123
+ var _a78, _b7, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
20048
20124
  let message;
20049
20125
  let signature;
20050
20126
  if ("message" in credentials) {
@@ -20068,7 +20144,7 @@ var GoTrueClient = class _GoTrueClient {
20068
20144
  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.`);
20069
20145
  }
20070
20146
  }
20071
- const url = new URL((_a74 = options === null || options === void 0 ? void 0 : options.url) !== null && _a74 !== void 0 ? _a74 : window.location.href);
20147
+ const url = new URL((_a78 = options === null || options === void 0 ? void 0 : options.url) !== null && _a78 !== void 0 ? _a78 : window.location.href);
20072
20148
  if ("signIn" in resolvedWallet && resolvedWallet.signIn) {
20073
20149
  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), {
20074
20150
  // non-overridable properties
@@ -20242,7 +20318,7 @@ var GoTrueClient = class _GoTrueClient {
20242
20318
  * This method supports PKCE when an email is passed.
20243
20319
  */
20244
20320
  async signInWithOtp(credentials) {
20245
- var _a74, _b7, _c, _d, _e;
20321
+ var _a78, _b7, _c, _d, _e;
20246
20322
  try {
20247
20323
  if ("email" in credentials) {
20248
20324
  const { email, options } = credentials;
@@ -20256,7 +20332,7 @@ var GoTrueClient = class _GoTrueClient {
20256
20332
  headers: this.headers,
20257
20333
  body: {
20258
20334
  email,
20259
- data: (_a74 = options === null || options === void 0 ? void 0 : options.data) !== null && _a74 !== void 0 ? _a74 : {},
20335
+ data: (_a78 = options === null || options === void 0 ? void 0 : options.data) !== null && _a78 !== void 0 ? _a78 : {},
20260
20336
  create_user: (_b7 = options === null || options === void 0 ? void 0 : options.shouldCreateUser) !== null && _b7 !== void 0 ? _b7 : true,
20261
20337
  gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },
20262
20338
  code_challenge: codeChallenge,
@@ -20296,12 +20372,12 @@ var GoTrueClient = class _GoTrueClient {
20296
20372
  * Log in a user given a User supplied OTP or TokenHash received through mobile or email.
20297
20373
  */
20298
20374
  async verifyOtp(params) {
20299
- var _a74, _b7;
20375
+ var _a78, _b7;
20300
20376
  try {
20301
20377
  let redirectTo = void 0;
20302
20378
  let captchaToken = void 0;
20303
20379
  if ("options" in params) {
20304
- redirectTo = (_a74 = params.options) === null || _a74 === void 0 ? void 0 : _a74.redirectTo;
20380
+ redirectTo = (_a78 = params.options) === null || _a78 === void 0 ? void 0 : _a78.redirectTo;
20305
20381
  captchaToken = (_b7 = params.options) === null || _b7 === void 0 ? void 0 : _b7.captchaToken;
20306
20382
  }
20307
20383
  const { data, error } = await _request(this.fetch, "POST", `${this.url}/verify`, {
@@ -20346,7 +20422,7 @@ var GoTrueClient = class _GoTrueClient {
20346
20422
  * organization's SSO Identity Provider UUID directly instead.
20347
20423
  */
20348
20424
  async signInWithSSO(params) {
20349
- var _a74, _b7, _c, _d, _e;
20425
+ var _a78, _b7, _c, _d, _e;
20350
20426
  try {
20351
20427
  let codeChallenge = null;
20352
20428
  let codeChallengeMethod = null;
@@ -20355,7 +20431,7 @@ var GoTrueClient = class _GoTrueClient {
20355
20431
  [codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(this.storage, this.storageKey);
20356
20432
  }
20357
20433
  const result = await _request(this.fetch, "POST", `${this.url}/sso`, {
20358
- 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 }),
20434
+ 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 }),
20359
20435
  headers: this.headers,
20360
20436
  xform: _ssoResponse
20361
20437
  });
@@ -20609,12 +20685,12 @@ var GoTrueClient = class _GoTrueClient {
20609
20685
  });
20610
20686
  }
20611
20687
  return await this._useSession(async (result) => {
20612
- var _a74, _b7, _c;
20688
+ var _a78, _b7, _c;
20613
20689
  const { data, error } = result;
20614
20690
  if (error) {
20615
20691
  throw error;
20616
20692
  }
20617
- if (!((_a74 = data.session) === null || _a74 === void 0 ? void 0 : _a74.access_token) && !this.hasCustomAuthorizationHeader) {
20693
+ if (!((_a78 = data.session) === null || _a78 === void 0 ? void 0 : _a78.access_token) && !this.hasCustomAuthorizationHeader) {
20618
20694
  return { data: { user: null }, error: new AuthSessionMissingError() };
20619
20695
  }
20620
20696
  return await _request(this.fetch, "GET", `${this.url}/user`, {
@@ -20756,13 +20832,13 @@ var GoTrueClient = class _GoTrueClient {
20756
20832
  async _refreshSession(currentSession) {
20757
20833
  try {
20758
20834
  return await this._useSession(async (result) => {
20759
- var _a74;
20835
+ var _a78;
20760
20836
  if (!currentSession) {
20761
20837
  const { data, error: error2 } = result;
20762
20838
  if (error2) {
20763
20839
  throw error2;
20764
20840
  }
20765
- currentSession = (_a74 = data.session) !== null && _a74 !== void 0 ? _a74 : void 0;
20841
+ currentSession = (_a78 = data.session) !== null && _a78 !== void 0 ? _a78 : void 0;
20766
20842
  }
20767
20843
  if (!(currentSession === null || currentSession === void 0 ? void 0 : currentSession.refresh_token)) {
20768
20844
  throw new AuthSessionMissingError();
@@ -20900,12 +20976,12 @@ var GoTrueClient = class _GoTrueClient {
20900
20976
  }
20901
20977
  async _signOut({ scope } = { scope: "global" }) {
20902
20978
  return await this._useSession(async (result) => {
20903
- var _a74;
20979
+ var _a78;
20904
20980
  const { data, error: sessionError } = result;
20905
20981
  if (sessionError) {
20906
20982
  return this._returnResult({ error: sessionError });
20907
20983
  }
20908
- const accessToken = (_a74 = data.session) === null || _a74 === void 0 ? void 0 : _a74.access_token;
20984
+ const accessToken = (_a78 = data.session) === null || _a78 === void 0 ? void 0 : _a78.access_token;
20909
20985
  if (accessToken) {
20910
20986
  const { error } = await this.admin.signOut(accessToken, scope);
20911
20987
  if (error) {
@@ -20943,12 +21019,12 @@ var GoTrueClient = class _GoTrueClient {
20943
21019
  }
20944
21020
  async _emitInitialSession(id) {
20945
21021
  return await this._useSession(async (result) => {
20946
- var _a74, _b7;
21022
+ var _a78, _b7;
20947
21023
  try {
20948
21024
  const { data: { session }, error } = result;
20949
21025
  if (error)
20950
21026
  throw error;
20951
- await ((_a74 = this.stateChangeEmitters.get(id)) === null || _a74 === void 0 ? void 0 : _a74.callback("INITIAL_SESSION", session));
21027
+ await ((_a78 = this.stateChangeEmitters.get(id)) === null || _a78 === void 0 ? void 0 : _a78.callback("INITIAL_SESSION", session));
20952
21028
  this._debug("INITIAL_SESSION", "callback id", id, "session", session);
20953
21029
  } catch (err) {
20954
21030
  await ((_b7 = this.stateChangeEmitters.get(id)) === null || _b7 === void 0 ? void 0 : _b7.callback("INITIAL_SESSION", null));
@@ -20999,12 +21075,12 @@ var GoTrueClient = class _GoTrueClient {
20999
21075
  * Gets all the identities linked to a user.
21000
21076
  */
21001
21077
  async getUserIdentities() {
21002
- var _a74;
21078
+ var _a78;
21003
21079
  try {
21004
21080
  const { data, error } = await this.getUser();
21005
21081
  if (error)
21006
21082
  throw error;
21007
- return this._returnResult({ data: { identities: (_a74 = data.user.identities) !== null && _a74 !== void 0 ? _a74 : [] }, error: null });
21083
+ return this._returnResult({ data: { identities: (_a78 = data.user.identities) !== null && _a78 !== void 0 ? _a78 : [] }, error: null });
21008
21084
  } catch (error) {
21009
21085
  if (isAuthError(error)) {
21010
21086
  return this._returnResult({ data: null, error });
@@ -21019,15 +21095,15 @@ var GoTrueClient = class _GoTrueClient {
21019
21095
  return this.linkIdentityOAuth(credentials);
21020
21096
  }
21021
21097
  async linkIdentityOAuth(credentials) {
21022
- var _a74;
21098
+ var _a78;
21023
21099
  try {
21024
21100
  const { data, error } = await this._useSession(async (result) => {
21025
- var _a75, _b7, _c, _d, _e;
21101
+ var _a79, _b7, _c, _d, _e;
21026
21102
  const { data: data2, error: error2 } = result;
21027
21103
  if (error2)
21028
21104
  throw error2;
21029
21105
  const url = await this._getUrlForProvider(`${this.url}/user/identities/authorize`, credentials.provider, {
21030
- redirectTo: (_a75 = credentials.options) === null || _a75 === void 0 ? void 0 : _a75.redirectTo,
21106
+ redirectTo: (_a79 = credentials.options) === null || _a79 === void 0 ? void 0 : _a79.redirectTo,
21031
21107
  scopes: (_b7 = credentials.options) === null || _b7 === void 0 ? void 0 : _b7.scopes,
21032
21108
  queryParams: (_c = credentials.options) === null || _c === void 0 ? void 0 : _c.queryParams,
21033
21109
  skipBrowserRedirect: true
@@ -21039,7 +21115,7 @@ var GoTrueClient = class _GoTrueClient {
21039
21115
  });
21040
21116
  if (error)
21041
21117
  throw error;
21042
- if (isBrowser() && !((_a74 = credentials.options) === null || _a74 === void 0 ? void 0 : _a74.skipBrowserRedirect)) {
21118
+ if (isBrowser() && !((_a78 = credentials.options) === null || _a78 === void 0 ? void 0 : _a78.skipBrowserRedirect)) {
21043
21119
  window.location.assign(data === null || data === void 0 ? void 0 : data.url);
21044
21120
  }
21045
21121
  return this._returnResult({
@@ -21055,7 +21131,7 @@ var GoTrueClient = class _GoTrueClient {
21055
21131
  }
21056
21132
  async linkIdentityIdToken(credentials) {
21057
21133
  return await this._useSession(async (result) => {
21058
- var _a74;
21134
+ var _a78;
21059
21135
  try {
21060
21136
  const { error: sessionError, data: { session } } = result;
21061
21137
  if (sessionError)
@@ -21063,7 +21139,7 @@ var GoTrueClient = class _GoTrueClient {
21063
21139
  const { options, provider, token, access_token, nonce } = credentials;
21064
21140
  const res = await _request(this.fetch, "POST", `${this.url}/token?grant_type=id_token`, {
21065
21141
  headers: this.headers,
21066
- jwt: (_a74 = session === null || session === void 0 ? void 0 : session.access_token) !== null && _a74 !== void 0 ? _a74 : void 0,
21142
+ jwt: (_a78 = session === null || session === void 0 ? void 0 : session.access_token) !== null && _a78 !== void 0 ? _a78 : void 0,
21067
21143
  body: {
21068
21144
  provider,
21069
21145
  id_token: token,
@@ -21103,14 +21179,14 @@ var GoTrueClient = class _GoTrueClient {
21103
21179
  async unlinkIdentity(identity) {
21104
21180
  try {
21105
21181
  return await this._useSession(async (result) => {
21106
- var _a74, _b7;
21182
+ var _a78, _b7;
21107
21183
  const { data, error } = result;
21108
21184
  if (error) {
21109
21185
  throw error;
21110
21186
  }
21111
21187
  return await _request(this.fetch, "DELETE", `${this.url}/user/identities/${identity.identity_id}`, {
21112
21188
  headers: this.headers,
21113
- jwt: (_b7 = (_a74 = data.session) === null || _a74 === void 0 ? void 0 : _a74.access_token) !== null && _b7 !== void 0 ? _b7 : void 0
21189
+ jwt: (_b7 = (_a78 = data.session) === null || _a78 === void 0 ? void 0 : _a78.access_token) !== null && _b7 !== void 0 ? _b7 : void 0
21114
21190
  });
21115
21191
  });
21116
21192
  } catch (error) {
@@ -21175,7 +21251,7 @@ var GoTrueClient = class _GoTrueClient {
21175
21251
  * Note: this method is async to accommodate for AsyncStorage e.g. in React native.
21176
21252
  */
21177
21253
  async _recoverAndRefresh() {
21178
- var _a74, _b7;
21254
+ var _a78, _b7;
21179
21255
  const debugName = "#_recoverAndRefresh()";
21180
21256
  this._debug(debugName, "begin");
21181
21257
  try {
@@ -21186,7 +21262,7 @@ var GoTrueClient = class _GoTrueClient {
21186
21262
  maybeUser = { user: currentSession.user };
21187
21263
  await setItemAsync(this.userStorage, this.storageKey + "-user", maybeUser);
21188
21264
  }
21189
- currentSession.user = (_a74 = maybeUser === null || maybeUser === void 0 ? void 0 : maybeUser.user) !== null && _a74 !== void 0 ? _a74 : userNotAvailableProxy();
21265
+ currentSession.user = (_a78 = maybeUser === null || maybeUser === void 0 ? void 0 : maybeUser.user) !== null && _a78 !== void 0 ? _a78 : userNotAvailableProxy();
21190
21266
  } else if (currentSession && !currentSession.user) {
21191
21267
  if (!currentSession.user) {
21192
21268
  const separateUser = await getItemAsync(this.storage, this.storageKey + "-user");
@@ -21246,7 +21322,7 @@ var GoTrueClient = class _GoTrueClient {
21246
21322
  }
21247
21323
  }
21248
21324
  async _callRefreshToken(refreshToken) {
21249
- var _a74, _b7;
21325
+ var _a78, _b7;
21250
21326
  if (!refreshToken) {
21251
21327
  throw new AuthSessionMissingError();
21252
21328
  }
@@ -21274,7 +21350,7 @@ var GoTrueClient = class _GoTrueClient {
21274
21350
  if (!isAuthRetryableFetchError(error)) {
21275
21351
  await this._removeSession();
21276
21352
  }
21277
- (_a74 = this.refreshingDeferred) === null || _a74 === void 0 ? void 0 : _a74.resolve(result);
21353
+ (_a78 = this.refreshingDeferred) === null || _a78 === void 0 ? void 0 : _a78.resolve(result);
21278
21354
  return result;
21279
21355
  }
21280
21356
  (_b7 = this.refreshingDeferred) === null || _b7 === void 0 ? void 0 : _b7.reject(error);
@@ -21563,14 +21639,14 @@ var GoTrueClient = class _GoTrueClient {
21563
21639
  async _unenroll(params) {
21564
21640
  try {
21565
21641
  return await this._useSession(async (result) => {
21566
- var _a74;
21642
+ var _a78;
21567
21643
  const { data: sessionData, error: sessionError } = result;
21568
21644
  if (sessionError) {
21569
21645
  return this._returnResult({ data: null, error: sessionError });
21570
21646
  }
21571
21647
  return await _request(this.fetch, "DELETE", `${this.url}/factors/${params.factorId}`, {
21572
21648
  headers: this.headers,
21573
- jwt: (_a74 = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a74 === void 0 ? void 0 : _a74.access_token
21649
+ jwt: (_a78 = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a78 === void 0 ? void 0 : _a78.access_token
21574
21650
  });
21575
21651
  });
21576
21652
  } catch (error) {
@@ -21583,7 +21659,7 @@ var GoTrueClient = class _GoTrueClient {
21583
21659
  async _enroll(params) {
21584
21660
  try {
21585
21661
  return await this._useSession(async (result) => {
21586
- var _a74, _b7;
21662
+ var _a78, _b7;
21587
21663
  const { data: sessionData, error: sessionError } = result;
21588
21664
  if (sessionError) {
21589
21665
  return this._returnResult({ data: null, error: sessionError });
@@ -21592,7 +21668,7 @@ var GoTrueClient = class _GoTrueClient {
21592
21668
  const { data, error } = await _request(this.fetch, "POST", `${this.url}/factors`, {
21593
21669
  body,
21594
21670
  headers: this.headers,
21595
- jwt: (_a74 = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a74 === void 0 ? void 0 : _a74.access_token
21671
+ jwt: (_a78 = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a78 === void 0 ? void 0 : _a78.access_token
21596
21672
  });
21597
21673
  if (error) {
21598
21674
  return this._returnResult({ data: null, error });
@@ -21613,7 +21689,7 @@ var GoTrueClient = class _GoTrueClient {
21613
21689
  return this._acquireLock(this.lockAcquireTimeout, async () => {
21614
21690
  try {
21615
21691
  return await this._useSession(async (result) => {
21616
- var _a74;
21692
+ var _a78;
21617
21693
  const { data: sessionData, error: sessionError } = result;
21618
21694
  if (sessionError) {
21619
21695
  return this._returnResult({ data: null, error: sessionError });
@@ -21624,7 +21700,7 @@ var GoTrueClient = class _GoTrueClient {
21624
21700
  const { data, error } = await _request(this.fetch, "POST", `${this.url}/factors/${params.factorId}/verify`, {
21625
21701
  body,
21626
21702
  headers: this.headers,
21627
- jwt: (_a74 = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a74 === void 0 ? void 0 : _a74.access_token
21703
+ jwt: (_a78 = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a78 === void 0 ? void 0 : _a78.access_token
21628
21704
  });
21629
21705
  if (error) {
21630
21706
  return this._returnResult({ data: null, error });
@@ -21645,7 +21721,7 @@ var GoTrueClient = class _GoTrueClient {
21645
21721
  return this._acquireLock(this.lockAcquireTimeout, async () => {
21646
21722
  try {
21647
21723
  return await this._useSession(async (result) => {
21648
- var _a74;
21724
+ var _a78;
21649
21725
  const { data: sessionData, error: sessionError } = result;
21650
21726
  if (sessionError) {
21651
21727
  return this._returnResult({ data: null, error: sessionError });
@@ -21653,7 +21729,7 @@ var GoTrueClient = class _GoTrueClient {
21653
21729
  const response = await _request(this.fetch, "POST", `${this.url}/factors/${params.factorId}/challenge`, {
21654
21730
  body: params,
21655
21731
  headers: this.headers,
21656
- jwt: (_a74 = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a74 === void 0 ? void 0 : _a74.access_token
21732
+ jwt: (_a78 = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a78 === void 0 ? void 0 : _a78.access_token
21657
21733
  });
21658
21734
  if (response.error) {
21659
21735
  return response;
@@ -21703,7 +21779,7 @@ var GoTrueClient = class _GoTrueClient {
21703
21779
  * {@see GoTrueMFAApi#listFactors}
21704
21780
  */
21705
21781
  async _listFactors() {
21706
- var _a74;
21782
+ var _a78;
21707
21783
  const { data: { user }, error: userError } = await this.getUser();
21708
21784
  if (userError) {
21709
21785
  return { data: null, error: userError };
@@ -21714,7 +21790,7 @@ var GoTrueClient = class _GoTrueClient {
21714
21790
  totp: [],
21715
21791
  webauthn: []
21716
21792
  };
21717
- for (const factor of (_a74 = user === null || user === void 0 ? void 0 : user.factors) !== null && _a74 !== void 0 ? _a74 : []) {
21793
+ for (const factor of (_a78 = user === null || user === void 0 ? void 0 : user.factors) !== null && _a78 !== void 0 ? _a78 : []) {
21718
21794
  data.all.push(factor);
21719
21795
  if (factor.status === "verified") {
21720
21796
  ;
@@ -21730,7 +21806,7 @@ var GoTrueClient = class _GoTrueClient {
21730
21806
  * {@see GoTrueMFAApi#getAuthenticatorAssuranceLevel}
21731
21807
  */
21732
21808
  async _getAuthenticatorAssuranceLevel() {
21733
- var _a74, _b7;
21809
+ var _a78, _b7;
21734
21810
  const { data: { session }, error: sessionError } = await this.getSession();
21735
21811
  if (sessionError) {
21736
21812
  return this._returnResult({ data: null, error: sessionError });
@@ -21747,7 +21823,7 @@ var GoTrueClient = class _GoTrueClient {
21747
21823
  currentLevel = payload.aal;
21748
21824
  }
21749
21825
  let nextLevel = currentLevel;
21750
- const verifiedFactors = (_b7 = (_a74 = session.user.factors) === null || _a74 === void 0 ? void 0 : _a74.filter((factor) => factor.status === "verified")) !== null && _b7 !== void 0 ? _b7 : [];
21826
+ const verifiedFactors = (_b7 = (_a78 = session.user.factors) === null || _a78 === void 0 ? void 0 : _a78.filter((factor) => factor.status === "verified")) !== null && _b7 !== void 0 ? _b7 : [];
21751
21827
  if (verifiedFactors.length > 0) {
21752
21828
  nextLevel = "aal2";
21753
21829
  }
@@ -22353,10 +22429,10 @@ if (shouldShowDeprecationWarning()) console.warn("\u26A0\uFE0F Node.js 18 and b
22353
22429
  var cachedStargate = null;
22354
22430
  var cachedPublic = null;
22355
22431
  function getSupabase() {
22356
- var _a74;
22432
+ var _a78;
22357
22433
  if (cachedStargate) return cachedStargate;
22358
22434
  const url = getRuntimeEnv("VITE_SUPABASE_URL");
22359
- const anon = (_a74 = getRuntimeEnv("VITE_SUPABASE_ANON_KEY")) != null ? _a74 : getRuntimeEnv("VITE_SUPABASE_PUBLISHABLE_KEY");
22435
+ const anon = (_a78 = getRuntimeEnv("VITE_SUPABASE_ANON_KEY")) != null ? _a78 : getRuntimeEnv("VITE_SUPABASE_PUBLISHABLE_KEY");
22360
22436
  const schema = getRuntimeEnvOr("VITE_SUPABASE_SCHEMA", "public");
22361
22437
  if (!url || !anon) {
22362
22438
  if (isRuntimeDev()) {
@@ -22374,10 +22450,10 @@ function getSupabase() {
22374
22450
  return cachedStargate;
22375
22451
  }
22376
22452
  function getSupabasePublic() {
22377
- var _a74;
22453
+ var _a78;
22378
22454
  if (cachedPublic) return cachedPublic;
22379
22455
  const url = getRuntimeEnv("VITE_SUPABASE_URL");
22380
- const anon = (_a74 = getRuntimeEnv("VITE_SUPABASE_ANON_KEY")) != null ? _a74 : getRuntimeEnv("VITE_SUPABASE_PUBLISHABLE_KEY");
22456
+ const anon = (_a78 = getRuntimeEnv("VITE_SUPABASE_ANON_KEY")) != null ? _a78 : getRuntimeEnv("VITE_SUPABASE_PUBLISHABLE_KEY");
22381
22457
  if (!url || !anon) {
22382
22458
  if (isRuntimeDev()) {
22383
22459
  console.log("[supabase] getSupabasePublic: env faltando", { hasUrl: !!url, hasAnon: !!anon });
@@ -22452,9 +22528,9 @@ var Toaster = ({ theme, ...props }) => {
22452
22528
  // src/lib/accountsAuth.ts
22453
22529
  var normalizeBaseUrl2 = (value) => value.replace(/\/+$/, "");
22454
22530
  var getAccountsConfig = () => {
22455
- var _a74, _b7, _c;
22531
+ var _a78, _b7, _c;
22456
22532
  const baseUrl = normalizeBaseUrl2(
22457
- (_a74 = getRuntimeEnv("VITE_ACCOUNTS_BASE_URL")) != null ? _a74 : "https://accounts.cupcode.com.br"
22533
+ (_a78 = getRuntimeEnv("VITE_ACCOUNTS_BASE_URL")) != null ? _a78 : "https://accounts.cupcode.com.br"
22458
22534
  );
22459
22535
  const clientId = getRuntimeEnv("VITE_ACCOUNTS_CLIENT_ID");
22460
22536
  if (!clientId) {
@@ -22475,7 +22551,7 @@ var getAccountsConfig = () => {
22475
22551
  };
22476
22552
  var cachedDiscovery = null;
22477
22553
  var resolveOidcEndpoints = async (config) => {
22478
- var _a74, _b7, _c, _d, _e, _f;
22554
+ var _a78, _b7, _c, _d, _e, _f;
22479
22555
  if (config.authUrl && config.tokenUrl) {
22480
22556
  return {
22481
22557
  authUrl: config.authUrl,
@@ -22485,7 +22561,7 @@ var resolveOidcEndpoints = async (config) => {
22485
22561
  }
22486
22562
  if (cachedDiscovery) {
22487
22563
  return {
22488
- authUrl: (_a74 = cachedDiscovery.authorization_endpoint) != null ? _a74 : config.authUrl,
22564
+ authUrl: (_a78 = cachedDiscovery.authorization_endpoint) != null ? _a78 : config.authUrl,
22489
22565
  tokenUrl: (_b7 = cachedDiscovery.token_endpoint) != null ? _b7 : config.tokenUrl,
22490
22566
  logoutUrl: (_c = cachedDiscovery.end_session_endpoint) != null ? _c : config.logoutUrl
22491
22567
  };
@@ -22550,6 +22626,30 @@ var buildAuthorizeUrl = (config, authUrl, state, challenge, nonce, options) => {
22550
22626
  if (options == null ? void 0 : options.loginHint) params.set("login_hint", options.loginHint);
22551
22627
  return `${authUrl}?${params.toString()}`;
22552
22628
  };
22629
+ var readTokenField = (payload, keys) => {
22630
+ for (const key of keys) {
22631
+ const candidate = payload[key];
22632
+ if (typeof candidate !== "string") continue;
22633
+ const normalized = candidate.trim();
22634
+ if (normalized) return normalized;
22635
+ }
22636
+ return void 0;
22637
+ };
22638
+ var readNumericField = (payload, keys) => {
22639
+ for (const key of keys) {
22640
+ const candidate = payload[key];
22641
+ if (typeof candidate === "number" && Number.isFinite(candidate) && candidate > 0) {
22642
+ return candidate;
22643
+ }
22644
+ if (typeof candidate === "string") {
22645
+ const parsed = Number(candidate);
22646
+ if (Number.isFinite(parsed) && parsed > 0) {
22647
+ return parsed;
22648
+ }
22649
+ }
22650
+ }
22651
+ return void 0;
22652
+ };
22553
22653
  var exchangeCodeForToken = async (config, tokenUrl, code, verifier) => {
22554
22654
  const body = new URLSearchParams({
22555
22655
  grant_type: "authorization_code",
@@ -22567,7 +22667,22 @@ var exchangeCodeForToken = async (config, tokenUrl, code, verifier) => {
22567
22667
  const text = await response.text();
22568
22668
  throw new Error(text || "Falha ao obter token do accounts.");
22569
22669
  }
22570
- return await response.json();
22670
+ const payload = await response.json();
22671
+ const accessToken = readTokenField(payload, ["access_token", "accessToken", "token"]);
22672
+ if (!accessToken) {
22673
+ throw new Error("Token de acesso n\xE3o retornado pelo accounts.");
22674
+ }
22675
+ const idToken = readTokenField(payload, ["id_token", "idToken"]);
22676
+ const refreshToken = readTokenField(payload, ["refresh_token", "refreshToken"]);
22677
+ const tokenType = readTokenField(payload, ["token_type", "tokenType"]);
22678
+ const expiresIn = readNumericField(payload, ["expires_in", "expiresIn", "expires"]);
22679
+ return {
22680
+ access_token: accessToken,
22681
+ id_token: idToken,
22682
+ refresh_token: refreshToken,
22683
+ token_type: tokenType,
22684
+ expires_in: expiresIn
22685
+ };
22571
22686
  };
22572
22687
  var buildLogoutUrl = (config, logoutUrl, idTokenHint) => {
22573
22688
  if (!logoutUrl) return void 0;
@@ -22591,6 +22706,11 @@ var decodeJwt = (token) => {
22591
22706
 
22592
22707
  // src/components/cupcode/MainNavbar.tsx
22593
22708
  import { Fragment as Fragment4, jsx as jsx45, jsxs as jsxs28 } from "react/jsx-runtime";
22709
+ var parsePositiveInteger = (rawValue, fallback) => {
22710
+ const parsed = Number(rawValue);
22711
+ if (!Number.isFinite(parsed) || parsed <= 0) return fallback;
22712
+ return Math.floor(parsed);
22713
+ };
22594
22714
  var _a18, _b5;
22595
22715
  var SUPABASE_SCHEMA = ((_b5 = (_a18 = getRuntimeEnv("VITE_CHAT_SCHEMA")) != null ? _a18 : getRuntimeEnv("VITE_SUPABASE_SCHEMA")) != null ? _b5 : "public").trim();
22596
22716
  var _a19;
@@ -22600,27 +22720,37 @@ var USER_PRESENCE_USER_ID_COLUMN = ((_a20 = getRuntimeEnv("VITE_USER_PRESENCE_US
22600
22720
  var _a21;
22601
22721
  var USER_PRESENCE_STATUS_COLUMN = ((_a21 = getRuntimeEnv("VITE_USER_PRESENCE_STATUS_COLUMN")) != null ? _a21 : "status").trim();
22602
22722
  var _a22;
22603
- var CHAT_USERS_TABLE = ((_a22 = getRuntimeEnv("VITE_CHAT_USERS_TABLE")) != null ? _a22 : "chat_users").trim();
22723
+ var USER_PRESENCE_SOURCE_COLUMN = ((_a22 = getRuntimeEnv("VITE_USER_PRESENCE_SOURCE_COLUMN")) != null ? _a22 : "status_source").trim();
22604
22724
  var _a23;
22605
- var CHAT_USERS_ID_COLUMN = ((_a23 = getRuntimeEnv("VITE_CHAT_USERS_ID_COLUMN")) != null ? _a23 : "id").trim();
22725
+ var USER_PRESENCE_LAST_ACTIVE_COLUMN = ((_a23 = getRuntimeEnv("VITE_USER_PRESENCE_LAST_ACTIVE_COLUMN")) != null ? _a23 : "last_active_at").trim();
22726
+ var PRESENCE_IDLE_TIMEOUT_MS = parsePositiveInteger(getRuntimeEnv("VITE_PRESENCE_IDLE_TIMEOUT_MS"), 10 * 60 * 1e3);
22727
+ var PRESENCE_OFFLINE_TIMEOUT_MS = Math.max(
22728
+ parsePositiveInteger(getRuntimeEnv("VITE_PRESENCE_OFFLINE_TIMEOUT_MS"), 10 * 60 * 1e3),
22729
+ PRESENCE_IDLE_TIMEOUT_MS
22730
+ );
22731
+ var PRESENCE_RECALC_INTERVAL_MS = 3e4;
22606
22732
  var _a24;
22607
- var CHAT_USERS_NAME_COLUMN = ((_a24 = getRuntimeEnv("VITE_CHAT_USERS_NAME_COLUMN")) != null ? _a24 : "name").trim();
22733
+ var CHAT_USERS_TABLE = ((_a24 = getRuntimeEnv("VITE_CHAT_USERS_TABLE")) != null ? _a24 : "chat_users").trim();
22608
22734
  var _a25;
22609
- var CHAT_USERS_USERNAME_COLUMN = ((_a25 = getRuntimeEnv("VITE_CHAT_USERS_USERNAME_COLUMN")) != null ? _a25 : "username").trim();
22735
+ var CHAT_USERS_ID_COLUMN = ((_a25 = getRuntimeEnv("VITE_CHAT_USERS_ID_COLUMN")) != null ? _a25 : "id").trim();
22610
22736
  var _a26;
22611
- var CHAT_USERS_EMAIL_COLUMN = ((_a26 = getRuntimeEnv("VITE_CHAT_USERS_EMAIL_COLUMN")) != null ? _a26 : "email").trim();
22737
+ var CHAT_USERS_NAME_COLUMN = ((_a26 = getRuntimeEnv("VITE_CHAT_USERS_NAME_COLUMN")) != null ? _a26 : "name").trim();
22612
22738
  var _a27;
22613
- var CHAT_USERS_AVATAR_COLUMN = ((_a27 = getRuntimeEnv("VITE_CHAT_USERS_AVATAR_COLUMN")) != null ? _a27 : "avatar_url").trim();
22739
+ var CHAT_USERS_USERNAME_COLUMN = ((_a27 = getRuntimeEnv("VITE_CHAT_USERS_USERNAME_COLUMN")) != null ? _a27 : "username").trim();
22614
22740
  var _a28;
22615
- var CHAT_USERS_ROLE_COLUMN = ((_a28 = getRuntimeEnv("VITE_CHAT_USERS_ROLE_COLUMN")) != null ? _a28 : "job_title").trim();
22741
+ var CHAT_USERS_EMAIL_COLUMN = ((_a28 = getRuntimeEnv("VITE_CHAT_USERS_EMAIL_COLUMN")) != null ? _a28 : "email").trim();
22616
22742
  var _a29;
22617
- var CHAT_USERS_UPDATE_TABLE = ((_a29 = getRuntimeEnv("VITE_CHAT_USERS_UPDATE_TABLE")) != null ? _a29 : "profiles").trim();
22743
+ var CHAT_USERS_AVATAR_COLUMN = ((_a29 = getRuntimeEnv("VITE_CHAT_USERS_AVATAR_COLUMN")) != null ? _a29 : "avatar_url").trim();
22618
22744
  var _a30;
22619
- var CHAT_USERS_UPDATE_ID_COLUMN = ((_a30 = getRuntimeEnv("VITE_CHAT_USERS_UPDATE_ID_COLUMN")) != null ? _a30 : "id").trim();
22745
+ var CHAT_USERS_ROLE_COLUMN = ((_a30 = getRuntimeEnv("VITE_CHAT_USERS_ROLE_COLUMN")) != null ? _a30 : "job_title").trim();
22620
22746
  var _a31;
22621
- var CHAT_USERS_UPDATE_EMAIL_COLUMN = ((_a31 = getRuntimeEnv("VITE_CHAT_USERS_UPDATE_EMAIL_COLUMN")) != null ? _a31 : "email").trim();
22747
+ var CHAT_USERS_UPDATE_TABLE = ((_a31 = getRuntimeEnv("VITE_CHAT_USERS_UPDATE_TABLE")) != null ? _a31 : "profiles").trim();
22622
22748
  var _a32;
22623
- var CHAT_USERS_UPDATE_AVATAR_COLUMN = ((_a32 = getRuntimeEnv("VITE_CHAT_USERS_UPDATE_AVATAR_COLUMN")) != null ? _a32 : "avatar_url").trim();
22749
+ var CHAT_USERS_UPDATE_ID_COLUMN = ((_a32 = getRuntimeEnv("VITE_CHAT_USERS_UPDATE_ID_COLUMN")) != null ? _a32 : "id").trim();
22750
+ var _a33;
22751
+ var CHAT_USERS_UPDATE_EMAIL_COLUMN = ((_a33 = getRuntimeEnv("VITE_CHAT_USERS_UPDATE_EMAIL_COLUMN")) != null ? _a33 : "email").trim();
22752
+ var _a34;
22753
+ var CHAT_USERS_UPDATE_AVATAR_COLUMN = ((_a34 = getRuntimeEnv("VITE_CHAT_USERS_UPDATE_AVATAR_COLUMN")) != null ? _a34 : "avatar_url").trim();
22624
22754
  var CHAT_USERS_LOOKUP_TABLES = Array.from(
22625
22755
  new Set(
22626
22756
  [CHAT_USERS_TABLE, "chat_users", CHAT_USERS_UPDATE_TABLE, "profiles", "users"].map((entry) => entry.trim()).filter((entry) => entry.length > 0)
@@ -22636,73 +22766,73 @@ var CHAT_USERS_LOOKUP_EMAIL_COLUMNS = Array.from(
22636
22766
  [CHAT_USERS_EMAIL_COLUMN, CHAT_USERS_UPDATE_EMAIL_COLUMN, "email"].map((entry) => entry.trim()).filter((entry) => entry.length > 0)
22637
22767
  )
22638
22768
  );
22639
- var _a33;
22640
- var CHAT_MESSAGES_TABLE = ((_a33 = getRuntimeEnv("VITE_CHAT_MESSAGES_TABLE")) != null ? _a33 : "chat_messages").trim();
22641
- var _a34;
22642
- var CHAT_MESSAGES_ID_COLUMN = ((_a34 = getRuntimeEnv("VITE_CHAT_MESSAGES_ID_COLUMN")) != null ? _a34 : "id").trim();
22643
22769
  var _a35;
22644
- var CHAT_MESSAGES_SENDER_COLUMN = ((_a35 = getRuntimeEnv("VITE_CHAT_MESSAGES_SENDER_COLUMN")) != null ? _a35 : "sender_id").trim();
22770
+ var CHAT_MESSAGES_TABLE = ((_a35 = getRuntimeEnv("VITE_CHAT_MESSAGES_TABLE")) != null ? _a35 : "chat_messages").trim();
22645
22771
  var _a36;
22646
- var CHAT_MESSAGES_RECIPIENT_COLUMN = ((_a36 = getRuntimeEnv("VITE_CHAT_MESSAGES_RECIPIENT_COLUMN")) != null ? _a36 : "recipient_id").trim();
22772
+ var CHAT_MESSAGES_ID_COLUMN = ((_a36 = getRuntimeEnv("VITE_CHAT_MESSAGES_ID_COLUMN")) != null ? _a36 : "id").trim();
22647
22773
  var _a37;
22648
- var CHAT_MESSAGES_TEXT_COLUMN = ((_a37 = getRuntimeEnv("VITE_CHAT_MESSAGES_TEXT_COLUMN")) != null ? _a37 : "text").trim();
22774
+ var CHAT_MESSAGES_SENDER_COLUMN = ((_a37 = getRuntimeEnv("VITE_CHAT_MESSAGES_SENDER_COLUMN")) != null ? _a37 : "sender_id").trim();
22649
22775
  var _a38;
22650
- var CHAT_MESSAGES_CREATED_AT_COLUMN = ((_a38 = getRuntimeEnv("VITE_CHAT_MESSAGES_CREATED_AT_COLUMN")) != null ? _a38 : "created_at").trim();
22776
+ var CHAT_MESSAGES_RECIPIENT_COLUMN = ((_a38 = getRuntimeEnv("VITE_CHAT_MESSAGES_RECIPIENT_COLUMN")) != null ? _a38 : "recipient_id").trim();
22651
22777
  var _a39;
22652
- var CHAT_MESSAGES_READ_AT_COLUMN = ((_a39 = getRuntimeEnv("VITE_CHAT_MESSAGES_READ_AT_COLUMN")) != null ? _a39 : "read_at").trim();
22778
+ var CHAT_MESSAGES_TEXT_COLUMN = ((_a39 = getRuntimeEnv("VITE_CHAT_MESSAGES_TEXT_COLUMN")) != null ? _a39 : "text").trim();
22653
22779
  var _a40;
22654
- var CHAT_MESSAGES_REPLY_TO_COLUMN = ((_a40 = getRuntimeEnv("VITE_CHAT_MESSAGES_REPLY_TO_COLUMN")) != null ? _a40 : "reply_to_message_id").trim();
22780
+ var CHAT_MESSAGES_CREATED_AT_COLUMN = ((_a40 = getRuntimeEnv("VITE_CHAT_MESSAGES_CREATED_AT_COLUMN")) != null ? _a40 : "created_at").trim();
22655
22781
  var _a41;
22656
- var CHAT_MESSAGES_EDITED_AT_COLUMN = ((_a41 = getRuntimeEnv("VITE_CHAT_MESSAGES_EDITED_AT_COLUMN")) != null ? _a41 : "edited_at").trim();
22782
+ var CHAT_MESSAGES_READ_AT_COLUMN = ((_a41 = getRuntimeEnv("VITE_CHAT_MESSAGES_READ_AT_COLUMN")) != null ? _a41 : "read_at").trim();
22657
22783
  var _a42;
22658
- var CHAT_MESSAGES_DELETED_AT_COLUMN = ((_a42 = getRuntimeEnv("VITE_CHAT_MESSAGES_DELETED_AT_COLUMN")) != null ? _a42 : "deleted_at").trim();
22784
+ var CHAT_MESSAGES_REPLY_TO_COLUMN = ((_a42 = getRuntimeEnv("VITE_CHAT_MESSAGES_REPLY_TO_COLUMN")) != null ? _a42 : "reply_to_message_id").trim();
22659
22785
  var _a43;
22660
- var CHAT_MESSAGES_DELETED_BY_COLUMN = ((_a43 = getRuntimeEnv("VITE_CHAT_MESSAGES_DELETED_BY_COLUMN")) != null ? _a43 : "deleted_by").trim();
22786
+ var CHAT_MESSAGES_EDITED_AT_COLUMN = ((_a43 = getRuntimeEnv("VITE_CHAT_MESSAGES_EDITED_AT_COLUMN")) != null ? _a43 : "edited_at").trim();
22661
22787
  var _a44;
22662
- var CHAT_REACTIONS_TABLE = ((_a44 = getRuntimeEnv("VITE_CHAT_REACTIONS_TABLE")) != null ? _a44 : "chat_message_reactions").trim();
22788
+ var CHAT_MESSAGES_DELETED_AT_COLUMN = ((_a44 = getRuntimeEnv("VITE_CHAT_MESSAGES_DELETED_AT_COLUMN")) != null ? _a44 : "deleted_at").trim();
22663
22789
  var _a45;
22664
- var CHAT_REACTIONS_ID_COLUMN = ((_a45 = getRuntimeEnv("VITE_CHAT_REACTIONS_ID_COLUMN")) != null ? _a45 : "id").trim();
22790
+ var CHAT_MESSAGES_DELETED_BY_COLUMN = ((_a45 = getRuntimeEnv("VITE_CHAT_MESSAGES_DELETED_BY_COLUMN")) != null ? _a45 : "deleted_by").trim();
22665
22791
  var _a46;
22666
- var CHAT_REACTIONS_MESSAGE_ID_COLUMN = ((_a46 = getRuntimeEnv("VITE_CHAT_REACTIONS_MESSAGE_ID_COLUMN")) != null ? _a46 : "message_id").trim();
22792
+ var CHAT_REACTIONS_TABLE = ((_a46 = getRuntimeEnv("VITE_CHAT_REACTIONS_TABLE")) != null ? _a46 : "chat_message_reactions").trim();
22667
22793
  var _a47;
22668
- var CHAT_REACTIONS_USER_ID_COLUMN = ((_a47 = getRuntimeEnv("VITE_CHAT_REACTIONS_USER_ID_COLUMN")) != null ? _a47 : "user_id").trim();
22794
+ var CHAT_REACTIONS_ID_COLUMN = ((_a47 = getRuntimeEnv("VITE_CHAT_REACTIONS_ID_COLUMN")) != null ? _a47 : "id").trim();
22669
22795
  var _a48;
22670
- var CHAT_REACTIONS_EMOJI_COLUMN = ((_a48 = getRuntimeEnv("VITE_CHAT_REACTIONS_EMOJI_COLUMN")) != null ? _a48 : "emoji").trim();
22796
+ var CHAT_REACTIONS_MESSAGE_ID_COLUMN = ((_a48 = getRuntimeEnv("VITE_CHAT_REACTIONS_MESSAGE_ID_COLUMN")) != null ? _a48 : "message_id").trim();
22671
22797
  var _a49;
22672
- var CHAT_REACTIONS_CREATED_AT_COLUMN = ((_a49 = getRuntimeEnv("VITE_CHAT_REACTIONS_CREATED_AT_COLUMN")) != null ? _a49 : "created_at").trim();
22798
+ var CHAT_REACTIONS_USER_ID_COLUMN = ((_a49 = getRuntimeEnv("VITE_CHAT_REACTIONS_USER_ID_COLUMN")) != null ? _a49 : "user_id").trim();
22673
22799
  var _a50;
22674
- var CHAT_LOGS_TABLE = ((_a50 = getRuntimeEnv("VITE_CHAT_LOGS_TABLE")) != null ? _a50 : "chat_message_logs").trim();
22800
+ var CHAT_REACTIONS_EMOJI_COLUMN = ((_a50 = getRuntimeEnv("VITE_CHAT_REACTIONS_EMOJI_COLUMN")) != null ? _a50 : "emoji").trim();
22675
22801
  var _a51;
22676
- var CHAT_LOGS_ID_COLUMN = ((_a51 = getRuntimeEnv("VITE_CHAT_LOGS_ID_COLUMN")) != null ? _a51 : "id").trim();
22802
+ var CHAT_REACTIONS_CREATED_AT_COLUMN = ((_a51 = getRuntimeEnv("VITE_CHAT_REACTIONS_CREATED_AT_COLUMN")) != null ? _a51 : "created_at").trim();
22677
22803
  var _a52;
22678
- var CHAT_LOGS_MESSAGE_ID_COLUMN = ((_a52 = getRuntimeEnv("VITE_CHAT_LOGS_MESSAGE_ID_COLUMN")) != null ? _a52 : "message_id").trim();
22804
+ var CHAT_LOGS_TABLE = ((_a52 = getRuntimeEnv("VITE_CHAT_LOGS_TABLE")) != null ? _a52 : "chat_message_logs").trim();
22679
22805
  var _a53;
22680
- var CHAT_LOGS_ACTOR_ID_COLUMN = ((_a53 = getRuntimeEnv("VITE_CHAT_LOGS_ACTOR_ID_COLUMN")) != null ? _a53 : "actor_id").trim();
22806
+ var CHAT_LOGS_ID_COLUMN = ((_a53 = getRuntimeEnv("VITE_CHAT_LOGS_ID_COLUMN")) != null ? _a53 : "id").trim();
22681
22807
  var _a54;
22682
- var CHAT_LOGS_ACTION_COLUMN = ((_a54 = getRuntimeEnv("VITE_CHAT_LOGS_ACTION_COLUMN")) != null ? _a54 : "action").trim();
22808
+ var CHAT_LOGS_MESSAGE_ID_COLUMN = ((_a54 = getRuntimeEnv("VITE_CHAT_LOGS_MESSAGE_ID_COLUMN")) != null ? _a54 : "message_id").trim();
22683
22809
  var _a55;
22684
- var CHAT_LOGS_PREVIOUS_TEXT_COLUMN = ((_a55 = getRuntimeEnv("VITE_CHAT_LOGS_PREVIOUS_TEXT_COLUMN")) != null ? _a55 : "previous_text").trim();
22810
+ var CHAT_LOGS_ACTOR_ID_COLUMN = ((_a55 = getRuntimeEnv("VITE_CHAT_LOGS_ACTOR_ID_COLUMN")) != null ? _a55 : "actor_id").trim();
22685
22811
  var _a56;
22686
- var CHAT_LOGS_NEXT_TEXT_COLUMN = ((_a56 = getRuntimeEnv("VITE_CHAT_LOGS_NEXT_TEXT_COLUMN")) != null ? _a56 : "next_text").trim();
22812
+ var CHAT_LOGS_ACTION_COLUMN = ((_a56 = getRuntimeEnv("VITE_CHAT_LOGS_ACTION_COLUMN")) != null ? _a56 : "action").trim();
22687
22813
  var _a57;
22688
- var CHAT_LOGS_CREATED_AT_COLUMN = ((_a57 = getRuntimeEnv("VITE_CHAT_LOGS_CREATED_AT_COLUMN")) != null ? _a57 : "created_at").trim();
22814
+ var CHAT_LOGS_PREVIOUS_TEXT_COLUMN = ((_a57 = getRuntimeEnv("VITE_CHAT_LOGS_PREVIOUS_TEXT_COLUMN")) != null ? _a57 : "previous_text").trim();
22815
+ var _a58;
22816
+ var CHAT_LOGS_NEXT_TEXT_COLUMN = ((_a58 = getRuntimeEnv("VITE_CHAT_LOGS_NEXT_TEXT_COLUMN")) != null ? _a58 : "next_text").trim();
22817
+ var _a59;
22818
+ var CHAT_LOGS_CREATED_AT_COLUMN = ((_a59 = getRuntimeEnv("VITE_CHAT_LOGS_CREATED_AT_COLUMN")) != null ? _a59 : "created_at").trim();
22689
22819
  var CHAT_MESSAGE_HISTORY_LIMIT = 200;
22690
22820
  var CHAT_EDIT_WINDOW_MINUTES2 = 15;
22691
22821
  var CHAT_DELETED_PLACEHOLDER_TEXT2 = "Mensagem deletada";
22692
- var _a58;
22693
- var TELESCUP_BASE_URL = (_a58 = getRuntimeEnv("VITE_TELESCUP_BASE_URL")) == null ? void 0 : _a58.trim();
22694
- var _a59;
22695
- var SUPABASE_URL2 = (_a59 = getRuntimeEnv("VITE_SUPABASE_URL")) == null ? void 0 : _a59.trim();
22696
- var TELESCUP_BASE_URL_FALLBACK = SUPABASE_URL2 ? `${SUPABASE_URL2.replace(/\/+$/, "")}/functions/v1` : void 0;
22697
- var ACCESS_TOKEN_STORAGE_KEY = "cc_access_token";
22698
22822
  var _a60;
22699
- var ACCOUNTS_BASE_URL2 = ((_a60 = getRuntimeEnv("VITE_ACCOUNTS_BASE_URL")) != null ? _a60 : "https://accounts.cupcode.com.br").trim().replace(/\/+$/, "");
22823
+ var TELESCUP_BASE_URL = (_a60 = getRuntimeEnv("VITE_TELESCUP_BASE_URL")) == null ? void 0 : _a60.trim();
22700
22824
  var _a61;
22701
- var MC_BASE_URL2 = ((_a61 = getRuntimeEnv("VITE_MC_BASE_URL")) != null ? _a61 : "https://mc.cupcode.com.br").trim().replace(/\/+$/, "");
22825
+ var SUPABASE_URL2 = (_a61 = getRuntimeEnv("VITE_SUPABASE_URL")) == null ? void 0 : _a61.trim();
22826
+ var TELESCUP_BASE_URL_FALLBACK = SUPABASE_URL2 ? `${SUPABASE_URL2.replace(/\/+$/, "")}/functions/v1` : void 0;
22827
+ var ACCESS_TOKEN_STORAGE_KEY = "cc_access_token";
22702
22828
  var _a62;
22703
- var ACCOUNTS_LANGUAGE_ENDPOINT = (_a62 = getRuntimeEnv("VITE_ACCOUNTS_LANGUAGE_ENDPOINT")) == null ? void 0 : _a62.trim();
22829
+ var ACCOUNTS_BASE_URL2 = ((_a62 = getRuntimeEnv("VITE_ACCOUNTS_BASE_URL")) != null ? _a62 : "https://accounts.cupcode.com.br").trim().replace(/\/+$/, "");
22704
22830
  var _a63;
22705
- var ACCOUNTS_ACTIVITY_ENDPOINT = (_a63 = getRuntimeEnv("VITE_ACCOUNTS_ACTIVITY_ENDPOINT")) == null ? void 0 : _a63.trim();
22831
+ var MC_BASE_URL2 = ((_a63 = getRuntimeEnv("VITE_MC_BASE_URL")) != null ? _a63 : "https://mc.cupcode.com.br").trim().replace(/\/+$/, "");
22832
+ var _a64;
22833
+ var ACCOUNTS_LANGUAGE_ENDPOINT = (_a64 = getRuntimeEnv("VITE_ACCOUNTS_LANGUAGE_ENDPOINT")) == null ? void 0 : _a64.trim();
22834
+ var _a65;
22835
+ var ACCOUNTS_ACTIVITY_ENDPOINT = (_a65 = getRuntimeEnv("VITE_ACCOUNTS_ACTIVITY_ENDPOINT")) == null ? void 0 : _a65.trim();
22706
22836
  var PRESENCE_STATUS_VALUES = [
22707
22837
  "online",
22708
22838
  "away",
@@ -22713,6 +22843,17 @@ var PRESENCE_STATUS_VALUES = [
22713
22843
  "designing",
22714
22844
  "offline"
22715
22845
  ];
22846
+ var PRESENCE_SOURCE_VALUES = ["auto", "manual", "system"];
22847
+ var PRESENCE_STATUS_LABELS = {
22848
+ online: "On-line",
22849
+ away: "Ausente",
22850
+ busy: "Ocupado",
22851
+ lunch: "Almo\xE7o",
22852
+ call: "Em call",
22853
+ coding: "Coding",
22854
+ designing: "Designing",
22855
+ offline: "Off-line"
22856
+ };
22716
22857
  var CHAT_FEATURE_FLAGS_STORAGE_KEY = "cc_chat_feature_flags";
22717
22858
  var getDefaultChatFeatureFlags = () => ({
22718
22859
  hasReadAt: true,
@@ -22814,6 +22955,59 @@ var normalizePresenceStatus = (value) => {
22814
22955
  const normalized = value.trim().toLowerCase();
22815
22956
  return PRESENCE_STATUS_VALUES.includes(normalized) ? normalized : "offline";
22816
22957
  };
22958
+ var normalizePresenceSource = (value) => {
22959
+ if (typeof value !== "string") return "auto";
22960
+ const normalized = value.trim().toLowerCase();
22961
+ return PRESENCE_SOURCE_VALUES.includes(normalized) ? normalized : "auto";
22962
+ };
22963
+ var toTimestampMs = (value) => {
22964
+ if (typeof value === "number" && Number.isFinite(value)) {
22965
+ return value > 1e12 ? value : value * 1e3;
22966
+ }
22967
+ if (typeof value !== "string") return void 0;
22968
+ const trimmed = value.trim();
22969
+ if (!trimmed) return void 0;
22970
+ const parsed = new Date(trimmed).getTime();
22971
+ return Number.isNaN(parsed) ? void 0 : parsed;
22972
+ };
22973
+ var resolveEffectivePresenceStatus = (snapshot, now = Date.now()) => {
22974
+ if (snapshot.status === "offline") {
22975
+ return "offline";
22976
+ }
22977
+ if (typeof snapshot.lastActiveAtMs === "number" && Number.isFinite(snapshot.lastActiveAtMs)) {
22978
+ const inactiveMs = now - snapshot.lastActiveAtMs;
22979
+ if (inactiveMs >= PRESENCE_OFFLINE_TIMEOUT_MS) {
22980
+ return "offline";
22981
+ }
22982
+ if (snapshot.source === "auto") {
22983
+ return inactiveMs >= PRESENCE_IDLE_TIMEOUT_MS ? "away" : "online";
22984
+ }
22985
+ return snapshot.status;
22986
+ }
22987
+ if (snapshot.source === "auto") {
22988
+ return snapshot.status === "away" ? "away" : "online";
22989
+ }
22990
+ return snapshot.status;
22991
+ };
22992
+ var resolvePresenceStatusLabel = (snapshot, effectiveStatus, now = Date.now()) => {
22993
+ if (effectiveStatus === "online") {
22994
+ return PRESENCE_STATUS_LABELS.online;
22995
+ }
22996
+ const lastActiveAtMs = snapshot.lastActiveAtMs;
22997
+ if ((effectiveStatus === "away" || effectiveStatus === "offline") && typeof lastActiveAtMs === "number" && Number.isFinite(lastActiveAtMs) && now >= lastActiveAtMs) {
22998
+ const diffMinutes = Math.max(1, Math.floor((now - lastActiveAtMs) / 6e4));
22999
+ return `On-line h\xE1 ${diffMinutes} min`;
23000
+ }
23001
+ return PRESENCE_STATUS_LABELS[effectiveStatus];
23002
+ };
23003
+ var readPresenceSnapshotFromRecord = (row) => {
23004
+ var _a78, _b7, _c, _d;
23005
+ if (!row) return null;
23006
+ const status = normalizePresenceStatus((_a78 = row[USER_PRESENCE_STATUS_COLUMN]) != null ? _a78 : row.status);
23007
+ const source = normalizePresenceSource((_b7 = row[USER_PRESENCE_SOURCE_COLUMN]) != null ? _b7 : row.status_source);
23008
+ const lastActiveAtMs = toTimestampMs((_d = (_c = row[USER_PRESENCE_LAST_ACTIVE_COLUMN]) != null ? _c : row.last_active_at) != null ? _d : row.updated_at);
23009
+ return { status, source, lastActiveAtMs };
23010
+ };
22817
23011
  var normalizeHandle2 = (value) => {
22818
23012
  if (!value) return void 0;
22819
23013
  return value.startsWith("@") ? value.slice(1) : value;
@@ -22843,12 +23037,12 @@ var resolveCurrentUserId = (user) => {
22843
23037
  return null;
22844
23038
  };
22845
23039
  var resolveUserIdFromClaims = (claims) => {
22846
- var _a74, _b7, _c, _d, _e;
22847
- 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"]);
23040
+ var _a78, _b7, _c, _d, _e;
23041
+ 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"]);
22848
23042
  };
22849
23043
  var resolveEmailFromClaims = (claims) => {
22850
- var _a74, _b7;
22851
- const candidate = (_b7 = (_a74 = toStringOrUndefined(claims.email)) != null ? _a74 : toStringOrUndefined(claims["https://cupcode.com/email"])) != null ? _b7 : toStringOrUndefined(claims.preferred_username);
23044
+ var _a78, _b7;
23045
+ const candidate = (_b7 = (_a78 = toStringOrUndefined(claims.email)) != null ? _a78 : toStringOrUndefined(claims["https://cupcode.com/email"])) != null ? _b7 : toStringOrUndefined(claims.preferred_username);
22852
23046
  if (!candidate || !candidate.includes("@")) return void 0;
22853
23047
  return candidate.toLowerCase();
22854
23048
  };
@@ -22913,8 +23107,8 @@ var parseRecentActivityItems = (payload) => {
22913
23107
  return [];
22914
23108
  };
22915
23109
  return toRows(payload).map((item, index) => {
22916
- var _a74, _b7, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
22917
- const id = (_b7 = (_a74 = toStringOrUndefined(item.id)) != null ? _a74 : toStringOrUndefined(item.event_id)) != null ? _b7 : `accounts-activity-${index}`;
23110
+ var _a78, _b7, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
23111
+ const id = (_b7 = (_a78 = toStringOrUndefined(item.id)) != null ? _a78 : toStringOrUndefined(item.event_id)) != null ? _b7 : `accounts-activity-${index}`;
22918
23112
  const title = (_e = (_d = (_c = toStringOrUndefined(item.title)) != null ? _c : toStringOrUndefined(item.action)) != null ? _d : toStringOrUndefined(item.event)) != null ? _e : toStringOrUndefined(item.type);
22919
23113
  if (!title) return null;
22920
23114
  const description = (_h = (_g = (_f = toStringOrUndefined(item.description)) != null ? _f : toStringOrUndefined(item.details)) != null ? _g : toStringOrUndefined(item.message)) != null ? _h : toStringOrUndefined(item.summary);
@@ -22997,9 +23191,9 @@ var dedupeAndSortReactions = (reactions) => {
22997
23191
  });
22998
23192
  };
22999
23193
  var getErrorText = (error) => {
23000
- var _a74, _b7, _c;
23194
+ var _a78, _b7, _c;
23001
23195
  const typed = error;
23002
- 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();
23196
+ 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();
23003
23197
  };
23004
23198
  var isMissingColumnError = (error, column) => {
23005
23199
  const normalized = getErrorText(error);
@@ -23025,8 +23219,8 @@ var isRecoverableLookupError = (error, relationName) => {
23025
23219
  return normalized.includes("schema cache") || normalized.includes("permission denied") || normalized.includes("does not exist") || normalized.includes("could not find");
23026
23220
  };
23027
23221
  var toChatMessage = (row, currentUserId) => {
23028
- var _a74, _b7, _c, _d, _e, _f;
23029
- 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])}`;
23222
+ var _a78, _b7, _c, _d, _e, _f;
23223
+ 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])}`;
23030
23224
  const senderId = toStringOrUndefined(row[CHAT_MESSAGES_SENDER_COLUMN]);
23031
23225
  const recipientId = toStringOrUndefined(row[CHAT_MESSAGES_RECIPIENT_COLUMN]);
23032
23226
  const text = toStringOrUndefined(row[CHAT_MESSAGES_TEXT_COLUMN]);
@@ -23066,12 +23260,12 @@ var toChatReaction = (row) => {
23066
23260
  return { id, messageId, userId, emoji, createdAt };
23067
23261
  };
23068
23262
  var toChatMessageLog = (row, messagesById) => {
23069
- var _a74, _b7;
23263
+ var _a78, _b7;
23070
23264
  const id = toStringOrUndefined(row[CHAT_LOGS_ID_COLUMN]);
23071
23265
  const messageId = toStringOrUndefined(row[CHAT_LOGS_MESSAGE_ID_COLUMN]);
23072
23266
  const actorId = toStringOrUndefined(row[CHAT_LOGS_ACTOR_ID_COLUMN]);
23073
23267
  const action = toStringOrUndefined(row[CHAT_LOGS_ACTION_COLUMN]);
23074
- const previousText = (_a74 = toStringOrUndefined(row[CHAT_LOGS_PREVIOUS_TEXT_COLUMN])) != null ? _a74 : null;
23268
+ const previousText = (_a78 = toStringOrUndefined(row[CHAT_LOGS_PREVIOUS_TEXT_COLUMN])) != null ? _a78 : null;
23075
23269
  const nextText = (_b7 = toStringOrUndefined(row[CHAT_LOGS_NEXT_TEXT_COLUMN])) != null ? _b7 : null;
23076
23270
  const createdAt = toStringOrUndefined(row[CHAT_LOGS_CREATED_AT_COLUMN]);
23077
23271
  if (!id || !messageId || !action || action !== "edit" && action !== "delete") return null;
@@ -23114,7 +23308,7 @@ var MainNavbar = ({
23114
23308
  getAccessToken,
23115
23309
  appVersion
23116
23310
  }) => {
23117
- var _a74, _b7, _c;
23311
+ var _a78, _b7, _c;
23118
23312
  const [chatUsers, setChatUsers] = useState13([]);
23119
23313
  const [chatMessages, setChatMessages] = useState13([]);
23120
23314
  const [chatMessageLogs, setChatMessageLogs] = useState13([]);
@@ -23131,6 +23325,7 @@ var MainNavbar = ({
23131
23325
  const [isAccountsActivityLoading, setIsAccountsActivityLoading] = useState13(false);
23132
23326
  const chatMessagesRef = useRef12([]);
23133
23327
  const chatFeatureFlagsRef = useRef12(readStoredChatFeatureFlags());
23328
+ const presenceSnapshotsRef = useRef12(/* @__PURE__ */ new Map());
23134
23329
  const updateChatFeatureFlags = useCallback6((partial) => {
23135
23330
  const nextFlags = {
23136
23331
  ...chatFeatureFlagsRef.current,
@@ -23145,19 +23340,19 @@ var MainNavbar = ({
23145
23340
  return "/";
23146
23341
  }, [pathname]);
23147
23342
  const currentUserId = useMemo9(() => {
23148
- var _a75;
23149
- return (_a75 = resolveCurrentUserId(authUser)) != null ? _a75 : tokenDerivedUserId;
23343
+ var _a79;
23344
+ return (_a79 = resolveCurrentUserId(authUser)) != null ? _a79 : tokenDerivedUserId;
23150
23345
  }, [authUser, tokenDerivedUserId]);
23151
23346
  const authEmail = useMemo9(
23152
23347
  () => {
23153
- var _a75, _b8;
23154
- return (_b8 = (_a75 = toStringOrUndefined(authUser == null ? void 0 : authUser.email)) == null ? void 0 : _a75.toLowerCase()) != null ? _b8 : tokenDerivedEmail;
23348
+ var _a79, _b8;
23349
+ return (_b8 = (_a79 = toStringOrUndefined(authUser == null ? void 0 : authUser.email)) == null ? void 0 : _a79.toLowerCase()) != null ? _b8 : tokenDerivedEmail;
23155
23350
  },
23156
23351
  [authUser == null ? void 0 : authUser.email, tokenDerivedEmail]
23157
23352
  );
23158
23353
  const isChatSuperAdmin = useMemo9(() => {
23159
- var _a75, _b8;
23160
- const roleTokens = `${(_a75 = authUser == null ? void 0 : authUser.role) != null ? _a75 : ""} ${(_b8 = authUser == null ? void 0 : authUser.jobTitle) != null ? _b8 : ""}`.toLowerCase();
23354
+ var _a79, _b8;
23355
+ const roleTokens = `${(_a79 = authUser == null ? void 0 : authUser.role) != null ? _a79 : ""} ${(_b8 = authUser == null ? void 0 : authUser.jobTitle) != null ? _b8 : ""}`.toLowerCase();
23161
23356
  return roleTokens.includes("superadmin") || roleTokens.includes("super admin");
23162
23357
  }, [authUser == null ? void 0 : authUser.jobTitle, authUser == null ? void 0 : authUser.role]);
23163
23358
  const resolvedTelescupBaseUrl = useMemo9(() => {
@@ -23166,7 +23361,7 @@ var MainNavbar = ({
23166
23361
  }
23167
23362
  return TELESCUP_BASE_URL_FALLBACK;
23168
23363
  }, []);
23169
- const resolvedProfileAvatarUrl = (_b7 = (_a74 = resolveChatAvatarUrl(persistedProfileAvatarValue)) != null ? _a74 : authUser == null ? void 0 : authUser.picture) != null ? _b7 : void 0;
23364
+ const resolvedProfileAvatarUrl = (_b7 = (_a78 = resolveChatAvatarUrl(persistedProfileAvatarValue)) != null ? _a78 : authUser == null ? void 0 : authUser.picture) != null ? _b7 : void 0;
23170
23365
  const effectiveCurrentUserId = resolvedSenderId != null ? resolvedSenderId : currentUserId;
23171
23366
  const hasStoredAccessToken = (() => {
23172
23367
  if (typeof window === "undefined") return false;
@@ -23204,7 +23399,7 @@ var MainNavbar = ({
23204
23399
  }
23205
23400
  let canceled = false;
23206
23401
  const resolveIdentityFromToken = async () => {
23207
- var _a75, _b8;
23402
+ var _a79, _b8;
23208
23403
  try {
23209
23404
  let token = null;
23210
23405
  if (typeof window !== "undefined") {
@@ -23224,7 +23419,7 @@ var MainNavbar = ({
23224
23419
  }
23225
23420
  return;
23226
23421
  }
23227
- const claims = (_a75 = decodeJwt(token)) != null ? _a75 : {};
23422
+ const claims = (_a79 = decodeJwt(token)) != null ? _a79 : {};
23228
23423
  if (canceled) return;
23229
23424
  setTokenDerivedUserId((_b8 = resolveUserIdFromClaims(claims)) != null ? _b8 : null);
23230
23425
  setTokenDerivedEmail(resolveEmailFromClaims(claims));
@@ -23269,7 +23464,7 @@ var MainNavbar = ({
23269
23464
  );
23270
23465
  const warnings = [];
23271
23466
  const runLookup = async (kind, value, columns) => {
23272
- var _a75, _b8, _c2;
23467
+ var _a79, _b8, _c2;
23273
23468
  for (const tableName of CHAT_USERS_LOOKUP_TABLES) {
23274
23469
  for (const columnName of columns) {
23275
23470
  if (!columnName) continue;
@@ -23278,7 +23473,7 @@ var MainNavbar = ({
23278
23473
  const lookupError = response.error;
23279
23474
  if (lookupError) {
23280
23475
  if (isRecoverableLookupError(lookupError, tableName)) {
23281
- warnings.push(`${tableName}.${columnName}: ${(_a75 = lookupError.message) != null ? _a75 : "falha de lookup"}`);
23476
+ warnings.push(`${tableName}.${columnName}: ${(_a79 = lookupError.message) != null ? _a79 : "falha de lookup"}`);
23282
23477
  continue;
23283
23478
  }
23284
23479
  warnings.push(`${tableName}.${columnName}: ${(_b8 = lookupError.message) != null ? _b8 : "falha de lookup"}`);
@@ -23330,7 +23525,7 @@ var MainNavbar = ({
23330
23525
  return sessionStorage.getItem(ACCESS_TOKEN_STORAGE_KEY);
23331
23526
  };
23332
23527
  const loadAccountsContext = async () => {
23333
- var _a75, _b8, _c2, _d, _e, _f, _g;
23528
+ var _a79, _b8, _c2, _d, _e, _f, _g;
23334
23529
  setIsAccountsActivityLoading(true);
23335
23530
  try {
23336
23531
  const token = await resolveAccountsToken();
@@ -23340,7 +23535,7 @@ var MainNavbar = ({
23340
23535
  }
23341
23536
  return;
23342
23537
  }
23343
- const claims = (_a75 = decodeJwt(token)) != null ? _a75 : {};
23538
+ const claims = (_a79 = decodeJwt(token)) != null ? _a79 : {};
23344
23539
  const languageFromToken = normalizeMenuLanguage(
23345
23540
  (_d = (_c2 = (_b8 = claims.locale) != null ? _b8 : claims.lang) != null ? _c2 : claims.language) != null ? _d : claims["https://cupcode.com/locale"]
23346
23541
  );
@@ -23399,6 +23594,7 @@ var MainNavbar = ({
23399
23594
  }, [chatMessages]);
23400
23595
  useEffect16(() => {
23401
23596
  if (!isAuthenticated) {
23597
+ presenceSnapshotsRef.current.clear();
23402
23598
  setChatUsers([]);
23403
23599
  setChatMessages([]);
23404
23600
  setChatMessageLogs([]);
@@ -23408,6 +23604,7 @@ var MainNavbar = ({
23408
23604
  return;
23409
23605
  }
23410
23606
  if (!effectiveCurrentUserId) {
23607
+ presenceSnapshotsRef.current.clear();
23411
23608
  setChatUsers([]);
23412
23609
  setChatMessages([]);
23413
23610
  setChatMessageLogs([]);
@@ -23418,6 +23615,7 @@ var MainNavbar = ({
23418
23615
  }
23419
23616
  const supabase = getSupabase();
23420
23617
  if (!supabase) {
23618
+ presenceSnapshotsRef.current.clear();
23421
23619
  setChatUsers([]);
23422
23620
  setChatMessages([]);
23423
23621
  setChatMessageLogs([]);
@@ -23428,11 +23626,11 @@ var MainNavbar = ({
23428
23626
  }
23429
23627
  let canceled = false;
23430
23628
  const loadChatData = async () => {
23431
- var _a75, _b8, _c2, _d, _e, _f, _g, _h, _i;
23629
+ var _a79, _b8, _c2, _d, _e, _f, _g, _h, _i;
23432
23630
  setIsChatLoading(true);
23433
23631
  setChatError(null);
23434
23632
  const fetchFirstAvailableTable = async (tableNames) => {
23435
- var _a76;
23633
+ var _a80;
23436
23634
  let lastError = null;
23437
23635
  for (const tableName of tableNames) {
23438
23636
  const response = await supabase.from(tableName).select("*");
@@ -23454,7 +23652,7 @@ var MainNavbar = ({
23454
23652
  }
23455
23653
  }
23456
23654
  return {
23457
- tableName: (_a76 = tableNames[0]) != null ? _a76 : null,
23655
+ tableName: (_a80 = tableNames[0]) != null ? _a80 : null,
23458
23656
  data: null,
23459
23657
  error: lastError
23460
23658
  };
@@ -23505,7 +23703,16 @@ var MainNavbar = ({
23505
23703
  ]);
23506
23704
  };
23507
23705
  const [presenceResponse, usersResponse, profilesResponse] = await Promise.all([
23508
- supabase.from(USER_PRESENCE_TABLE).select(`${USER_PRESENCE_USER_ID_COLUMN},${USER_PRESENCE_STATUS_COLUMN}`),
23706
+ supabase.from(USER_PRESENCE_TABLE).select(
23707
+ Array.from(
23708
+ /* @__PURE__ */ new Set([
23709
+ USER_PRESENCE_USER_ID_COLUMN,
23710
+ USER_PRESENCE_STATUS_COLUMN,
23711
+ USER_PRESENCE_SOURCE_COLUMN,
23712
+ USER_PRESENCE_LAST_ACTIVE_COLUMN
23713
+ ])
23714
+ ).join(",")
23715
+ ),
23509
23716
  fetchFirstAvailableTable(CHAT_USERS_LOOKUP_TABLES),
23510
23717
  fetchFirstAvailableTable(profileLookupTables)
23511
23718
  ]);
@@ -23551,18 +23758,26 @@ var MainNavbar = ({
23551
23758
  }
23552
23759
  if (canceled) return;
23553
23760
  const presenceMap = /* @__PURE__ */ new Map();
23761
+ const presenceStatusLabelMap = /* @__PURE__ */ new Map();
23762
+ const presenceSnapshots = /* @__PURE__ */ new Map();
23763
+ const now = Date.now();
23554
23764
  if (presenceResponse.error) {
23555
23765
  if (isRuntimeDev()) {
23556
23766
  console.warn("[chat] Falha ao carregar presen\xE7a:", presenceResponse.error.message);
23557
23767
  }
23558
23768
  } else {
23559
- (_a75 = presenceResponse.data) == null ? void 0 : _a75.forEach((row) => {
23769
+ (_a79 = presenceResponse.data) == null ? void 0 : _a79.forEach((row) => {
23560
23770
  const userId = readFirstRecordString(row, [USER_PRESENCE_USER_ID_COLUMN, "user_id", "id"]);
23561
23771
  if (!userId) return;
23562
- const statusValue = readFirstRecordString(row, [USER_PRESENCE_STATUS_COLUMN, "status", "presence_status"]);
23563
- presenceMap.set(userId, normalizePresenceStatus(statusValue));
23772
+ const snapshot = readPresenceSnapshotFromRecord(row);
23773
+ if (!snapshot) return;
23774
+ presenceSnapshots.set(userId, snapshot);
23775
+ const effectiveStatus = resolveEffectivePresenceStatus(snapshot, now);
23776
+ presenceMap.set(userId, effectiveStatus);
23777
+ presenceStatusLabelMap.set(userId, resolvePresenceStatusLabel(snapshot, effectiveStatus, now));
23564
23778
  });
23565
23779
  }
23780
+ presenceSnapshotsRef.current = presenceSnapshots;
23566
23781
  const profileById = /* @__PURE__ */ new Map();
23567
23782
  const profileByEmail = /* @__PURE__ */ new Map();
23568
23783
  if (profilesResponse.error) {
@@ -23598,11 +23813,11 @@ var MainNavbar = ({
23598
23813
  }
23599
23814
  } else {
23600
23815
  (_e = usersResponse.data) == null ? void 0 : _e.forEach((row) => {
23601
- var _a76, _b9, _c3, _d2, _e2, _f2, _g2, _h2;
23816
+ var _a80, _b9, _c3, _d2, _e2, _f2, _g2, _h2, _i2;
23602
23817
  const id = readFirstRecordString(row, [...CHAT_USERS_LOOKUP_ID_COLUMNS, "id", "user_id"]);
23603
23818
  if (!id || id === effectiveCurrentUserId) return;
23604
23819
  const rowEmail = readFirstRecordString(row, [...CHAT_USERS_LOOKUP_EMAIL_COLUMNS, "email"]);
23605
- const profile = (_a76 = profileById.get(id)) != null ? _a76 : rowEmail ? profileByEmail.get(rowEmail.toLowerCase()) : void 0;
23820
+ const profile = (_a80 = profileById.get(id)) != null ? _a80 : rowEmail ? profileByEmail.get(rowEmail.toLowerCase()) : void 0;
23606
23821
  const email = rowEmail != null ? rowEmail : readFirstRecordString(profile, [CHAT_USERS_UPDATE_EMAIL_COLUMN, CHAT_USERS_EMAIL_COLUMN, "email"]);
23607
23822
  const rawUsername = (_b9 = readFirstRecordString(row, [CHAT_USERS_USERNAME_COLUMN, "username", "user_name"])) != null ? _b9 : readFirstRecordString(profile, [CHAT_USERS_USERNAME_COLUMN, "username", "user_name"]);
23608
23823
  const username = buildHandle2(rawUsername, email);
@@ -23610,6 +23825,7 @@ var MainNavbar = ({
23610
23825
  const name = resolveReadableUserLabel(rawName, rawUsername, email, id);
23611
23826
  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"]);
23612
23827
  const roleLabel = (_e2 = readFirstRecordString(row, [CHAT_USERS_ROLE_COLUMN, "job_title", "role"])) != null ? _e2 : readFirstRecordString(profile, [CHAT_USERS_ROLE_COLUMN, "job_title", "role"]);
23828
+ const resolvedStatus = (_h2 = (_g2 = (_f2 = presenceMap.get(id)) != null ? _f2 : readPresenceStatusFromRecord(profile)) != null ? _g2 : readPresenceStatusFromRecord(row)) != null ? _h2 : "offline";
23613
23829
  usersMap.set(id, {
23614
23830
  id,
23615
23831
  name,
@@ -23617,12 +23833,13 @@ var MainNavbar = ({
23617
23833
  email,
23618
23834
  avatarUrl: resolveChatAvatarUrl(avatarValue),
23619
23835
  roleLabel,
23620
- status: (_h2 = (_g2 = (_f2 = presenceMap.get(id)) != null ? _f2 : readPresenceStatusFromRecord(profile)) != null ? _g2 : readPresenceStatusFromRecord(row)) != null ? _h2 : "offline"
23836
+ status: resolvedStatus,
23837
+ statusLabel: (_i2 = presenceStatusLabelMap.get(id)) != null ? _i2 : PRESENCE_STATUS_LABELS[resolvedStatus]
23621
23838
  });
23622
23839
  });
23623
23840
  }
23624
23841
  profileById.forEach((profile, id) => {
23625
- var _a76, _b9;
23842
+ var _a80, _b9, _c3;
23626
23843
  if (!id || id === effectiveCurrentUserId || usersMap.has(id)) return;
23627
23844
  const email = readFirstRecordString(profile, [CHAT_USERS_UPDATE_EMAIL_COLUMN, CHAT_USERS_EMAIL_COLUMN, "email"]);
23628
23845
  const rawUsername = readFirstRecordString(profile, [CHAT_USERS_USERNAME_COLUMN, "username", "user_name"]);
@@ -23636,6 +23853,7 @@ var MainNavbar = ({
23636
23853
  "avatar"
23637
23854
  ]);
23638
23855
  const roleLabel = readFirstRecordString(profile, [CHAT_USERS_ROLE_COLUMN, "job_title", "role"]);
23856
+ const resolvedStatus = (_b9 = (_a80 = presenceMap.get(id)) != null ? _a80 : readPresenceStatusFromRecord(profile)) != null ? _b9 : "offline";
23639
23857
  usersMap.set(id, {
23640
23858
  id,
23641
23859
  name: resolveReadableUserLabel(rawName, rawUsername, email, id),
@@ -23643,10 +23861,12 @@ var MainNavbar = ({
23643
23861
  email,
23644
23862
  avatarUrl: resolveChatAvatarUrl(avatarValue),
23645
23863
  roleLabel,
23646
- status: (_b9 = (_a76 = presenceMap.get(id)) != null ? _a76 : readPresenceStatusFromRecord(profile)) != null ? _b9 : "offline"
23864
+ status: resolvedStatus,
23865
+ statusLabel: (_c3 = presenceStatusLabelMap.get(id)) != null ? _c3 : PRESENCE_STATUS_LABELS[resolvedStatus]
23647
23866
  });
23648
23867
  });
23649
23868
  presenceMap.forEach((statusValue, id) => {
23869
+ var _a80;
23650
23870
  if (id === effectiveCurrentUserId || usersMap.has(id)) return;
23651
23871
  const profile = profileById.get(id);
23652
23872
  const email = readFirstRecordString(profile, [CHAT_USERS_UPDATE_EMAIL_COLUMN, CHAT_USERS_EMAIL_COLUMN, "email"]);
@@ -23668,7 +23888,8 @@ var MainNavbar = ({
23668
23888
  email,
23669
23889
  avatarUrl: resolveChatAvatarUrl(avatarValue),
23670
23890
  roleLabel,
23671
- status: statusValue
23891
+ status: statusValue,
23892
+ statusLabel: (_a80 = presenceStatusLabelMap.get(id)) != null ? _a80 : PRESENCE_STATUS_LABELS[statusValue]
23672
23893
  });
23673
23894
  });
23674
23895
  if (messageErrors.length > 0) {
@@ -23685,7 +23906,7 @@ var MainNavbar = ({
23685
23906
  );
23686
23907
  setChatMessages(resolvedMessages);
23687
23908
  resolvedMessages.forEach((message) => {
23688
- var _a76, _b9;
23909
+ var _a80, _b9, _c3;
23689
23910
  const contactId = message.contactId;
23690
23911
  if (!contactId || contactId === effectiveCurrentUserId || usersMap.has(contactId)) return;
23691
23912
  const profile = profileById.get(contactId);
@@ -23701,6 +23922,7 @@ var MainNavbar = ({
23701
23922
  "avatar"
23702
23923
  ]);
23703
23924
  const roleLabel = readFirstRecordString(profile, [CHAT_USERS_ROLE_COLUMN, "job_title", "role"]);
23925
+ const resolvedStatus = (_b9 = (_a80 = presenceMap.get(contactId)) != null ? _a80 : readPresenceStatusFromRecord(profile)) != null ? _b9 : "offline";
23704
23926
  usersMap.set(contactId, {
23705
23927
  id: contactId,
23706
23928
  name: resolveReadableUserLabel(rawName, rawUsername, email, contactId),
@@ -23708,7 +23930,8 @@ var MainNavbar = ({
23708
23930
  email,
23709
23931
  avatarUrl: resolveChatAvatarUrl(avatarValue),
23710
23932
  roleLabel,
23711
- status: (_b9 = (_a76 = presenceMap.get(contactId)) != null ? _a76 : readPresenceStatusFromRecord(profile)) != null ? _b9 : "offline"
23933
+ status: resolvedStatus,
23934
+ statusLabel: (_c3 = presenceStatusLabelMap.get(contactId)) != null ? _c3 : PRESENCE_STATUS_LABELS[resolvedStatus]
23712
23935
  });
23713
23936
  });
23714
23937
  const resolvedUsers = [...usersMap.values()].sort((left, right) => left.name.localeCompare(right.name, "pt-BR"));
@@ -23855,10 +24078,21 @@ var MainNavbar = ({
23855
24078
  table: USER_PRESENCE_TABLE
23856
24079
  },
23857
24080
  (payload) => {
24081
+ var _a79, _b8;
23858
24082
  const row = payload.new || payload.old;
23859
- const userId = toStringOrUndefined(row[USER_PRESENCE_USER_ID_COLUMN]);
24083
+ const userId = toStringOrUndefined((_b8 = (_a79 = row[USER_PRESENCE_USER_ID_COLUMN]) != null ? _a79 : row.user_id) != null ? _b8 : row.id);
23860
24084
  if (!userId || userId === effectiveCurrentUserId) return;
23861
- const nextStatus = payload.eventType === "DELETE" ? "offline" : normalizePresenceStatus(row[USER_PRESENCE_STATUS_COLUMN]);
24085
+ let nextStatus = "offline";
24086
+ let nextStatusLabel = PRESENCE_STATUS_LABELS.offline;
24087
+ if (payload.eventType === "DELETE") {
24088
+ presenceSnapshotsRef.current.delete(userId);
24089
+ } else {
24090
+ const snapshot = readPresenceSnapshotFromRecord(row);
24091
+ if (!snapshot) return;
24092
+ presenceSnapshotsRef.current.set(userId, snapshot);
24093
+ nextStatus = resolveEffectivePresenceStatus(snapshot);
24094
+ nextStatusLabel = resolvePresenceStatusLabel(snapshot, nextStatus);
24095
+ }
23862
24096
  setChatUsers((current) => {
23863
24097
  const index = current.findIndex((user) => user.id === userId);
23864
24098
  if (index === -1) {
@@ -23869,12 +24103,13 @@ var MainNavbar = ({
23869
24103
  id: userId,
23870
24104
  name: resolveReadableUserLabel(void 0, void 0, void 0, userId),
23871
24105
  username,
23872
- status: nextStatus
24106
+ status: nextStatus,
24107
+ statusLabel: nextStatusLabel
23873
24108
  }
23874
24109
  ].sort((left, right) => left.name.localeCompare(right.name, "pt-BR"));
23875
24110
  }
23876
24111
  const updated = [...current];
23877
- updated[index] = { ...updated[index], status: nextStatus };
24112
+ updated[index] = { ...updated[index], status: nextStatus, statusLabel: nextStatusLabel };
23878
24113
  return updated;
23879
24114
  });
23880
24115
  }
@@ -23890,13 +24125,39 @@ var MainNavbar = ({
23890
24125
  void supabase.removeChannel(presenceChannel);
23891
24126
  };
23892
24127
  }, [effectiveCurrentUserId, isAuthenticated, isChatSuperAdmin]);
24128
+ useEffect16(() => {
24129
+ if (!isAuthenticated) return;
24130
+ const intervalId = window.setInterval(() => {
24131
+ const now = Date.now();
24132
+ setChatUsers((current) => {
24133
+ let hasChanges = false;
24134
+ const nextUsers = current.map((entry) => {
24135
+ const snapshot = presenceSnapshotsRef.current.get(entry.id);
24136
+ if (!snapshot) return entry;
24137
+ const effectiveStatus = resolveEffectivePresenceStatus(snapshot, now);
24138
+ const effectiveStatusLabel = resolvePresenceStatusLabel(snapshot, effectiveStatus, now);
24139
+ if (entry.status === effectiveStatus && entry.statusLabel === effectiveStatusLabel) return entry;
24140
+ hasChanges = true;
24141
+ return {
24142
+ ...entry,
24143
+ status: effectiveStatus,
24144
+ statusLabel: effectiveStatusLabel
24145
+ };
24146
+ });
24147
+ return hasChanges ? nextUsers : current;
24148
+ });
24149
+ }, PRESENCE_RECALC_INTERVAL_MS);
24150
+ return () => {
24151
+ window.clearInterval(intervalId);
24152
+ };
24153
+ }, [isAuthenticated]);
23893
24154
  const chatUnreadByUser = useMemo9(() => {
23894
24155
  const counters = {};
23895
24156
  chatMessages.forEach((message) => {
23896
- var _a75;
24157
+ var _a79;
23897
24158
  if (message.sender !== "them") return;
23898
24159
  if (message.readAt) return;
23899
- counters[message.contactId] = ((_a75 = counters[message.contactId]) != null ? _a75 : 0) + 1;
24160
+ counters[message.contactId] = ((_a79 = counters[message.contactId]) != null ? _a79 : 0) + 1;
23900
24161
  });
23901
24162
  return counters;
23902
24163
  }, [chatMessages]);
@@ -23944,9 +24205,9 @@ var MainNavbar = ({
23944
24205
  }
23945
24206
  const persistedReadAtByMessageId = /* @__PURE__ */ new Map();
23946
24207
  (data != null ? data : []).forEach((row) => {
23947
- var _a75;
24208
+ var _a79;
23948
24209
  const messageId = toStringOrUndefined(row[CHAT_MESSAGES_ID_COLUMN]);
23949
- const persistedReadAt = (_a75 = toStringOrUndefined(row[CHAT_MESSAGES_READ_AT_COLUMN])) != null ? _a75 : readAt;
24210
+ const persistedReadAt = (_a79 = toStringOrUndefined(row[CHAT_MESSAGES_READ_AT_COLUMN])) != null ? _a79 : readAt;
23950
24211
  if (!messageId) return;
23951
24212
  persistedReadAtByMessageId.set(messageId, persistedReadAt);
23952
24213
  });
@@ -24115,8 +24376,8 @@ var MainNavbar = ({
24115
24376
  (current) => dedupeAndSortMessages(
24116
24377
  current.map(
24117
24378
  (message) => {
24118
- var _a75;
24119
- return message.id === messageId ? { ...message, text: previousText, editedAt: (_a75 = targetMessage.editedAt) != null ? _a75 : null } : message;
24379
+ var _a79;
24380
+ return message.id === messageId ? { ...message, text: previousText, editedAt: (_a79 = targetMessage.editedAt) != null ? _a79 : null } : message;
24120
24381
  }
24121
24382
  )
24122
24383
  )
@@ -24147,13 +24408,13 @@ var MainNavbar = ({
24147
24408
  (current) => dedupeAndSortMessages(
24148
24409
  current.map(
24149
24410
  (message) => {
24150
- var _a75;
24411
+ var _a79;
24151
24412
  return message.id === messageId ? {
24152
24413
  ...message,
24153
24414
  text: CHAT_DELETED_PLACEHOLDER_TEXT2,
24154
24415
  deletedAt,
24155
24416
  deletedBy: effectiveCurrentUserId,
24156
- editedAt: (_a75 = message.editedAt) != null ? _a75 : deletedAt
24417
+ editedAt: (_a79 = message.editedAt) != null ? _a79 : deletedAt
24157
24418
  } : message;
24158
24419
  }
24159
24420
  )
@@ -24337,8 +24598,8 @@ var MainNavbar = ({
24337
24598
  ...item,
24338
24599
  isActive,
24339
24600
  onClick: isAnchor ? item.onClick : (event) => {
24340
- var _a75;
24341
- (_a75 = item.onClick) == null ? void 0 : _a75.call(item, event);
24601
+ var _a79;
24602
+ (_a79 = item.onClick) == null ? void 0 : _a79.call(item, event);
24342
24603
  if (!onNavigate || event.defaultPrevented) return;
24343
24604
  event.preventDefault();
24344
24605
  onNavigate(item.href);
@@ -24380,9 +24641,9 @@ var MainNavbar = ({
24380
24641
  window.open(`${MC_BASE_URL2}/tasks`, "_blank", "noopener,noreferrer");
24381
24642
  };
24382
24643
  const handleChatOpenUserProfile = useCallback6(({ userId }) => {
24383
- var _a75;
24644
+ var _a79;
24384
24645
  if (!userId || typeof window === "undefined") return;
24385
- const baseUrl = ((_a75 = getRuntimeEnv("VITE_ACCOUNTS_BASE_URL")) != null ? _a75 : "https://accounts.cupcode.com.br").replace(
24646
+ const baseUrl = ((_a79 = getRuntimeEnv("VITE_ACCOUNTS_BASE_URL")) != null ? _a79 : "https://accounts.cupcode.com.br").replace(
24386
24647
  /\/+$/,
24387
24648
  ""
24388
24649
  );
@@ -24452,8 +24713,8 @@ var MainNavbar = ({
24452
24713
  );
24453
24714
  const handleProfileAvatarChange = useCallback6(
24454
24715
  async ({ avatarId, avatarUrl }) => {
24455
- var _a75;
24456
- const normalizedAvatarId = (_a75 = parseAssetId(avatarId)) != null ? _a75 : parseAssetId(avatarUrl);
24716
+ var _a79;
24717
+ const normalizedAvatarId = (_a79 = parseAssetId(avatarId)) != null ? _a79 : parseAssetId(avatarUrl);
24457
24718
  if (!normalizedAvatarId) {
24458
24719
  throw new Error("ID da imagem inv\xE1lido.");
24459
24720
  }
@@ -24469,27 +24730,27 @@ var MainNavbar = ({
24469
24730
  );
24470
24731
  const updateErrors = [];
24471
24732
  const isRecoverableUpdateError = (error) => {
24472
- var _a76;
24473
- const message = ((_a76 = error.message) != null ? _a76 : "").toLowerCase();
24733
+ var _a80;
24734
+ const message = ((_a80 = error.message) != null ? _a80 : "").toLowerCase();
24474
24735
  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");
24475
24736
  };
24476
24737
  const isRecoverableLookupError2 = (error) => {
24477
- var _a76;
24478
- const message = ((_a76 = error.message) != null ? _a76 : "").toLowerCase();
24738
+ var _a80;
24739
+ const message = ((_a80 = error.message) != null ? _a80 : "").toLowerCase();
24479
24740
  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");
24480
24741
  };
24481
24742
  const isPermissionDeniedError2 = (error) => {
24482
- var _a76;
24483
- const message = ((_a76 = error.message) != null ? _a76 : "").toLowerCase();
24743
+ var _a80;
24744
+ const message = ((_a80 = error.message) != null ? _a80 : "").toLowerCase();
24484
24745
  return error.code === "42501" || message.includes("permission denied");
24485
24746
  };
24486
24747
  const updateAvatarByUserId = async (userId) => {
24487
- var _a76, _b8, _c2, _d, _e;
24748
+ var _a80, _b8, _c2, _d, _e;
24488
24749
  for (const tableName of updateTargets) {
24489
24750
  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);
24490
24751
  if (!updateWithSelect.error) {
24491
24752
  const rows = updateWithSelect.data;
24492
- const row = (_a76 = rows == null ? void 0 : rows[0]) != null ? _a76 : null;
24753
+ const row = (_a80 = rows == null ? void 0 : rows[0]) != null ? _a80 : null;
24493
24754
  if (row) {
24494
24755
  return row;
24495
24756
  }
@@ -24521,13 +24782,13 @@ var MainNavbar = ({
24521
24782
  return null;
24522
24783
  };
24523
24784
  const resolveUserIdByEmail = async (emailValue) => {
24524
- var _a76;
24785
+ var _a80;
24525
24786
  let lastRecoverableError = null;
24526
24787
  for (const tableName of lookupTargets) {
24527
24788
  const { data, error } = await supabase.from(tableName).select(CHAT_USERS_UPDATE_ID_COLUMN).ilike(CHAT_USERS_UPDATE_EMAIL_COLUMN, emailValue).limit(1);
24528
24789
  if (!error) {
24529
24790
  const rows = data;
24530
- const resolvedId = toStringOrUndefined((_a76 = rows == null ? void 0 : rows[0]) == null ? void 0 : _a76[CHAT_USERS_UPDATE_ID_COLUMN]);
24791
+ const resolvedId = toStringOrUndefined((_a80 = rows == null ? void 0 : rows[0]) == null ? void 0 : _a80[CHAT_USERS_UPDATE_ID_COLUMN]);
24531
24792
  if (resolvedId) {
24532
24793
  return resolvedId;
24533
24794
  }
@@ -25149,10 +25410,10 @@ function isThemeMode(value) {
25149
25410
  return value === "light" || value === "dark";
25150
25411
  }
25151
25412
  function readStoredTheme() {
25152
- var _a74;
25413
+ var _a78;
25153
25414
  if (typeof window === "undefined") return null;
25154
25415
  try {
25155
- const storedTheme = (_a74 = window.localStorage.getItem(THEME_STORAGE_KEY2)) != null ? _a74 : window.localStorage.getItem("theme");
25416
+ const storedTheme = (_a78 = window.localStorage.getItem(THEME_STORAGE_KEY2)) != null ? _a78 : window.localStorage.getItem("theme");
25156
25417
  return isThemeMode(storedTheme) ? storedTheme : null;
25157
25418
  } catch (e) {
25158
25419
  return null;
@@ -25189,11 +25450,11 @@ var ThemeToggle = ({
25189
25450
  defaultTheme = "light",
25190
25451
  onThemeChange
25191
25452
  }) => {
25192
- var _a74;
25453
+ var _a78;
25193
25454
  const [mounted, setMounted] = React34.useState(false);
25194
25455
  const [internalTheme, setInternalTheme] = React34.useState(defaultTheme);
25195
25456
  const isControlled = typeof theme !== "undefined";
25196
- const activeTheme = (_a74 = isControlled ? theme : internalTheme) != null ? _a74 : defaultTheme;
25457
+ const activeTheme = (_a78 = isControlled ? theme : internalTheme) != null ? _a78 : defaultTheme;
25197
25458
  React34.useEffect(() => {
25198
25459
  if (!isControlled) {
25199
25460
  setInternalTheme(resolveTheme(defaultTheme));
@@ -25831,8 +26092,8 @@ var ChartStyle = ({ id, config }) => {
25831
26092
  ([theme, prefix]) => `
25832
26093
  ${prefix} [data-chart=${id}] {
25833
26094
  ${colorConfig.map(([key, itemConfig]) => {
25834
- var _a74;
25835
- const color = ((_a74 = itemConfig.theme) == null ? void 0 : _a74[theme]) || itemConfig.color;
26095
+ var _a78;
26096
+ const color = ((_a78 = itemConfig.theme) == null ? void 0 : _a78[theme]) || itemConfig.color;
25836
26097
  return color ? ` --color-${key}: ${color};` : null;
25837
26098
  }).join("\n")}
25838
26099
  }
@@ -25861,14 +26122,14 @@ var ChartTooltipContent = React41.forwardRef(
25861
26122
  }, ref) => {
25862
26123
  const { config } = useChart();
25863
26124
  const tooltipLabel = React41.useMemo(() => {
25864
- var _a74;
26125
+ var _a78;
25865
26126
  if (hideLabel || !(payload == null ? void 0 : payload.length)) {
25866
26127
  return null;
25867
26128
  }
25868
26129
  const [item] = payload;
25869
26130
  const key = `${labelKey || item.dataKey || item.name || "value"}`;
25870
26131
  const itemConfig = getPayloadConfigFromPayload(config, item, key);
25871
- const value = !labelKey && typeof label === "string" ? ((_a74 = config[label]) == null ? void 0 : _a74.label) || label : itemConfig == null ? void 0 : itemConfig.label;
26132
+ const value = !labelKey && typeof label === "string" ? ((_a78 = config[label]) == null ? void 0 : _a78.label) || label : itemConfig == null ? void 0 : itemConfig.label;
25872
26133
  if (labelFormatter) {
25873
26134
  return /* @__PURE__ */ jsx64("div", { className: cn("font-medium", labelClassName), children: labelFormatter(value, payload) });
25874
26135
  }
@@ -27553,8 +27814,8 @@ ToggleGroupItem.displayName = ToggleGroupPrimitive.Item.displayName;
27553
27814
  // src/hooks/useActiveSection.ts
27554
27815
  import { useEffect as useEffect23, useState as useState18 } from "react";
27555
27816
  var useActiveSection = (sectionIds, offset = 180) => {
27556
- var _a74;
27557
- const [activeId, setActiveId] = useState18((_a74 = sectionIds[0]) != null ? _a74 : "");
27817
+ var _a78;
27818
+ const [activeId, setActiveId] = useState18((_a78 = sectionIds[0]) != null ? _a78 : "");
27558
27819
  useEffect23(() => {
27559
27820
  if (!sectionIds.length || typeof window === "undefined") return;
27560
27821
  const update = () => {
@@ -27599,29 +27860,40 @@ var STORAGE_KEYS = {
27599
27860
  presenceSource: "cc_user_presence_source"
27600
27861
  };
27601
27862
  var LOCAL_STORAGE_KEYS = {
27602
- lastActivityAt: "cc_last_activity_at",
27603
27863
  presenceSource: "cc_user_presence_source"
27604
27864
  };
27605
- var _a64;
27606
- var USER_PRESENCE_TABLE2 = ((_a64 = getRuntimeEnv("VITE_USER_PRESENCE_TABLE")) != null ? _a64 : "user_presence").trim();
27607
- var _a65;
27608
- var USER_PRESENCE_USER_ID_COLUMN2 = ((_a65 = getRuntimeEnv("VITE_USER_PRESENCE_USER_ID_COLUMN")) != null ? _a65 : "user_id").trim();
27609
27865
  var _a66;
27610
- var USER_PRESENCE_STATUS_COLUMN2 = ((_a66 = getRuntimeEnv("VITE_USER_PRESENCE_STATUS_COLUMN")) != null ? _a66 : "status").trim();
27611
- var _a67, _b6;
27612
- var SUPABASE_CHAT_SCHEMA = ((_b6 = (_a67 = getRuntimeEnv("VITE_CHAT_SCHEMA")) != null ? _a67 : getRuntimeEnv("VITE_SUPABASE_SCHEMA")) != null ? _b6 : "public").trim();
27866
+ var USER_PRESENCE_TABLE2 = ((_a66 = getRuntimeEnv("VITE_USER_PRESENCE_TABLE")) != null ? _a66 : "user_presence").trim();
27867
+ var _a67;
27868
+ var USER_PRESENCE_USER_ID_COLUMN2 = ((_a67 = getRuntimeEnv("VITE_USER_PRESENCE_USER_ID_COLUMN")) != null ? _a67 : "user_id").trim();
27613
27869
  var _a68;
27614
- var CHAT_USERS_TABLE2 = ((_a68 = getRuntimeEnv("VITE_CHAT_USERS_TABLE")) != null ? _a68 : "chat_users").trim();
27870
+ var USER_PRESENCE_STATUS_COLUMN2 = ((_a68 = getRuntimeEnv("VITE_USER_PRESENCE_STATUS_COLUMN")) != null ? _a68 : "status").trim();
27615
27871
  var _a69;
27616
- var CHAT_USERS_ID_COLUMN2 = ((_a69 = getRuntimeEnv("VITE_CHAT_USERS_ID_COLUMN")) != null ? _a69 : "id").trim();
27872
+ var USER_PRESENCE_SOURCE_COLUMN2 = ((_a69 = getRuntimeEnv("VITE_USER_PRESENCE_SOURCE_COLUMN")) != null ? _a69 : "status_source").trim();
27617
27873
  var _a70;
27618
- var CHAT_USERS_EMAIL_COLUMN2 = ((_a70 = getRuntimeEnv("VITE_CHAT_USERS_EMAIL_COLUMN")) != null ? _a70 : "email").trim();
27619
- var _a71;
27620
- var CHAT_USERS_UPDATE_TABLE2 = ((_a71 = getRuntimeEnv("VITE_CHAT_USERS_UPDATE_TABLE")) != null ? _a71 : "profiles").trim();
27874
+ var USER_PRESENCE_LAST_ACTIVE_COLUMN2 = ((_a70 = getRuntimeEnv("VITE_USER_PRESENCE_LAST_ACTIVE_COLUMN")) != null ? _a70 : "last_active_at").trim();
27875
+ var _a71, _b6;
27876
+ var SUPABASE_CHAT_SCHEMA = ((_b6 = (_a71 = getRuntimeEnv("VITE_CHAT_SCHEMA")) != null ? _a71 : getRuntimeEnv("VITE_SUPABASE_SCHEMA")) != null ? _b6 : "public").trim();
27877
+ var PRESENCE_TOUCH_RPC = "cc_presence_touch";
27878
+ var PRESENCE_MARK_IDLE_RPC = "cc_presence_mark_idle";
27879
+ var PRESENCE_SET_STATUS_RPC = "cc_presence_set_status";
27880
+ var parsePositiveInteger2 = (rawValue, fallback) => {
27881
+ const parsed = Number(rawValue);
27882
+ if (!Number.isFinite(parsed) || parsed <= 0) return fallback;
27883
+ return Math.floor(parsed);
27884
+ };
27621
27885
  var _a72;
27622
- var CHAT_USERS_UPDATE_ID_COLUMN2 = ((_a72 = getRuntimeEnv("VITE_CHAT_USERS_UPDATE_ID_COLUMN")) != null ? _a72 : "id").trim();
27886
+ var CHAT_USERS_TABLE2 = ((_a72 = getRuntimeEnv("VITE_CHAT_USERS_TABLE")) != null ? _a72 : "chat_users").trim();
27623
27887
  var _a73;
27624
- var CHAT_USERS_UPDATE_EMAIL_COLUMN2 = ((_a73 = getRuntimeEnv("VITE_CHAT_USERS_UPDATE_EMAIL_COLUMN")) != null ? _a73 : "email").trim();
27888
+ var CHAT_USERS_ID_COLUMN2 = ((_a73 = getRuntimeEnv("VITE_CHAT_USERS_ID_COLUMN")) != null ? _a73 : "id").trim();
27889
+ var _a74;
27890
+ var CHAT_USERS_EMAIL_COLUMN2 = ((_a74 = getRuntimeEnv("VITE_CHAT_USERS_EMAIL_COLUMN")) != null ? _a74 : "email").trim();
27891
+ var _a75;
27892
+ var CHAT_USERS_UPDATE_TABLE2 = ((_a75 = getRuntimeEnv("VITE_CHAT_USERS_UPDATE_TABLE")) != null ? _a75 : "profiles").trim();
27893
+ var _a76;
27894
+ var CHAT_USERS_UPDATE_ID_COLUMN2 = ((_a76 = getRuntimeEnv("VITE_CHAT_USERS_UPDATE_ID_COLUMN")) != null ? _a76 : "id").trim();
27895
+ var _a77;
27896
+ var CHAT_USERS_UPDATE_EMAIL_COLUMN2 = ((_a77 = getRuntimeEnv("VITE_CHAT_USERS_UPDATE_EMAIL_COLUMN")) != null ? _a77 : "email").trim();
27625
27897
  var PRESENCE_USER_LOOKUP_TABLES = Array.from(
27626
27898
  new Set(
27627
27899
  [CHAT_USERS_UPDATE_TABLE2, CHAT_USERS_TABLE2, "profiles", "chat_users"].map((entry) => entry.trim()).filter((entry) => entry.length > 0)
@@ -27637,8 +27909,19 @@ var PRESENCE_USER_LOOKUP_EMAIL_COLUMNS = Array.from(
27637
27909
  [CHAT_USERS_UPDATE_EMAIL_COLUMN2, CHAT_USERS_EMAIL_COLUMN2, "email"].map((entry) => entry.trim()).filter((entry) => entry.length > 0)
27638
27910
  )
27639
27911
  );
27640
- var AWAY_AFTER_MS = 10 * 60 * 1e3;
27641
- var ACTIVITY_BROADCAST_THROTTLE_MS = 5e3;
27912
+ var AWAY_AFTER_MS = parsePositiveInteger2(getRuntimeEnv("VITE_PRESENCE_IDLE_TIMEOUT_MS"), 10 * 60 * 1e3);
27913
+ var OFFLINE_AFTER_MS = Math.max(
27914
+ parsePositiveInteger2(getRuntimeEnv("VITE_PRESENCE_OFFLINE_TIMEOUT_MS"), 10 * 60 * 1e3),
27915
+ AWAY_AFTER_MS
27916
+ );
27917
+ var ACTIVITY_BROADCAST_THROTTLE_MS = parsePositiveInteger2(
27918
+ getRuntimeEnv("VITE_PRESENCE_ACTIVITY_THROTTLE_MS"),
27919
+ 15e3
27920
+ );
27921
+ var PRESENCE_HEARTBEAT_INTERVAL_MS = parsePositiveInteger2(
27922
+ getRuntimeEnv("VITE_PRESENCE_HEARTBEAT_INTERVAL_MS"),
27923
+ 3e4
27924
+ );
27642
27925
  var INACTIVITY_CHECK_INTERVAL_MS = 3e4;
27643
27926
  var SILENT_AUTH_ERRORS = /* @__PURE__ */ new Set(["login_required", "interaction_required", "consent_required", "account_selection_required"]);
27644
27927
  var DEFAULT_PRESENCE_STATUS = "online";
@@ -27652,14 +27935,55 @@ var PRESENCE_STATUS_VALUES2 = [
27652
27935
  "designing",
27653
27936
  "offline"
27654
27937
  ];
27938
+ var PRESENCE_SOURCES = ["auto", "manual", "system"];
27655
27939
  var isUserPresenceStatus = (value) => {
27656
27940
  return typeof value === "string" && PRESENCE_STATUS_VALUES2.includes(value);
27657
27941
  };
27942
+ var isPresenceSource = (value) => {
27943
+ return typeof value === "string" && PRESENCE_SOURCES.includes(value);
27944
+ };
27658
27945
  var toNonEmptyString = (value) => {
27659
27946
  if (typeof value !== "string") return void 0;
27660
27947
  const trimmed = value.trim();
27661
27948
  return trimmed === "" ? void 0 : trimmed;
27662
27949
  };
27950
+ var normalizePresenceSource2 = (value) => {
27951
+ if (typeof value !== "string") return "auto";
27952
+ const normalized = value.trim().toLowerCase();
27953
+ return isPresenceSource(normalized) ? normalized : "auto";
27954
+ };
27955
+ var toTimestampMs2 = (value) => {
27956
+ if (typeof value === "number" && Number.isFinite(value)) {
27957
+ const epochMs = value > 1e12 ? value : value * 1e3;
27958
+ return epochMs;
27959
+ }
27960
+ if (typeof value !== "string") return void 0;
27961
+ const trimmed = value.trim();
27962
+ if (!trimmed) return void 0;
27963
+ const parsed = new Date(trimmed).getTime();
27964
+ return Number.isNaN(parsed) ? void 0 : parsed;
27965
+ };
27966
+ var readPresenceRow = (payload) => {
27967
+ if (!payload) return null;
27968
+ if (Array.isArray(payload)) {
27969
+ const first = payload.find((entry) => typeof entry === "object" && entry !== null);
27970
+ return first != null ? first : null;
27971
+ }
27972
+ if (typeof payload === "object") {
27973
+ return payload;
27974
+ }
27975
+ return null;
27976
+ };
27977
+ var isMissingColumnError2 = (error, column) => {
27978
+ var _a78;
27979
+ const message = ((_a78 = error == null ? void 0 : error.message) != null ? _a78 : "").toLowerCase();
27980
+ const code = error == null ? void 0 : error.code;
27981
+ const token = column.trim().toLowerCase();
27982
+ if (!token) return false;
27983
+ if (!message.includes(token)) return false;
27984
+ if (code === "42703" || code === "PGRST204") return true;
27985
+ return message.includes("column") && (message.includes("does not exist") || message.includes("could not find"));
27986
+ };
27663
27987
  var readFirstRecordString2 = (row, keys) => {
27664
27988
  if (!row) return void 0;
27665
27989
  for (const key of keys) {
@@ -27674,9 +27998,10 @@ var readStoredPresence = () => {
27674
27998
  return isUserPresenceStatus(stored) ? stored : DEFAULT_PRESENCE_STATUS;
27675
27999
  };
27676
28000
  var readStoredPresenceSource = () => {
27677
- var _a74;
27678
- const stored = (_a74 = sessionStorage.getItem(STORAGE_KEYS.presenceSource)) != null ? _a74 : localStorage.getItem(LOCAL_STORAGE_KEYS.presenceSource);
27679
- return stored === "system" ? "system" : "manual";
28001
+ var _a78;
28002
+ const stored = (_a78 = sessionStorage.getItem(STORAGE_KEYS.presenceSource)) != null ? _a78 : localStorage.getItem(LOCAL_STORAGE_KEYS.presenceSource);
28003
+ if (isPresenceSource(stored)) return stored;
28004
+ return "auto";
27680
28005
  };
27681
28006
  var AuthContext = createContext6(void 0);
27682
28007
  var readStoredToken = () => {
@@ -27693,36 +28018,107 @@ var readStoredToken = () => {
27693
28018
  return { accessToken, idToken };
27694
28019
  };
27695
28020
  var storeTokens = (tokens) => {
27696
- var _a74;
27697
28021
  sessionStorage.setItem(STORAGE_KEYS.accessToken, tokens.accessToken);
27698
- if (tokens.idToken) sessionStorage.setItem(STORAGE_KEYS.idToken, tokens.idToken);
27699
- if (tokens.refreshToken) sessionStorage.setItem(STORAGE_KEYS.refreshToken, tokens.refreshToken);
27700
- const expiresAt2 = Date.now() + ((_a74 = tokens.expiresIn) != null ? _a74 : 3600) * 1e3;
28022
+ if (tokens.idToken) {
28023
+ sessionStorage.setItem(STORAGE_KEYS.idToken, tokens.idToken);
28024
+ } else {
28025
+ sessionStorage.removeItem(STORAGE_KEYS.idToken);
28026
+ }
28027
+ if (tokens.refreshToken) {
28028
+ sessionStorage.setItem(STORAGE_KEYS.refreshToken, tokens.refreshToken);
28029
+ } else {
28030
+ sessionStorage.removeItem(STORAGE_KEYS.refreshToken);
28031
+ }
28032
+ const expiresInSeconds = Number(tokens.expiresIn);
28033
+ const validExpiresInSeconds = Number.isFinite(expiresInSeconds) && expiresInSeconds > 0 ? expiresInSeconds : 3600;
28034
+ const expiresAt2 = Date.now() + validExpiresInSeconds * 1e3;
27701
28035
  sessionStorage.setItem(STORAGE_KEYS.expiresAt, String(expiresAt2));
27702
28036
  };
27703
28037
  var clearTokens = () => {
27704
28038
  Object.values(STORAGE_KEYS).forEach((key) => sessionStorage.removeItem(key));
27705
28039
  };
27706
- var buildUserFromToken = (idToken) => {
27707
- var _a74, _b7, _c, _d, _e, _f, _g, _h;
27708
- const payload = decodeJwt(idToken);
27709
- if (!payload) return null;
27710
- 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);
27711
- const roleClaim = (_e = payload.role) != null ? _e : payload.roles;
27712
- const resolvedRole = typeof roleClaim === "string" ? roleClaim : Array.isArray(roleClaim) ? roleClaim.find((entry) => typeof entry === "string") : void 0;
27713
- const jobTitleClaim = (_g = (_f = payload.job_title) != null ? _f : payload.jobTitle) != null ? _g : payload.title;
27714
- const resolvedJobTitle = typeof jobTitleClaim === "string" ? jobTitleClaim : void 0;
28040
+ var readClaimValue = (claims, keys) => {
28041
+ if (!claims) return void 0;
28042
+ for (const key of keys) {
28043
+ const value = toNonEmptyString(claims[key]);
28044
+ if (value) return value;
28045
+ }
28046
+ return void 0;
28047
+ };
28048
+ var readClaimRole = (claims) => {
28049
+ var _a78, _b7, _c;
28050
+ if (!claims) return void 0;
28051
+ 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"];
28052
+ if (typeof roleClaim === "string") return toNonEmptyString(roleClaim);
28053
+ if (Array.isArray(roleClaim)) {
28054
+ return roleClaim.find((entry) => typeof entry === "string" && entry.trim() !== "");
28055
+ }
28056
+ return void 0;
28057
+ };
28058
+ var buildUserFromTokens = ({
28059
+ idToken,
28060
+ accessToken
28061
+ }) => {
28062
+ var _a78;
28063
+ const idClaims = decodeJwt(idToken != null ? idToken : void 0);
28064
+ const accessClaims = decodeJwt(accessToken != null ? accessToken : void 0);
28065
+ if (!idClaims && !accessClaims) return null;
28066
+ const claimSources = [idClaims, accessClaims];
28067
+ const readFromClaims = (keys) => {
28068
+ for (const claims of claimSources) {
28069
+ const value = readClaimValue(claims, keys);
28070
+ if (value) return value;
28071
+ }
28072
+ return void 0;
28073
+ };
28074
+ const readRole = () => {
28075
+ for (const claims of claimSources) {
28076
+ const value = readClaimRole(claims);
28077
+ if (value) return value;
28078
+ }
28079
+ return void 0;
28080
+ };
28081
+ const resolvedId = readFromClaims([
28082
+ "https://cupcode.com/user_id",
28083
+ "user_id",
28084
+ "userId",
28085
+ "uid",
28086
+ "id",
28087
+ "sub"
28088
+ ]);
28089
+ const resolvedSub = (_a78 = readFromClaims(["sub"])) != null ? _a78 : resolvedId;
28090
+ const preferredUsername = readFromClaims([
28091
+ "preferred_username",
28092
+ "preferredUsername",
28093
+ "username",
28094
+ "user_name",
28095
+ "https://cupcode.com/username"
28096
+ ]);
28097
+ const nickname = readFromClaims(["nickname", "nick", "https://cupcode.com/nickname"]);
28098
+ const email = readFromClaims(["email", "https://cupcode.com/email", "upn", "preferred_username", "preferredUsername"]);
28099
+ const givenName = readFromClaims(["given_name", "givenName", "first_name", "firstName"]);
28100
+ const familyName = readFromClaims(["family_name", "familyName", "last_name", "lastName"]);
28101
+ const fullNameFromClaims = readFromClaims(["name", "full_name", "fullName", "https://cupcode.com/name"]);
28102
+ const derivedName = fullNameFromClaims != null ? fullNameFromClaims : [givenName, familyName].filter(Boolean).join(" ").trim() || void 0;
28103
+ const resolvedPicture = readFromClaims([
28104
+ "picture",
28105
+ "avatar_url",
28106
+ "avatarUrl",
28107
+ "photo_url",
28108
+ "photoURL",
28109
+ "https://cupcode.com/picture"
28110
+ ]);
27715
28111
  return {
27716
- sub: payload.sub,
28112
+ sub: resolvedSub,
27717
28113
  id: resolvedId,
27718
28114
  userId: resolvedId,
27719
- name: payload.name,
27720
- email: payload.email,
27721
- picture: payload.picture,
27722
- preferredUsername: (_h = payload.preferred_username) != null ? _h : payload.preferredUsername,
27723
- nickname: payload.nickname,
27724
- role: resolvedRole,
27725
- jobTitle: resolvedJobTitle
28115
+ name: derivedName,
28116
+ email: (email == null ? void 0 : email.includes("@")) ? email.toLowerCase() : email,
28117
+ picture: resolvedPicture,
28118
+ preferredUsername,
28119
+ nickname,
28120
+ role: readRole(),
28121
+ jobTitle: readFromClaims(["job_title", "jobTitle", "title", "position", "https://cupcode.com/job_title"])
27726
28122
  };
27727
28123
  };
27728
28124
  var AuthProvider = ({ children }) => {
@@ -27732,24 +28128,26 @@ var AuthProvider = ({ children }) => {
27732
28128
  const [presenceStatus, setPresenceStatusState] = useState19(() => readStoredPresence());
27733
28129
  const presenceStatusRef = useRef14(readStoredPresence());
27734
28130
  const presenceSourceRef = useRef14(readStoredPresenceSource());
27735
- const lastManualPresenceRef = useRef14(
27736
- readStoredPresence() === "offline" ? DEFAULT_PRESENCE_STATUS : readStoredPresence()
27737
- );
27738
28131
  const lastActivityAtRef = useRef14(Date.now());
27739
28132
  const lastActivityBroadcastAtRef = useRef14(0);
27740
28133
  const resolvedPresenceIdentityKeyRef = useRef14(null);
27741
28134
  const resolvedPresenceUserIdRef = useRef14(null);
27742
- const storePresenceStatus = useCallback9((nextStatus) => {
28135
+ const storePresenceStatus = useCallback9((nextStatus, source) => {
27743
28136
  setPresenceStatusState(nextStatus);
27744
28137
  presenceStatusRef.current = nextStatus;
27745
28138
  sessionStorage.setItem(STORAGE_KEYS.presence, nextStatus);
28139
+ if (source) {
28140
+ presenceSourceRef.current = source;
28141
+ sessionStorage.setItem(STORAGE_KEYS.presenceSource, source);
28142
+ localStorage.setItem(LOCAL_STORAGE_KEYS.presenceSource, source);
28143
+ }
27746
28144
  }, []);
27747
28145
  const resolvePresenceUserId = useCallback9(async (targetUser) => {
27748
- var _a74, _b7, _c, _d;
28146
+ var _a78, _b7, _c, _d;
27749
28147
  const sub = toNonEmptyString(targetUser == null ? void 0 : targetUser.sub);
27750
28148
  const id = toNonEmptyString(targetUser == null ? void 0 : targetUser.id);
27751
28149
  const userId = toNonEmptyString(targetUser == null ? void 0 : targetUser.userId);
27752
- const email = (_a74 = toNonEmptyString(targetUser == null ? void 0 : targetUser.email)) == null ? void 0 : _a74.toLowerCase();
28150
+ const email = (_a78 = toNonEmptyString(targetUser == null ? void 0 : targetUser.email)) == null ? void 0 : _a78.toLowerCase();
27753
28151
  const identityKey = [sub != null ? sub : "", id != null ? id : "", userId != null ? userId : "", email != null ? email : ""].join("|");
27754
28152
  if (resolvedPresenceIdentityKeyRef.current === identityKey && resolvedPresenceUserIdRef.current) {
27755
28153
  return resolvedPresenceUserIdRef.current;
@@ -27782,50 +28180,165 @@ var AuthProvider = ({ children }) => {
27782
28180
  resolvedPresenceUserIdRef.current = fallbackUserId;
27783
28181
  return fallbackUserId;
27784
28182
  }, []);
27785
- const persistPresenceStatus = useCallback9(
27786
- async (nextStatus, targetUser) => {
28183
+ const syncPresenceFromRecord = useCallback9(
28184
+ (rawRow) => {
28185
+ var _a78, _b7, _c;
28186
+ if (!rawRow) return;
28187
+ const statusValue = toNonEmptyString((_a78 = rawRow[USER_PRESENCE_STATUS_COLUMN2]) != null ? _a78 : rawRow.status);
28188
+ if (!isUserPresenceStatus(statusValue)) return;
28189
+ const sourceValue = normalizePresenceSource2((_b7 = rawRow[USER_PRESENCE_SOURCE_COLUMN2]) != null ? _b7 : rawRow.status_source);
28190
+ const lastActiveTimestamp = toTimestampMs2((_c = rawRow[USER_PRESENCE_LAST_ACTIVE_COLUMN2]) != null ? _c : rawRow.last_active_at);
28191
+ if (typeof lastActiveTimestamp === "number" && Number.isFinite(lastActiveTimestamp)) {
28192
+ lastActivityAtRef.current = Math.max(lastActivityAtRef.current, lastActiveTimestamp);
28193
+ }
28194
+ storePresenceStatus(statusValue, sourceValue);
28195
+ },
28196
+ [storePresenceStatus]
28197
+ );
28198
+ const persistPresenceLegacy = useCallback9(
28199
+ async (nextStatus, source, targetUser, options) => {
27787
28200
  const userId = await resolvePresenceUserId(targetUser != null ? targetUser : user);
27788
- if (!userId) return;
28201
+ if (!userId) return false;
27789
28202
  const supabase = getSupabase();
27790
- if (!supabase) return;
28203
+ if (!supabase) return false;
27791
28204
  const payload = {
27792
28205
  [USER_PRESENCE_USER_ID_COLUMN2]: userId,
27793
- [USER_PRESENCE_STATUS_COLUMN2]: nextStatus
28206
+ [USER_PRESENCE_STATUS_COLUMN2]: nextStatus,
28207
+ [USER_PRESENCE_SOURCE_COLUMN2]: source
27794
28208
  };
27795
- const { error } = await supabase.from(USER_PRESENCE_TABLE2).upsert(payload, { onConflict: USER_PRESENCE_USER_ID_COLUMN2 });
27796
- if (error && isRuntimeDev()) {
27797
- console.warn("[auth] Falha ao salvar status de presen\xE7a:", error.message);
28209
+ if (options == null ? void 0 : options.updateLastActiveAt) {
28210
+ payload[USER_PRESENCE_LAST_ACTIVE_COLUMN2] = (/* @__PURE__ */ new Date()).toISOString();
28211
+ }
28212
+ let response = await supabase.from(USER_PRESENCE_TABLE2).upsert(payload, { onConflict: USER_PRESENCE_USER_ID_COLUMN2 }).select("*").maybeSingle();
28213
+ if (response.error && (isMissingColumnError2(response.error, USER_PRESENCE_SOURCE_COLUMN2) || isMissingColumnError2(response.error, USER_PRESENCE_LAST_ACTIVE_COLUMN2))) {
28214
+ response = await supabase.from(USER_PRESENCE_TABLE2).upsert(
28215
+ {
28216
+ [USER_PRESENCE_USER_ID_COLUMN2]: userId,
28217
+ [USER_PRESENCE_STATUS_COLUMN2]: nextStatus
28218
+ },
28219
+ { onConflict: USER_PRESENCE_USER_ID_COLUMN2 }
28220
+ ).select("*").maybeSingle();
28221
+ }
28222
+ if (response.error) {
28223
+ if (isRuntimeDev()) {
28224
+ console.warn("[auth] Falha no fallback de presen\xE7a:", response.error.message);
28225
+ }
28226
+ return false;
27798
28227
  }
28228
+ syncPresenceFromRecord(response.data);
28229
+ return true;
27799
28230
  },
27800
- [resolvePresenceUserId, user]
28231
+ [resolvePresenceUserId, syncPresenceFromRecord, user]
27801
28232
  );
27802
- const applyPresenceStatus = useCallback9(
27803
- async (nextStatus, source, targetUser) => {
27804
- if (!isUserPresenceStatus(nextStatus)) return;
27805
- storePresenceStatus(nextStatus);
27806
- presenceSourceRef.current = source;
27807
- sessionStorage.setItem(STORAGE_KEYS.presenceSource, source);
27808
- localStorage.setItem(LOCAL_STORAGE_KEYS.presenceSource, source);
27809
- if (source === "manual" && nextStatus !== "offline") {
27810
- lastManualPresenceRef.current = nextStatus;
28233
+ const executePresenceRpc = useCallback9(
28234
+ async (fnName, payload, options) => {
28235
+ const supabase = getSupabase();
28236
+ if (!supabase) {
28237
+ if ((options == null ? void 0 : options.fallbackStatus) && options.fallbackSource) {
28238
+ await persistPresenceLegacy(options.fallbackStatus, options.fallbackSource, options.fallbackTargetUser, {
28239
+ updateLastActiveAt: options.updateLastActiveAt
28240
+ });
28241
+ }
28242
+ return false;
28243
+ }
28244
+ const { data, error } = await supabase.rpc(fnName, payload);
28245
+ if (error) {
28246
+ if (isRuntimeDev()) {
28247
+ console.warn(`[auth] Falha ao executar RPC de presen\xE7a (${fnName}):`, error.message);
28248
+ }
28249
+ if ((options == null ? void 0 : options.fallbackStatus) && options.fallbackSource) {
28250
+ await persistPresenceLegacy(options.fallbackStatus, options.fallbackSource, options.fallbackTargetUser, {
28251
+ updateLastActiveAt: options.updateLastActiveAt
28252
+ });
28253
+ }
28254
+ return false;
27811
28255
  }
27812
- await persistPresenceStatus(nextStatus, targetUser);
28256
+ syncPresenceFromRecord(readPresenceRow(data));
28257
+ return true;
27813
28258
  },
27814
- [persistPresenceStatus, storePresenceStatus]
28259
+ [persistPresenceLegacy, syncPresenceFromRecord]
27815
28260
  );
27816
- const syncPresenceFromDatabase = useCallback9(
27817
- (nextStatus) => {
27818
- storePresenceStatus(nextStatus);
27819
- const storedSource = readStoredPresenceSource();
27820
- const sourceFromDatabase = nextStatus === "away" ? storedSource : nextStatus === "offline" ? "system" : "manual";
27821
- presenceSourceRef.current = sourceFromDatabase;
27822
- sessionStorage.setItem(STORAGE_KEYS.presenceSource, sourceFromDatabase);
27823
- localStorage.setItem(LOCAL_STORAGE_KEYS.presenceSource, sourceFromDatabase);
27824
- if (nextStatus !== "offline") {
27825
- lastManualPresenceRef.current = nextStatus;
28261
+ const touchPresence = useCallback9(
28262
+ async (options) => {
28263
+ var _a78;
28264
+ const targetUser = (_a78 = options == null ? void 0 : options.targetUser) != null ? _a78 : user;
28265
+ const userId = await resolvePresenceUserId(targetUser);
28266
+ if (!userId) return;
28267
+ const now = Date.now();
28268
+ lastActivityAtRef.current = now;
28269
+ if ((options == null ? void 0 : options.throttle) && now - lastActivityBroadcastAtRef.current < ACTIVITY_BROADCAST_THROTTLE_MS) {
28270
+ return;
27826
28271
  }
28272
+ lastActivityBroadcastAtRef.current = now;
28273
+ const fallbackStatus = presenceSourceRef.current === "manual" ? presenceStatusRef.current : "online";
28274
+ const fallbackSource = presenceSourceRef.current === "manual" ? "manual" : "auto";
28275
+ await executePresenceRpc(
28276
+ PRESENCE_TOUCH_RPC,
28277
+ {
28278
+ p_user_id: userId,
28279
+ p_idle_after_seconds: Math.floor(AWAY_AFTER_MS / 1e3),
28280
+ p_force_online: Boolean(options == null ? void 0 : options.forceOnline)
28281
+ },
28282
+ {
28283
+ fallbackStatus,
28284
+ fallbackSource,
28285
+ fallbackTargetUser: targetUser,
28286
+ updateLastActiveAt: true
28287
+ }
28288
+ );
27827
28289
  },
27828
- [storePresenceStatus]
28290
+ [executePresenceRpc, resolvePresenceUserId, user]
28291
+ );
28292
+ const markPresenceIdle = useCallback9(
28293
+ async (targetUser) => {
28294
+ const resolvedTargetUser = targetUser != null ? targetUser : user;
28295
+ const userId = await resolvePresenceUserId(resolvedTargetUser);
28296
+ if (!userId) return;
28297
+ const idleMs = Date.now() - lastActivityAtRef.current;
28298
+ const fallbackStatus = idleMs >= OFFLINE_AFTER_MS ? "offline" : "away";
28299
+ const fallbackSource = fallbackStatus === "offline" ? "system" : "auto";
28300
+ await executePresenceRpc(
28301
+ PRESENCE_MARK_IDLE_RPC,
28302
+ {
28303
+ p_user_id: userId,
28304
+ p_idle_after_seconds: Math.floor(AWAY_AFTER_MS / 1e3),
28305
+ p_offline_after_seconds: Math.floor(OFFLINE_AFTER_MS / 1e3)
28306
+ },
28307
+ {
28308
+ fallbackStatus,
28309
+ fallbackSource,
28310
+ fallbackTargetUser: resolvedTargetUser,
28311
+ updateLastActiveAt: false
28312
+ }
28313
+ );
28314
+ },
28315
+ [executePresenceRpc, resolvePresenceUserId, user]
28316
+ );
28317
+ const setPresenceNetworkStatus = useCallback9(
28318
+ async (nextStatus, source, targetUser) => {
28319
+ const resolvedTargetUser = targetUser != null ? targetUser : user;
28320
+ const userId = await resolvePresenceUserId(resolvedTargetUser);
28321
+ if (!userId) return;
28322
+ const shouldUpdateLastActiveAt = nextStatus !== "offline";
28323
+ if (shouldUpdateLastActiveAt) {
28324
+ lastActivityAtRef.current = Date.now();
28325
+ }
28326
+ await executePresenceRpc(
28327
+ PRESENCE_SET_STATUS_RPC,
28328
+ {
28329
+ p_user_id: userId,
28330
+ p_status: nextStatus,
28331
+ p_source: source
28332
+ },
28333
+ {
28334
+ fallbackStatus: nextStatus,
28335
+ fallbackSource: source,
28336
+ fallbackTargetUser: resolvedTargetUser,
28337
+ updateLastActiveAt: shouldUpdateLastActiveAt
28338
+ }
28339
+ );
28340
+ },
28341
+ [executePresenceRpc, resolvePresenceUserId, user]
27829
28342
  );
27830
28343
  const loadPresenceFromDatabase = useCallback9(
27831
28344
  async (targetUser) => {
@@ -27833,7 +28346,19 @@ var AuthProvider = ({ children }) => {
27833
28346
  if (!userId) return;
27834
28347
  const supabase = getSupabase();
27835
28348
  if (!supabase) return;
27836
- const { data, error } = await supabase.from(USER_PRESENCE_TABLE2).select(USER_PRESENCE_STATUS_COLUMN2).eq(USER_PRESENCE_USER_ID_COLUMN2, userId).maybeSingle();
28349
+ const columns = Array.from(
28350
+ /* @__PURE__ */ new Set([
28351
+ USER_PRESENCE_STATUS_COLUMN2,
28352
+ USER_PRESENCE_SOURCE_COLUMN2,
28353
+ USER_PRESENCE_LAST_ACTIVE_COLUMN2
28354
+ ])
28355
+ ).join(",");
28356
+ let { data, error } = await supabase.from(USER_PRESENCE_TABLE2).select(columns).eq(USER_PRESENCE_USER_ID_COLUMN2, userId).maybeSingle();
28357
+ if (error && (isMissingColumnError2(error, USER_PRESENCE_SOURCE_COLUMN2) || isMissingColumnError2(error, USER_PRESENCE_LAST_ACTIVE_COLUMN2))) {
28358
+ const fallbackResponse = await supabase.from(USER_PRESENCE_TABLE2).select(USER_PRESENCE_STATUS_COLUMN2).eq(USER_PRESENCE_USER_ID_COLUMN2, userId).maybeSingle();
28359
+ data = fallbackResponse.data;
28360
+ error = fallbackResponse.error;
28361
+ }
27837
28362
  if (error) {
27838
28363
  if (isRuntimeDev()) {
27839
28364
  console.warn("[auth] Falha ao carregar status de presen\xE7a:", error.message);
@@ -27841,14 +28366,13 @@ var AuthProvider = ({ children }) => {
27841
28366
  return;
27842
28367
  }
27843
28368
  const row = data;
27844
- const rawStatus = row == null ? void 0 : row[USER_PRESENCE_STATUS_COLUMN2];
27845
- if (!isUserPresenceStatus(rawStatus)) {
27846
- await persistPresenceStatus(presenceStatusRef.current, targetUser);
28369
+ if (!row) {
28370
+ await touchPresence({ targetUser, forceOnline: false, throttle: false });
27847
28371
  return;
27848
28372
  }
27849
- syncPresenceFromDatabase(rawStatus);
28373
+ syncPresenceFromRecord(row);
27850
28374
  },
27851
- [persistPresenceStatus, resolvePresenceUserId, syncPresenceFromDatabase]
28375
+ [resolvePresenceUserId, syncPresenceFromRecord, touchPresence]
27852
28376
  );
27853
28377
  const clearAuthFlowState = useCallback9((options) => {
27854
28378
  sessionStorage.removeItem(STORAGE_KEYS.state);
@@ -27862,7 +28386,7 @@ var AuthProvider = ({ children }) => {
27862
28386
  }, []);
27863
28387
  const startAuthorization = useCallback9(
27864
28388
  async (options) => {
27865
- var _a74, _b7;
28389
+ var _a78, _b7;
27866
28390
  const config = getAccountsConfig();
27867
28391
  const { authUrl } = await resolveOidcEndpoints(config);
27868
28392
  if (!authUrl) {
@@ -27872,7 +28396,7 @@ var AuthProvider = ({ children }) => {
27872
28396
  const challenge = await generateCodeChallenge(verifier);
27873
28397
  const state = generateState();
27874
28398
  const nonce = generateNonce();
27875
- const redirectTo = (_a74 = options == null ? void 0 : options.redirectTo) != null ? _a74 : window.location.pathname + window.location.search + window.location.hash;
28399
+ const redirectTo = (_a78 = options == null ? void 0 : options.redirectTo) != null ? _a78 : window.location.pathname + window.location.search + window.location.hash;
27876
28400
  const mode = (_b7 = options == null ? void 0 : options.mode) != null ? _b7 : "interactive";
27877
28401
  sessionStorage.setItem(STORAGE_KEYS.verifier, verifier);
27878
28402
  sessionStorage.setItem(STORAGE_KEYS.state, state);
@@ -27900,14 +28424,18 @@ var AuthProvider = ({ children }) => {
27900
28424
  useEffect24(() => {
27901
28425
  let cancelled = false;
27902
28426
  const initializeAuth = async () => {
27903
- var _a74;
28427
+ var _a78;
27904
28428
  const stored = readStoredToken();
27905
28429
  const storedPresence = readStoredPresence();
27906
28430
  setPresenceStatusState(storedPresence);
27907
28431
  if (stored == null ? void 0 : stored.accessToken) {
27908
28432
  if (cancelled) return;
28433
+ const hydratedUser = buildUserFromTokens({
28434
+ idToken: (_a78 = stored.idToken) != null ? _a78 : void 0,
28435
+ accessToken: stored.accessToken
28436
+ });
27909
28437
  setAccessToken(stored.accessToken);
27910
- setUser(buildUserFromToken((_a74 = stored.idToken) != null ? _a74 : void 0));
28438
+ setUser(hydratedUser);
27911
28439
  setStatus("authenticated");
27912
28440
  return;
27913
28441
  }
@@ -27934,6 +28462,19 @@ var AuthProvider = ({ children }) => {
27934
28462
  cancelled = true;
27935
28463
  };
27936
28464
  }, [attemptSilentLogin]);
28465
+ useEffect24(() => {
28466
+ var _a78;
28467
+ if (status !== "authenticated") return;
28468
+ if (user) return;
28469
+ const stored = readStoredToken();
28470
+ if (!(stored == null ? void 0 : stored.accessToken)) return;
28471
+ const hydratedUser = buildUserFromTokens({
28472
+ idToken: (_a78 = stored.idToken) != null ? _a78 : void 0,
28473
+ accessToken: stored.accessToken
28474
+ });
28475
+ if (!hydratedUser) return;
28476
+ setUser(hydratedUser);
28477
+ }, [status, user]);
27937
28478
  useEffect24(() => {
27938
28479
  resolvedPresenceIdentityKeyRef.current = null;
27939
28480
  resolvedPresenceUserIdRef.current = null;
@@ -27959,16 +28500,15 @@ var AuthProvider = ({ children }) => {
27959
28500
  table: USER_PRESENCE_TABLE2
27960
28501
  },
27961
28502
  (payload) => {
28503
+ var _a78, _b7;
27962
28504
  const row = payload.new || payload.old;
27963
- const rowUserId = toNonEmptyString(row == null ? void 0 : row[USER_PRESENCE_USER_ID_COLUMN2]);
28505
+ 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);
27964
28506
  if (!rowUserId || rowUserId !== currentUserId) return;
27965
28507
  if (payload.eventType === "DELETE") {
27966
- syncPresenceFromDatabase("offline");
28508
+ storePresenceStatus("offline", "system");
27967
28509
  return;
27968
28510
  }
27969
- const nextStatus = row == null ? void 0 : row[USER_PRESENCE_STATUS_COLUMN2];
27970
- if (!isUserPresenceStatus(nextStatus)) return;
27971
- syncPresenceFromDatabase(nextStatus);
28511
+ syncPresenceFromRecord(row);
27972
28512
  }
27973
28513
  ).subscribe();
27974
28514
  };
@@ -27979,55 +28519,34 @@ var AuthProvider = ({ children }) => {
27979
28519
  void supabase.removeChannel(presenceChannel);
27980
28520
  }
27981
28521
  };
27982
- }, [resolvePresenceUserId, status, syncPresenceFromDatabase, user]);
28522
+ }, [resolvePresenceUserId, status, storePresenceStatus, syncPresenceFromRecord, user]);
27983
28523
  useEffect24(() => {
27984
- var _a74;
27985
28524
  if (status !== "authenticated") return;
27986
- const initialFromStorage = Number((_a74 = localStorage.getItem(LOCAL_STORAGE_KEYS.lastActivityAt)) != null ? _a74 : "0");
27987
- if (Number.isFinite(initialFromStorage) && initialFromStorage > 0) {
27988
- lastActivityAtRef.current = Math.max(lastActivityAtRef.current, initialFromStorage);
27989
- } else {
27990
- const now = Date.now();
27991
- lastActivityAtRef.current = now;
27992
- localStorage.setItem(LOCAL_STORAGE_KEYS.lastActivityAt, String(now));
27993
- }
27994
- const registerActivity = (shouldBroadcast = true) => {
27995
- const now = Date.now();
27996
- lastActivityAtRef.current = now;
27997
- if (shouldBroadcast && now - lastActivityBroadcastAtRef.current >= ACTIVITY_BROADCAST_THROTTLE_MS) {
27998
- lastActivityBroadcastAtRef.current = now;
27999
- localStorage.setItem(LOCAL_STORAGE_KEYS.lastActivityAt, String(now));
28000
- }
28001
- const currentStatus = presenceStatusRef.current;
28002
- if (presenceSourceRef.current === "system" && (currentStatus === "away" || currentStatus === "offline")) {
28003
- void applyPresenceStatus(DEFAULT_PRESENCE_STATUS, "manual");
28004
- }
28525
+ const registerActivity = () => {
28526
+ lastActivityAtRef.current = Date.now();
28527
+ void touchPresence({ throttle: true });
28005
28528
  };
28006
- const onActivity = () => registerActivity(true);
28529
+ const onActivity = () => registerActivity();
28007
28530
  const onVisibility = () => {
28008
28531
  if (document.visibilityState === "visible") {
28009
- registerActivity(true);
28532
+ registerActivity();
28010
28533
  }
28011
28534
  };
28012
- const onStorage = (event) => {
28013
- if (event.key !== LOCAL_STORAGE_KEYS.lastActivityAt || !event.newValue) return;
28014
- const parsed = Number(event.newValue);
28015
- if (!Number.isFinite(parsed) || parsed <= 0) return;
28016
- if (parsed > lastActivityAtRef.current) {
28017
- lastActivityAtRef.current = parsed;
28018
- }
28019
- const elapsed = Date.now() - parsed;
28020
- if (presenceSourceRef.current === "system" && (presenceStatusRef.current === "away" || presenceStatusRef.current === "offline") && elapsed < AWAY_AFTER_MS) {
28021
- void applyPresenceStatus(DEFAULT_PRESENCE_STATUS, "manual");
28022
- }
28023
- };
28024
- const intervalId = window.setInterval(() => {
28535
+ const heartbeatIntervalId = window.setInterval(() => {
28536
+ if (document.visibilityState !== "visible") return;
28025
28537
  const idleMs = Date.now() - lastActivityAtRef.current;
28026
- const currentStatus = presenceStatusRef.current;
28027
- if (idleMs >= AWAY_AFTER_MS) {
28028
- if (currentStatus !== "away" && currentStatus !== "offline") {
28029
- void applyPresenceStatus("away", "system");
28030
- }
28538
+ if (idleMs >= AWAY_AFTER_MS) return;
28539
+ void touchPresence({ throttle: false });
28540
+ }, PRESENCE_HEARTBEAT_INTERVAL_MS);
28541
+ const idleIntervalId = window.setInterval(() => {
28542
+ if (presenceStatusRef.current === "offline") return;
28543
+ const idleMs = Date.now() - lastActivityAtRef.current;
28544
+ if (idleMs >= OFFLINE_AFTER_MS) {
28545
+ void markPresenceIdle();
28546
+ return;
28547
+ }
28548
+ if (presenceSourceRef.current === "auto" && idleMs >= AWAY_AFTER_MS) {
28549
+ void markPresenceIdle();
28031
28550
  }
28032
28551
  }, INACTIVITY_CHECK_INTERVAL_MS);
28033
28552
  window.addEventListener("mousemove", onActivity, { passive: true });
@@ -28037,10 +28556,10 @@ var AuthProvider = ({ children }) => {
28037
28556
  window.addEventListener("touchstart", onActivity, { passive: true });
28038
28557
  window.addEventListener("focus", onActivity);
28039
28558
  document.addEventListener("visibilitychange", onVisibility);
28040
- window.addEventListener("storage", onStorage);
28041
- registerActivity(true);
28559
+ registerActivity();
28042
28560
  return () => {
28043
- window.clearInterval(intervalId);
28561
+ window.clearInterval(heartbeatIntervalId);
28562
+ window.clearInterval(idleIntervalId);
28044
28563
  window.removeEventListener("mousemove", onActivity);
28045
28564
  window.removeEventListener("mousedown", onActivity);
28046
28565
  window.removeEventListener("keydown", onActivity);
@@ -28048,9 +28567,8 @@ var AuthProvider = ({ children }) => {
28048
28567
  window.removeEventListener("touchstart", onActivity);
28049
28568
  window.removeEventListener("focus", onActivity);
28050
28569
  document.removeEventListener("visibilitychange", onVisibility);
28051
- window.removeEventListener("storage", onStorage);
28052
28570
  };
28053
- }, [applyPresenceStatus, status]);
28571
+ }, [markPresenceIdle, status, touchPresence]);
28054
28572
  const login = useCallback9(async (redirectTo) => {
28055
28573
  await startAuthorization({
28056
28574
  mode: "interactive",
@@ -28058,9 +28576,9 @@ var AuthProvider = ({ children }) => {
28058
28576
  });
28059
28577
  }, [startAuthorization]);
28060
28578
  const completeLogin = useCallback9(async () => {
28061
- var _a74;
28579
+ var _a78;
28062
28580
  const params = new URLSearchParams(window.location.search);
28063
- const redirectTo = (_a74 = sessionStorage.getItem(STORAGE_KEYS.redirect)) != null ? _a74 : "/";
28581
+ const redirectTo = (_a78 = sessionStorage.getItem(STORAGE_KEYS.redirect)) != null ? _a78 : "/";
28064
28582
  const authMode = sessionStorage.getItem(STORAGE_KEYS.authMode);
28065
28583
  const isSilentAuth = authMode === "silent";
28066
28584
  const error = params.get("error");
@@ -28113,8 +28631,12 @@ var AuthProvider = ({ children }) => {
28113
28631
  refreshToken: tokens.refresh_token,
28114
28632
  expiresIn: tokens.expires_in
28115
28633
  });
28634
+ const nextUser = buildUserFromTokens({
28635
+ idToken: tokens.id_token,
28636
+ accessToken: tokens.access_token
28637
+ });
28116
28638
  setAccessToken(tokens.access_token);
28117
- setUser(buildUserFromToken(tokens.id_token));
28639
+ setUser(nextUser);
28118
28640
  setStatus("authenticated");
28119
28641
  clearAuthFlowState();
28120
28642
  return { ok: true, redirectTo };
@@ -28124,42 +28646,40 @@ var AuthProvider = ({ children }) => {
28124
28646
  }
28125
28647
  }, [clearAuthFlowState]);
28126
28648
  const logout = useCallback9(async () => {
28127
- var _a74;
28649
+ var _a78;
28128
28650
  const config = getAccountsConfig();
28129
28651
  const { logoutUrl } = await resolveOidcEndpoints(config);
28130
- const idToken = (_a74 = sessionStorage.getItem(STORAGE_KEYS.idToken)) != null ? _a74 : void 0;
28652
+ const idToken = (_a78 = sessionStorage.getItem(STORAGE_KEYS.idToken)) != null ? _a78 : void 0;
28131
28653
  const currentUser = user;
28132
- await persistPresenceStatus("offline", currentUser);
28654
+ await setPresenceNetworkStatus("offline", "system", currentUser);
28133
28655
  clearTokens();
28134
28656
  setAccessToken(null);
28135
28657
  setUser(null);
28136
28658
  setStatus("unauthenticated");
28137
- setPresenceStatusState("offline");
28138
- presenceStatusRef.current = "offline";
28139
- presenceSourceRef.current = "system";
28659
+ storePresenceStatus("offline", "system");
28140
28660
  sessionStorage.removeItem(STORAGE_KEYS.presenceSource);
28141
28661
  localStorage.removeItem(LOCAL_STORAGE_KEYS.presenceSource);
28142
- localStorage.removeItem(LOCAL_STORAGE_KEYS.lastActivityAt);
28143
28662
  const url = buildLogoutUrl(config, logoutUrl, idToken);
28144
28663
  if (url) {
28145
28664
  window.location.assign(url);
28146
28665
  }
28147
- }, [persistPresenceStatus, user]);
28666
+ }, [setPresenceNetworkStatus, storePresenceStatus, user]);
28148
28667
  const getAccessToken = useCallback9(async () => {
28149
28668
  const stored = readStoredToken();
28150
28669
  if (stored == null ? void 0 : stored.accessToken) return stored.accessToken;
28670
+ if (accessToken) return accessToken;
28151
28671
  throw new Error("Usu\xE1rio n\xE3o autenticado.");
28152
- }, []);
28672
+ }, [accessToken]);
28153
28673
  const setPresenceStatus = useCallback9(
28154
28674
  async (nextStatus) => {
28155
28675
  if (!isUserPresenceStatus(nextStatus) || nextStatus === "offline") return;
28156
28676
  const now = Date.now();
28157
28677
  lastActivityAtRef.current = now;
28158
28678
  lastActivityBroadcastAtRef.current = now;
28159
- localStorage.setItem(LOCAL_STORAGE_KEYS.lastActivityAt, String(now));
28160
- await applyPresenceStatus(nextStatus, "manual");
28679
+ const source = nextStatus === "online" ? "auto" : "manual";
28680
+ await setPresenceNetworkStatus(nextStatus, source);
28161
28681
  },
28162
- [applyPresenceStatus]
28682
+ [setPresenceNetworkStatus]
28163
28683
  );
28164
28684
  const value = useMemo12(
28165
28685
  () => ({
@@ -28390,6 +28910,11 @@ export {
28390
28910
  NavigationMenuList,
28391
28911
  NavigationMenuTrigger,
28392
28912
  NavigationMenuViewport,
28913
+ PRESENCE_ACTIVITY_THROTTLE_MS_ENV_KEY,
28914
+ PRESENCE_HEARTBEAT_INTERVAL_MS_ENV_KEY,
28915
+ PRESENCE_IDLE_TIMEOUT_MS_ENV_KEY,
28916
+ PRESENCE_OFFLINE_TIMEOUT_MS_ENV_KEY,
28917
+ PRESENCE_RUNTIME_ENV_KEYS,
28393
28918
  Pagination,
28394
28919
  PaginationContent,
28395
28920
  PaginationEllipsis,
@@ -28503,6 +29028,8 @@ export {
28503
29028
  TooltipCupcode,
28504
29029
  TooltipProvider,
28505
29030
  TooltipTrigger,
29031
+ USER_PRESENCE_LAST_ACTIVE_COLUMN_ENV_KEY,
29032
+ USER_PRESENCE_SOURCE_COLUMN_ENV_KEY,
28506
29033
  UserMenuCupcode,
28507
29034
  badgeVariants,
28508
29035
  buildAuthorizeUrl,