@liveblocks/core 1.11.3 → 1.12.0-lexical2

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.mjs CHANGED
@@ -6,7 +6,7 @@ var __export = (target, all) => {
6
6
 
7
7
  // src/version.ts
8
8
  var PKG_NAME = "@liveblocks/core";
9
- var PKG_VERSION = "1.11.3";
9
+ var PKG_VERSION = "1.12.0-lexical2";
10
10
  var PKG_FORMAT = "esm";
11
11
 
12
12
  // src/dupe-detection.ts
@@ -1389,7 +1389,6 @@ function createAuthManager(authOptions) {
1389
1389
  room: options.roomId
1390
1390
  });
1391
1391
  const parsed = parseAuthToken(response.token);
1392
- verifyTokenPermissions(parsed, options);
1393
1392
  if (seenTokens.has(parsed.raw)) {
1394
1393
  throw new StopRetrying(
1395
1394
  "The same Liveblocks auth token was issued from the backend before. Caching Liveblocks tokens is not supported."
@@ -1402,7 +1401,6 @@ function createAuthManager(authOptions) {
1402
1401
  if (response && typeof response === "object") {
1403
1402
  if (typeof response.token === "string") {
1404
1403
  const parsed = parseAuthToken(response.token);
1405
- verifyTokenPermissions(parsed, options);
1406
1404
  return parsed;
1407
1405
  } else if (typeof response.error === "string") {
1408
1406
  const reason = `Authentication failed: ${"reason" in response && typeof response.reason === "string" ? response.reason : "Forbidden"}`;
@@ -1421,23 +1419,6 @@ function createAuthManager(authOptions) {
1421
1419
  "Unexpected authentication type. Must be private or custom."
1422
1420
  );
1423
1421
  }
1424
- function verifyTokenPermissions(parsedToken, options) {
1425
- if (!options.roomId && parsedToken.parsed.k === "acc" /* ACCESS_TOKEN */) {
1426
- if (Object.entries(parsedToken.parsed.perms).length === 0) {
1427
- return;
1428
- }
1429
- for (const [resource, scopes] of Object.entries(
1430
- parsedToken.parsed.perms
1431
- )) {
1432
- if (resource.includes("*") && hasCorrespondingScopes(options.requestedScope, scopes)) {
1433
- return;
1434
- }
1435
- }
1436
- throw new StopRetrying(
1437
- "The issued access token doesn't grant enough permissions. Please follow the instructions at https://liveblocks.io/docs/errors/liveblocks-client/access-tokens-not-enough-permissions"
1438
- );
1439
- }
1440
- }
1441
1422
  async function getAuthValue(requestOptions) {
1442
1423
  if (authentication.type === "public") {
1443
1424
  return { type: "public", publicApiKey: authentication.publicApiKey };
@@ -1561,430 +1542,564 @@ async function fetchAuthEndpoint(fetch2, endpoint, body) {
1561
1542
  return { token };
1562
1543
  }
1563
1544
 
1564
- // src/constants.ts
1565
- var DEFAULT_BASE_URL = "https://api.liveblocks.io";
1545
+ // ../../node_modules/nanoid/index.js
1546
+ import crypto from "crypto";
1566
1547
 
1567
- // src/internal.ts
1568
- var kInternal = Symbol();
1548
+ // ../../node_modules/nanoid/url-alphabet/index.js
1549
+ var urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
1569
1550
 
1570
- // src/devtools/bridge.ts
1571
- var _bridgeActive = false;
1572
- function activateBridge(allowed) {
1573
- _bridgeActive = allowed;
1574
- }
1575
- function sendToPanel(message, options) {
1576
- if (process.env.NODE_ENV === "production" || typeof window === "undefined") {
1577
- return;
1578
- }
1579
- const fullMsg = {
1580
- ...message,
1581
- source: "liveblocks-devtools-client"
1582
- };
1583
- if (!(options?.force || _bridgeActive)) {
1584
- return;
1551
+ // ../../node_modules/nanoid/index.js
1552
+ var POOL_SIZE_MULTIPLIER = 128;
1553
+ var pool;
1554
+ var poolOffset;
1555
+ var fillPool = (bytes) => {
1556
+ if (!pool || pool.length < bytes) {
1557
+ pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER);
1558
+ crypto.randomFillSync(pool);
1559
+ poolOffset = 0;
1560
+ } else if (poolOffset + bytes > pool.length) {
1561
+ crypto.randomFillSync(pool);
1562
+ poolOffset = 0;
1563
+ }
1564
+ poolOffset += bytes;
1565
+ };
1566
+ var nanoid = (size = 21) => {
1567
+ fillPool(size -= 0);
1568
+ let id = "";
1569
+ for (let i = poolOffset - size; i < poolOffset; i++) {
1570
+ id += urlAlphabet[pool[i] & 63];
1585
1571
  }
1586
- window.postMessage(fullMsg, "*");
1587
- }
1588
- var eventSource = makeEventSource();
1589
- if (process.env.NODE_ENV !== "production" && typeof window !== "undefined") {
1590
- window.addEventListener("message", (event) => {
1591
- if (event.source === window && event.data?.source === "liveblocks-devtools-panel") {
1592
- eventSource.notify(event.data);
1593
- } else {
1594
- }
1595
- });
1596
- }
1597
- var onMessageFromPanel = eventSource.observable;
1572
+ return id;
1573
+ };
1598
1574
 
1599
- // src/devtools/index.ts
1600
- var VERSION = PKG_VERSION || "dev";
1601
- var _devtoolsSetupHasRun = false;
1602
- function setupDevTools(getAllRooms) {
1603
- if (process.env.NODE_ENV === "production" || typeof window === "undefined") {
1604
- return;
1605
- }
1606
- if (_devtoolsSetupHasRun) {
1607
- return;
1608
- }
1609
- _devtoolsSetupHasRun = true;
1610
- onMessageFromPanel.subscribe((msg) => {
1611
- switch (msg.msg) {
1612
- case "connect": {
1613
- activateBridge(true);
1614
- for (const roomId of getAllRooms()) {
1615
- sendToPanel({
1616
- msg: "room::available",
1617
- roomId,
1618
- clientVersion: VERSION
1619
- });
1620
- }
1621
- break;
1622
- }
1623
- }
1624
- });
1625
- sendToPanel({ msg: "wake-up-devtools" }, { force: true });
1626
- }
1627
- var unsubsByRoomId = /* @__PURE__ */ new Map();
1628
- function stopSyncStream(roomId) {
1629
- const unsubs = unsubsByRoomId.get(roomId) ?? [];
1630
- unsubsByRoomId.delete(roomId);
1631
- for (const unsub of unsubs) {
1632
- unsub();
1633
- }
1634
- }
1635
- function startSyncStream(room) {
1636
- stopSyncStream(room.id);
1637
- fullSync(room);
1638
- unsubsByRoomId.set(room.id, [
1639
- // When the connection status changes
1640
- room.events.status.subscribe(() => partialSyncConnection(room)),
1641
- // When storage initializes, send the update
1642
- room.events.storageDidLoad.subscribeOnce(() => partialSyncStorage(room)),
1643
- // Any time storage updates, send the new storage root
1644
- room.events.storage.subscribe(() => partialSyncStorage(room)),
1645
- // Any time "me" or "others" updates, send the new values accordingly
1646
- room.events.self.subscribe(() => partialSyncMe(room)),
1647
- room.events.others.subscribe(() => partialSyncOthers(room)),
1648
- // Any time ydoc is updated, forward the update
1649
- room.events.ydoc.subscribe((update) => syncYdocUpdate(room, update)),
1650
- // Any time a custom room event is received, forward it
1651
- room.events.customEvent.subscribe(
1652
- (eventData) => forwardEvent(room, eventData)
1653
- )
1654
- ]);
1655
- }
1656
- function syncYdocUpdate(room, update) {
1657
- sendToPanel({
1658
- msg: "room::sync::ydoc",
1659
- roomId: room.id,
1660
- update
1661
- });
1575
+ // src/comments/lib/createIds.ts
1576
+ var THREAD_ID_PREFIX = "th";
1577
+ var COMMENT_ID_PREFIX = "cm";
1578
+ var INBOX_NOTIFICATION_ID_PREFIX = "in";
1579
+ function createOptimisticId(prefix) {
1580
+ return `${prefix}_${nanoid()}`;
1662
1581
  }
1663
- var loadedAt = Date.now();
1664
- var eventCounter = 0;
1665
- function nextEventId() {
1666
- return `event-${loadedAt}-${eventCounter++}`;
1582
+ function createThreadId() {
1583
+ return createOptimisticId(THREAD_ID_PREFIX);
1667
1584
  }
1668
- function forwardEvent(room, eventData) {
1669
- sendToPanel({
1670
- msg: "room::events::custom-event",
1671
- roomId: room.id,
1672
- event: {
1673
- type: "CustomEvent",
1674
- id: nextEventId(),
1675
- key: "Event",
1676
- connectionId: eventData.connectionId,
1677
- payload: eventData.event
1678
- }
1679
- });
1585
+ function createCommentId() {
1586
+ return createOptimisticId(COMMENT_ID_PREFIX);
1680
1587
  }
1681
- function partialSyncConnection(room) {
1682
- sendToPanel({
1683
- msg: "room::sync::partial",
1684
- roomId: room.id,
1685
- status: room.getStatus()
1686
- });
1588
+ function createInboxNotificationId() {
1589
+ return createOptimisticId(INBOX_NOTIFICATION_ID_PREFIX);
1687
1590
  }
1688
- function partialSyncStorage(room) {
1689
- const root = room.getStorageSnapshot();
1690
- if (root) {
1691
- sendToPanel({
1692
- msg: "room::sync::partial",
1693
- roomId: room.id,
1694
- storage: root.toTreeNode("root").payload
1695
- });
1591
+
1592
+ // src/lib/create-store.ts
1593
+ function createStore(initialState) {
1594
+ let state = initialState;
1595
+ const subscribers = /* @__PURE__ */ new Set();
1596
+ function get() {
1597
+ return state;
1696
1598
  }
1697
- }
1698
- function partialSyncMe(room) {
1699
- const me = room[kInternal].getSelf_forDevTools();
1700
- if (me) {
1701
- sendToPanel({
1702
- msg: "room::sync::partial",
1703
- roomId: room.id,
1704
- me
1705
- });
1599
+ function set(callback) {
1600
+ const newState = callback(state);
1601
+ if (state === newState) {
1602
+ return;
1603
+ }
1604
+ state = newState;
1605
+ for (const subscriber of subscribers) {
1606
+ subscriber(state);
1607
+ }
1706
1608
  }
1707
- }
1708
- function partialSyncOthers(room) {
1709
- const others = room[kInternal].getOthers_forDevTools();
1710
- if (others) {
1711
- sendToPanel({
1712
- msg: "room::sync::partial",
1713
- roomId: room.id,
1714
- others
1715
- });
1609
+ function subscribe(callback) {
1610
+ subscribers.add(callback);
1611
+ callback(state);
1612
+ return () => {
1613
+ subscribers.delete(callback);
1614
+ };
1716
1615
  }
1616
+ return {
1617
+ get,
1618
+ set,
1619
+ subscribe
1620
+ };
1717
1621
  }
1718
- function fullSync(room) {
1719
- const root = room.getStorageSnapshot();
1720
- const me = room[kInternal].getSelf_forDevTools();
1721
- const others = room[kInternal].getOthers_forDevTools();
1722
- room.fetchYDoc("");
1723
- sendToPanel({
1724
- msg: "room::sync::full",
1725
- roomId: room.id,
1726
- status: room.getStatus(),
1727
- storage: root?.toTreeNode("root").payload ?? null,
1728
- me,
1729
- others
1622
+
1623
+ // src/store.ts
1624
+ function createClientStore() {
1625
+ const store = createStore({
1626
+ threads: {},
1627
+ queries: {},
1628
+ optimisticUpdates: [],
1629
+ inboxNotifications: {},
1630
+ notificationSettings: {}
1730
1631
  });
1731
- }
1732
- var roomChannelListeners = /* @__PURE__ */ new Map();
1733
- function stopRoomChannelListener(roomId) {
1734
- const listener = roomChannelListeners.get(roomId);
1735
- roomChannelListeners.delete(roomId);
1736
- if (listener) {
1737
- listener();
1738
- }
1739
- }
1740
- function linkDevTools(roomId, room) {
1741
- if (process.env.NODE_ENV === "production" || typeof window === "undefined") {
1742
- return;
1743
- }
1744
- sendToPanel({ msg: "room::available", roomId, clientVersion: VERSION });
1745
- stopRoomChannelListener(roomId);
1746
- roomChannelListeners.set(
1747
- roomId,
1748
- // Returns the unsubscribe callback, that we store in the
1749
- // roomChannelListeners registry
1750
- onMessageFromPanel.subscribe((msg) => {
1751
- switch (msg.msg) {
1752
- case "room::subscribe": {
1753
- if (msg.roomId === roomId) {
1754
- startSyncStream(room);
1755
- }
1756
- break;
1757
- }
1758
- case "room::unsubscribe": {
1759
- if (msg.roomId === roomId) {
1760
- stopSyncStream(roomId);
1632
+ const optimisticUpdatesEventSource = makeEventSource();
1633
+ return {
1634
+ ...store,
1635
+ deleteThread(threadId) {
1636
+ store.set((state) => {
1637
+ return {
1638
+ ...state,
1639
+ threads: deleteKeyImmutable(state.threads, threadId),
1640
+ inboxNotifications: Object.fromEntries(
1641
+ Object.entries(state.inboxNotifications).filter(
1642
+ ([_id, notification]) => notification.kind === "thread" && notification.threadId === threadId
1643
+ )
1644
+ )
1645
+ };
1646
+ });
1647
+ },
1648
+ updateThreadAndNotification(thread, inboxNotification) {
1649
+ store.set((state) => {
1650
+ const existingThread = state.threads[thread.id];
1651
+ return {
1652
+ ...state,
1653
+ threads: existingThread === void 0 || compareThreads(thread, existingThread) === 1 ? { ...state.threads, [thread.id]: thread } : state.threads,
1654
+ inboxNotifications: inboxNotification === void 0 ? state.inboxNotifications : {
1655
+ ...state.inboxNotifications,
1656
+ [inboxNotification.id]: inboxNotification
1761
1657
  }
1762
- break;
1763
- }
1764
- }
1765
- })
1766
- );
1658
+ };
1659
+ });
1660
+ },
1661
+ updateThreadsAndNotifications(threads, inboxNotifications, deletedThreads, deletedInboxNotifications, queryKey) {
1662
+ store.set((state) => ({
1663
+ ...state,
1664
+ threads: applyThreadUpdates(state.threads, {
1665
+ newThreads: threads,
1666
+ deletedThreads
1667
+ }),
1668
+ inboxNotifications: applyNotificationsUpdates(
1669
+ state.inboxNotifications,
1670
+ {
1671
+ newInboxNotifications: inboxNotifications,
1672
+ deletedNotifications: deletedInboxNotifications
1673
+ }
1674
+ ),
1675
+ queries: queryKey !== void 0 ? {
1676
+ ...state.queries,
1677
+ [queryKey]: {
1678
+ isLoading: false
1679
+ }
1680
+ } : state.queries
1681
+ }));
1682
+ },
1683
+ updateRoomInboxNotificationSettings(roomId, settings, queryKey) {
1684
+ store.set((state) => ({
1685
+ ...state,
1686
+ notificationSettings: {
1687
+ ...state.notificationSettings,
1688
+ [roomId]: settings
1689
+ },
1690
+ queries: {
1691
+ ...state.queries,
1692
+ [queryKey]: {
1693
+ isLoading: false
1694
+ }
1695
+ }
1696
+ }));
1697
+ },
1698
+ pushOptimisticUpdate(optimisticUpdate) {
1699
+ optimisticUpdatesEventSource.notify(optimisticUpdate);
1700
+ store.set((state) => ({
1701
+ ...state,
1702
+ optimisticUpdates: [...state.optimisticUpdates, optimisticUpdate]
1703
+ }));
1704
+ },
1705
+ setQueryState(queryKey, queryState) {
1706
+ store.set((state) => ({
1707
+ ...state,
1708
+ queries: {
1709
+ ...state.queries,
1710
+ [queryKey]: queryState
1711
+ }
1712
+ }));
1713
+ },
1714
+ optimisticUpdatesEventSource
1715
+ };
1767
1716
  }
1768
- function unlinkDevTools(roomId) {
1769
- if (process.env.NODE_ENV === "production" || typeof window === "undefined") {
1770
- return;
1717
+ function deleteKeyImmutable(record, key) {
1718
+ if (Object.prototype.hasOwnProperty.call(record, key)) {
1719
+ const { [key]: _toDelete, ...rest } = record;
1720
+ return rest;
1771
1721
  }
1772
- stopSyncStream(roomId);
1773
- stopRoomChannelListener(roomId);
1774
- sendToPanel({
1775
- msg: "room::unavailable",
1776
- roomId
1777
- });
1722
+ return record;
1778
1723
  }
1779
-
1780
- // src/lib/stringify.ts
1781
- function stringify(object, ...args) {
1782
- if (typeof object !== "object" || object === null || Array.isArray(object)) {
1783
- return JSON.stringify(object, ...args);
1724
+ function compareThreads(thread1, thread2) {
1725
+ if (thread1.updatedAt && thread2.updatedAt) {
1726
+ return thread1.updatedAt > thread2.updatedAt ? 1 : thread1.updatedAt < thread2.updatedAt ? -1 : 0;
1727
+ } else if (thread1.updatedAt || thread2.updatedAt) {
1728
+ return thread1.updatedAt ? 1 : -1;
1784
1729
  }
1785
- const sortedObject = Object.keys(object).sort().reduce(
1786
- (sortedObject2, key) => {
1787
- sortedObject2[key] = object[key];
1788
- return sortedObject2;
1730
+ if (thread1.createdAt > thread2.createdAt) {
1731
+ return 1;
1732
+ } else if (thread1.createdAt < thread2.createdAt) {
1733
+ return -1;
1734
+ }
1735
+ return 0;
1736
+ }
1737
+ function applyOptimisticUpdates(state) {
1738
+ const result = {
1739
+ threads: {
1740
+ ...state.threads
1789
1741
  },
1790
- {}
1742
+ inboxNotifications: {
1743
+ ...state.inboxNotifications
1744
+ },
1745
+ notificationSettings: {
1746
+ ...state.notificationSettings
1747
+ }
1748
+ };
1749
+ for (const optimisticUpdate of state.optimisticUpdates) {
1750
+ switch (optimisticUpdate.type) {
1751
+ case "create-thread": {
1752
+ result.threads[optimisticUpdate.thread.id] = optimisticUpdate.thread;
1753
+ break;
1754
+ }
1755
+ case "edit-thread-metadata": {
1756
+ const thread = result.threads[optimisticUpdate.threadId];
1757
+ if (thread === void 0) {
1758
+ break;
1759
+ }
1760
+ if (thread.deletedAt !== void 0) {
1761
+ break;
1762
+ }
1763
+ if (thread.updatedAt !== void 0 && thread.updatedAt > optimisticUpdate.updatedAt) {
1764
+ break;
1765
+ }
1766
+ result.threads[thread.id] = {
1767
+ ...thread,
1768
+ updatedAt: optimisticUpdate.updatedAt,
1769
+ metadata: {
1770
+ ...thread.metadata,
1771
+ ...optimisticUpdate.metadata
1772
+ }
1773
+ };
1774
+ break;
1775
+ }
1776
+ case "create-comment": {
1777
+ const thread = result.threads[optimisticUpdate.comment.threadId];
1778
+ if (thread === void 0) {
1779
+ break;
1780
+ }
1781
+ result.threads[thread.id] = upsertComment(
1782
+ thread,
1783
+ optimisticUpdate.comment
1784
+ );
1785
+ const inboxNotification = Object.values(result.inboxNotifications).find(
1786
+ (notification) => notification.kind === "thread" && notification.threadId === thread.id
1787
+ );
1788
+ if (inboxNotification === void 0) {
1789
+ break;
1790
+ }
1791
+ result.inboxNotifications[inboxNotification.id] = {
1792
+ ...inboxNotification,
1793
+ notifiedAt: optimisticUpdate.comment.createdAt,
1794
+ readAt: optimisticUpdate.comment.createdAt
1795
+ };
1796
+ break;
1797
+ }
1798
+ case "edit-comment": {
1799
+ const thread = result.threads[optimisticUpdate.comment.threadId];
1800
+ if (thread === void 0) {
1801
+ break;
1802
+ }
1803
+ result.threads[thread.id] = upsertComment(
1804
+ thread,
1805
+ optimisticUpdate.comment
1806
+ );
1807
+ break;
1808
+ }
1809
+ case "delete-comment": {
1810
+ const thread = result.threads[optimisticUpdate.threadId];
1811
+ if (thread === void 0) {
1812
+ break;
1813
+ }
1814
+ result.threads[thread.id] = deleteComment(
1815
+ thread,
1816
+ optimisticUpdate.commentId,
1817
+ optimisticUpdate.deletedAt
1818
+ );
1819
+ break;
1820
+ }
1821
+ case "add-reaction": {
1822
+ const thread = result.threads[optimisticUpdate.threadId];
1823
+ if (thread === void 0) {
1824
+ break;
1825
+ }
1826
+ result.threads[thread.id] = addReaction(
1827
+ thread,
1828
+ optimisticUpdate.commentId,
1829
+ optimisticUpdate.reaction
1830
+ );
1831
+ break;
1832
+ }
1833
+ case "remove-reaction": {
1834
+ const thread = result.threads[optimisticUpdate.threadId];
1835
+ if (thread === void 0) {
1836
+ break;
1837
+ }
1838
+ result.threads[thread.id] = removeReaction(
1839
+ thread,
1840
+ optimisticUpdate.commentId,
1841
+ optimisticUpdate.emoji,
1842
+ optimisticUpdate.userId,
1843
+ optimisticUpdate.removedAt
1844
+ );
1845
+ break;
1846
+ }
1847
+ case "mark-inbox-notification-as-read": {
1848
+ result.inboxNotifications[optimisticUpdate.inboxNotificationId] = {
1849
+ ...state.inboxNotifications[optimisticUpdate.inboxNotificationId],
1850
+ readAt: optimisticUpdate.readAt
1851
+ };
1852
+ break;
1853
+ }
1854
+ case "mark-inbox-notifications-as-read": {
1855
+ for (const id in result.inboxNotifications) {
1856
+ result.inboxNotifications[id] = {
1857
+ ...result.inboxNotifications[id],
1858
+ readAt: optimisticUpdate.readAt
1859
+ };
1860
+ }
1861
+ break;
1862
+ }
1863
+ case "update-notification-settings": {
1864
+ result.notificationSettings[optimisticUpdate.roomId] = {
1865
+ ...result.notificationSettings[optimisticUpdate.roomId],
1866
+ ...optimisticUpdate.settings
1867
+ };
1868
+ }
1869
+ }
1870
+ }
1871
+ return result;
1872
+ }
1873
+ function applyThreadUpdates(existingThreads, updates) {
1874
+ const updatedThreads = { ...existingThreads };
1875
+ updates.newThreads.forEach((thread) => {
1876
+ const existingThread = updatedThreads[thread.id];
1877
+ if (existingThread) {
1878
+ const result = compareThreads(existingThread, thread);
1879
+ if (result === 1)
1880
+ return;
1881
+ }
1882
+ updatedThreads[thread.id] = thread;
1883
+ });
1884
+ updates.deletedThreads.forEach(({ id, deletedAt }) => {
1885
+ const existingThread = updatedThreads[id];
1886
+ if (existingThread === void 0)
1887
+ return;
1888
+ existingThread.deletedAt = deletedAt;
1889
+ existingThread.updatedAt = deletedAt;
1890
+ existingThread.comments = [];
1891
+ });
1892
+ return updatedThreads;
1893
+ }
1894
+ function applyNotificationsUpdates(existingInboxNotifications, updates) {
1895
+ const updatedInboxNotifications = { ...existingInboxNotifications };
1896
+ updates.newInboxNotifications.forEach((notification) => {
1897
+ const existingNotification = updatedInboxNotifications[notification.id];
1898
+ if (existingNotification) {
1899
+ const result = compareInboxNotifications(
1900
+ existingNotification,
1901
+ notification
1902
+ );
1903
+ if (result === 1)
1904
+ return;
1905
+ }
1906
+ updatedInboxNotifications[notification.id] = notification;
1907
+ });
1908
+ updates.deletedNotifications.forEach(
1909
+ ({ id }) => delete updatedInboxNotifications[id]
1791
1910
  );
1792
- return JSON.stringify(sortedObject, ...args);
1911
+ return updatedInboxNotifications;
1793
1912
  }
1794
-
1795
- // src/lib/batch.ts
1796
- var DEFAULT_SIZE = 50;
1797
- var DEFAULT_DELAY = 100;
1798
- var noop = () => {
1799
- };
1800
- var BatchCall = class {
1801
- constructor(args) {
1802
- this.resolve = noop;
1803
- this.reject = noop;
1804
- this.promise = new Promise(noop);
1805
- this.args = args;
1913
+ function compareInboxNotifications(inboxNotificationA, inboxNotificationB) {
1914
+ if (inboxNotificationA.notifiedAt > inboxNotificationB.notifiedAt) {
1915
+ return 1;
1916
+ } else if (inboxNotificationA.notifiedAt < inboxNotificationB.notifiedAt) {
1917
+ return -1;
1806
1918
  }
1807
- };
1808
- var Batch = class {
1809
- constructor(callback, options) {
1810
- this.queue = [];
1811
- this.error = false;
1812
- this.callback = callback;
1813
- this.size = options?.size ?? DEFAULT_SIZE;
1814
- this.delay = options?.delay ?? DEFAULT_DELAY;
1919
+ if (inboxNotificationA.readAt && inboxNotificationB.readAt) {
1920
+ return inboxNotificationA.readAt > inboxNotificationB.readAt ? 1 : inboxNotificationA.readAt < inboxNotificationB.readAt ? -1 : 0;
1921
+ } else if (inboxNotificationA.readAt || inboxNotificationB.readAt) {
1922
+ return inboxNotificationA.readAt ? 1 : -1;
1815
1923
  }
1816
- clearDelayTimeout() {
1817
- if (this.delayTimeoutId !== void 0) {
1818
- clearTimeout(this.delayTimeoutId);
1819
- this.delayTimeoutId = void 0;
1820
- }
1924
+ return 0;
1925
+ }
1926
+ function upsertComment(thread, comment) {
1927
+ if (thread.deletedAt !== void 0) {
1928
+ return thread;
1821
1929
  }
1822
- schedule() {
1823
- if (this.queue.length === this.size) {
1824
- void this.flush();
1825
- } else if (this.queue.length === 1) {
1826
- this.clearDelayTimeout();
1827
- this.delayTimeoutId = setTimeout(() => void this.flush(), this.delay);
1828
- }
1930
+ if (comment.threadId !== thread.id) {
1931
+ warn(
1932
+ `Comment ${comment.id} does not belong to thread ${thread.id}`
1933
+ );
1934
+ return thread;
1829
1935
  }
1830
- async flush() {
1831
- if (this.queue.length === 0) {
1832
- return;
1833
- }
1834
- const calls = this.queue.splice(0);
1835
- const args = calls.map((call) => call.args);
1836
- try {
1837
- const results = await this.callback(args);
1838
- this.error = false;
1839
- calls.forEach((call, index) => {
1840
- const result = results?.[index];
1841
- if (!Array.isArray(results)) {
1842
- call.reject(new Error("Callback must return an array."));
1843
- } else if (calls.length !== results.length) {
1844
- call.reject(
1845
- new Error(
1846
- `Callback must return an array of the same length as the number of provided items. Expected ${calls.length}, but got ${results.length}.`
1847
- )
1848
- );
1849
- } else if (result instanceof Error) {
1850
- call.reject(result);
1851
- } else {
1852
- call.resolve(result);
1853
- }
1854
- });
1855
- } catch (error3) {
1856
- this.error = true;
1857
- calls.forEach((call) => {
1858
- call.reject(error3);
1859
- });
1860
- }
1936
+ const existingComment = thread.comments.find(
1937
+ (existingComment2) => existingComment2.id === comment.id
1938
+ );
1939
+ if (existingComment === void 0) {
1940
+ const updatedAt = new Date(
1941
+ Math.max(thread.updatedAt?.getTime() || 0, comment.createdAt.getTime())
1942
+ );
1943
+ const updatedThread = {
1944
+ ...thread,
1945
+ updatedAt,
1946
+ comments: [...thread.comments, comment]
1947
+ };
1948
+ return updatedThread;
1861
1949
  }
1862
- get(...args) {
1863
- const existingCall = this.queue.find(
1864
- (call2) => stringify(call2.args) === stringify(args)
1950
+ if (existingComment.deletedAt !== void 0) {
1951
+ return thread;
1952
+ }
1953
+ if (existingComment.editedAt === void 0 || comment.editedAt === void 0 || existingComment.editedAt <= comment.editedAt) {
1954
+ const updatedComments = thread.comments.map(
1955
+ (existingComment2) => existingComment2.id === comment.id ? comment : existingComment2
1865
1956
  );
1866
- if (existingCall) {
1867
- return existingCall.promise;
1868
- }
1869
- const call = new BatchCall(args);
1870
- call.promise = new Promise((resolve, reject) => {
1871
- call.resolve = resolve;
1872
- call.reject = reject;
1873
- });
1874
- this.queue.push(call);
1875
- this.schedule();
1876
- return call.promise;
1957
+ const updatedThread = {
1958
+ ...thread,
1959
+ updatedAt: new Date(
1960
+ Math.max(
1961
+ thread.updatedAt?.getTime() || 0,
1962
+ comment.editedAt?.getTime() || comment.createdAt.getTime()
1963
+ )
1964
+ ),
1965
+ comments: updatedComments
1966
+ };
1967
+ return updatedThread;
1877
1968
  }
1878
- clear() {
1879
- this.queue = [];
1880
- this.error = false;
1881
- this.clearDelayTimeout();
1969
+ return thread;
1970
+ }
1971
+ function deleteComment(thread, commentId, deletedAt) {
1972
+ if (thread.deletedAt !== void 0) {
1973
+ return thread;
1882
1974
  }
1883
- };
1884
- function createBatchStore(callback, options) {
1885
- const batch = new Batch(callback, options);
1886
- const cache = /* @__PURE__ */ new Map();
1887
- const eventSource2 = makeEventSource();
1888
- function getCacheKey(args) {
1889
- return stringify(args);
1975
+ const existingComment = thread.comments.find(
1976
+ (comment) => comment.id === commentId
1977
+ );
1978
+ if (existingComment === void 0) {
1979
+ return thread;
1890
1980
  }
1891
- function setStateAndNotify(cacheKey, state) {
1892
- if (state) {
1893
- cache.set(cacheKey, state);
1894
- } else {
1895
- cache.delete(cacheKey);
1896
- }
1897
- eventSource2.notify(state);
1981
+ if (existingComment.deletedAt !== void 0) {
1982
+ return thread;
1898
1983
  }
1899
- async function get(...args) {
1900
- const cacheKey = getCacheKey(args);
1901
- if (cache.has(cacheKey)) {
1902
- return;
1903
- }
1904
- try {
1905
- setStateAndNotify(cacheKey, { isLoading: true });
1906
- const result = await batch.get(...args);
1907
- setStateAndNotify(cacheKey, { isLoading: false, data: result });
1908
- } catch (error3) {
1909
- setStateAndNotify(cacheKey, {
1910
- isLoading: false,
1911
- error: error3
1912
- });
1913
- }
1984
+ const updatedComments = thread.comments.map(
1985
+ (comment) => comment.id === commentId ? {
1986
+ ...comment,
1987
+ deletedAt,
1988
+ body: void 0
1989
+ } : comment
1990
+ );
1991
+ if (!updatedComments.some((comment) => comment.deletedAt === void 0)) {
1992
+ return {
1993
+ ...thread,
1994
+ deletedAt,
1995
+ updatedAt: deletedAt,
1996
+ comments: []
1997
+ };
1998
+ }
1999
+ return {
2000
+ ...thread,
2001
+ updatedAt: deletedAt,
2002
+ comments: updatedComments
2003
+ };
2004
+ }
2005
+ function addReaction(thread, commentId, reaction) {
2006
+ if (thread.deletedAt !== void 0) {
2007
+ return thread;
2008
+ }
2009
+ const existingComment = thread.comments.find(
2010
+ (comment) => comment.id === commentId
2011
+ );
2012
+ if (existingComment === void 0) {
2013
+ return thread;
1914
2014
  }
1915
- function getState(...args) {
1916
- const cacheKey = getCacheKey(args);
1917
- return cache.get(cacheKey);
2015
+ if (existingComment.deletedAt !== void 0) {
2016
+ return thread;
1918
2017
  }
2018
+ const updatedComments = thread.comments.map(
2019
+ (comment) => comment.id === commentId ? {
2020
+ ...comment,
2021
+ reactions: upsertReaction(comment.reactions, reaction)
2022
+ } : comment
2023
+ );
1919
2024
  return {
1920
- ...eventSource2,
1921
- get,
1922
- getState
2025
+ ...thread,
2026
+ updatedAt: new Date(
2027
+ Math.max(reaction.createdAt.getTime(), thread.updatedAt?.getTime() || 0)
2028
+ ),
2029
+ comments: updatedComments
1923
2030
  };
1924
2031
  }
1925
-
1926
- // src/lib/create-store.ts
1927
- function createStore(initialState) {
1928
- let state = initialState;
1929
- const subscribers = /* @__PURE__ */ new Set();
1930
- function get() {
1931
- return state;
2032
+ function removeReaction(thread, commentId, emoji, userId, removedAt) {
2033
+ if (thread.deletedAt !== void 0) {
2034
+ return thread;
1932
2035
  }
1933
- function set(callback) {
1934
- const newState = callback(state);
1935
- if (state === newState) {
1936
- return;
1937
- }
1938
- state = newState;
1939
- for (const subscriber of subscribers) {
1940
- subscriber(state);
1941
- }
2036
+ const existingComment = thread.comments.find(
2037
+ (comment) => comment.id === commentId
2038
+ );
2039
+ if (existingComment === void 0) {
2040
+ return thread;
1942
2041
  }
1943
- function subscribe(callback) {
1944
- subscribers.add(callback);
1945
- callback(state);
1946
- return () => {
1947
- subscribers.delete(callback);
1948
- };
2042
+ if (existingComment.deletedAt !== void 0) {
2043
+ return thread;
1949
2044
  }
2045
+ const updatedComments = thread.comments.map(
2046
+ (comment) => comment.id === commentId ? {
2047
+ ...comment,
2048
+ reactions: comment.reactions.map(
2049
+ (reaction) => reaction.emoji === emoji ? {
2050
+ ...reaction,
2051
+ users: reaction.users.filter((user) => user.id !== userId)
2052
+ } : reaction
2053
+ ).filter((reaction) => reaction.users.length > 0)
2054
+ // Remove reactions with no users left
2055
+ } : comment
2056
+ );
1950
2057
  return {
1951
- get,
1952
- set,
1953
- subscribe
2058
+ ...thread,
2059
+ updatedAt: new Date(
2060
+ Math.max(removedAt.getTime(), thread.updatedAt?.getTime() || 0)
2061
+ ),
2062
+ comments: updatedComments
1954
2063
  };
1955
2064
  }
1956
-
1957
- // src/lib/deprecation.ts
1958
- var _emittedDeprecationWarnings = /* @__PURE__ */ new Set();
1959
- function deprecate(message, key = message) {
1960
- if (process.env.NODE_ENV !== "production") {
1961
- if (!_emittedDeprecationWarnings.has(key)) {
1962
- _emittedDeprecationWarnings.add(key);
1963
- errorWithTitle("Deprecation warning", message);
1964
- }
2065
+ function upsertReaction(reactions, reaction) {
2066
+ const existingReaction = reactions.find(
2067
+ (existingReaction2) => existingReaction2.emoji === reaction.emoji
2068
+ );
2069
+ if (existingReaction === void 0) {
2070
+ return [
2071
+ ...reactions,
2072
+ {
2073
+ emoji: reaction.emoji,
2074
+ createdAt: reaction.createdAt,
2075
+ users: [{ id: reaction.userId }]
2076
+ }
2077
+ ];
1965
2078
  }
1966
- }
1967
- function deprecateIf(condition, message, key = message) {
1968
- if (process.env.NODE_ENV !== "production") {
1969
- if (condition) {
1970
- deprecate(message, key);
1971
- }
2079
+ if (existingReaction.users.some((user) => user.id === reaction.userId) === false) {
2080
+ return reactions.map(
2081
+ (existingReaction2) => existingReaction2.emoji === reaction.emoji ? {
2082
+ ...existingReaction2,
2083
+ users: [...existingReaction2.users, { id: reaction.userId }]
2084
+ } : existingReaction2
2085
+ );
1972
2086
  }
2087
+ return reactions;
1973
2088
  }
1974
- function throwUsageError(message) {
1975
- if (process.env.NODE_ENV !== "production") {
1976
- const usageError = new Error(message);
1977
- usageError.name = "Usage error";
1978
- errorWithTitle("Usage error", message);
1979
- throw usageError;
1980
- }
2089
+
2090
+ // src/comments/lib/select-notification-settings.ts
2091
+ function selectNotificationSettings(roomId, state) {
2092
+ const { notificationSettings } = applyOptimisticUpdates(state);
2093
+ return nn(notificationSettings[roomId]);
1981
2094
  }
1982
- function errorIf(condition, message) {
1983
- if (process.env.NODE_ENV !== "production") {
1984
- if (condition) {
1985
- throwUsageError(message);
1986
- }
1987
- }
2095
+
2096
+ // src/comments/lib/selected-inbox-notifications.ts
2097
+ function selectedInboxNotifications(state) {
2098
+ const result = applyOptimisticUpdates(state);
2099
+ return Object.values(result.inboxNotifications).sort(
2100
+ // Sort so that the most recent notifications are first
2101
+ (a, b) => b.notifiedAt.getTime() - a.notifiedAt.getTime()
2102
+ );
1988
2103
  }
1989
2104
 
1990
2105
  // src/convert-plain-data.ts
@@ -2035,6 +2150,18 @@ function convertToCommentUserReaction(data) {
2035
2150
  function convertToInboxNotificationData(data) {
2036
2151
  const notifiedAt = new Date(data.notifiedAt);
2037
2152
  const readAt = data.readAt ? new Date(data.readAt) : null;
2153
+ if ("activities" in data) {
2154
+ const activities = data.activities.map((activity) => ({
2155
+ ...activity,
2156
+ createdAt: new Date(activity.createdAt)
2157
+ }));
2158
+ return {
2159
+ ...data,
2160
+ notifiedAt,
2161
+ readAt,
2162
+ activities
2163
+ };
2164
+ }
2038
2165
  return {
2039
2166
  ...data,
2040
2167
  notifiedAt,
@@ -2051,139 +2178,8 @@ function convertToThreadDeleteInfo(data) {
2051
2178
  function convertToInboxNotificationDeleteInfo(data) {
2052
2179
  const deletedAt = new Date(data.deletedAt);
2053
2180
  return {
2054
- ...data,
2055
- deletedAt
2056
- };
2057
- }
2058
-
2059
- // src/lib/url.ts
2060
- function toURLSearchParams(params) {
2061
- const result = new URLSearchParams();
2062
- for (const [key, value] of Object.entries(params)) {
2063
- if (value !== void 0 && value !== null) {
2064
- result.set(key, value.toString());
2065
- }
2066
- }
2067
- return result;
2068
- }
2069
- function urljoin(baseUrl, path, params) {
2070
- const url = new URL(path, baseUrl);
2071
- if (params !== void 0) {
2072
- url.search = (params instanceof URLSearchParams ? params : toURLSearchParams(params)).toString();
2073
- }
2074
- return url.toString();
2075
- }
2076
-
2077
- // src/notifications.ts
2078
- var MARK_INBOX_NOTIFICATIONS_AS_READ_BATCH_DELAY = 50;
2079
- function createNotificationsApi({
2080
- baseUrl,
2081
- authManager,
2082
- currentUserIdStore,
2083
- fetcher
2084
- }) {
2085
- async function fetchJson(endpoint, options, params) {
2086
- const authValue = await authManager.getAuthValue({
2087
- requestedScope: "comments:read"
2088
- });
2089
- if (authValue.type === "secret" && authValue.token.parsed.k === "acc" /* ACCESS_TOKEN */) {
2090
- const userId = authValue.token.parsed.uid;
2091
- currentUserIdStore.set(() => userId);
2092
- }
2093
- const url = urljoin(baseUrl, `/v2/c${endpoint}`, params);
2094
- const response = await fetcher(url.toString(), {
2095
- ...options,
2096
- headers: {
2097
- ...options?.headers,
2098
- Authorization: `Bearer ${getAuthBearerHeaderFromAuthValue(authValue)}`
2099
- }
2100
- });
2101
- if (!response.ok) {
2102
- if (response.status >= 400 && response.status < 600) {
2103
- let error3;
2104
- try {
2105
- const errorBody = await response.json();
2106
- error3 = new NotificationsApiError(
2107
- errorBody.message,
2108
- response.status,
2109
- errorBody
2110
- );
2111
- } catch {
2112
- error3 = new NotificationsApiError(
2113
- response.statusText,
2114
- response.status
2115
- );
2116
- }
2117
- throw error3;
2118
- }
2119
- }
2120
- let body;
2121
- try {
2122
- body = await response.json();
2123
- } catch {
2124
- body = {};
2125
- }
2126
- return body;
2127
- }
2128
- async function getInboxNotifications(options) {
2129
- const json = await fetchJson("/inbox-notifications", void 0, {
2130
- limit: options?.limit,
2131
- since: options?.since?.toISOString()
2132
- });
2133
- return {
2134
- threads: json.threads.map((thread) => convertToThreadData(thread)),
2135
- inboxNotifications: json.inboxNotifications.map(
2136
- (notification) => convertToInboxNotificationData(notification)
2137
- ),
2138
- deletedThreads: json.deletedThreads.map(
2139
- (info) => convertToThreadDeleteInfo(info)
2140
- ),
2141
- deletedInboxNotifications: json.deletedInboxNotifications.map(
2142
- (info) => convertToInboxNotificationDeleteInfo(info)
2143
- ),
2144
- meta: {
2145
- requestedAt: new Date(json.meta.requestedAt)
2146
- }
2147
- };
2148
- }
2149
- async function getUnreadInboxNotificationsCount() {
2150
- const { count } = await fetchJson("/inbox-notifications/count");
2151
- return count;
2152
- }
2153
- async function markAllInboxNotificationsAsRead() {
2154
- await fetchJson("/inbox-notifications/read", {
2155
- method: "POST",
2156
- headers: {
2157
- "Content-Type": "application/json"
2158
- },
2159
- body: JSON.stringify({ inboxNotificationIds: "all" })
2160
- });
2161
- }
2162
- async function markInboxNotificationsAsRead(inboxNotificationIds) {
2163
- await fetchJson("/inbox-notifications/read", {
2164
- method: "POST",
2165
- headers: {
2166
- "Content-Type": "application/json"
2167
- },
2168
- body: JSON.stringify({ inboxNotificationIds })
2169
- });
2170
- }
2171
- const batchedMarkInboxNotificationsAsRead = new Batch(
2172
- async (batchedInboxNotificationIds) => {
2173
- const inboxNotificationIds = batchedInboxNotificationIds.flat();
2174
- await markInboxNotificationsAsRead(inboxNotificationIds);
2175
- return inboxNotificationIds;
2176
- },
2177
- { delay: MARK_INBOX_NOTIFICATIONS_AS_READ_BATCH_DELAY }
2178
- );
2179
- async function markInboxNotificationAsRead(inboxNotificationId) {
2180
- await batchedMarkInboxNotificationsAsRead.get(inboxNotificationId);
2181
- }
2182
- return {
2183
- getInboxNotifications,
2184
- getUnreadInboxNotificationsCount,
2185
- markAllInboxNotificationsAsRead,
2186
- markInboxNotificationAsRead
2181
+ ...data,
2182
+ deletedAt
2187
2183
  };
2188
2184
  }
2189
2185
 
@@ -2441,13 +2437,13 @@ var AbstractCrdt = class {
2441
2437
  }
2442
2438
  }
2443
2439
  /** @internal */
2444
- _attach(id, pool) {
2440
+ _attach(id, pool2) {
2445
2441
  if (this.__id || this.__pool) {
2446
2442
  throw new Error("Cannot attach node: already attached");
2447
2443
  }
2448
- pool.addNode(id, crdtAsLiveNode(this));
2444
+ pool2.addNode(id, crdtAsLiveNode(this));
2449
2445
  this.__id = id;
2450
- this.__pool = pool;
2446
+ this.__pool = pool2;
2451
2447
  }
2452
2448
  /** @internal */
2453
2449
  _detach() {
@@ -2526,7 +2522,7 @@ function isChildCrdt(crdt) {
2526
2522
  }
2527
2523
 
2528
2524
  // src/lib/nanoid.ts
2529
- function nanoid(length = 7) {
2525
+ function nanoid2(length = 7) {
2530
2526
  const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789,./;[]~!@#$%&*()_+=-";
2531
2527
  const len = alphabet.length;
2532
2528
  return Array.from(
@@ -2545,13 +2541,13 @@ var LiveRegister = class _LiveRegister extends AbstractCrdt {
2545
2541
  return this._data;
2546
2542
  }
2547
2543
  /** @internal */
2548
- static _deserialize([id, item], _parentToChildren, pool) {
2544
+ static _deserialize([id, item], _parentToChildren, pool2) {
2549
2545
  const register = new _LiveRegister(item.data);
2550
- register._attach(id, pool);
2546
+ register._attach(id, pool2);
2551
2547
  return register;
2552
2548
  }
2553
2549
  /** @internal */
2554
- _toOps(parentId, parentKey, pool) {
2550
+ _toOps(parentId, parentKey, pool2) {
2555
2551
  if (this._id === void 0) {
2556
2552
  throw new Error(
2557
2553
  "Cannot serialize register if parentId or parentKey is undefined"
@@ -2560,7 +2556,7 @@ var LiveRegister = class _LiveRegister extends AbstractCrdt {
2560
2556
  return [
2561
2557
  {
2562
2558
  type: 8 /* CREATE_REGISTER */,
2563
- opId: pool?.generateOpId(),
2559
+ opId: pool2?.generateOpId(),
2564
2560
  id: this._id,
2565
2561
  parentId,
2566
2562
  parentKey,
@@ -2596,7 +2592,7 @@ var LiveRegister = class _LiveRegister extends AbstractCrdt {
2596
2592
  _toTreeNode(key) {
2597
2593
  return {
2598
2594
  type: "Json",
2599
- id: this._id ?? nanoid(),
2595
+ id: this._id ?? nanoid2(),
2600
2596
  key,
2601
2597
  payload: this._data
2602
2598
  };
@@ -2632,15 +2628,15 @@ var LiveList = class _LiveList extends AbstractCrdt {
2632
2628
  }
2633
2629
  }
2634
2630
  /** @internal */
2635
- static _deserialize([id], parentToChildren, pool) {
2631
+ static _deserialize([id], parentToChildren, pool2) {
2636
2632
  const list = new _LiveList();
2637
- list._attach(id, pool);
2633
+ list._attach(id, pool2);
2638
2634
  const children = parentToChildren.get(id);
2639
2635
  if (children === void 0) {
2640
2636
  return list;
2641
2637
  }
2642
2638
  for (const [id2, crdt] of children) {
2643
- const child = deserialize([id2, crdt], parentToChildren, pool);
2639
+ const child = deserialize([id2, crdt], parentToChildren, pool2);
2644
2640
  child._setParentLink(list, crdt.parentKey);
2645
2641
  list._insertAndSort(child);
2646
2642
  }
@@ -2655,14 +2651,14 @@ var LiveList = class _LiveList extends AbstractCrdt {
2655
2651
  * This is quite unintuitive and should disappear as soon as
2656
2652
  * we introduce an explicit LiveList.Set operation
2657
2653
  */
2658
- _toOps(parentId, parentKey, pool) {
2654
+ _toOps(parentId, parentKey, pool2) {
2659
2655
  if (this._id === void 0) {
2660
2656
  throw new Error("Cannot serialize item is not attached");
2661
2657
  }
2662
2658
  const ops = [];
2663
2659
  const op = {
2664
2660
  id: this._id,
2665
- opId: pool?.generateOpId(),
2661
+ opId: pool2?.generateOpId(),
2666
2662
  type: 2 /* CREATE_LIST */,
2667
2663
  parentId,
2668
2664
  parentKey
@@ -2671,7 +2667,7 @@ var LiveList = class _LiveList extends AbstractCrdt {
2671
2667
  for (const item of this._items) {
2672
2668
  const parentKey2 = item._getParentKeyOrThrow();
2673
2669
  const childOps = HACK_addIntentAndDeletedIdToOperation(
2674
- item._toOps(this._id, parentKey2, pool),
2670
+ item._toOps(this._id, parentKey2, pool2),
2675
2671
  void 0
2676
2672
  );
2677
2673
  const childOpId = childOps[0].opId;
@@ -2703,10 +2699,10 @@ var LiveList = class _LiveList extends AbstractCrdt {
2703
2699
  );
2704
2700
  }
2705
2701
  /** @internal */
2706
- _attach(id, pool) {
2707
- super._attach(id, pool);
2702
+ _attach(id, pool2) {
2703
+ super._attach(id, pool2);
2708
2704
  for (const item of this._items) {
2709
- item._attach(pool.generateId(), pool);
2705
+ item._attach(pool2.generateId(), pool2);
2710
2706
  }
2711
2707
  }
2712
2708
  /** @internal */
@@ -3536,7 +3532,7 @@ var LiveList = class _LiveList extends AbstractCrdt {
3536
3532
  _toTreeNode(key) {
3537
3533
  return {
3538
3534
  type: "LiveList",
3539
- id: this._id ?? nanoid(),
3535
+ id: this._id ?? nanoid2(),
3540
3536
  key,
3541
3537
  payload: this._items.map(
3542
3538
  (item, index) => item.toTreeNode(index.toString())
@@ -3650,36 +3646,36 @@ var LiveMap = class _LiveMap extends AbstractCrdt {
3650
3646
  /**
3651
3647
  * @internal
3652
3648
  */
3653
- _toOps(parentId, parentKey, pool) {
3649
+ _toOps(parentId, parentKey, pool2) {
3654
3650
  if (this._id === void 0) {
3655
3651
  throw new Error("Cannot serialize item is not attached");
3656
3652
  }
3657
3653
  const ops = [];
3658
3654
  const op = {
3659
3655
  id: this._id,
3660
- opId: pool?.generateOpId(),
3656
+ opId: pool2?.generateOpId(),
3661
3657
  type: 7 /* CREATE_MAP */,
3662
3658
  parentId,
3663
3659
  parentKey
3664
3660
  };
3665
3661
  ops.push(op);
3666
3662
  for (const [key, value] of this._map) {
3667
- ops.push(...value._toOps(this._id, key, pool));
3663
+ ops.push(...value._toOps(this._id, key, pool2));
3668
3664
  }
3669
3665
  return ops;
3670
3666
  }
3671
3667
  /**
3672
3668
  * @internal
3673
3669
  */
3674
- static _deserialize([id, _item], parentToChildren, pool) {
3670
+ static _deserialize([id, _item], parentToChildren, pool2) {
3675
3671
  const map = new _LiveMap();
3676
- map._attach(id, pool);
3672
+ map._attach(id, pool2);
3677
3673
  const children = parentToChildren.get(id);
3678
3674
  if (children === void 0) {
3679
3675
  return map;
3680
3676
  }
3681
3677
  for (const [id2, crdt] of children) {
3682
- const child = deserialize([id2, crdt], parentToChildren, pool);
3678
+ const child = deserialize([id2, crdt], parentToChildren, pool2);
3683
3679
  child._setParentLink(map, crdt.parentKey);
3684
3680
  map._map.set(crdt.parentKey, child);
3685
3681
  map.invalidate();
@@ -3689,11 +3685,11 @@ var LiveMap = class _LiveMap extends AbstractCrdt {
3689
3685
  /**
3690
3686
  * @internal
3691
3687
  */
3692
- _attach(id, pool) {
3693
- super._attach(id, pool);
3688
+ _attach(id, pool2) {
3689
+ super._attach(id, pool2);
3694
3690
  for (const [_key, value] of this._map) {
3695
3691
  if (isLiveNode(value)) {
3696
- value._attach(pool.generateId(), pool);
3692
+ value._attach(pool2.generateId(), pool2);
3697
3693
  }
3698
3694
  }
3699
3695
  }
@@ -3953,7 +3949,7 @@ var LiveMap = class _LiveMap extends AbstractCrdt {
3953
3949
  _toTreeNode(key) {
3954
3950
  return {
3955
3951
  type: "LiveMap",
3956
- id: this._id ?? nanoid(),
3952
+ id: this._id ?? nanoid2(),
3957
3953
  key,
3958
3954
  payload: Array.from(this._map.entries()).map(
3959
3955
  ([key2, val]) => val.toTreeNode(key2)
@@ -4015,20 +4011,20 @@ var LiveObject = class _LiveObject extends AbstractCrdt {
4015
4011
  return [root, parentToChildren];
4016
4012
  }
4017
4013
  /** @internal */
4018
- static _fromItems(items, pool) {
4014
+ static _fromItems(items, pool2) {
4019
4015
  const [root, parentToChildren] = _LiveObject._buildRootAndParentToChildren(items);
4020
4016
  return _LiveObject._deserialize(
4021
4017
  root,
4022
4018
  parentToChildren,
4023
- pool
4019
+ pool2
4024
4020
  );
4025
4021
  }
4026
4022
  /** @internal */
4027
- _toOps(parentId, parentKey, pool) {
4023
+ _toOps(parentId, parentKey, pool2) {
4028
4024
  if (this._id === void 0) {
4029
4025
  throw new Error("Cannot serialize item is not attached");
4030
4026
  }
4031
- const opId = pool?.generateOpId();
4027
+ const opId = pool2?.generateOpId();
4032
4028
  const ops = [];
4033
4029
  const op = {
4034
4030
  type: 4 /* CREATE_OBJECT */,
@@ -4041,7 +4037,7 @@ var LiveObject = class _LiveObject extends AbstractCrdt {
4041
4037
  ops.push(op);
4042
4038
  for (const [key, value] of this._map) {
4043
4039
  if (isLiveNode(value)) {
4044
- ops.push(...value._toOps(this._id, key, pool));
4040
+ ops.push(...value._toOps(this._id, key, pool2));
4045
4041
  } else {
4046
4042
  op.data[key] = value;
4047
4043
  }
@@ -4049,19 +4045,19 @@ var LiveObject = class _LiveObject extends AbstractCrdt {
4049
4045
  return ops;
4050
4046
  }
4051
4047
  /** @internal */
4052
- static _deserialize([id, item], parentToChildren, pool) {
4048
+ static _deserialize([id, item], parentToChildren, pool2) {
4053
4049
  const liveObj = new _LiveObject(item.data);
4054
- liveObj._attach(id, pool);
4055
- return this._deserializeChildren(liveObj, parentToChildren, pool);
4050
+ liveObj._attach(id, pool2);
4051
+ return this._deserializeChildren(liveObj, parentToChildren, pool2);
4056
4052
  }
4057
4053
  /** @internal */
4058
- static _deserializeChildren(liveObj, parentToChildren, pool) {
4054
+ static _deserializeChildren(liveObj, parentToChildren, pool2) {
4059
4055
  const children = parentToChildren.get(nn(liveObj._id));
4060
4056
  if (children === void 0) {
4061
4057
  return liveObj;
4062
4058
  }
4063
4059
  for (const [id, crdt] of children) {
4064
- const child = deserializeToLson([id, crdt], parentToChildren, pool);
4060
+ const child = deserializeToLson([id, crdt], parentToChildren, pool2);
4065
4061
  if (isLiveStructure(child)) {
4066
4062
  child._setParentLink(liveObj, crdt.parentKey);
4067
4063
  }
@@ -4071,11 +4067,11 @@ var LiveObject = class _LiveObject extends AbstractCrdt {
4071
4067
  return liveObj;
4072
4068
  }
4073
4069
  /** @internal */
4074
- _attach(id, pool) {
4075
- super._attach(id, pool);
4070
+ _attach(id, pool2) {
4071
+ super._attach(id, pool2);
4076
4072
  for (const [_key, value] of this._map) {
4077
4073
  if (isLiveNode(value)) {
4078
- value._attach(pool.generateId(), pool);
4074
+ value._attach(pool2.generateId(), pool2);
4079
4075
  }
4080
4076
  }
4081
4077
  }
@@ -4464,7 +4460,7 @@ var LiveObject = class _LiveObject extends AbstractCrdt {
4464
4460
  }
4465
4461
  /** @internal */
4466
4462
  _toTreeNode(key) {
4467
- const nodeId = this._id ?? nanoid();
4463
+ const nodeId = this._id ?? nanoid2();
4468
4464
  return {
4469
4465
  type: "LiveObject",
4470
4466
  id: nodeId,
@@ -4521,35 +4517,35 @@ function isSameNodeOrChildOf(node, parent) {
4521
4517
  }
4522
4518
  return false;
4523
4519
  }
4524
- function deserialize([id, crdt], parentToChildren, pool) {
4520
+ function deserialize([id, crdt], parentToChildren, pool2) {
4525
4521
  switch (crdt.type) {
4526
4522
  case 0 /* OBJECT */: {
4527
- return LiveObject._deserialize([id, crdt], parentToChildren, pool);
4523
+ return LiveObject._deserialize([id, crdt], parentToChildren, pool2);
4528
4524
  }
4529
4525
  case 1 /* LIST */: {
4530
- return LiveList._deserialize([id, crdt], parentToChildren, pool);
4526
+ return LiveList._deserialize([id, crdt], parentToChildren, pool2);
4531
4527
  }
4532
4528
  case 2 /* MAP */: {
4533
- return LiveMap._deserialize([id, crdt], parentToChildren, pool);
4529
+ return LiveMap._deserialize([id, crdt], parentToChildren, pool2);
4534
4530
  }
4535
4531
  case 3 /* REGISTER */: {
4536
- return LiveRegister._deserialize([id, crdt], parentToChildren, pool);
4532
+ return LiveRegister._deserialize([id, crdt], parentToChildren, pool2);
4537
4533
  }
4538
4534
  default: {
4539
4535
  throw new Error("Unexpected CRDT type");
4540
4536
  }
4541
4537
  }
4542
4538
  }
4543
- function deserializeToLson([id, crdt], parentToChildren, pool) {
4539
+ function deserializeToLson([id, crdt], parentToChildren, pool2) {
4544
4540
  switch (crdt.type) {
4545
4541
  case 0 /* OBJECT */: {
4546
- return LiveObject._deserialize([id, crdt], parentToChildren, pool);
4542
+ return LiveObject._deserialize([id, crdt], parentToChildren, pool2);
4547
4543
  }
4548
4544
  case 1 /* LIST */: {
4549
- return LiveList._deserialize([id, crdt], parentToChildren, pool);
4545
+ return LiveList._deserialize([id, crdt], parentToChildren, pool2);
4550
4546
  }
4551
4547
  case 2 /* MAP */: {
4552
- return LiveMap._deserialize([id, crdt], parentToChildren, pool);
4548
+ return LiveMap._deserialize([id, crdt], parentToChildren, pool2);
4553
4549
  }
4554
4550
  case 3 /* REGISTER */: {
4555
4551
  return crdt.data;
@@ -4747,6 +4743,155 @@ function findNonSerializableValue(value, path = "") {
4747
4743
  return false;
4748
4744
  }
4749
4745
 
4746
+ // src/internal.ts
4747
+ var kInternal = Symbol();
4748
+
4749
+ // src/lib/stringify.ts
4750
+ function stringify(object, ...args) {
4751
+ if (typeof object !== "object" || object === null || Array.isArray(object)) {
4752
+ return JSON.stringify(object, ...args);
4753
+ }
4754
+ const sortedObject = Object.keys(object).sort().reduce(
4755
+ (sortedObject2, key) => {
4756
+ sortedObject2[key] = object[key];
4757
+ return sortedObject2;
4758
+ },
4759
+ {}
4760
+ );
4761
+ return JSON.stringify(sortedObject, ...args);
4762
+ }
4763
+
4764
+ // src/lib/batch.ts
4765
+ var DEFAULT_SIZE = 50;
4766
+ var DEFAULT_DELAY = 100;
4767
+ var noop = () => {
4768
+ };
4769
+ var BatchCall = class {
4770
+ constructor(args) {
4771
+ this.resolve = noop;
4772
+ this.reject = noop;
4773
+ this.promise = new Promise(noop);
4774
+ this.args = args;
4775
+ }
4776
+ };
4777
+ var Batch = class {
4778
+ constructor(callback, options) {
4779
+ this.queue = [];
4780
+ this.error = false;
4781
+ this.callback = callback;
4782
+ this.size = options?.size ?? DEFAULT_SIZE;
4783
+ this.delay = options?.delay ?? DEFAULT_DELAY;
4784
+ }
4785
+ clearDelayTimeout() {
4786
+ if (this.delayTimeoutId !== void 0) {
4787
+ clearTimeout(this.delayTimeoutId);
4788
+ this.delayTimeoutId = void 0;
4789
+ }
4790
+ }
4791
+ schedule() {
4792
+ if (this.queue.length === this.size) {
4793
+ void this.flush();
4794
+ } else if (this.queue.length === 1) {
4795
+ this.clearDelayTimeout();
4796
+ this.delayTimeoutId = setTimeout(() => void this.flush(), this.delay);
4797
+ }
4798
+ }
4799
+ async flush() {
4800
+ if (this.queue.length === 0) {
4801
+ return;
4802
+ }
4803
+ const calls = this.queue.splice(0);
4804
+ const args = calls.map((call) => call.args);
4805
+ try {
4806
+ const results = await this.callback(args);
4807
+ this.error = false;
4808
+ calls.forEach((call, index) => {
4809
+ const result = results?.[index];
4810
+ if (!Array.isArray(results)) {
4811
+ call.reject(new Error("Callback must return an array."));
4812
+ } else if (calls.length !== results.length) {
4813
+ call.reject(
4814
+ new Error(
4815
+ `Callback must return an array of the same length as the number of provided items. Expected ${calls.length}, but got ${results.length}.`
4816
+ )
4817
+ );
4818
+ } else if (result instanceof Error) {
4819
+ call.reject(result);
4820
+ } else {
4821
+ call.resolve(result);
4822
+ }
4823
+ });
4824
+ } catch (error3) {
4825
+ this.error = true;
4826
+ calls.forEach((call) => {
4827
+ call.reject(error3);
4828
+ });
4829
+ }
4830
+ }
4831
+ get(...args) {
4832
+ const existingCall = this.queue.find(
4833
+ (call2) => stringify(call2.args) === stringify(args)
4834
+ );
4835
+ if (existingCall) {
4836
+ return existingCall.promise;
4837
+ }
4838
+ const call = new BatchCall(args);
4839
+ call.promise = new Promise((resolve, reject) => {
4840
+ call.resolve = resolve;
4841
+ call.reject = reject;
4842
+ });
4843
+ this.queue.push(call);
4844
+ this.schedule();
4845
+ return call.promise;
4846
+ }
4847
+ clear() {
4848
+ this.queue = [];
4849
+ this.error = false;
4850
+ this.clearDelayTimeout();
4851
+ }
4852
+ };
4853
+ function createBatchStore(callback, options) {
4854
+ const batch = new Batch(callback, options);
4855
+ const cache = /* @__PURE__ */ new Map();
4856
+ const eventSource2 = makeEventSource();
4857
+ function getCacheKey(args) {
4858
+ return stringify(args);
4859
+ }
4860
+ function setStateAndNotify(cacheKey, state) {
4861
+ if (state) {
4862
+ cache.set(cacheKey, state);
4863
+ } else {
4864
+ cache.delete(cacheKey);
4865
+ }
4866
+ eventSource2.notify(state);
4867
+ }
4868
+ async function get(...args) {
4869
+ const cacheKey = getCacheKey(args);
4870
+ if (cache.has(cacheKey)) {
4871
+ return;
4872
+ }
4873
+ try {
4874
+ setStateAndNotify(cacheKey, { isLoading: true });
4875
+ const result = await batch.get(...args);
4876
+ setStateAndNotify(cacheKey, { isLoading: false, data: result });
4877
+ } catch (error3) {
4878
+ setStateAndNotify(cacheKey, {
4879
+ isLoading: false,
4880
+ error: error3
4881
+ });
4882
+ }
4883
+ }
4884
+ function getState(...args) {
4885
+ const cacheKey = getCacheKey(args);
4886
+ return cache.get(cacheKey);
4887
+ }
4888
+ return {
4889
+ ...eventSource2,
4890
+ get,
4891
+ getState
4892
+ };
4893
+ }
4894
+
4750
4895
  // src/lib/debug.ts
4751
4896
  function captureStackTrace(msg, traceRoot) {
4752
4897
  const errorLike = { name: msg };
@@ -4768,6 +4913,133 @@ function isJsonObject(data) {
4768
4913
  return !isJsonScalar(data) && !isJsonArray(data);
4769
4914
  }
4770
4915
 
4916
+ // src/lib/objectToQuery.ts
4917
+ var identifierRegex = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
4918
+ function objectToQuery(obj) {
4919
+ let filterList = [];
4920
+ const entries2 = Object.entries(obj);
4921
+ const keyValuePairs = [];
4922
+ const keyValuePairsWithOperator = [];
4923
+ const indexedKeys = [];
4924
+ entries2.forEach(([key, value]) => {
4925
+ if (!identifierRegex.test(key)) {
4926
+ throw new Error("Key must only contain letters, numbers, _");
4927
+ }
4928
+ if (isSimpleValue(value)) {
4929
+ keyValuePairs.push([key, value]);
4930
+ } else if (isValueWithOperator(value)) {
4931
+ keyValuePairsWithOperator.push([key, value]);
4932
+ } else if (typeof value === "object" && !("startsWith" in value)) {
4933
+ indexedKeys.push([key, value]);
4934
+ }
4935
+ });
4936
+ filterList = [
4937
+ ...getFiltersFromKeyValuePairs(keyValuePairs),
4938
+ ...getFiltersFromKeyValuePairsWithOperator(keyValuePairsWithOperator)
4939
+ ];
4940
+ indexedKeys.forEach(([key, value]) => {
4941
+ const nestedEntries = Object.entries(value);
4942
+ const nKeyValuePairs = [];
4943
+ const nKeyValuePairsWithOperator = [];
4944
+ nestedEntries.forEach(([nestedKey, nestedValue]) => {
4945
+ if (isStringEmpty(nestedKey)) {
4946
+ throw new Error("Key cannot be empty");
4947
+ }
4948
+ if (isSimpleValue(nestedValue)) {
4949
+ nKeyValuePairs.push([formatFilterKey(key, nestedKey), nestedValue]);
4950
+ } else if (isValueWithOperator(nestedValue)) {
4951
+ nKeyValuePairsWithOperator.push([
4952
+ formatFilterKey(key, nestedKey),
4953
+ nestedValue
4954
+ ]);
4955
+ }
4956
+ });
4957
+ filterList = [
4958
+ ...filterList,
4959
+ ...getFiltersFromKeyValuePairs(nKeyValuePairs),
4960
+ ...getFiltersFromKeyValuePairsWithOperator(nKeyValuePairsWithOperator)
4961
+ ];
4962
+ });
4963
+ return filterList.map(
4964
+ ({ key, operator, value }) => formatFilter(key, operator, formatFilterValue(value))
4965
+ ).join(" AND ");
4966
+ }
4967
+ var getFiltersFromKeyValuePairs = (keyValuePairs) => {
4968
+ const filters = [];
4969
+ keyValuePairs.forEach(([key, value]) => {
4970
+ filters.push({
4971
+ key,
4972
+ operator: ":",
4973
+ value
4974
+ });
4975
+ });
4976
+ return filters;
4977
+ };
4978
+ var getFiltersFromKeyValuePairsWithOperator = (keyValuePairsWithOperator) => {
4979
+ const filters = [];
4980
+ keyValuePairsWithOperator.forEach(([key, value]) => {
4981
+ if ("startsWith" in value && typeof value.startsWith === "string") {
4982
+ filters.push({
4983
+ key,
4984
+ operator: "^",
4985
+ value: value.startsWith
4986
+ });
4987
+ }
4988
+ });
4989
+ return filters;
4990
+ };
4991
+ var isSimpleValue = (value) => {
4992
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
4993
+ return true;
4994
+ }
4995
+ return false;
4996
+ };
4997
+ var isValueWithOperator = (value) => {
4998
+ if (typeof value === "object" && value !== null && "startsWith" in value) {
4999
+ return true;
5000
+ }
5001
+ return false;
5002
+ };
5003
+ var formatFilter = (key, operator, value) => {
5004
+ return `${key}${operator}${value}`;
5005
+ };
5006
+ var formatFilterKey = (key, nestedKey) => {
5007
+ if (nestedKey) {
5008
+ return `${key}[${JSON.stringify(nestedKey)}]`;
5009
+ }
5010
+ return key;
5011
+ };
5012
+ var formatFilterValue = (value) => {
5013
+ if (typeof value === "string") {
5014
+ if (isStringEmpty(value)) {
5015
+ throw new Error("Value cannot be empty");
5016
+ }
5017
+ return JSON.stringify(value);
5018
+ }
5019
+ return value.toString();
5020
+ };
5021
+ var isStringEmpty = (value) => {
5022
+ return !value || value.toString().trim() === "";
5023
+ };
5024
+
5025
+ // src/lib/url.ts
5026
+ function toURLSearchParams(params) {
5027
+ const result = new URLSearchParams();
5028
+ for (const [key, value] of Object.entries(params)) {
5029
+ if (value !== void 0 && value !== null) {
5030
+ result.set(key, value.toString());
5031
+ }
5032
+ }
5033
+ return result;
5034
+ }
5035
+ function urljoin(baseUrl, path, params) {
5036
+ const url = new URL(path, baseUrl);
5037
+ if (params !== void 0) {
5038
+ url.search = (params instanceof URLSearchParams ? params : toURLSearchParams(params)).toString();
5039
+ }
5040
+ return url.toString();
5041
+ }
5042
+
4771
5043
  // src/protocol/ClientMsg.ts
4772
5044
  var ClientMsgCode = /* @__PURE__ */ ((ClientMsgCode2) => {
4773
5045
  ClientMsgCode2[ClientMsgCode2["UPDATE_PRESENCE"] = 100] = "UPDATE_PRESENCE";
@@ -5070,19 +5342,20 @@ function createCommentsApi(roomId, getAuthValue, fetchClientApi) {
5070
5342
  return body;
5071
5343
  }
5072
5344
  async function getThreads(options) {
5345
+ let query;
5346
+ if (options?.query) {
5347
+ query = objectToQuery(options.query);
5348
+ }
5073
5349
  const response = await fetchCommentsApi(
5074
- "/threads/search",
5350
+ "/threads",
5075
5351
  {
5076
- since: options?.since?.toISOString()
5352
+ since: options?.since?.toISOString(),
5353
+ query
5077
5354
  },
5078
5355
  {
5079
- body: JSON.stringify({
5080
- ...options?.query?.metadata && { metadata: options.query.metadata }
5081
- }),
5082
5356
  headers: {
5083
5357
  "Content-Type": "application/json"
5084
- },
5085
- method: "POST"
5358
+ }
5086
5359
  }
5087
5360
  );
5088
5361
  if (response.ok) {
@@ -5138,23 +5411,20 @@ function createCommentsApi(roomId, getAuthValue, fetchClientApi) {
5138
5411
  commentId,
5139
5412
  threadId
5140
5413
  }) {
5141
- const thread = await fetchJson(
5142
- "/threads",
5143
- {
5144
- method: "POST",
5145
- headers: {
5146
- "Content-Type": "application/json"
5414
+ const thread = await fetchJson("/threads", {
5415
+ method: "POST",
5416
+ headers: {
5417
+ "Content-Type": "application/json"
5418
+ },
5419
+ body: JSON.stringify({
5420
+ id: threadId,
5421
+ comment: {
5422
+ id: commentId,
5423
+ body
5147
5424
  },
5148
- body: JSON.stringify({
5149
- id: threadId,
5150
- comment: {
5151
- id: commentId,
5152
- body
5153
- },
5154
- metadata
5155
- })
5156
- }
5157
- );
5425
+ metadata
5426
+ })
5427
+ });
5158
5428
  return convertToThreadData(thread);
5159
5429
  }
5160
5430
  async function editThreadMetadata({
@@ -5271,7 +5541,7 @@ function createCommentsApi(roomId, getAuthValue, fetchClientApi) {
5271
5541
  removeReaction: removeReaction2
5272
5542
  };
5273
5543
  }
5274
- var MARK_INBOX_NOTIFICATIONS_AS_READ_BATCH_DELAY2 = 50;
5544
+ var MARK_INBOX_NOTIFICATIONS_AS_READ_BATCH_DELAY = 50;
5275
5545
  function createRoom(options, config) {
5276
5546
  const initialPresence = typeof options.initialPresence === "function" ? options.initialPresence(config.roomId) : options.initialPresence;
5277
5547
  const initialStorage = typeof options.initialStorage === "function" ? options.initialStorage(config.roomId) : options.initialStorage;
@@ -5416,7 +5686,7 @@ function createRoom(options, config) {
5416
5686
  eventHub.error.notify(err);
5417
5687
  });
5418
5688
  });
5419
- const pool = {
5689
+ const pool2 = {
5420
5690
  roomId: config.roomId,
5421
5691
  getNode: (id) => context.nodes.get(id),
5422
5692
  addNode: (id, node) => void context.nodes.set(id, node),
@@ -5513,16 +5783,55 @@ function createRoom(options, config) {
5513
5783
  }
5514
5784
  });
5515
5785
  }
5516
- async function httpPostToRoom(endpoint, body) {
5786
+ async function httpPostToRoom(endpoint, body) {
5787
+ if (!managedSocket.authValue) {
5788
+ throw new Error("Not authorized");
5789
+ }
5790
+ return fetchClientApi(config.roomId, endpoint, managedSocket.authValue, {
5791
+ method: "POST",
5792
+ headers: {
5793
+ "Content-Type": "application/json"
5794
+ },
5795
+ body: JSON.stringify(body)
5796
+ });
5797
+ }
5798
+ async function createTextMention(userId, mentionId) {
5799
+ if (!managedSocket.authValue) {
5800
+ throw new Error("Not authorized");
5801
+ }
5802
+ return fetchClientApi(
5803
+ config.roomId,
5804
+ "/text-mentions",
5805
+ managedSocket.authValue,
5806
+ {
5807
+ method: "POST",
5808
+ headers: {
5809
+ "Content-Type": "application/json"
5810
+ },
5811
+ body: JSON.stringify({
5812
+ userId,
5813
+ mentionId
5814
+ })
5815
+ }
5816
+ );
5817
+ }
5818
+ async function deleteTextMention(mentionId) {
5517
5819
  if (!managedSocket.authValue) {
5518
5820
  throw new Error("Not authorized");
5519
5821
  }
5520
- return fetchClientApi(config.roomId, endpoint, managedSocket.authValue, {
5521
- method: "POST",
5522
- headers: {
5523
- "Content-Type": "application/json"
5524
- },
5525
- body: JSON.stringify(body)
5822
+ return fetchClientApi(
5823
+ config.roomId,
5824
+ `/text-mentions/${mentionId}`,
5825
+ managedSocket.authValue,
5826
+ {
5827
+ method: "DELETE"
5828
+ }
5829
+ );
5830
+ }
5831
+ async function reportTextEditor(type, rootKey) {
5832
+ return httpPostToRoom("/text-metadata", {
5833
+ type,
5834
+ rootKey
5526
5835
  });
5527
5836
  }
5528
5837
  function sendMessages(messages) {
@@ -5589,7 +5898,7 @@ function createRoom(options, config) {
5589
5898
  if (context.root !== void 0) {
5590
5899
  updateRoot(message.items, batchedUpdatesWrapper);
5591
5900
  } else {
5592
- context.root = LiveObject._fromItems(message.items, pool);
5901
+ context.root = LiveObject._fromItems(message.items, pool2);
5593
5902
  }
5594
5903
  const stackSizeBefore = context.undoStack.length;
5595
5904
  for (const key in context.initialStorage) {
@@ -5664,7 +5973,7 @@ function createRoom(options, config) {
5664
5973
  const createdNodeIds = /* @__PURE__ */ new Set();
5665
5974
  const ops = rawOps.map((op) => {
5666
5975
  if (op.type !== "presence" && !op.opId) {
5667
- return { ...op, opId: pool.generateOpId() };
5976
+ return { ...op, opId: pool2.generateOpId() };
5668
5977
  } else {
5669
5978
  return op;
5670
5979
  }
@@ -6395,7 +6704,7 @@ ${Array.from(traces).join("\n\n")}`
6395
6704
  await markInboxNotificationsAsRead(inboxNotificationIds);
6396
6705
  return inboxNotificationIds;
6397
6706
  },
6398
- { delay: MARK_INBOX_NOTIFICATIONS_AS_READ_BATCH_DELAY2 }
6707
+ { delay: MARK_INBOX_NOTIFICATIONS_AS_READ_BATCH_DELAY }
6399
6708
  );
6400
6709
  async function markInboxNotificationAsRead(inboxNotificationId) {
6401
6710
  await batchedMarkInboxNotificationsAsRead.get(inboxNotificationId);
@@ -6415,6 +6724,12 @@ ${Array.from(traces).join("\n\n")}`
6415
6724
  return context.nodes.size;
6416
6725
  },
6417
6726
  // prettier-ignore
6727
+ // send metadata when using a text editor
6728
+ reportTextEditor,
6729
+ // create a text mention when using a text editor
6730
+ createTextMention,
6731
+ // delete a text mention when using a text editor
6732
+ deleteTextMention,
6418
6733
  // Support for the Liveblocks browser extension
6419
6734
  getSelf_forDevTools: () => selfAsTreeNode.current,
6420
6735
  getOthers_forDevTools: () => others_forDevTools.current,
@@ -6599,469 +6914,405 @@ function makeCreateSocketDelegateForRoom(roomId, baseUrl, WebSocketPolyfill) {
6599
6914
  };
6600
6915
  }
6601
6916
 
6602
- // src/store.ts
6603
- function createClientStore() {
6604
- const store = createStore({
6605
- threads: {},
6606
- queries: {},
6607
- optimisticUpdates: [],
6608
- inboxNotifications: {},
6609
- notificationSettings: {}
6610
- });
6611
- return {
6612
- ...store,
6613
- deleteThread(threadId) {
6614
- store.set((state) => {
6615
- return {
6616
- ...state,
6617
- threads: deleteKeyImmutable(state.threads, threadId),
6618
- inboxNotifications: Object.fromEntries(
6619
- Object.entries(state.inboxNotifications).filter(
6620
- ([_id, notification]) => notification.threadId !== threadId
6621
- )
6622
- )
6623
- };
6624
- });
6625
- },
6626
- updateThreadAndNotification(thread, inboxNotification) {
6627
- store.set((state) => {
6628
- const existingThread = state.threads[thread.id];
6629
- return {
6630
- ...state,
6631
- threads: existingThread === void 0 || compareThreads(thread, existingThread) === 1 ? { ...state.threads, [thread.id]: thread } : state.threads,
6632
- inboxNotifications: inboxNotification === void 0 ? state.inboxNotifications : {
6633
- ...state.inboxNotifications,
6634
- [inboxNotification.id]: inboxNotification
6635
- }
6636
- };
6637
- });
6638
- },
6639
- updateThreadsAndNotifications(threads, inboxNotifications, deletedThreads, deletedInboxNotifications, queryKey) {
6640
- store.set((state) => ({
6641
- ...state,
6642
- threads: applyThreadUpdates(state.threads, {
6643
- newThreads: threads,
6644
- deletedThreads
6645
- }),
6646
- inboxNotifications: applyNotificationsUpdates(
6647
- state.inboxNotifications,
6648
- {
6649
- newInboxNotifications: inboxNotifications,
6650
- deletedNotifications: deletedInboxNotifications
6651
- }
6652
- ),
6653
- queries: queryKey !== void 0 ? {
6654
- ...state.queries,
6655
- [queryKey]: {
6656
- isLoading: false
6657
- }
6658
- } : state.queries
6659
- }));
6660
- },
6661
- updateRoomInboxNotificationSettings(roomId, settings, queryKey) {
6662
- store.set((state) => ({
6663
- ...state,
6664
- notificationSettings: {
6665
- ...state.notificationSettings,
6666
- [roomId]: settings
6667
- },
6668
- queries: {
6669
- ...state.queries,
6670
- [queryKey]: {
6671
- isLoading: false
6917
+ // src/comments/lib/selected-threads.ts
6918
+ function selectedThreads(roomId, state, options) {
6919
+ const result = applyOptimisticUpdates(state);
6920
+ const threads = Object.values(result.threads).filter(
6921
+ (thread) => {
6922
+ if (thread.roomId !== roomId)
6923
+ return false;
6924
+ if (thread.deletedAt !== void 0) {
6925
+ return false;
6926
+ }
6927
+ const query = options.query;
6928
+ if (!query)
6929
+ return true;
6930
+ for (const key in query.metadata) {
6931
+ const metadataValue = thread.metadata[key];
6932
+ const filterValue = query.metadata[key];
6933
+ if (assertFilterIsStartsWithOperator(filterValue) && assertMetadataValueIsString(metadataValue)) {
6934
+ if (metadataValue.startsWith(filterValue.startsWith)) {
6935
+ return true;
6672
6936
  }
6673
6937
  }
6674
- }));
6675
- },
6676
- pushOptimisticUpdate(optimisticUpdate) {
6677
- store.set((state) => ({
6678
- ...state,
6679
- optimisticUpdates: [...state.optimisticUpdates, optimisticUpdate]
6680
- }));
6681
- },
6682
- setQueryState(queryKey, queryState) {
6683
- store.set((state) => ({
6684
- ...state,
6685
- queries: {
6686
- ...state.queries,
6687
- [queryKey]: queryState
6938
+ if (metadataValue !== filterValue) {
6939
+ return false;
6688
6940
  }
6689
- }));
6941
+ }
6942
+ return true;
6690
6943
  }
6691
- };
6692
- }
6693
- function deleteKeyImmutable(record, key) {
6694
- if (Object.prototype.hasOwnProperty.call(record, key)) {
6695
- const { [key]: _toDelete, ...rest } = record;
6696
- return rest;
6697
- }
6698
- return record;
6944
+ );
6945
+ return threads.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
6699
6946
  }
6700
- function compareThreads(thread1, thread2) {
6701
- if (thread1.updatedAt && thread2.updatedAt) {
6702
- return thread1.updatedAt > thread2.updatedAt ? 1 : thread1.updatedAt < thread2.updatedAt ? -1 : 0;
6703
- } else if (thread1.updatedAt || thread2.updatedAt) {
6704
- return thread1.updatedAt ? 1 : -1;
6705
- }
6706
- if (thread1.createdAt > thread2.createdAt) {
6707
- return 1;
6708
- } else if (thread1.createdAt < thread2.createdAt) {
6709
- return -1;
6947
+ var assertFilterIsStartsWithOperator = (filter) => {
6948
+ if (typeof filter === "object" && typeof filter.startsWith === "string") {
6949
+ return true;
6950
+ } else {
6951
+ return false;
6710
6952
  }
6711
- return 0;
6712
- }
6713
- function applyOptimisticUpdates(state) {
6714
- const result = {
6715
- threads: {
6716
- ...state.threads
6717
- },
6718
- inboxNotifications: {
6719
- ...state.inboxNotifications
6720
- },
6721
- notificationSettings: {
6722
- ...state.notificationSettings
6723
- }
6724
- };
6725
- for (const optimisticUpdate of state.optimisticUpdates) {
6726
- switch (optimisticUpdate.type) {
6727
- case "create-thread": {
6728
- result.threads[optimisticUpdate.thread.id] = optimisticUpdate.thread;
6729
- break;
6730
- }
6731
- case "edit-thread-metadata": {
6732
- const thread = result.threads[optimisticUpdate.threadId];
6733
- if (thread === void 0) {
6734
- break;
6735
- }
6736
- if (thread.deletedAt !== void 0) {
6737
- break;
6738
- }
6739
- if (thread.updatedAt !== void 0 && thread.updatedAt > optimisticUpdate.updatedAt) {
6740
- break;
6741
- }
6742
- result.threads[thread.id] = {
6743
- ...thread,
6744
- updatedAt: optimisticUpdate.updatedAt,
6745
- metadata: {
6746
- ...thread.metadata,
6747
- ...optimisticUpdate.metadata
6748
- }
6749
- };
6750
- break;
6751
- }
6752
- case "create-comment": {
6753
- const thread = result.threads[optimisticUpdate.comment.threadId];
6754
- if (thread === void 0) {
6755
- break;
6756
- }
6757
- result.threads[thread.id] = upsertComment(
6758
- thread,
6759
- optimisticUpdate.comment
6760
- );
6761
- const inboxNotification = Object.values(result.inboxNotifications).find(
6762
- (notification) => notification.threadId === thread.id
6763
- );
6764
- if (inboxNotification === void 0) {
6765
- break;
6766
- }
6767
- result.inboxNotifications[inboxNotification.id] = {
6768
- ...inboxNotification,
6769
- notifiedAt: optimisticUpdate.comment.createdAt,
6770
- readAt: optimisticUpdate.comment.createdAt
6771
- };
6772
- break;
6773
- }
6774
- case "edit-comment": {
6775
- const thread = result.threads[optimisticUpdate.comment.threadId];
6776
- if (thread === void 0) {
6777
- break;
6778
- }
6779
- result.threads[thread.id] = upsertComment(
6780
- thread,
6781
- optimisticUpdate.comment
6782
- );
6783
- break;
6784
- }
6785
- case "delete-comment": {
6786
- const thread = result.threads[optimisticUpdate.threadId];
6787
- if (thread === void 0) {
6788
- break;
6789
- }
6790
- result.threads[thread.id] = deleteComment(
6791
- thread,
6792
- optimisticUpdate.commentId,
6793
- optimisticUpdate.deletedAt
6794
- );
6795
- break;
6796
- }
6797
- case "add-reaction": {
6798
- const thread = result.threads[optimisticUpdate.threadId];
6799
- if (thread === void 0) {
6800
- break;
6801
- }
6802
- result.threads[thread.id] = addReaction(
6803
- thread,
6804
- optimisticUpdate.commentId,
6805
- optimisticUpdate.reaction
6806
- );
6807
- break;
6808
- }
6809
- case "remove-reaction": {
6810
- const thread = result.threads[optimisticUpdate.threadId];
6811
- if (thread === void 0) {
6812
- break;
6813
- }
6814
- result.threads[thread.id] = removeReaction(
6815
- thread,
6816
- optimisticUpdate.commentId,
6817
- optimisticUpdate.emoji,
6818
- optimisticUpdate.userId,
6819
- optimisticUpdate.removedAt
6820
- );
6821
- break;
6822
- }
6823
- case "mark-inbox-notification-as-read": {
6824
- result.inboxNotifications[optimisticUpdate.inboxNotificationId] = {
6825
- ...state.inboxNotifications[optimisticUpdate.inboxNotificationId],
6826
- readAt: optimisticUpdate.readAt
6827
- };
6828
- break;
6829
- }
6830
- case "mark-inbox-notifications-as-read": {
6831
- for (const id in result.inboxNotifications) {
6832
- result.inboxNotifications[id] = {
6833
- ...result.inboxNotifications[id],
6834
- readAt: optimisticUpdate.readAt
6835
- };
6953
+ };
6954
+ var assertMetadataValueIsString = (value) => {
6955
+ return typeof value === "string";
6956
+ };
6957
+
6958
+ // src/constants.ts
6959
+ var DEFAULT_BASE_URL = "https://api.liveblocks.io";
6960
+
6961
+ // src/devtools/bridge.ts
6962
+ var _bridgeActive = false;
6963
+ function activateBridge(allowed) {
6964
+ _bridgeActive = allowed;
6965
+ }
6966
+ function sendToPanel(message, options) {
6967
+ if (process.env.NODE_ENV === "production" || typeof window === "undefined") {
6968
+ return;
6969
+ }
6970
+ const fullMsg = {
6971
+ ...message,
6972
+ source: "liveblocks-devtools-client"
6973
+ };
6974
+ if (!(options?.force || _bridgeActive)) {
6975
+ return;
6976
+ }
6977
+ window.postMessage(fullMsg, "*");
6978
+ }
6979
+ var eventSource = makeEventSource();
6980
+ if (process.env.NODE_ENV !== "production" && typeof window !== "undefined") {
6981
+ window.addEventListener("message", (event) => {
6982
+ if (event.source === window && event.data?.source === "liveblocks-devtools-panel") {
6983
+ eventSource.notify(event.data);
6984
+ } else {
6985
+ }
6986
+ });
6987
+ }
6988
+ var onMessageFromPanel = eventSource.observable;
6989
+
6990
+ // src/devtools/index.ts
6991
+ var VERSION = PKG_VERSION || "dev";
6992
+ var _devtoolsSetupHasRun = false;
6993
+ function setupDevTools(getAllRooms) {
6994
+ if (process.env.NODE_ENV === "production" || typeof window === "undefined") {
6995
+ return;
6996
+ }
6997
+ if (_devtoolsSetupHasRun) {
6998
+ return;
6999
+ }
7000
+ _devtoolsSetupHasRun = true;
7001
+ onMessageFromPanel.subscribe((msg) => {
7002
+ switch (msg.msg) {
7003
+ case "connect": {
7004
+ activateBridge(true);
7005
+ for (const roomId of getAllRooms()) {
7006
+ sendToPanel({
7007
+ msg: "room::available",
7008
+ roomId,
7009
+ clientVersion: VERSION
7010
+ });
6836
7011
  }
6837
7012
  break;
6838
7013
  }
6839
- case "update-notification-settings": {
6840
- result.notificationSettings[optimisticUpdate.roomId] = {
6841
- ...result.notificationSettings[optimisticUpdate.roomId],
6842
- ...optimisticUpdate.settings
6843
- };
6844
- }
6845
7014
  }
7015
+ });
7016
+ sendToPanel({ msg: "wake-up-devtools" }, { force: true });
7017
+ }
7018
+ var unsubsByRoomId = /* @__PURE__ */ new Map();
7019
+ function stopSyncStream(roomId) {
7020
+ const unsubs = unsubsByRoomId.get(roomId) ?? [];
7021
+ unsubsByRoomId.delete(roomId);
7022
+ for (const unsub of unsubs) {
7023
+ unsub();
6846
7024
  }
6847
- return result;
6848
7025
  }
6849
- function applyThreadUpdates(existingThreads, updates) {
6850
- const updatedThreads = { ...existingThreads };
6851
- updates.newThreads.forEach((thread) => {
6852
- const existingThread = updatedThreads[thread.id];
6853
- if (existingThread) {
6854
- const result = compareThreads(existingThread, thread);
6855
- if (result === 1)
6856
- return;
6857
- }
6858
- updatedThreads[thread.id] = thread;
6859
- });
6860
- updates.deletedThreads.forEach(({ id, deletedAt }) => {
6861
- const existingThread = updatedThreads[id];
6862
- if (existingThread === void 0)
6863
- return;
6864
- existingThread.deletedAt = deletedAt;
6865
- existingThread.updatedAt = deletedAt;
6866
- existingThread.comments = [];
7026
+ function startSyncStream(room) {
7027
+ stopSyncStream(room.id);
7028
+ fullSync(room);
7029
+ unsubsByRoomId.set(room.id, [
7030
+ // When the connection status changes
7031
+ room.events.status.subscribe(() => partialSyncConnection(room)),
7032
+ // When storage initializes, send the update
7033
+ room.events.storageDidLoad.subscribeOnce(() => partialSyncStorage(room)),
7034
+ // Any time storage updates, send the new storage root
7035
+ room.events.storage.subscribe(() => partialSyncStorage(room)),
7036
+ // Any time "me" or "others" updates, send the new values accordingly
7037
+ room.events.self.subscribe(() => partialSyncMe(room)),
7038
+ room.events.others.subscribe(() => partialSyncOthers(room)),
7039
+ // Any time ydoc is updated, forward the update
7040
+ room.events.ydoc.subscribe((update) => syncYdocUpdate(room, update)),
7041
+ // Any time a custom room event is received, forward it
7042
+ room.events.customEvent.subscribe(
7043
+ (eventData) => forwardEvent(room, eventData)
7044
+ )
7045
+ ]);
7046
+ }
7047
+ function syncYdocUpdate(room, update) {
7048
+ sendToPanel({
7049
+ msg: "room::sync::ydoc",
7050
+ roomId: room.id,
7051
+ update
6867
7052
  });
6868
- return updatedThreads;
6869
7053
  }
6870
- function applyNotificationsUpdates(existingInboxNotifications, updates) {
6871
- const updatedInboxNotifications = { ...existingInboxNotifications };
6872
- updates.newInboxNotifications.forEach((notification) => {
6873
- const existingNotification = updatedInboxNotifications[notification.id];
6874
- if (existingNotification) {
6875
- const result = compareInboxNotifications(
6876
- existingNotification,
6877
- notification
6878
- );
6879
- if (result === 1)
6880
- return;
7054
+ var loadedAt = Date.now();
7055
+ var eventCounter = 0;
7056
+ function nextEventId() {
7057
+ return `event-${loadedAt}-${eventCounter++}`;
7058
+ }
7059
+ function forwardEvent(room, eventData) {
7060
+ sendToPanel({
7061
+ msg: "room::events::custom-event",
7062
+ roomId: room.id,
7063
+ event: {
7064
+ type: "CustomEvent",
7065
+ id: nextEventId(),
7066
+ key: "Event",
7067
+ connectionId: eventData.connectionId,
7068
+ payload: eventData.event
6881
7069
  }
6882
- updatedInboxNotifications[notification.id] = notification;
6883
7070
  });
6884
- updates.deletedNotifications.forEach(
6885
- ({ id }) => delete updatedInboxNotifications[id]
6886
- );
6887
- return updatedInboxNotifications;
6888
7071
  }
6889
- function compareInboxNotifications(inboxNotificationA, inboxNotificationB) {
6890
- if (inboxNotificationA.notifiedAt > inboxNotificationB.notifiedAt) {
6891
- return 1;
6892
- } else if (inboxNotificationA.notifiedAt < inboxNotificationB.notifiedAt) {
6893
- return -1;
7072
+ function partialSyncConnection(room) {
7073
+ sendToPanel({
7074
+ msg: "room::sync::partial",
7075
+ roomId: room.id,
7076
+ status: room.getStatus()
7077
+ });
7078
+ }
7079
+ function partialSyncStorage(room) {
7080
+ const root = room.getStorageSnapshot();
7081
+ if (root) {
7082
+ sendToPanel({
7083
+ msg: "room::sync::partial",
7084
+ roomId: room.id,
7085
+ storage: root.toTreeNode("root").payload
7086
+ });
6894
7087
  }
6895
- if (inboxNotificationA.readAt && inboxNotificationB.readAt) {
6896
- return inboxNotificationA.readAt > inboxNotificationB.readAt ? 1 : inboxNotificationA.readAt < inboxNotificationB.readAt ? -1 : 0;
6897
- } else if (inboxNotificationA.readAt || inboxNotificationB.readAt) {
6898
- return inboxNotificationA.readAt ? 1 : -1;
7088
+ }
7089
+ function partialSyncMe(room) {
7090
+ const me = room[kInternal].getSelf_forDevTools();
7091
+ if (me) {
7092
+ sendToPanel({
7093
+ msg: "room::sync::partial",
7094
+ roomId: room.id,
7095
+ me
7096
+ });
6899
7097
  }
6900
- return 0;
6901
7098
  }
6902
- function upsertComment(thread, comment) {
6903
- if (thread.deletedAt !== void 0) {
6904
- return thread;
7099
+ function partialSyncOthers(room) {
7100
+ const others = room[kInternal].getOthers_forDevTools();
7101
+ if (others) {
7102
+ sendToPanel({
7103
+ msg: "room::sync::partial",
7104
+ roomId: room.id,
7105
+ others
7106
+ });
6905
7107
  }
6906
- if (comment.threadId !== thread.id) {
6907
- warn(
6908
- `Comment ${comment.id} does not belong to thread ${thread.id}`
6909
- );
6910
- return thread;
7108
+ }
7109
+ function fullSync(room) {
7110
+ const root = room.getStorageSnapshot();
7111
+ const me = room[kInternal].getSelf_forDevTools();
7112
+ const others = room[kInternal].getOthers_forDevTools();
7113
+ room.fetchYDoc("");
7114
+ sendToPanel({
7115
+ msg: "room::sync::full",
7116
+ roomId: room.id,
7117
+ status: room.getStatus(),
7118
+ storage: root?.toTreeNode("root").payload ?? null,
7119
+ me,
7120
+ others
7121
+ });
7122
+ }
7123
+ var roomChannelListeners = /* @__PURE__ */ new Map();
7124
+ function stopRoomChannelListener(roomId) {
7125
+ const listener = roomChannelListeners.get(roomId);
7126
+ roomChannelListeners.delete(roomId);
7127
+ if (listener) {
7128
+ listener();
6911
7129
  }
6912
- const existingComment = thread.comments.find(
6913
- (existingComment2) => existingComment2.id === comment.id
7130
+ }
7131
+ function linkDevTools(roomId, room) {
7132
+ if (process.env.NODE_ENV === "production" || typeof window === "undefined") {
7133
+ return;
7134
+ }
7135
+ sendToPanel({ msg: "room::available", roomId, clientVersion: VERSION });
7136
+ stopRoomChannelListener(roomId);
7137
+ roomChannelListeners.set(
7138
+ roomId,
7139
+ // Returns the unsubscribe callback, that we store in the
7140
+ // roomChannelListeners registry
7141
+ onMessageFromPanel.subscribe((msg) => {
7142
+ switch (msg.msg) {
7143
+ case "room::subscribe": {
7144
+ if (msg.roomId === roomId) {
7145
+ startSyncStream(room);
7146
+ }
7147
+ break;
7148
+ }
7149
+ case "room::unsubscribe": {
7150
+ if (msg.roomId === roomId) {
7151
+ stopSyncStream(roomId);
7152
+ }
7153
+ break;
7154
+ }
7155
+ }
7156
+ })
6914
7157
  );
6915
- if (existingComment === void 0) {
6916
- const updatedAt = new Date(
6917
- Math.max(thread.updatedAt?.getTime() || 0, comment.createdAt.getTime())
6918
- );
6919
- const updatedThread = {
6920
- ...thread,
6921
- updatedAt,
6922
- comments: [...thread.comments, comment]
6923
- };
6924
- return updatedThread;
7158
+ }
7159
+ function unlinkDevTools(roomId) {
7160
+ if (process.env.NODE_ENV === "production" || typeof window === "undefined") {
7161
+ return;
6925
7162
  }
6926
- if (existingComment.deletedAt !== void 0) {
6927
- return thread;
7163
+ stopSyncStream(roomId);
7164
+ stopRoomChannelListener(roomId);
7165
+ sendToPanel({
7166
+ msg: "room::unavailable",
7167
+ roomId
7168
+ });
7169
+ }
7170
+
7171
+ // src/lib/deprecation.ts
7172
+ var _emittedDeprecationWarnings = /* @__PURE__ */ new Set();
7173
+ function deprecate(message, key = message) {
7174
+ if (process.env.NODE_ENV !== "production") {
7175
+ if (!_emittedDeprecationWarnings.has(key)) {
7176
+ _emittedDeprecationWarnings.add(key);
7177
+ errorWithTitle("Deprecation warning", message);
7178
+ }
6928
7179
  }
6929
- if (existingComment.editedAt === void 0 || comment.editedAt === void 0 || existingComment.editedAt <= comment.editedAt) {
6930
- const updatedComments = thread.comments.map(
6931
- (existingComment2) => existingComment2.id === comment.id ? comment : existingComment2
6932
- );
6933
- const updatedThread = {
6934
- ...thread,
6935
- updatedAt: new Date(
6936
- Math.max(
6937
- thread.updatedAt?.getTime() || 0,
6938
- comment.editedAt?.getTime() || comment.createdAt.getTime()
6939
- )
6940
- ),
6941
- comments: updatedComments
6942
- };
6943
- return updatedThread;
7180
+ }
7181
+ function deprecateIf(condition, message, key = message) {
7182
+ if (process.env.NODE_ENV !== "production") {
7183
+ if (condition) {
7184
+ deprecate(message, key);
7185
+ }
6944
7186
  }
6945
- return thread;
6946
7187
  }
6947
- function deleteComment(thread, commentId, deletedAt) {
6948
- if (thread.deletedAt !== void 0) {
6949
- return thread;
7188
+ function throwUsageError(message) {
7189
+ if (process.env.NODE_ENV !== "production") {
7190
+ const usageError = new Error(message);
7191
+ usageError.name = "Usage error";
7192
+ errorWithTitle("Usage error", message);
7193
+ throw usageError;
6950
7194
  }
6951
- const existingComment = thread.comments.find(
6952
- (comment) => comment.id === commentId
6953
- );
6954
- if (existingComment === void 0) {
6955
- return thread;
7195
+ }
7196
+ function errorIf(condition, message) {
7197
+ if (process.env.NODE_ENV !== "production") {
7198
+ if (condition) {
7199
+ throwUsageError(message);
7200
+ }
6956
7201
  }
6957
- if (existingComment.deletedAt !== void 0) {
6958
- return thread;
7202
+ }
7203
+
7204
+ // src/notifications.ts
7205
+ var MARK_INBOX_NOTIFICATIONS_AS_READ_BATCH_DELAY2 = 50;
7206
+ function createNotificationsApi({
7207
+ baseUrl,
7208
+ authManager,
7209
+ currentUserIdStore,
7210
+ fetcher
7211
+ }) {
7212
+ async function fetchJson(endpoint, options, params) {
7213
+ const authValue = await authManager.getAuthValue({
7214
+ requestedScope: "comments:read"
7215
+ });
7216
+ if (authValue.type === "secret" && authValue.token.parsed.k === "acc" /* ACCESS_TOKEN */) {
7217
+ const userId = authValue.token.parsed.uid;
7218
+ currentUserIdStore.set(() => userId);
7219
+ }
7220
+ const url = urljoin(baseUrl, `/v2/c${endpoint}`, params);
7221
+ const response = await fetcher(url.toString(), {
7222
+ ...options,
7223
+ headers: {
7224
+ ...options?.headers,
7225
+ Authorization: `Bearer ${getAuthBearerHeaderFromAuthValue(authValue)}`
7226
+ }
7227
+ });
7228
+ if (!response.ok) {
7229
+ if (response.status >= 400 && response.status < 600) {
7230
+ let error3;
7231
+ try {
7232
+ const errorBody = await response.json();
7233
+ error3 = new NotificationsApiError(
7234
+ errorBody.message,
7235
+ response.status,
7236
+ errorBody
7237
+ );
7238
+ } catch {
7239
+ error3 = new NotificationsApiError(
7240
+ response.statusText,
7241
+ response.status
7242
+ );
7243
+ }
7244
+ throw error3;
7245
+ }
7246
+ }
7247
+ let body;
7248
+ try {
7249
+ body = await response.json();
7250
+ } catch {
7251
+ body = {};
7252
+ }
7253
+ return body;
6959
7254
  }
6960
- const updatedComments = thread.comments.map(
6961
- (comment) => comment.id === commentId ? {
6962
- ...comment,
6963
- deletedAt,
6964
- body: void 0
6965
- } : comment
6966
- );
6967
- if (!updatedComments.some((comment) => comment.deletedAt === void 0)) {
7255
+ async function getInboxNotifications(options) {
7256
+ const json = await fetchJson("/inbox-notifications", void 0, {
7257
+ limit: options?.limit,
7258
+ since: options?.since?.toISOString()
7259
+ });
6968
7260
  return {
6969
- ...thread,
6970
- deletedAt,
6971
- updatedAt: deletedAt,
6972
- comments: []
7261
+ threads: json.threads.map((thread) => convertToThreadData(thread)),
7262
+ inboxNotifications: json.inboxNotifications.map(
7263
+ (notification) => convertToInboxNotificationData(notification)
7264
+ ),
7265
+ deletedThreads: json.deletedThreads.map(
7266
+ (info) => convertToThreadDeleteInfo(info)
7267
+ ),
7268
+ deletedInboxNotifications: json.deletedInboxNotifications.map(
7269
+ (info) => convertToInboxNotificationDeleteInfo(info)
7270
+ ),
7271
+ meta: {
7272
+ requestedAt: new Date(json.meta.requestedAt)
7273
+ }
6973
7274
  };
6974
7275
  }
6975
- return {
6976
- ...thread,
6977
- updatedAt: deletedAt,
6978
- comments: updatedComments
6979
- };
6980
- }
6981
- function addReaction(thread, commentId, reaction) {
6982
- if (thread.deletedAt !== void 0) {
6983
- return thread;
6984
- }
6985
- const existingComment = thread.comments.find(
6986
- (comment) => comment.id === commentId
6987
- );
6988
- if (existingComment === void 0) {
6989
- return thread;
7276
+ async function getUnreadInboxNotificationsCount() {
7277
+ const { count } = await fetchJson("/inbox-notifications/count");
7278
+ return count;
6990
7279
  }
6991
- if (existingComment.deletedAt !== void 0) {
6992
- return thread;
7280
+ async function markAllInboxNotificationsAsRead() {
7281
+ await fetchJson("/inbox-notifications/read", {
7282
+ method: "POST",
7283
+ headers: {
7284
+ "Content-Type": "application/json"
7285
+ },
7286
+ body: JSON.stringify({ inboxNotificationIds: "all" })
7287
+ });
6993
7288
  }
6994
- const updatedComments = thread.comments.map(
6995
- (comment) => comment.id === commentId ? {
6996
- ...comment,
6997
- reactions: upsertReaction(comment.reactions, reaction)
6998
- } : comment
6999
- );
7000
- return {
7001
- ...thread,
7002
- updatedAt: new Date(
7003
- Math.max(reaction.createdAt.getTime(), thread.updatedAt?.getTime() || 0)
7004
- ),
7005
- comments: updatedComments
7006
- };
7007
- }
7008
- function removeReaction(thread, commentId, emoji, userId, removedAt) {
7009
- if (thread.deletedAt !== void 0) {
7010
- return thread;
7289
+ async function markInboxNotificationsAsRead(inboxNotificationIds) {
7290
+ await fetchJson("/inbox-notifications/read", {
7291
+ method: "POST",
7292
+ headers: {
7293
+ "Content-Type": "application/json"
7294
+ },
7295
+ body: JSON.stringify({ inboxNotificationIds })
7296
+ });
7011
7297
  }
7012
- const existingComment = thread.comments.find(
7013
- (comment) => comment.id === commentId
7298
+ const batchedMarkInboxNotificationsAsRead = new Batch(
7299
+ async (batchedInboxNotificationIds) => {
7300
+ const inboxNotificationIds = batchedInboxNotificationIds.flat();
7301
+ await markInboxNotificationsAsRead(inboxNotificationIds);
7302
+ return inboxNotificationIds;
7303
+ },
7304
+ { delay: MARK_INBOX_NOTIFICATIONS_AS_READ_BATCH_DELAY2 }
7014
7305
  );
7015
- if (existingComment === void 0) {
7016
- return thread;
7017
- }
7018
- if (existingComment.deletedAt !== void 0) {
7019
- return thread;
7306
+ async function markInboxNotificationAsRead(inboxNotificationId) {
7307
+ await batchedMarkInboxNotificationsAsRead.get(inboxNotificationId);
7020
7308
  }
7021
- const updatedComments = thread.comments.map(
7022
- (comment) => comment.id === commentId ? {
7023
- ...comment,
7024
- reactions: comment.reactions.map(
7025
- (reaction) => reaction.emoji === emoji ? {
7026
- ...reaction,
7027
- users: reaction.users.filter((user) => user.id !== userId)
7028
- } : reaction
7029
- ).filter((reaction) => reaction.users.length > 0)
7030
- // Remove reactions with no users left
7031
- } : comment
7032
- );
7033
7309
  return {
7034
- ...thread,
7035
- updatedAt: new Date(
7036
- Math.max(removedAt.getTime(), thread.updatedAt?.getTime() || 0)
7037
- ),
7038
- comments: updatedComments
7310
+ getInboxNotifications,
7311
+ getUnreadInboxNotificationsCount,
7312
+ markAllInboxNotificationsAsRead,
7313
+ markInboxNotificationAsRead
7039
7314
  };
7040
7315
  }
7041
- function upsertReaction(reactions, reaction) {
7042
- const existingReaction = reactions.find(
7043
- (existingReaction2) => existingReaction2.emoji === reaction.emoji
7044
- );
7045
- if (existingReaction === void 0) {
7046
- return [
7047
- ...reactions,
7048
- {
7049
- emoji: reaction.emoji,
7050
- createdAt: reaction.createdAt,
7051
- users: [{ id: reaction.userId }]
7052
- }
7053
- ];
7054
- }
7055
- if (existingReaction.users.some((user) => user.id === reaction.userId) === false) {
7056
- return reactions.map(
7057
- (existingReaction2) => existingReaction2.emoji === reaction.emoji ? {
7058
- ...existingReaction2,
7059
- users: [...existingReaction2.users, { id: reaction.userId }]
7060
- } : existingReaction2
7061
- );
7062
- }
7063
- return reactions;
7064
- }
7065
7316
 
7066
7317
  // src/client.ts
7067
7318
  var MIN_THROTTLE = 16;
@@ -7261,6 +7512,14 @@ function createClient(options) {
7261
7512
  markAllInboxNotificationsAsRead,
7262
7513
  markInboxNotificationAsRead
7263
7514
  },
7515
+ comments: {
7516
+ createThreadId,
7517
+ createCommentId,
7518
+ createInboxNotificationId,
7519
+ selectedThreads,
7520
+ selectedInboxNotifications,
7521
+ selectNotificationSettings
7522
+ },
7264
7523
  currentUserIdStore,
7265
7524
  resolveMentionSuggestions: clientOptions.resolveMentionSuggestions,
7266
7525
  cacheStore,
@@ -8121,6 +8380,7 @@ export {
8121
8380
  fancy_console_exports as console,
8122
8381
  convertToCommentData,
8123
8382
  convertToCommentUserReaction,
8383
+ convertToInboxNotificationData,
8124
8384
  convertToThreadData,
8125
8385
  createClient,
8126
8386
  deleteComment,
@@ -8144,6 +8404,7 @@ export {
8144
8404
  makePoller,
8145
8405
  makePosition,
8146
8406
  nn,
8407
+ objectToQuery,
8147
8408
  patchLiveObjectKey,
8148
8409
  raise,
8149
8410
  removeReaction,