@liveblocks/core 1.0.12 → 1.1.0-beta1

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.
Files changed (3) hide show
  1. package/dist/index.d.ts +156 -59
  2. package/dist/index.js +1272 -522
  3. package/package.json +1 -1
package/dist/index.d.ts CHANGED
@@ -568,8 +568,23 @@ declare type BaseUserMeta = {
568
568
  declare type Callback<T> = (event: T) => void;
569
569
  declare type UnsubscribeCallback = () => void;
570
570
  declare type Observable<T> = {
571
+ /**
572
+ * Register a callback function to be called whenever the event source emits
573
+ * an event.
574
+ */
571
575
  subscribe(callback: Callback<T>): UnsubscribeCallback;
576
+ /**
577
+ * Register a one-time callback function to be called whenever the event
578
+ * source emits an event. After the event fires, the callback is
579
+ * auto-unsubscribed.
580
+ */
572
581
  subscribeOnce(callback: Callback<T>): UnsubscribeCallback;
582
+ /**
583
+ * Returns a promise that will resolve when an event is emitted by this
584
+ * event source. Optionally, specify a predicate that has to match. The first
585
+ * event matching that predicate will then resolve the promise.
586
+ */
587
+ waitUntil(predicate?: (event: T) => boolean): Promise<T>;
573
588
  };
574
589
 
575
590
  interface IWebSocketEvent {
@@ -621,6 +636,64 @@ declare enum WebsocketCloseCodes {
621
636
  CLOSE_WITHOUT_RETRY = 4999
622
637
  }
623
638
 
639
+ /**
640
+ * Old connection statuses, here for backward-compatibility reasons only.
641
+ */
642
+ declare type LegacyConnectionStatus = "closed" | "authenticating" | "connecting" | "open" | "unavailable" | "failed";
643
+ /**
644
+ * Returns a human-readable status indicating the current connection status of
645
+ * a Room, as returned by `room.getStatus()`. Can be used to implement
646
+ * a connection status badge.
647
+ */
648
+ declare type Status = "initial" | "connecting" | "connected" | "reconnecting" | "disconnected";
649
+ /**
650
+ * Used to report about app-level reconnection issues.
651
+ *
652
+ * Normal (quick) reconnects won't be reported as a "lost connection". Instead,
653
+ * the application will only get an event if the reconnection attempts by the
654
+ * client are taking (much) longer than usual. Definitely a situation you want
655
+ * to inform your users about, for example, by throwing a toast message on
656
+ * screen, or show a "trying to reconnect" banner.
657
+ */
658
+ declare type LostConnectionEvent = "lost" | "restored" | "failed";
659
+ /**
660
+ * Arbitrary record that will be used as the authentication "token". It's the
661
+ * value that is returned by calling the authentication delegate, and will get
662
+ * passed to the connection factory delegate. This value will be remembered by
663
+ * the connection manager, but its value will not be interpreted, so it can be
664
+ * any value (except null).
665
+ */
666
+ declare type BaseAuthResult = NonNullable<Json>;
667
+ declare type Delegates<T extends BaseAuthResult> = {
668
+ authenticate: () => Promise<T>;
669
+ createSocket: (token: T) => IWebSocketInstance;
670
+ };
671
+
672
+ declare type AppOnlyAuthToken = {
673
+ appId: string;
674
+ roomId?: never;
675
+ scopes: string[];
676
+ };
677
+ declare type RoomAuthToken = {
678
+ appId: string;
679
+ roomId: string;
680
+ scopes: string[];
681
+ actor: number;
682
+ maxConnectionsPerRoom?: number;
683
+ info?: Json;
684
+ groupIds?: string[];
685
+ } & ({
686
+ id: string;
687
+ anonymousId?: never;
688
+ } | {
689
+ id?: never;
690
+ anonymousId: string;
691
+ });
692
+ declare type AuthToken = AppOnlyAuthToken | RoomAuthToken;
693
+ declare function isAppOnlyAuthToken(data: JsonObject): data is AppOnlyAuthToken;
694
+ declare function isRoomAuthToken(data: JsonObject): data is RoomAuthToken;
695
+ declare function isAuthToken(data: JsonObject): data is AuthToken;
696
+
624
697
  declare type ReadonlyArrayWithLegacyMethods<T> = readonly T[] & {
625
698
  /**
626
699
  * @deprecated Prefer the normal .length property on arrays.
@@ -682,28 +755,6 @@ declare type CustomEvent<TRoomEvent extends Json> = {
682
755
  connectionId: number;
683
756
  event: TRoomEvent;
684
757
  };
685
- declare type Connection = {
686
- status: "closed";
687
- } | {
688
- status: "authenticating";
689
- } | {
690
- status: "connecting";
691
- id: number;
692
- userId?: string;
693
- userInfo?: Json;
694
- isReadOnly: boolean;
695
- } | {
696
- status: "open";
697
- id: number;
698
- userId?: string;
699
- userInfo?: Json;
700
- isReadOnly: boolean;
701
- } | {
702
- status: "unavailable";
703
- } | {
704
- status: "failed";
705
- };
706
- declare type ConnectionStatus = Connection["status"];
707
758
  declare type StorageStatus = "not-loaded" | "loading" | "synchronizing" | "synchronized";
708
759
  interface History {
709
760
  /**
@@ -840,12 +891,47 @@ declare type SubscribeFn<TPresence extends JsonObject, _TStorage extends LsonObj
840
891
  */
841
892
  (type: "error", listener: ErrorCallback): () => void;
842
893
  /**
843
- * Subscribe to connection state updates.
894
+ * @deprecated This API will be removed in a future version of Liveblocks.
895
+ * Prefer using the newer `.subscribe('status')` API.
896
+ *
897
+ * We recommend making the following changes if you use these APIs:
898
+ *
899
+ * OLD APIs NEW APIs
900
+ * .getConnectionState() --> .getStatus()
901
+ * .subscribe('connection') --> .subscribe('status')
902
+ *
903
+ * OLD STATUSES NEW STATUSES
904
+ * closed --> initial
905
+ * authenticating --> connecting
906
+ * connecting --> connecting
907
+ * open --> connected
908
+ * unavailable --> reconnecting
909
+ * failed --> disconnected
910
+ *
911
+ * Subscribe to legacy connection status updates.
912
+ *
913
+ * @returns Unsubscribe function.
914
+ *
915
+ */
916
+ (type: "connection", listener: Callback<LegacyConnectionStatus>): () => void;
917
+ /**
918
+ * Subscribe to connection status updates. The callback will be called any
919
+ * time the status changes.
844
920
  *
845
921
  * @returns Unsubscribe function.
846
922
  *
847
923
  */
848
- (type: "connection", listener: Callback<ConnectionStatus>): () => void;
924
+ (type: "status", listener: Callback<Status>): () => void;
925
+ /**
926
+ * Subscribe to the exceptional event where reconnecting to the Liveblocks
927
+ * servers is taking longer than usual. This typically is a sign of a client
928
+ * that has lost internet connectivity.
929
+ *
930
+ * This isn't problematic (because the Liveblocks client is still trying to
931
+ * reconnect), but it's typically a good idea to inform users about it if
932
+ * the connection takes too long to recover.
933
+ */
934
+ (type: "lost-connection", listener: Callback<LostConnectionEvent>): () => void;
849
935
  /**
850
936
  * Subscribes to changes made on a Live structure. Returns an unsubscribe function.
851
937
  * In a future version, we will also expose what exactly changed in the Live structure.
@@ -922,7 +1008,30 @@ declare type Room<TPresence extends JsonObject, TStorage extends LsonObject, TUs
922
1008
  * metadata and connection ID (from the auth server).
923
1009
  */
924
1010
  isSelfAware(): boolean;
925
- getConnectionState(): ConnectionStatus;
1011
+ /**
1012
+ * @deprecated This API will be removed in a future version of Liveblocks.
1013
+ * Prefer using `.getStatus()` instead.
1014
+ *
1015
+ * We recommend making the following changes if you use these APIs:
1016
+ *
1017
+ * OLD APIs NEW APIs
1018
+ * .getConnectionState() --> .getStatus()
1019
+ * .subscribe('connection') --> .subscribe('status')
1020
+ *
1021
+ * OLD STATUSES NEW STATUSES
1022
+ * closed --> initial
1023
+ * authenticating --> connecting
1024
+ * connecting --> connecting
1025
+ * open --> connected
1026
+ * unavailable --> reconnecting
1027
+ * failed --> disconnected
1028
+ */
1029
+ getConnectionState(): LegacyConnectionStatus;
1030
+ /**
1031
+ * Return the current connection status for this room. Can be used to display
1032
+ * a status badge for your Liveblocks connection.
1033
+ */
1034
+ getStatus(): Status;
926
1035
  readonly subscribe: SubscribeFn<TPresence, TStorage, TUserMeta, TRoomEvent>;
927
1036
  /**
928
1037
  * Room's history contains functions that let you undo and redo operation made on by the current client on the presence and storage.
@@ -1003,6 +1112,9 @@ declare type Room<TPresence extends JsonObject, TStorage extends LsonObject, TUs
1003
1112
  */
1004
1113
  getStorageSnapshot(): LiveObject<TStorage> | null;
1005
1114
  readonly events: {
1115
+ readonly connection: Observable<LegacyConnectionStatus>;
1116
+ readonly status: Observable<Status>;
1117
+ readonly lostConnection: Observable<LostConnectionEvent>;
1006
1118
  readonly customEvent: Observable<{
1007
1119
  connectionId: number;
1008
1120
  event: TRoomEvent;
@@ -1013,12 +1125,12 @@ declare type Room<TPresence extends JsonObject, TStorage extends LsonObject, TUs
1013
1125
  event: OthersEvent<TPresence, TUserMeta>;
1014
1126
  }>;
1015
1127
  readonly error: Observable<Error>;
1016
- readonly connection: Observable<ConnectionStatus>;
1017
1128
  readonly storage: Observable<StorageUpdate[]>;
1018
1129
  readonly history: Observable<HistoryEvent>;
1019
1130
  /**
1020
- * Subscribe to the storage loaded event. Will fire at most once during the
1021
- * lifetime of a Room.
1131
+ * Subscribe to the storage loaded event. Will fire any time a full Storage
1132
+ * copy is downloaded. (This happens after the initial connect, and on
1133
+ * every reconnect.)
1022
1134
  */
1023
1135
  readonly storageDidLoad: Observable<void>;
1024
1136
  readonly storageStatus: Observable<StorageStatus>;
@@ -1047,7 +1159,8 @@ declare type Room<TPresence extends JsonObject, TStorage extends LsonObject, TUs
1047
1159
  */
1048
1160
  getStorageStatus(): StorageStatus;
1049
1161
  /**
1050
- * Close room connection and try to reconnect
1162
+ * Reconnect the room to the Liveblocks server by re-establishing a fresh
1163
+ * connection. If the room is not connected yet, initiate it.
1051
1164
  */
1052
1165
  reconnect(): void;
1053
1166
  };
@@ -1114,14 +1227,17 @@ declare type AuthEndpoint = string | ((room: string) => Promise<{
1114
1227
  */
1115
1228
  declare type ClientOptions = {
1116
1229
  throttle?: number;
1230
+ lostConnectionTimeout?: number;
1117
1231
  polyfills?: Polyfills;
1118
1232
  unstable_fallbackToHTTP?: boolean;
1119
1233
  /**
1120
- * Backward-compatible way to set `polyfills.fetch`.
1234
+ * @deprecated Use `polyfills: { fetch: ... }` instead.
1235
+ * This option will be removed in a future release.
1121
1236
  */
1122
1237
  fetchPolyfill?: Polyfills["fetch"];
1123
1238
  /**
1124
- * Backward-compatible way to set `polyfills.WebSocket`.
1239
+ * @deprecated Use `polyfills: { WebSocket: ... }` instead.
1240
+ * This option will be removed in a future release.
1125
1241
  */
1126
1242
  WebSocketPolyfill?: Polyfills["WebSocket"];
1127
1243
  } & ({
@@ -1253,6 +1369,12 @@ declare function tryParseJson(rawMessage: string): Json | undefined;
1253
1369
  * Decode base64 string.
1254
1370
  */
1255
1371
  declare function b64decode(b64value: string): string;
1372
+ /**
1373
+ * Returns whatever the given promise returns, but will be rejected with
1374
+ * a "Timed out" error if the given promise does not return or reject within
1375
+ * the given timeout period (in milliseconds).
1376
+ */
1377
+ declare function withTimeout<T>(promise: Promise<T>, millis: number, errmsg?: string): Promise<T>;
1256
1378
 
1257
1379
  /**
1258
1380
  * Positions, aka the Pos type, are efficient encodings of "positions" in
@@ -1330,31 +1452,6 @@ declare function asPos(str: string): Pos;
1330
1452
  */
1331
1453
  declare function shallow(a: unknown, b: unknown): boolean;
1332
1454
 
1333
- declare type AppOnlyAuthToken = {
1334
- appId: string;
1335
- roomId?: never;
1336
- scopes: string[];
1337
- };
1338
- declare type RoomAuthToken = {
1339
- appId: string;
1340
- roomId: string;
1341
- scopes: string[];
1342
- actor: number;
1343
- maxConnectionsPerRoom?: number;
1344
- info?: Json;
1345
- groupIds?: string[];
1346
- } & ({
1347
- id: string;
1348
- anonymousId?: never;
1349
- } | {
1350
- id?: never;
1351
- anonymousId: string;
1352
- });
1353
- declare type AuthToken = AppOnlyAuthToken | RoomAuthToken;
1354
- declare function isAppOnlyAuthToken(data: JsonObject): data is AppOnlyAuthToken;
1355
- declare function isRoomAuthToken(data: JsonObject): data is RoomAuthToken;
1356
- declare function isAuthToken(data: JsonObject): data is AuthToken;
1357
-
1358
1455
  declare enum ClientMsgCode {
1359
1456
  UPDATE_PRESENCE = 100,
1360
1457
  BROADCAST_EVENT = 103,
@@ -1725,7 +1822,7 @@ declare type ClientToPanelMessage =
1725
1822
  | {
1726
1823
  msg: "room::sync::full";
1727
1824
  roomId: string;
1728
- status: ConnectionStatus;
1825
+ status: Status;
1729
1826
  storage: readonly LsonTreeNode[] | null;
1730
1827
  me: UserTreeNode | null;
1731
1828
  others: readonly UserTreeNode[];
@@ -1736,7 +1833,7 @@ declare type ClientToPanelMessage =
1736
1833
  | {
1737
1834
  msg: "room::sync::partial";
1738
1835
  roomId: string;
1739
- status?: ConnectionStatus;
1836
+ status?: Status;
1740
1837
  storage?: readonly LsonTreeNode[];
1741
1838
  me?: UserTreeNode;
1742
1839
  others?: readonly UserTreeNode[];
@@ -1787,4 +1884,4 @@ declare type EnsureJson<T> = [
1787
1884
  [K in keyof T]: EnsureJson<T[K]>;
1788
1885
  };
1789
1886
 
1790
- export { AckOp, AppOnlyAuthToken, AuthToken, BaseUserMeta, BroadcastEventClientMsg, BroadcastOptions, BroadcastedEventServerMsg, Client, ClientMsg, ClientMsgCode, ConnectionStatus, CrdtType, CreateChildOp, CreateListOp, CreateMapOp, CreateObjectOp, CreateOp, CreateRegisterOp, CreateRootObjectOp, DeleteCrdtOp, DeleteObjectKeyOp, DevToolsTreeNode as DevTools, protocol as DevToolsMsg, EnsureJson, FetchStorageClientMsg, History, IWebSocket, IWebSocketCloseEvent, IWebSocketEvent, IWebSocketInstance, IWebSocketMessageEvent, IdTuple, Immutable, InitialDocumentStateServerMsg, Json, JsonArray, JsonObject, JsonScalar, LiveList, LiveListUpdate, LiveMap, LiveMapUpdate, LiveNode, LiveObject, LiveObjectUpdate, LiveStructure, Lson, LsonObject, NodeMap, Op, OpCode, Others, ParentToChildNodeMap, PlainLson, PlainLsonFields, PlainLsonList, PlainLsonMap, PlainLsonObject, RejectedStorageOpServerMsg, Resolve, Room, RoomAuthToken, RoomInitializers, RoomStateServerMsg, SerializedChild, SerializedCrdt, SerializedList, SerializedMap, SerializedObject, SerializedRegister, SerializedRootObject, ServerMsg, ServerMsgCode, SetParentKeyOp, StorageStatus, StorageUpdate, ToImmutable, ToJson, UpdateObjectOp, UpdatePresenceClientMsg, UpdatePresenceServerMsg, UpdateStorageClientMsg, UpdateStorageServerMsg, User, UserJoinServerMsg, UserLeftServerMsg, WebsocketCloseCodes, asArrayWithLegacyMethods, asPos, assert, assertNever, b64decode, createClient, deprecate, deprecateIf, errorIf, freeze, isAppOnlyAuthToken, isAuthToken, isChildCrdt, isJsonArray, isJsonObject, isJsonScalar, isPlainObject, isRoomAuthToken, isRootCrdt, legacy_patchImmutableObject, lsonToJson, makePosition, nn, patchLiveObjectKey, shallow, throwUsageError, toPlainLson, tryParseJson };
1887
+ export { AckOp, AppOnlyAuthToken, AuthToken, BaseAuthResult, BaseUserMeta, BroadcastEventClientMsg, BroadcastOptions, BroadcastedEventServerMsg, Client, ClientMsg, ClientMsgCode, CrdtType, CreateChildOp, CreateListOp, CreateMapOp, CreateObjectOp, CreateOp, CreateRegisterOp, CreateRootObjectOp, Delegates, DeleteCrdtOp, DeleteObjectKeyOp, DevToolsTreeNode as DevTools, protocol as DevToolsMsg, EnsureJson, FetchStorageClientMsg, History, IWebSocket, IWebSocketCloseEvent, IWebSocketEvent, IWebSocketInstance, IWebSocketMessageEvent, IdTuple, Immutable, InitialDocumentStateServerMsg, Json, JsonArray, JsonObject, JsonScalar, LegacyConnectionStatus, LiveList, LiveListUpdate, LiveMap, LiveMapUpdate, LiveNode, LiveObject, LiveObjectUpdate, LiveStructure, LostConnectionEvent, Lson, LsonObject, NodeMap, Op, OpCode, Others, ParentToChildNodeMap, PlainLson, PlainLsonFields, PlainLsonList, PlainLsonMap, PlainLsonObject, RejectedStorageOpServerMsg, Resolve, Room, RoomAuthToken, RoomInitializers, RoomStateServerMsg, SerializedChild, SerializedCrdt, SerializedList, SerializedMap, SerializedObject, SerializedRegister, SerializedRootObject, ServerMsg, ServerMsgCode, SetParentKeyOp, Status, StorageStatus, StorageUpdate, ToImmutable, ToJson, UpdateObjectOp, UpdatePresenceClientMsg, UpdatePresenceServerMsg, UpdateStorageClientMsg, UpdateStorageServerMsg, User, UserJoinServerMsg, UserLeftServerMsg, WebsocketCloseCodes, asArrayWithLegacyMethods, asPos, assert, assertNever, b64decode, createClient, deprecate, deprecateIf, errorIf, freeze, isAppOnlyAuthToken, isAuthToken, isChildCrdt, isJsonArray, isJsonObject, isJsonScalar, isPlainObject, isRoomAuthToken, isRootCrdt, legacy_patchImmutableObject, lsonToJson, makePosition, nn, patchLiveObjectKey, shallow, throwUsageError, toPlainLson, tryParseJson, withTimeout };