@liveblocks/core 1.11.2 → 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.2";
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,629 +1542,644 @@ 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
- );
1767
- }
1768
- function unlinkDevTools(roomId) {
1769
- if (process.env.NODE_ENV === "production" || typeof window === "undefined") {
1770
- return;
1771
- }
1772
- stopSyncStream(roomId);
1773
- stopRoomChannelListener(roomId);
1774
- sendToPanel({
1775
- msg: "room::unavailable",
1776
- roomId
1777
- });
1778
- }
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);
1784
- }
1785
- const sortedObject = Object.keys(object).sort().reduce(
1786
- (sortedObject2, key) => {
1787
- sortedObject2[key] = object[key];
1788
- return sortedObject2;
1658
+ };
1659
+ });
1789
1660
  },
1790
- {}
1791
- );
1792
- return JSON.stringify(sortedObject, ...args);
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
+ };
1793
1716
  }
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;
1806
- }
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;
1717
+ function deleteKeyImmutable(record, key) {
1718
+ if (Object.prototype.hasOwnProperty.call(record, key)) {
1719
+ const { [key]: _toDelete, ...rest } = record;
1720
+ return rest;
1815
1721
  }
1816
- clearDelayTimeout() {
1817
- if (this.delayTimeoutId !== void 0) {
1818
- clearTimeout(this.delayTimeoutId);
1819
- this.delayTimeoutId = void 0;
1820
- }
1722
+ return record;
1723
+ }
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;
1821
1729
  }
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
- }
1730
+ if (thread1.createdAt > thread2.createdAt) {
1731
+ return 1;
1732
+ } else if (thread1.createdAt < thread2.createdAt) {
1733
+ return -1;
1829
1734
  }
1830
- async flush() {
1831
- if (this.queue.length === 0) {
1832
- return;
1735
+ return 0;
1736
+ }
1737
+ function applyOptimisticUpdates(state) {
1738
+ const result = {
1739
+ threads: {
1740
+ ...state.threads
1741
+ },
1742
+ inboxNotifications: {
1743
+ ...state.inboxNotifications
1744
+ },
1745
+ notificationSettings: {
1746
+ ...state.notificationSettings
1833
1747
  }
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);
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;
1853
1759
  }
1854
- });
1855
- } catch (error3) {
1856
- this.error = true;
1857
- calls.forEach((call) => {
1858
- call.reject(error3);
1859
- });
1860
- }
1861
- }
1862
- get(...args) {
1863
- const existingCall = this.queue.find(
1864
- (call2) => stringify(call2.args) === stringify(args)
1865
- );
1866
- if (existingCall) {
1867
- return existingCall.promise;
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
+ }
1868
1869
  }
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;
1877
- }
1878
- clear() {
1879
- this.queue = [];
1880
- this.error = false;
1881
- this.clearDelayTimeout();
1882
1870
  }
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);
1890
- }
1891
- function setStateAndNotify(cacheKey, state) {
1892
- if (state) {
1893
- cache.set(cacheKey, state);
1894
- } else {
1895
- cache.delete(cacheKey);
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;
1896
1881
  }
1897
- eventSource2.notify(state);
1898
- }
1899
- async function get(...args) {
1900
- const cacheKey = getCacheKey(args);
1901
- if (cache.has(cacheKey)) {
1882
+ updatedThreads[thread.id] = thread;
1883
+ });
1884
+ updates.deletedThreads.forEach(({ id, deletedAt }) => {
1885
+ const existingThread = updatedThreads[id];
1886
+ if (existingThread === void 0)
1902
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;
1903
1905
  }
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
- }
1906
+ updatedInboxNotifications[notification.id] = notification;
1907
+ });
1908
+ updates.deletedNotifications.forEach(
1909
+ ({ id }) => delete updatedInboxNotifications[id]
1910
+ );
1911
+ return updatedInboxNotifications;
1912
+ }
1913
+ function compareInboxNotifications(inboxNotificationA, inboxNotificationB) {
1914
+ if (inboxNotificationA.notifiedAt > inboxNotificationB.notifiedAt) {
1915
+ return 1;
1916
+ } else if (inboxNotificationA.notifiedAt < inboxNotificationB.notifiedAt) {
1917
+ return -1;
1914
1918
  }
1915
- function getState(...args) {
1916
- const cacheKey = getCacheKey(args);
1917
- return cache.get(cacheKey);
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;
1918
1923
  }
1919
- return {
1920
- ...eventSource2,
1921
- get,
1922
- getState
1923
- };
1924
+ return 0;
1924
1925
  }
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;
1926
+ function upsertComment(thread, comment) {
1927
+ if (thread.deletedAt !== void 0) {
1928
+ return thread;
1932
1929
  }
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
- }
1930
+ if (comment.threadId !== thread.id) {
1931
+ warn(
1932
+ `Comment ${comment.id} does not belong to thread ${thread.id}`
1933
+ );
1934
+ return thread;
1942
1935
  }
1943
- function subscribe(callback) {
1944
- subscribers.add(callback);
1945
- callback(state);
1946
- return () => {
1947
- subscribers.delete(callback);
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]
1948
1947
  };
1948
+ return updatedThread;
1949
1949
  }
1950
- return {
1951
- get,
1952
- set,
1953
- subscribe
1954
- };
1955
- }
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
- }
1950
+ if (existingComment.deletedAt !== void 0) {
1951
+ return thread;
1965
1952
  }
1966
- }
1967
- function deprecateIf(condition, message, key = message) {
1968
- if (process.env.NODE_ENV !== "production") {
1969
- if (condition) {
1970
- deprecate(message, key);
1971
- }
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
1956
+ );
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;
1972
1968
  }
1969
+ return thread;
1973
1970
  }
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;
1971
+ function deleteComment(thread, commentId, deletedAt) {
1972
+ if (thread.deletedAt !== void 0) {
1973
+ return thread;
1980
1974
  }
1981
- }
1982
- function errorIf(condition, message) {
1983
- if (process.env.NODE_ENV !== "production") {
1984
- if (condition) {
1985
- throwUsageError(message);
1986
- }
1975
+ const existingComment = thread.comments.find(
1976
+ (comment) => comment.id === commentId
1977
+ );
1978
+ if (existingComment === void 0) {
1979
+ return thread;
1987
1980
  }
1988
- }
1989
-
1990
- // src/convert-plain-data.ts
1991
- function convertToCommentData(data) {
1992
- const editedAt = data.editedAt ? new Date(data.editedAt) : void 0;
1993
- const createdAt = new Date(data.createdAt);
1994
- const reactions = data.reactions.map((reaction) => ({
1995
- ...reaction,
1996
- createdAt: new Date(reaction.createdAt)
1997
- }));
1998
- if (data.body) {
1999
- return {
2000
- ...data,
2001
- reactions,
2002
- createdAt,
2003
- editedAt
2004
- };
2005
- } else {
2006
- const deletedAt = new Date(data.deletedAt);
1981
+ if (existingComment.deletedAt !== void 0) {
1982
+ return thread;
1983
+ }
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)) {
2007
1992
  return {
2008
- ...data,
2009
- reactions,
2010
- createdAt,
2011
- editedAt,
2012
- deletedAt
1993
+ ...thread,
1994
+ deletedAt,
1995
+ updatedAt: deletedAt,
1996
+ comments: []
2013
1997
  };
2014
1998
  }
2015
- }
2016
- function convertToThreadData(data) {
2017
- const updatedAt = data.updatedAt ? new Date(data.updatedAt) : void 0;
2018
- const createdAt = new Date(data.createdAt);
2019
- const comments = data.comments.map(
2020
- (comment) => convertToCommentData(comment)
2021
- );
2022
- return {
2023
- ...data,
2024
- createdAt,
2025
- updatedAt,
2026
- comments
2027
- };
2028
- }
2029
- function convertToCommentUserReaction(data) {
2030
- return {
2031
- ...data,
2032
- createdAt: new Date(data.createdAt)
2033
- };
2034
- }
2035
- function convertToInboxNotificationData(data) {
2036
- const notifiedAt = new Date(data.notifiedAt);
2037
- const readAt = data.readAt ? new Date(data.readAt) : null;
2038
- return {
2039
- ...data,
2040
- notifiedAt,
2041
- readAt
2042
- };
2043
- }
2044
- function convertToThreadDeleteInfo(data) {
2045
- const deletedAt = new Date(data.deletedAt);
2046
1999
  return {
2047
- ...data,
2048
- deletedAt
2000
+ ...thread,
2001
+ updatedAt: deletedAt,
2002
+ comments: updatedComments
2049
2003
  };
2050
2004
  }
2051
- function convertToInboxNotificationDeleteInfo(data) {
2052
- const deletedAt = new Date(data.deletedAt);
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;
2014
+ }
2015
+ if (existingComment.deletedAt !== void 0) {
2016
+ return thread;
2017
+ }
2018
+ const updatedComments = thread.comments.map(
2019
+ (comment) => comment.id === commentId ? {
2020
+ ...comment,
2021
+ reactions: upsertReaction(comment.reactions, reaction)
2022
+ } : comment
2023
+ );
2053
2024
  return {
2054
- ...data,
2055
- deletedAt
2025
+ ...thread,
2026
+ updatedAt: new Date(
2027
+ Math.max(reaction.createdAt.getTime(), thread.updatedAt?.getTime() || 0)
2028
+ ),
2029
+ comments: updatedComments
2056
2030
  };
2057
2031
  }
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();
2032
+ function removeReaction(thread, commentId, emoji, userId, removedAt) {
2033
+ if (thread.deletedAt !== void 0) {
2034
+ return thread;
2073
2035
  }
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;
2036
+ const existingComment = thread.comments.find(
2037
+ (comment) => comment.id === commentId
2038
+ );
2039
+ if (existingComment === void 0) {
2040
+ return thread;
2127
2041
  }
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
- };
2042
+ if (existingComment.deletedAt !== void 0) {
2043
+ return thread;
2148
2044
  }
2149
- async function getUnreadInboxNotificationsCount() {
2150
- const { count } = await fetchJson("/inbox-notifications/count");
2151
- return count;
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
+ );
2057
+ return {
2058
+ ...thread,
2059
+ updatedAt: new Date(
2060
+ Math.max(removedAt.getTime(), thread.updatedAt?.getTime() || 0)
2061
+ ),
2062
+ comments: updatedComments
2063
+ };
2064
+ }
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
+ ];
2152
2078
  }
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
- });
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
+ );
2161
2086
  }
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
- });
2087
+ return reactions;
2088
+ }
2089
+
2090
+ // src/comments/lib/select-notification-settings.ts
2091
+ function selectNotificationSettings(roomId, state) {
2092
+ const { notificationSettings } = applyOptimisticUpdates(state);
2093
+ return nn(notificationSettings[roomId]);
2094
+ }
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
+ );
2103
+ }
2104
+
2105
+ // src/convert-plain-data.ts
2106
+ function convertToCommentData(data) {
2107
+ const editedAt = data.editedAt ? new Date(data.editedAt) : void 0;
2108
+ const createdAt = new Date(data.createdAt);
2109
+ const reactions = data.reactions.map((reaction) => ({
2110
+ ...reaction,
2111
+ createdAt: new Date(reaction.createdAt)
2112
+ }));
2113
+ if (data.body) {
2114
+ return {
2115
+ ...data,
2116
+ reactions,
2117
+ createdAt,
2118
+ editedAt
2119
+ };
2120
+ } else {
2121
+ const deletedAt = new Date(data.deletedAt);
2122
+ return {
2123
+ ...data,
2124
+ reactions,
2125
+ createdAt,
2126
+ editedAt,
2127
+ deletedAt
2128
+ };
2170
2129
  }
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 }
2130
+ }
2131
+ function convertToThreadData(data) {
2132
+ const updatedAt = data.updatedAt ? new Date(data.updatedAt) : void 0;
2133
+ const createdAt = new Date(data.createdAt);
2134
+ const comments = data.comments.map(
2135
+ (comment) => convertToCommentData(comment)
2178
2136
  );
2179
- async function markInboxNotificationAsRead(inboxNotificationId) {
2180
- await batchedMarkInboxNotificationsAsRead.get(inboxNotificationId);
2137
+ return {
2138
+ ...data,
2139
+ createdAt,
2140
+ updatedAt,
2141
+ comments
2142
+ };
2143
+ }
2144
+ function convertToCommentUserReaction(data) {
2145
+ return {
2146
+ ...data,
2147
+ createdAt: new Date(data.createdAt)
2148
+ };
2149
+ }
2150
+ function convertToInboxNotificationData(data) {
2151
+ const notifiedAt = new Date(data.notifiedAt);
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
+ };
2181
2164
  }
2182
2165
  return {
2183
- getInboxNotifications,
2184
- getUnreadInboxNotificationsCount,
2185
- markAllInboxNotificationsAsRead,
2186
- markInboxNotificationAsRead
2166
+ ...data,
2167
+ notifiedAt,
2168
+ readAt
2169
+ };
2170
+ }
2171
+ function convertToThreadDeleteInfo(data) {
2172
+ const deletedAt = new Date(data.deletedAt);
2173
+ return {
2174
+ ...data,
2175
+ deletedAt
2176
+ };
2177
+ }
2178
+ function convertToInboxNotificationDeleteInfo(data) {
2179
+ const deletedAt = new Date(data.deletedAt);
2180
+ return {
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;
@@ -4668,83 +4664,232 @@ function getTreesDiffOperations(currentItems, newItems) {
4668
4664
  break;
4669
4665
  }
4670
4666
  }
4671
- });
4672
- return ops;
4673
- }
4674
- function mergeObjectStorageUpdates(first, second) {
4675
- const updates = first.updates;
4676
- for (const [key, value] of entries(second.updates)) {
4677
- updates[key] = value;
4678
- }
4679
- return {
4680
- ...second,
4681
- updates
4682
- };
4683
- }
4684
- function mergeMapStorageUpdates(first, second) {
4685
- const updates = first.updates;
4686
- for (const [key, value] of entries(second.updates)) {
4687
- updates[key] = value;
4667
+ });
4668
+ return ops;
4669
+ }
4670
+ function mergeObjectStorageUpdates(first, second) {
4671
+ const updates = first.updates;
4672
+ for (const [key, value] of entries(second.updates)) {
4673
+ updates[key] = value;
4674
+ }
4675
+ return {
4676
+ ...second,
4677
+ updates
4678
+ };
4679
+ }
4680
+ function mergeMapStorageUpdates(first, second) {
4681
+ const updates = first.updates;
4682
+ for (const [key, value] of entries(second.updates)) {
4683
+ updates[key] = value;
4684
+ }
4685
+ return {
4686
+ ...second,
4687
+ updates
4688
+ };
4689
+ }
4690
+ function mergeListStorageUpdates(first, second) {
4691
+ const updates = first.updates;
4692
+ return {
4693
+ ...second,
4694
+ updates: updates.concat(second.updates)
4695
+ };
4696
+ }
4697
+ function mergeStorageUpdates(first, second) {
4698
+ if (first === void 0) {
4699
+ return second;
4700
+ }
4701
+ if (first.type === "LiveObject" && second.type === "LiveObject") {
4702
+ return mergeObjectStorageUpdates(first, second);
4703
+ } else if (first.type === "LiveMap" && second.type === "LiveMap") {
4704
+ return mergeMapStorageUpdates(first, second);
4705
+ } else if (first.type === "LiveList" && second.type === "LiveList") {
4706
+ return mergeListStorageUpdates(first, second);
4707
+ } else {
4708
+ }
4709
+ return second;
4710
+ }
4711
+ function isPlain(value) {
4712
+ const type = typeof value;
4713
+ return value === void 0 || value === null || type === "string" || type === "boolean" || type === "number" || Array.isArray(value) || isPlainObject(value);
4714
+ }
4715
+ function findNonSerializableValue(value, path = "") {
4716
+ if (!isPlain) {
4717
+ return {
4718
+ path: path || "root",
4719
+ value
4720
+ };
4721
+ }
4722
+ if (typeof value !== "object" || value === null) {
4723
+ return false;
4724
+ }
4725
+ for (const [key, nestedValue] of Object.entries(value)) {
4726
+ const nestedPath = path ? path + "." + key : key;
4727
+ if (!isPlain(nestedValue)) {
4728
+ return {
4729
+ path: nestedPath,
4730
+ value: nestedValue
4731
+ };
4732
+ }
4733
+ if (typeof nestedValue === "object") {
4734
+ const nonSerializableNestedValue = findNonSerializableValue(
4735
+ nestedValue,
4736
+ nestedPath
4737
+ );
4738
+ if (nonSerializableNestedValue) {
4739
+ return nonSerializableNestedValue;
4740
+ }
4741
+ }
4742
+ }
4743
+ return false;
4744
+ }
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
+ }
4688
4830
  }
4689
- return {
4690
- ...second,
4691
- updates
4692
- };
4693
- }
4694
- function mergeListStorageUpdates(first, second) {
4695
- const updates = first.updates;
4696
- return {
4697
- ...second,
4698
- updates: updates.concat(second.updates)
4699
- };
4700
- }
4701
- function mergeStorageUpdates(first, second) {
4702
- if (first === void 0) {
4703
- return second;
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;
4704
4846
  }
4705
- if (first.type === "LiveObject" && second.type === "LiveObject") {
4706
- return mergeObjectStorageUpdates(first, second);
4707
- } else if (first.type === "LiveMap" && second.type === "LiveMap") {
4708
- return mergeMapStorageUpdates(first, second);
4709
- } else if (first.type === "LiveList" && second.type === "LiveList") {
4710
- return mergeListStorageUpdates(first, second);
4711
- } else {
4847
+ clear() {
4848
+ this.queue = [];
4849
+ this.error = false;
4850
+ this.clearDelayTimeout();
4712
4851
  }
4713
- return second;
4714
- }
4715
- function isPlain(value) {
4716
- const type = typeof value;
4717
- return value === void 0 || value === null || type === "string" || type === "boolean" || type === "number" || Array.isArray(value) || isPlainObject(value);
4718
- }
4719
- function findNonSerializableValue(value, path = "") {
4720
- if (!isPlain) {
4721
- return {
4722
- path: path || "root",
4723
- value
4724
- };
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);
4725
4859
  }
4726
- if (typeof value !== "object" || value === null) {
4727
- return false;
4860
+ function setStateAndNotify(cacheKey, state) {
4861
+ if (state) {
4862
+ cache.set(cacheKey, state);
4863
+ } else {
4864
+ cache.delete(cacheKey);
4865
+ }
4866
+ eventSource2.notify(state);
4728
4867
  }
4729
- for (const [key, nestedValue] of Object.entries(value)) {
4730
- const nestedPath = path ? path + "." + key : key;
4731
- if (!isPlain(nestedValue)) {
4732
- return {
4733
- path: nestedPath,
4734
- value: nestedValue
4735
- };
4868
+ async function get(...args) {
4869
+ const cacheKey = getCacheKey(args);
4870
+ if (cache.has(cacheKey)) {
4871
+ return;
4736
4872
  }
4737
- if (typeof nestedValue === "object") {
4738
- const nonSerializableNestedValue = findNonSerializableValue(
4739
- nestedValue,
4740
- nestedPath
4741
- );
4742
- if (nonSerializableNestedValue) {
4743
- return nonSerializableNestedValue;
4744
- }
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
+ });
4745
4882
  }
4746
4883
  }
4747
- return false;
4884
+ function getState(...args) {
4885
+ const cacheKey = getCacheKey(args);
4886
+ return cache.get(cacheKey);
4887
+ }
4888
+ return {
4889
+ ...eventSource2,
4890
+ get,
4891
+ getState
4892
+ };
4748
4893
  }
4749
4894
 
4750
4895
  // src/lib/debug.ts
@@ -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),
@@ -5436,7 +5706,9 @@ function createRoom(options, config) {
5436
5706
  }
5437
5707
  }
5438
5708
  if (activeBatch) {
5439
- activeBatch.ops.push(...ops);
5709
+ for (const op of ops) {
5710
+ activeBatch.ops.push(op);
5711
+ }
5440
5712
  for (const [key, value] of storageUpdates) {
5441
5713
  activeBatch.updates.storageUpdates.set(
5442
5714
  key,
@@ -5511,16 +5783,55 @@ function createRoom(options, config) {
5511
5783
  }
5512
5784
  });
5513
5785
  }
5514
- async function httpPostToRoom(endpoint, body) {
5515
- if (!managedSocket.authValue) {
5516
- throw new Error("Not authorized");
5517
- }
5518
- return fetchClientApi(config.roomId, endpoint, managedSocket.authValue, {
5519
- method: "POST",
5520
- headers: {
5521
- "Content-Type": "application/json"
5522
- },
5523
- body: JSON.stringify(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) {
5819
+ if (!managedSocket.authValue) {
5820
+ throw new Error("Not authorized");
5821
+ }
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
5524
5835
  });
5525
5836
  }
5526
5837
  function sendMessages(messages) {
@@ -5587,7 +5898,7 @@ function createRoom(options, config) {
5587
5898
  if (context.root !== void 0) {
5588
5899
  updateRoot(message.items, batchedUpdatesWrapper);
5589
5900
  } else {
5590
- context.root = LiveObject._fromItems(message.items, pool);
5901
+ context.root = LiveObject._fromItems(message.items, pool2);
5591
5902
  }
5592
5903
  const stackSizeBefore = context.undoStack.length;
5593
5904
  for (const key in context.initialStorage) {
@@ -5662,7 +5973,7 @@ function createRoom(options, config) {
5662
5973
  const createdNodeIds = /* @__PURE__ */ new Set();
5663
5974
  const ops = rawOps.map((op) => {
5664
5975
  if (op.type !== "presence" && !op.opId) {
5665
- return { ...op, opId: pool.generateOpId() };
5976
+ return { ...op, opId: pool2.generateOpId() };
5666
5977
  } else {
5667
5978
  return op;
5668
5979
  }
@@ -6115,7 +6426,10 @@ ${Array.from(traces).join("\n\n")}`
6115
6426
  flushNowOrSoon();
6116
6427
  }
6117
6428
  function dispatchOps(ops) {
6118
- context.buffer.storageOperations.push(...ops);
6429
+ const { storageOperations } = context.buffer;
6430
+ for (const op of ops) {
6431
+ storageOperations.push(op);
6432
+ }
6119
6433
  flushNowOrSoon();
6120
6434
  }
6121
6435
  let _getStorage$ = null;
@@ -6390,7 +6704,7 @@ ${Array.from(traces).join("\n\n")}`
6390
6704
  await markInboxNotificationsAsRead(inboxNotificationIds);
6391
6705
  return inboxNotificationIds;
6392
6706
  },
6393
- { delay: MARK_INBOX_NOTIFICATIONS_AS_READ_BATCH_DELAY2 }
6707
+ { delay: MARK_INBOX_NOTIFICATIONS_AS_READ_BATCH_DELAY }
6394
6708
  );
6395
6709
  async function markInboxNotificationAsRead(inboxNotificationId) {
6396
6710
  await batchedMarkInboxNotificationsAsRead.get(inboxNotificationId);
@@ -6410,6 +6724,12 @@ ${Array.from(traces).join("\n\n")}`
6410
6724
  return context.nodes.size;
6411
6725
  },
6412
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,
6413
6733
  // Support for the Liveblocks browser extension
6414
6734
  getSelf_forDevTools: () => selfAsTreeNode.current,
6415
6735
  getOthers_forDevTools: () => others_forDevTools.current,
@@ -6594,469 +6914,405 @@ function makeCreateSocketDelegateForRoom(roomId, baseUrl, WebSocketPolyfill) {
6594
6914
  };
6595
6915
  }
6596
6916
 
6597
- // src/store.ts
6598
- function createClientStore() {
6599
- const store = createStore({
6600
- threads: {},
6601
- queries: {},
6602
- optimisticUpdates: [],
6603
- inboxNotifications: {},
6604
- notificationSettings: {}
6605
- });
6606
- return {
6607
- ...store,
6608
- deleteThread(threadId) {
6609
- store.set((state) => {
6610
- return {
6611
- ...state,
6612
- threads: deleteKeyImmutable(state.threads, threadId),
6613
- inboxNotifications: Object.fromEntries(
6614
- Object.entries(state.inboxNotifications).filter(
6615
- ([_id, notification]) => notification.threadId !== threadId
6616
- )
6617
- )
6618
- };
6619
- });
6620
- },
6621
- updateThreadAndNotification(thread, inboxNotification) {
6622
- store.set((state) => {
6623
- const existingThread = state.threads[thread.id];
6624
- return {
6625
- ...state,
6626
- threads: existingThread === void 0 || compareThreads(thread, existingThread) === 1 ? { ...state.threads, [thread.id]: thread } : state.threads,
6627
- inboxNotifications: inboxNotification === void 0 ? state.inboxNotifications : {
6628
- ...state.inboxNotifications,
6629
- [inboxNotification.id]: inboxNotification
6630
- }
6631
- };
6632
- });
6633
- },
6634
- updateThreadsAndNotifications(threads, inboxNotifications, deletedThreads, deletedInboxNotifications, queryKey) {
6635
- store.set((state) => ({
6636
- ...state,
6637
- threads: applyThreadUpdates(state.threads, {
6638
- newThreads: threads,
6639
- deletedThreads
6640
- }),
6641
- inboxNotifications: applyNotificationsUpdates(
6642
- state.inboxNotifications,
6643
- {
6644
- newInboxNotifications: inboxNotifications,
6645
- deletedNotifications: deletedInboxNotifications
6646
- }
6647
- ),
6648
- queries: queryKey !== void 0 ? {
6649
- ...state.queries,
6650
- [queryKey]: {
6651
- isLoading: false
6652
- }
6653
- } : state.queries
6654
- }));
6655
- },
6656
- updateRoomInboxNotificationSettings(roomId, settings, queryKey) {
6657
- store.set((state) => ({
6658
- ...state,
6659
- notificationSettings: {
6660
- ...state.notificationSettings,
6661
- [roomId]: settings
6662
- },
6663
- queries: {
6664
- ...state.queries,
6665
- [queryKey]: {
6666
- 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;
6667
6936
  }
6668
6937
  }
6669
- }));
6670
- },
6671
- pushOptimisticUpdate(optimisticUpdate) {
6672
- store.set((state) => ({
6673
- ...state,
6674
- optimisticUpdates: [...state.optimisticUpdates, optimisticUpdate]
6675
- }));
6676
- },
6677
- setQueryState(queryKey, queryState) {
6678
- store.set((state) => ({
6679
- ...state,
6680
- queries: {
6681
- ...state.queries,
6682
- [queryKey]: queryState
6938
+ if (metadataValue !== filterValue) {
6939
+ return false;
6683
6940
  }
6684
- }));
6941
+ }
6942
+ return true;
6685
6943
  }
6686
- };
6687
- }
6688
- function deleteKeyImmutable(record, key) {
6689
- if (Object.prototype.hasOwnProperty.call(record, key)) {
6690
- const { [key]: _toDelete, ...rest } = record;
6691
- return rest;
6692
- }
6693
- return record;
6944
+ );
6945
+ return threads.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
6694
6946
  }
6695
- function compareThreads(thread1, thread2) {
6696
- if (thread1.updatedAt && thread2.updatedAt) {
6697
- return thread1.updatedAt > thread2.updatedAt ? 1 : thread1.updatedAt < thread2.updatedAt ? -1 : 0;
6698
- } else if (thread1.updatedAt || thread2.updatedAt) {
6699
- return thread1.updatedAt ? 1 : -1;
6700
- }
6701
- if (thread1.createdAt > thread2.createdAt) {
6702
- return 1;
6703
- } else if (thread1.createdAt < thread2.createdAt) {
6704
- return -1;
6947
+ var assertFilterIsStartsWithOperator = (filter) => {
6948
+ if (typeof filter === "object" && typeof filter.startsWith === "string") {
6949
+ return true;
6950
+ } else {
6951
+ return false;
6705
6952
  }
6706
- return 0;
6707
- }
6708
- function applyOptimisticUpdates(state) {
6709
- const result = {
6710
- threads: {
6711
- ...state.threads
6712
- },
6713
- inboxNotifications: {
6714
- ...state.inboxNotifications
6715
- },
6716
- notificationSettings: {
6717
- ...state.notificationSettings
6718
- }
6719
- };
6720
- for (const optimisticUpdate of state.optimisticUpdates) {
6721
- switch (optimisticUpdate.type) {
6722
- case "create-thread": {
6723
- result.threads[optimisticUpdate.thread.id] = optimisticUpdate.thread;
6724
- break;
6725
- }
6726
- case "edit-thread-metadata": {
6727
- const thread = result.threads[optimisticUpdate.threadId];
6728
- if (thread === void 0) {
6729
- break;
6730
- }
6731
- if (thread.deletedAt !== void 0) {
6732
- break;
6733
- }
6734
- if (thread.updatedAt !== void 0 && thread.updatedAt > optimisticUpdate.updatedAt) {
6735
- break;
6736
- }
6737
- result.threads[thread.id] = {
6738
- ...thread,
6739
- updatedAt: optimisticUpdate.updatedAt,
6740
- metadata: {
6741
- ...thread.metadata,
6742
- ...optimisticUpdate.metadata
6743
- }
6744
- };
6745
- break;
6746
- }
6747
- case "create-comment": {
6748
- const thread = result.threads[optimisticUpdate.comment.threadId];
6749
- if (thread === void 0) {
6750
- break;
6751
- }
6752
- result.threads[thread.id] = upsertComment(
6753
- thread,
6754
- optimisticUpdate.comment
6755
- );
6756
- const inboxNotification = Object.values(result.inboxNotifications).find(
6757
- (notification) => notification.threadId === thread.id
6758
- );
6759
- if (inboxNotification === void 0) {
6760
- break;
6761
- }
6762
- result.inboxNotifications[inboxNotification.id] = {
6763
- ...inboxNotification,
6764
- notifiedAt: optimisticUpdate.comment.createdAt,
6765
- readAt: optimisticUpdate.comment.createdAt
6766
- };
6767
- break;
6768
- }
6769
- case "edit-comment": {
6770
- const thread = result.threads[optimisticUpdate.comment.threadId];
6771
- if (thread === void 0) {
6772
- break;
6773
- }
6774
- result.threads[thread.id] = upsertComment(
6775
- thread,
6776
- optimisticUpdate.comment
6777
- );
6778
- break;
6779
- }
6780
- case "delete-comment": {
6781
- const thread = result.threads[optimisticUpdate.threadId];
6782
- if (thread === void 0) {
6783
- break;
6784
- }
6785
- result.threads[thread.id] = deleteComment(
6786
- thread,
6787
- optimisticUpdate.commentId,
6788
- optimisticUpdate.deletedAt
6789
- );
6790
- break;
6791
- }
6792
- case "add-reaction": {
6793
- const thread = result.threads[optimisticUpdate.threadId];
6794
- if (thread === void 0) {
6795
- break;
6796
- }
6797
- result.threads[thread.id] = addReaction(
6798
- thread,
6799
- optimisticUpdate.commentId,
6800
- optimisticUpdate.reaction
6801
- );
6802
- break;
6803
- }
6804
- case "remove-reaction": {
6805
- const thread = result.threads[optimisticUpdate.threadId];
6806
- if (thread === void 0) {
6807
- break;
6808
- }
6809
- result.threads[thread.id] = removeReaction(
6810
- thread,
6811
- optimisticUpdate.commentId,
6812
- optimisticUpdate.emoji,
6813
- optimisticUpdate.userId,
6814
- optimisticUpdate.removedAt
6815
- );
6816
- break;
6817
- }
6818
- case "mark-inbox-notification-as-read": {
6819
- result.inboxNotifications[optimisticUpdate.inboxNotificationId] = {
6820
- ...state.inboxNotifications[optimisticUpdate.inboxNotificationId],
6821
- readAt: optimisticUpdate.readAt
6822
- };
6823
- break;
6824
- }
6825
- case "mark-inbox-notifications-as-read": {
6826
- for (const id in result.inboxNotifications) {
6827
- result.inboxNotifications[id] = {
6828
- ...result.inboxNotifications[id],
6829
- readAt: optimisticUpdate.readAt
6830
- };
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
+ });
6831
7011
  }
6832
7012
  break;
6833
7013
  }
6834
- case "update-notification-settings": {
6835
- result.notificationSettings[optimisticUpdate.roomId] = {
6836
- ...result.notificationSettings[optimisticUpdate.roomId],
6837
- ...optimisticUpdate.settings
6838
- };
6839
- }
6840
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();
6841
7024
  }
6842
- return result;
6843
7025
  }
6844
- function applyThreadUpdates(existingThreads, updates) {
6845
- const updatedThreads = { ...existingThreads };
6846
- updates.newThreads.forEach((thread) => {
6847
- const existingThread = updatedThreads[thread.id];
6848
- if (existingThread) {
6849
- const result = compareThreads(existingThread, thread);
6850
- if (result === 1)
6851
- return;
6852
- }
6853
- updatedThreads[thread.id] = thread;
6854
- });
6855
- updates.deletedThreads.forEach(({ id, deletedAt }) => {
6856
- const existingThread = updatedThreads[id];
6857
- if (existingThread === void 0)
6858
- return;
6859
- existingThread.deletedAt = deletedAt;
6860
- existingThread.updatedAt = deletedAt;
6861
- 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
6862
7052
  });
6863
- return updatedThreads;
6864
7053
  }
6865
- function applyNotificationsUpdates(existingInboxNotifications, updates) {
6866
- const updatedInboxNotifications = { ...existingInboxNotifications };
6867
- updates.newInboxNotifications.forEach((notification) => {
6868
- const existingNotification = updatedInboxNotifications[notification.id];
6869
- if (existingNotification) {
6870
- const result = compareInboxNotifications(
6871
- existingNotification,
6872
- notification
6873
- );
6874
- if (result === 1)
6875
- 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
6876
7069
  }
6877
- updatedInboxNotifications[notification.id] = notification;
6878
7070
  });
6879
- updates.deletedNotifications.forEach(
6880
- ({ id }) => delete updatedInboxNotifications[id]
6881
- );
6882
- return updatedInboxNotifications;
6883
7071
  }
6884
- function compareInboxNotifications(inboxNotificationA, inboxNotificationB) {
6885
- if (inboxNotificationA.notifiedAt > inboxNotificationB.notifiedAt) {
6886
- return 1;
6887
- } else if (inboxNotificationA.notifiedAt < inboxNotificationB.notifiedAt) {
6888
- 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
+ });
6889
7087
  }
6890
- if (inboxNotificationA.readAt && inboxNotificationB.readAt) {
6891
- return inboxNotificationA.readAt > inboxNotificationB.readAt ? 1 : inboxNotificationA.readAt < inboxNotificationB.readAt ? -1 : 0;
6892
- } else if (inboxNotificationA.readAt || inboxNotificationB.readAt) {
6893
- 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
+ });
6894
7097
  }
6895
- return 0;
6896
7098
  }
6897
- function upsertComment(thread, comment) {
6898
- if (thread.deletedAt !== void 0) {
6899
- 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
+ });
6900
7107
  }
6901
- if (comment.threadId !== thread.id) {
6902
- warn(
6903
- `Comment ${comment.id} does not belong to thread ${thread.id}`
6904
- );
6905
- 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();
6906
7129
  }
6907
- const existingComment = thread.comments.find(
6908
- (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
+ })
6909
7157
  );
6910
- if (existingComment === void 0) {
6911
- const updatedAt = new Date(
6912
- Math.max(thread.updatedAt?.getTime() || 0, comment.createdAt.getTime())
6913
- );
6914
- const updatedThread = {
6915
- ...thread,
6916
- updatedAt,
6917
- comments: [...thread.comments, comment]
6918
- };
6919
- return updatedThread;
7158
+ }
7159
+ function unlinkDevTools(roomId) {
7160
+ if (process.env.NODE_ENV === "production" || typeof window === "undefined") {
7161
+ return;
6920
7162
  }
6921
- if (existingComment.deletedAt !== void 0) {
6922
- 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
+ }
6923
7179
  }
6924
- if (existingComment.editedAt === void 0 || comment.editedAt === void 0 || existingComment.editedAt <= comment.editedAt) {
6925
- const updatedComments = thread.comments.map(
6926
- (existingComment2) => existingComment2.id === comment.id ? comment : existingComment2
6927
- );
6928
- const updatedThread = {
6929
- ...thread,
6930
- updatedAt: new Date(
6931
- Math.max(
6932
- thread.updatedAt?.getTime() || 0,
6933
- comment.editedAt?.getTime() || comment.createdAt.getTime()
6934
- )
6935
- ),
6936
- comments: updatedComments
6937
- };
6938
- 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
+ }
6939
7186
  }
6940
- return thread;
6941
7187
  }
6942
- function deleteComment(thread, commentId, deletedAt) {
6943
- if (thread.deletedAt !== void 0) {
6944
- 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;
6945
7194
  }
6946
- const existingComment = thread.comments.find(
6947
- (comment) => comment.id === commentId
6948
- );
6949
- if (existingComment === void 0) {
6950
- return thread;
7195
+ }
7196
+ function errorIf(condition, message) {
7197
+ if (process.env.NODE_ENV !== "production") {
7198
+ if (condition) {
7199
+ throwUsageError(message);
7200
+ }
6951
7201
  }
6952
- if (existingComment.deletedAt !== void 0) {
6953
- 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;
6954
7254
  }
6955
- const updatedComments = thread.comments.map(
6956
- (comment) => comment.id === commentId ? {
6957
- ...comment,
6958
- deletedAt,
6959
- body: void 0
6960
- } : comment
6961
- );
6962
- 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
+ });
6963
7260
  return {
6964
- ...thread,
6965
- deletedAt,
6966
- updatedAt: deletedAt,
6967
- 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
+ }
6968
7274
  };
6969
7275
  }
6970
- return {
6971
- ...thread,
6972
- updatedAt: deletedAt,
6973
- comments: updatedComments
6974
- };
6975
- }
6976
- function addReaction(thread, commentId, reaction) {
6977
- if (thread.deletedAt !== void 0) {
6978
- return thread;
6979
- }
6980
- const existingComment = thread.comments.find(
6981
- (comment) => comment.id === commentId
6982
- );
6983
- if (existingComment === void 0) {
6984
- return thread;
7276
+ async function getUnreadInboxNotificationsCount() {
7277
+ const { count } = await fetchJson("/inbox-notifications/count");
7278
+ return count;
6985
7279
  }
6986
- if (existingComment.deletedAt !== void 0) {
6987
- 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
+ });
6988
7288
  }
6989
- const updatedComments = thread.comments.map(
6990
- (comment) => comment.id === commentId ? {
6991
- ...comment,
6992
- reactions: upsertReaction(comment.reactions, reaction)
6993
- } : comment
6994
- );
6995
- return {
6996
- ...thread,
6997
- updatedAt: new Date(
6998
- Math.max(reaction.createdAt.getTime(), thread.updatedAt?.getTime() || 0)
6999
- ),
7000
- comments: updatedComments
7001
- };
7002
- }
7003
- function removeReaction(thread, commentId, emoji, userId, removedAt) {
7004
- if (thread.deletedAt !== void 0) {
7005
- 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
+ });
7006
7297
  }
7007
- const existingComment = thread.comments.find(
7008
- (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 }
7009
7305
  );
7010
- if (existingComment === void 0) {
7011
- return thread;
7012
- }
7013
- if (existingComment.deletedAt !== void 0) {
7014
- return thread;
7306
+ async function markInboxNotificationAsRead(inboxNotificationId) {
7307
+ await batchedMarkInboxNotificationsAsRead.get(inboxNotificationId);
7015
7308
  }
7016
- const updatedComments = thread.comments.map(
7017
- (comment) => comment.id === commentId ? {
7018
- ...comment,
7019
- reactions: comment.reactions.map(
7020
- (reaction) => reaction.emoji === emoji ? {
7021
- ...reaction,
7022
- users: reaction.users.filter((user) => user.id !== userId)
7023
- } : reaction
7024
- ).filter((reaction) => reaction.users.length > 0)
7025
- // Remove reactions with no users left
7026
- } : comment
7027
- );
7028
7309
  return {
7029
- ...thread,
7030
- updatedAt: new Date(
7031
- Math.max(removedAt.getTime(), thread.updatedAt?.getTime() || 0)
7032
- ),
7033
- comments: updatedComments
7310
+ getInboxNotifications,
7311
+ getUnreadInboxNotificationsCount,
7312
+ markAllInboxNotificationsAsRead,
7313
+ markInboxNotificationAsRead
7034
7314
  };
7035
7315
  }
7036
- function upsertReaction(reactions, reaction) {
7037
- const existingReaction = reactions.find(
7038
- (existingReaction2) => existingReaction2.emoji === reaction.emoji
7039
- );
7040
- if (existingReaction === void 0) {
7041
- return [
7042
- ...reactions,
7043
- {
7044
- emoji: reaction.emoji,
7045
- createdAt: reaction.createdAt,
7046
- users: [{ id: reaction.userId }]
7047
- }
7048
- ];
7049
- }
7050
- if (existingReaction.users.some((user) => user.id === reaction.userId) === false) {
7051
- return reactions.map(
7052
- (existingReaction2) => existingReaction2.emoji === reaction.emoji ? {
7053
- ...existingReaction2,
7054
- users: [...existingReaction2.users, { id: reaction.userId }]
7055
- } : existingReaction2
7056
- );
7057
- }
7058
- return reactions;
7059
- }
7060
7316
 
7061
7317
  // src/client.ts
7062
7318
  var MIN_THROTTLE = 16;
@@ -7256,6 +7512,14 @@ function createClient(options) {
7256
7512
  markAllInboxNotificationsAsRead,
7257
7513
  markInboxNotificationAsRead
7258
7514
  },
7515
+ comments: {
7516
+ createThreadId,
7517
+ createCommentId,
7518
+ createInboxNotificationId,
7519
+ selectedThreads,
7520
+ selectedInboxNotifications,
7521
+ selectNotificationSettings
7522
+ },
7259
7523
  currentUserIdStore,
7260
7524
  resolveMentionSuggestions: clientOptions.resolveMentionSuggestions,
7261
7525
  cacheStore,
@@ -8116,6 +8380,7 @@ export {
8116
8380
  fancy_console_exports as console,
8117
8381
  convertToCommentData,
8118
8382
  convertToCommentUserReaction,
8383
+ convertToInboxNotificationData,
8119
8384
  convertToThreadData,
8120
8385
  createClient,
8121
8386
  deleteComment,
@@ -8139,6 +8404,7 @@ export {
8139
8404
  makePoller,
8140
8405
  makePosition,
8141
8406
  nn,
8407
+ objectToQuery,
8142
8408
  patchLiveObjectKey,
8143
8409
  raise,
8144
8410
  removeReaction,