-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathliveobjects.d.ts
More file actions
1834 lines (1683 loc) · 71.2 KB
/
Copy pathliveobjects.d.ts
File metadata and controls
1834 lines (1683 loc) · 71.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* You are currently viewing the Ably LiveObjects plugin type definitions for the Ably JavaScript Client Library SDK.
*
* To get started with LiveObjects, follow the [Quickstart Guide](https://ably.com/docs/liveobjects/quickstart/javascript) or view the [Introduction to LiveObjects](https://ably.com/docs/liveobjects).
*
* @module
*/
/* eslint-disable no-unused-vars, @typescript-eslint/no-unused-vars */
import {
ErrorInfo,
EventCallback,
RealtimeChannel,
RealtimeClient,
StatusSubscription,
Subscription,
__livetype,
} from './ably';
import { BaseRealtime } from './modular';
/* eslint-enable no-unused-vars, @typescript-eslint/no-unused-vars */
/**
* Blocks inferences to the contained type.
* Polyfill for TypeScript's `NoInfer` utility type introduced in TypeScript 5.4.
*
* This works by leveraging deferred conditional types - the compiler can't
* evaluate the conditional until it knows what T is, which prevents TypeScript
* from digging into the type to find inference candidates.
*
* See:
* - https://stackoverflow.com/questions/56687668
* - https://www.typescriptlang.org/docs/handbook/utility-types.html#noinfertype
*/
type NoInfer<T> = [T][T extends any ? 0 : never];
/**
* The `ObjectsEvents` namespace describes the possible values of the {@link ObjectsEvent} type.
*/
declare namespace ObjectsEvents {
/**
* The local copy of Objects on a channel is currently being synchronized with the Ably service.
*/
type SYNCING = 'syncing';
/**
* The local copy of Objects on a channel has been synchronized with the Ably service.
*/
type SYNCED = 'synced';
}
/**
* Describes the events emitted by a {@link RealtimeObject} object.
*/
export type ObjectsEvent = ObjectsEvents.SYNCED | ObjectsEvents.SYNCING;
/**
* The callback used for the events emitted by {@link RealtimeObject}.
*/
export type ObjectsEventCallback = () => void;
/**
* A function passed to the {@link BatchOperations.batch | batch} method to group multiple Objects operations into a single channel message.
*
* The function must be synchronous.
*
* @param ctx - The {@link BatchContext} used to group operations together.
*/
export type BatchFunction<T extends LiveObject> = (ctx: BatchContext<T>) => void;
/**
* Enables the Objects to be read, modified and subscribed to for a channel.
*/
export declare interface RealtimeObject {
/**
* Retrieves a {@link PathObject} for the object on a channel.
* Implicitly {@link RealtimeChannel.attach | attaches to the channel} if not already attached.
*
* A type parameter can be provided to describe the structure of the Objects on the channel.
*
* Example:
*
* ```typescript
* import { LiveCounter } from 'ably/liveobjects';
*
* type MyObject = {
* myTypedCounter: LiveCounter;
* };
*
* const myTypedObject = await channel.object.get<MyObject>();
* ```
*
* @returns A promise which, upon success, will be fulfilled with a {@link PathObject}. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
*/
get<T extends Record<string, Value>>(): Promise<PathObject<LiveMap<T>>>;
/**
* Registers the provided listener for the specified event. If `on()` is called more than once with the same listener and event, the listener is added multiple times to its listener registry. Therefore, as an example, assuming the same listener is registered twice using `on()`, and an event is emitted once, the listener would be invoked twice.
*
* @param event - The named event to listen for.
* @param callback - The event listener.
* @returns A {@link StatusSubscription} object that allows the provided listener to be deregistered from future updates.
*/
on(event: ObjectsEvent, callback: ObjectsEventCallback): StatusSubscription;
/**
* Removes all registrations that match both the specified listener and the specified event.
*
* @param event - The named event.
* @param callback - The event listener.
*/
off(event: ObjectsEvent, callback: ObjectsEventCallback): void;
}
/**
* Primitive types that can be stored in collection types.
* Includes JSON-serializable data so that maps and lists can hold plain JS values.
*/
export type Primitive =
| string
| number
| boolean
| Buffer
| ArrayBuffer
// JSON-serializable primitive values
| JsonArray
| JsonObject;
/**
* Represents a JSON-encodable value.
*/
export type Json = JsonScalar | JsonArray | JsonObject;
/**
* Represents a JSON-encodable scalar value.
*/
export type JsonScalar = null | boolean | number | string;
/**
* Represents a JSON-encodable array.
*/
export type JsonArray = Json[];
/**
* Represents a JSON-encodable object.
*/
export type JsonObject = { [prop: string]: Json | undefined };
// Branded interfaces that enables TypeScript to distinguish
// between LiveObject types even when they have identical structure (empty interfaces in this case).
// Enables PathObject<T> to dispatch to correct method sets via conditional types.
/**
* A {@link LiveMap} is a collection type that maps string keys to values, which can be either primitive values or other LiveObjects.
*/
export interface LiveMap<_T extends Record<string, Value> = Record<string, Value>> {
/** LiveMap type symbol */
[__livetype]: 'LiveMap';
}
/**
* A {@link LiveCounter} is a numeric type that supports atomic increment and decrement operations.
*/
export interface LiveCounter {
/** LiveCounter type symbol */
[__livetype]: 'LiveCounter';
}
/**
* Type union that matches any LiveObject type that can be mutated, subscribed to, etc.
*/
export type LiveObject = LiveMap | LiveCounter;
/**
* Type union that defines the base set of allowed types that can be stored in collection types.
* Describes the set of all possible values that can parameterize PathObject.
* This is the canonical union used when a narrower type cannot be inferred.
*/
export type Value = LiveObject | Primitive;
/**
* CompactedValue transforms LiveObject types into in-memory JavaScript equivalents.
* LiveMap becomes an object, LiveCounter becomes a number, primitive values remain unchanged.
*/
export type CompactedValue<T extends Value> =
// LiveMap types
[T] extends [LiveMap<infer U>]
? { [K in keyof U]: CompactedValue<U[K]> }
: [T] extends [LiveMap<infer U> | undefined]
? { [K in keyof U]: CompactedValue<U[K]> } | undefined
: // LiveCounter types
[T] extends [LiveCounter]
? number
: [T] extends [LiveCounter | undefined]
? number | undefined
: // Other primitive types
[T] extends [Primitive]
? T
: [T] extends [Primitive | undefined]
? T
: any;
/**
* Represents a cyclic object reference in a JSON-serializable format.
*/
export interface ObjectIdReference {
/** The referenced object Id. */
objectId: string;
}
/**
* CompactedJsonValue transforms LiveObject types into JSON-serializable equivalents.
* LiveMap becomes an object, LiveCounter becomes a number, binary values become base64-encoded strings,
* other primitives remain unchanged.
*
* Additionally, cyclic references are represented as `{ objectId: string }` instead of in-memory pointers to same objects.
*/
export type CompactedJsonValue<T extends Value> =
// LiveMap types - note: cyclic references become ObjectIdReference
[T] extends [LiveMap<infer U>]
? { [K in keyof U]: CompactedJsonValue<U[K]> } | ObjectIdReference
: [T] extends [LiveMap<infer U> | undefined]
? { [K in keyof U]: CompactedJsonValue<U[K]> } | ObjectIdReference | undefined
: // LiveCounter types
[T] extends [LiveCounter]
? number
: [T] extends [LiveCounter | undefined]
? number | undefined
: // Binary types (converted to base64 strings)
[T] extends [ArrayBuffer]
? string
: [T] extends [ArrayBuffer | undefined]
? string | undefined
: [T] extends [ArrayBufferView]
? string
: [T] extends [ArrayBufferView | undefined]
? string | undefined
: // Other primitive types
[T] extends [Primitive]
? T
: [T] extends [Primitive | undefined]
? T
: any;
/**
* PathObjectBase defines the set of common methods on a PathObject
* that are present regardless of the underlying type.
*/
interface PathObjectBase {
/**
* Get the fully-qualified path string for this PathObject.
*
* Path segments with dots in them are escaped with a backslash.
* For example, a path with segments `['a', 'b.c', 'd']` will be represented as `a.b\.c.d`.
*/
path(): string;
/**
* Registers a listener that is called each time the object or a primitive value at this path is updated.
*
* The provided listener receives a {@link PathObject} representing the path at which there was an object change,
* and, if applicable, an {@link ObjectMessage} that carried the operation that led to the change.
*
* By default, subscriptions observe nested changes, but you can configure the observation depth
* using the `options` parameter.
*
* A PathObject subscription observes whichever value currently exists at this path.
* The subscription remains active even if the path temporarily does not resolve to any value
* (for example, if an entry is removed from a map). If the object instance at this path changes,
* the subscription automatically switches to observe the new instance and stops observing the old one.
*
* @param listener - An event listener function.
* @param options - Optional subscription configuration.
* @returns A {@link Subscription} object that allows the provided listener to be deregistered from future updates.
*/
subscribe(
listener: EventCallback<PathObjectSubscriptionEvent>,
options?: PathObjectSubscriptionOptions,
): Subscription;
/**
* Registers a subscription listener and returns an async iterator that yields
* subscription events each time the object or a primitive value at this path is updated.
*
* This method functions in the same way as the regular {@link PathObjectBase.subscribe | PathObject.subscribe()} method,
* but instead returns an async iterator that can be used in a `for await...of` loop for convenience.
*
* @param options - Optional subscription configuration.
* @returns An async iterator that yields {@link PathObjectSubscriptionEvent} objects.
*/
subscribeIterator(options?: PathObjectSubscriptionOptions): AsyncIterableIterator<PathObjectSubscriptionEvent>;
}
/**
* PathObjectCollectionMethods defines the set of common methods on a PathObject
* that are present for any collection type, regardless of the specific underlying type.
*/
interface PathObjectCollectionMethods {
/**
* Collection types support obtaining a PathObject with a fully-qualified string path,
* which is evaluated from the current path.
* Using this method loses rich compile-time type information.
*
* @param path - A fully-qualified path string to navigate to, relative to the current path.
* @returns A {@link PathObject} for the specified path.
*/
at<T extends Value = Value>(path: string): PathObject<T>;
}
/**
* Defines collection methods available on a {@link LiveMapPathObject}.
*/
interface LiveMapPathObjectCollectionMethods<T extends Record<string, Value> = Record<string, Value>> {
/**
* Returns an iterable of key-value pairs for each entry in the map at this path.
* Each value is represented as a {@link PathObject} corresponding to its key.
*
* If the path does not resolve to a map object, returns an empty iterator.
*/
entries(): IterableIterator<[keyof T, PathObject<T[keyof T]>]>;
/**
* Returns an iterable of keys in the map at this path.
*
* If the path does not resolve to a map object, returns an empty iterator.
*/
keys(): IterableIterator<keyof T>;
/**
* Returns an iterable of values in the map at this path.
* Each value is represented as a {@link PathObject}.
*
* If the path does not resolve to a map object, returns an empty iterator.
*/
values(): IterableIterator<PathObject<T[keyof T]>>;
/**
* Returns the number of entries in the map at this path.
*
* If the path does not resolve to a map object, returns `undefined`.
*/
size(): number | undefined;
}
/**
* A PathObject representing a {@link LiveMap} instance at a specific path.
* The type parameter T describes the expected structure of the map's entries.
*/
export interface LiveMapPathObject<T extends Record<string, Value> = Record<string, Value>>
extends PathObjectBase,
PathObjectCollectionMethods,
LiveMapPathObjectCollectionMethods<T>,
LiveMapOperations<T> {
/**
* Navigate to a child path within the map by obtaining a PathObject for that path.
* The next path segment in a LiveMap is identified with a string key.
*
* @param key - A string key for the next path segment within the map.
* @returns A {@link PathObject} for the specified key.
*/
get<K extends keyof T & string>(key: K): PathObject<T[K]>;
/**
* Get the specific map instance currently at this path.
* If the path does not resolve to any specific instance, returns `undefined`.
*
* @returns The {@link LiveMapInstance} at this path, or `undefined` if none exists.
*/
instance(): LiveMapInstance<T> | undefined;
/**
* Get an in-memory JavaScript object representation of the map at this path.
* Cyclic references are handled through memoization, returning shared compacted
* object references for previously visited objects. This means the value returned
* from `compact()` cannot be directly JSON-stringified if the object may contain cycles.
*
* If the path does not resolve to any specific instance, returns `undefined`.
*
* Use {@link LiveMapPathObject.compactJson | compactJson()} for a JSON-serializable representation.
*/
compact(): CompactedValue<LiveMap<T>> | undefined;
/**
* Get a JSON-serializable representation of the map at this path.
* Binary values are converted to base64-encoded strings.
* Cyclic references are represented as `{ objectId: string }` instead of in-memory pointers,
* making the result safe to pass to `JSON.stringify()`.
*
* If the path does not resolve to any specific instance, returns `undefined`.
*
* Use {@link LiveMapPathObject.compact | compact()} for an in-memory representation.
*/
compactJson(): CompactedJsonValue<LiveMap<T>> | undefined;
}
/**
* A PathObject representing a {@link LiveCounter} instance at a specific path.
*/
export interface LiveCounterPathObject extends PathObjectBase, LiveCounterOperations {
/**
* Get the current value of the counter instance currently at this path.
* If the path does not resolve to any specific instance, returns `undefined`.
*/
value(): number | undefined;
/**
* Get the specific counter instance currently at this path.
* If the path does not resolve to any specific instance, returns `undefined`.
*
* @returns The {@link LiveCounterInstance} at this path, or `undefined` if none exists.
*/
instance(): LiveCounterInstance | undefined;
/**
* Get a number representation of the counter at this path.
* This is an alias for calling {@link LiveCounterPathObject.value | value()}.
*
* If the path does not resolve to any specific instance, returns `undefined`.
*/
compact(): CompactedValue<LiveCounter> | undefined;
/**
* Get a number representation of the counter at this path.
* This is an alias for calling {@link LiveCounterPathObject.value | value()}.
*
* If the path does not resolve to any specific instance, returns `undefined`.
*/
compactJson(): CompactedJsonValue<LiveCounter> | undefined;
}
/**
* A PathObject representing a primitive value at a specific path.
*/
export interface PrimitivePathObject<T extends Primitive = Primitive> extends PathObjectBase {
/**
* Get the current value of the primitive currently at this path.
* If the path does not resolve to any specific entry, returns `undefined`.
*/
value(): T | undefined;
/**
* Get a JavaScript object representation of the primitive value at this path.
* This is an alias for calling {@link PrimitivePathObject.value | value()}.
*
* If the path does not resolve to any specific entry, returns `undefined`.
*/
compact(): CompactedValue<T> | undefined;
/**
* Get a JSON-serializable representation of the primitive value at this path.
* Binary values are converted to base64-encoded strings.
*
* If the path does not resolve to any specific entry, returns `undefined`.
*/
compactJson(): CompactedJsonValue<T> | undefined;
}
/**
* AnyPathObjectCollectionMethods defines all possible methods available on a PathObject
* for the underlying collection types.
*/
interface AnyPathObjectCollectionMethods {
// LiveMap collection methods
/**
* Returns an iterable of key-value pairs for each entry in the map, if the path resolves to a {@link LiveMap}.
* Each value is represented as a {@link PathObject} corresponding to its key.
*
* If the path does not resolve to a map object, returns an empty iterator.
*/
entries<T extends Record<string, Value>>(): IterableIterator<[keyof T, PathObject<T[keyof T]>]>;
/**
* Returns an iterable of keys in the map, if the path resolves to a {@link LiveMap}.
*
* If the path does not resolve to a map object, returns an empty iterator.
*/
keys<T extends Record<string, Value>>(): IterableIterator<keyof T>;
/**
* Returns an iterable of values in the map, if the path resolves to a {@link LiveMap}.
* Each value is represented as a {@link PathObject}.
*
* If the path does not resolve to a map object, returns an empty iterator.
*/
values<T extends Record<string, Value>>(): IterableIterator<PathObject<T[keyof T]>>;
/**
* Returns the number of entries in the map, if the path resolves to a {@link LiveMap}.
*
* If the path does not resolve to a map object, returns `undefined`.
*/
size(): number | undefined;
}
/**
* Represents a {@link PathObject} when its underlying type is not known.
* Provides a unified interface that includes all possible methods.
*
* Each method supports type parameters to specify the expected
* underlying type when needed.
*/
export interface AnyPathObject
extends PathObjectBase,
PathObjectCollectionMethods,
AnyPathObjectCollectionMethods,
AnyOperations {
/**
* Navigate to a child path within the collection by obtaining a PathObject for that path.
* The next path segment in a collection is identified with a string key.
*
* @param key - A string key for the next path segment within the collection.
* @returns A {@link PathObject} for the specified key.
*/
get<T extends Value = Value>(key: string): PathObject<T>;
/**
* Get the current value of the LiveCounter or primitive currently at this path.
* If the path does not resolve to any specific entry, returns `undefined`.
*/
value<T extends number | Primitive = number | Primitive>(): T | undefined;
/**
* Get the specific object instance currently at this path.
* If the path does not resolve to any specific instance, returns `undefined`.
*
* @returns The object instance at this path, or `undefined` if none exists.
*/
instance<T extends Value = Value>(): Instance<T> | undefined;
/**
* Get an in-memory JavaScript object representation of the object at this path.
* For primitive types, this is an alias for calling {@link AnyPathObject.value | value()}.
*
* When compacting a {@link LiveMap}, cyclic references are handled through
* memoization, returning shared compacted object references for previously
* visited objects. This means the value returned from `compact()` cannot be
* directly JSON-stringified if the object may contain cycles.
*
* If the path does not resolve to any specific entry, returns `undefined`.
*
* Use {@link AnyPathObject.compactJson | compactJson()} for a JSON-serializable representation.
*/
compact<T extends Value = Value>(): CompactedValue<T> | undefined;
/**
* Get a JSON-serializable representation of the object at this path.
* Binary values are converted to base64-encoded strings.
*
* When compacting a {@link LiveMap}, cyclic references are represented as `{ objectId: string }`
* instead of in-memory pointers, making the result safe to pass to `JSON.stringify()`.
*
* If the path does not resolve to any specific entry, returns `undefined`.
*
* Use {@link AnyPathObject.compact | compact()} for an in-memory representation.
*/
compactJson<T extends Value = Value>(): CompactedJsonValue<T> | undefined;
}
/**
* PathObject wraps a reference to a path starting from the entrypoint object on a channel.
* The type parameter specifies the underlying type defined at that path,
* and is used to infer the correct set of methods available for that type.
*/
export type PathObject<T extends Value = Value> = [T] extends [LiveMap<infer U>]
? LiveMapPathObject<U>
: [T] extends [LiveCounter]
? LiveCounterPathObject
: [T] extends [Primitive]
? PrimitivePathObject<T>
: AnyPathObject;
/**
* BatchContextBase defines the set of common methods on a BatchContext
* that are present regardless of the underlying type.
*/
interface BatchContextBase {
/**
* Get the object ID of the underlying instance.
*
* If the underlying instance at runtime is not a {@link LiveObject}, returns `undefined`.
*/
readonly id: string | undefined;
}
/**
* Defines collection methods available on a {@link LiveMapBatchContext}.
*/
interface LiveMapBatchContextCollectionMethods<T extends Record<string, Value> = Record<string, Value>> {
/**
* Returns an iterable of key-value pairs for each entry in the map.
* Each value is represented as a {@link BatchContext} corresponding to its key.
*
* If the underlying instance at runtime is not a map, returns an empty iterator.
*/
entries(): IterableIterator<[keyof T, BatchContext<T[keyof T]>]>;
/**
* Returns an iterable of keys in the map.
*
* If the underlying instance at runtime is not a map, returns an empty iterator.
*/
keys(): IterableIterator<keyof T>;
/**
* Returns an iterable of values in the map.
* Each value is represented as a {@link BatchContext}.
*
* If the underlying instance at runtime is not a map, returns an empty iterator.
*/
values(): IterableIterator<BatchContext<T[keyof T]>>;
/**
* Returns the number of entries in the map.
*
* If the underlying instance at runtime is not a map, returns `undefined`.
*/
size(): number | undefined;
}
/**
* LiveMapBatchContext is a batch context wrapper for a LiveMap object.
* The type parameter T describes the expected structure of the map's entries.
*/
export interface LiveMapBatchContext<T extends Record<string, Value> = Record<string, Value>>
extends BatchContextBase,
BatchContextLiveMapOperations<T>,
LiveMapBatchContextCollectionMethods<T> {
/**
* Returns the value associated with a given key as a {@link BatchContext}.
*
* Returns `undefined` if the key doesn't exist in the map, if the referenced {@link LiveObject} has been deleted,
* or if this map object itself has been deleted.
*
* @param key - The key to retrieve the value for.
* @returns A {@link BatchContext} representing a {@link LiveObject}, a primitive type (string, number, boolean, JSON-serializable object or array, or binary data) or `undefined` if the key doesn't exist in a map or the referenced {@link LiveObject} has been deleted. Always `undefined` if this map object is deleted.
*/
get<K extends keyof T & string>(key: K): BatchContext<T[K]> | undefined;
/**
* Get an in-memory JavaScript object representation of the map instance.
* Cyclic references are handled through memoization, returning shared compacted
* object references for previously visited objects. This means the value returned
* from `compact()` cannot be directly JSON-stringified if the object may contain cycles.
*
* If the underlying instance's value is not of the expected type at runtime, returns `undefined`.
*
* Use {@link LiveMapBatchContext.compactJson | compactJson()} for a JSON-serializable representation.
*/
compact(): CompactedValue<LiveMap<T>> | undefined;
/**
* Get a JSON-serializable representation of the map instance.
* Binary values are converted to base64-encoded strings.
* Cyclic references are represented as `{ objectId: string }` instead of in-memory pointers,
* making the result safe to pass to `JSON.stringify()`.
*
* If the underlying instance's value is not of the expected type at runtime, returns `undefined`.
*
* Use {@link LiveMapBatchContext.compact | compact()} for an in-memory representation.
*/
compactJson(): CompactedJsonValue<LiveMap<T>> | undefined;
}
/**
* LiveCounterBatchContext is a batch context wrapper for a LiveCounter object.
*/
export interface LiveCounterBatchContext extends BatchContextBase, BatchContextLiveCounterOperations {
/**
* Get the current value of the counter instance.
* If the underlying instance at runtime is not a counter, returns `undefined`.
*/
value(): number | undefined;
/**
* Get a number representation of the counter instance.
* This is an alias for calling {@link LiveCounterBatchContext.value | value()}.
*
* If the underlying instance's value is not of the expected type at runtime, returns `undefined`.
*/
compact(): CompactedValue<LiveCounter> | undefined;
/**
* Get a number representation of the counter instance.
* This is an alias for calling {@link LiveCounterBatchContext.value | value()}.
*
* If the underlying instance's value is not of the expected type at runtime, returns `undefined`.
*/
compactJson(): CompactedJsonValue<LiveCounter> | undefined;
}
/**
* PrimitiveBatchContext is a batch context wrapper for a primitive value (string, number, boolean, JSON-serializable object or array, or binary data).
*/
export interface PrimitiveBatchContext<T extends Primitive = Primitive> {
/**
* Get the underlying primitive value.
* If the underlying instance at runtime is not a primitive value, returns `undefined`.
*/
value(): T | undefined;
/**
* Get a JavaScript object representation of the primitive value.
* This is an alias for calling {@link PrimitiveBatchContext.value | value()}.
*
* If the underlying instance's value is not of the expected type at runtime, returns `undefined`.
*/
compact(): CompactedValue<T> | undefined;
/**
* Get a JSON-serializable representation of the primitive value.
* Binary values are converted to base64-encoded strings.
*
* If the underlying instance's value is not of the expected type at runtime, returns `undefined`.
*/
compactJson(): CompactedJsonValue<T> | undefined;
}
/**
* AnyBatchContextCollectionMethods defines all possible methods available on an BatchContext object
* for the underlying collection types.
*/
interface AnyBatchContextCollectionMethods {
// LiveMap collection methods
/**
* Returns an iterable of key-value pairs for each entry in the map.
* Each value is represented as an {@link BatchContext} corresponding to its key.
*
* If the underlying instance at runtime is not a map, returns an empty iterator.
*/
entries<T extends Record<string, Value>>(): IterableIterator<[keyof T, BatchContext<T[keyof T]>]>;
/**
* Returns an iterable of keys in the map.
*
* If the underlying instance at runtime is not a map, returns an empty iterator.
*/
keys<T extends Record<string, Value>>(): IterableIterator<keyof T>;
/**
* Returns an iterable of values in the map.
* Each value is represented as a {@link BatchContext}.
*
* If the underlying instance at runtime is not a map, returns an empty iterator.
*/
values<T extends Record<string, Value>>(): IterableIterator<BatchContext<T[keyof T]>>;
/**
* Returns the number of entries in the map.
*
* If the underlying instance at runtime is not a map, returns `undefined`.
*/
size(): number | undefined;
}
/**
* Represents a {@link BatchContext} when its underlying type is not known.
* Provides a unified interface that includes all possible methods.
*
* Each method supports type parameters to specify the expected
* underlying type when needed.
*/
export interface AnyBatchContext extends BatchContextBase, AnyBatchContextCollectionMethods, BatchContextAnyOperations {
/**
* Navigate to a child entry within the collection by obtaining the {@link BatchContext} at that entry.
* The entry in a collection is identified with a string key.
*
* Returns `undefined` if:
* - The underlying instance at runtime is not a collection object.
* - The specified key does not exist in the collection.
* - The referenced {@link LiveObject} has been deleted.
* - This collection object itself has been deleted.
*
* @param key - The key to retrieve the value for.
* @returns A {@link BatchContext} representing either a {@link LiveObject} or a primitive value (string, number, boolean, JSON-serializable object or array, or binary data), or `undefined` if the underlying instance at runtime is not a collection object, the key does not exist, the referenced {@link LiveObject} has been deleted, or this collection object itself has been deleted.
*/
get<T extends Value = Value>(key: string): BatchContext<T> | undefined;
/**
* Get the current value of the underlying counter or primitive.
*
* If the underlying instance at runtime is neither a counter nor a primitive value, returns `undefined`.
*
* @returns The current value of the underlying primitive or counter, or `undefined` if the value cannot be retrieved.
*/
value<T extends number | Primitive = number | Primitive>(): T | undefined;
/**
* Get an in-memory JavaScript object representation of the object instance.
* For primitive types, this is an alias for calling {@link AnyBatchContext.value | value()}.
*
* When compacting a {@link LiveMap}, cyclic references are handled through
* memoization, returning shared compacted object references for previously
* visited objects. This means the value returned from `compact()` cannot be
* directly JSON-stringified if the object may contain cycles.
*
* If the underlying instance's value is not of the expected type at runtime, returns `undefined`.
*
* Use {@link AnyBatchContext.compactJson | compactJson()} for a JSON-serializable representation.
*/
compact<T extends Value = Value>(): CompactedValue<T> | undefined;
/**
* Get a JSON-serializable representation of the object instance.
* Binary values are converted to base64-encoded strings.
*
* When compacting a {@link LiveMap}, cyclic references are represented as `{ objectId: string }`
* instead of in-memory pointers, making the result safe to pass to `JSON.stringify()`.
*
* If the underlying instance's value is not of the expected type at runtime, returns `undefined`.
*
* Use {@link AnyBatchContext.compact | compact()} for an in-memory representation.
*/
compactJson<T extends Value = Value>(): CompactedJsonValue<T> | undefined;
}
/**
* BatchContext wraps a specific object instance or entry in a specific collection
* object instance and provides synchronous operation methods that can be aggregated
* and applied as a single batch operation.
*
* The type parameter specifies the underlying type of the instance,
* and is used to infer the correct set of methods available for that type.
*/
export type BatchContext<T extends Value> = [T] extends [LiveMap<infer U>]
? LiveMapBatchContext<U>
: [T] extends [LiveCounter]
? LiveCounterBatchContext
: [T] extends [Primitive]
? PrimitiveBatchContext<T>
: AnyBatchContext;
/**
* Defines operations available on {@link LiveMapBatchContext}.
*/
interface BatchContextLiveMapOperations<T extends Record<string, Value> = Record<string, Value>> {
/**
* Adds an operation to the current batch to set a key to a specified value on the underlying
* {@link LiveMapInstance}. All queued operations are sent together in a single message once the
* batch function completes.
*
* If the underlying instance at runtime is not a map, this method throws an error.
*
* This does not modify the underlying data of the map. Instead, when the batch function returns, the
* batched operations are sent to Ably. Once accepted, they are applied locally before the
* promise returned by {@link BatchOperations.batch | batch()} resolves.
*
* @param key - The key to set the value for.
* @param value - The value to assign to the key.
*/
set<K extends keyof T & string>(key: K, value: T[K]): void;
/**
* Adds an operation to the current batch to remove a key from the underlying
* {@link LiveMapInstance}. All queued operations are sent together in a single message once the
* batch function completes.
*
* If the underlying instance at runtime is not a map, this method throws an error.
*
* This does not modify the underlying data of the map. Instead, when the batch function returns, the
* batched operations are sent to Ably. Once accepted, they are applied locally before the
* promise returned by {@link BatchOperations.batch | batch()} resolves.
*
* @param key - The key to remove.
*/
remove(key: keyof T & string): void;
}
/**
* Defines operations available on {@link LiveCounterBatchContext}.
*/
interface BatchContextLiveCounterOperations {
/**
* Adds an operation to the current batch to increment the value of the underlying
* {@link LiveCounterInstance}. All queued operations are sent together in a single message once the
* batch function completes.
*
* If the underlying instance at runtime is not a counter, this method throws an error.
*
* This does not modify the underlying data of the counter. Instead, when the batch function returns, the
* batched operations are sent to Ably. Once accepted, they are applied locally before the
* promise returned by {@link BatchOperations.batch | batch()} resolves.
*
* @param amount - The amount by which to increase the counter value. If not provided, defaults to 1.
*/
increment(amount?: number): void;
/**
* An alias for calling {@link BatchContextLiveCounterOperations.increment | increment(-amount)}
*
* @param amount - The amount by which to decrease the counter value. If not provided, defaults to 1.
*/
decrement(amount?: number): void;
}
/**
* Defines all possible operations available on {@link BatchContext} objects.
*/
interface BatchContextAnyOperations {
// LiveMap operations
/**
* Adds an operation to the current batch to set a key to a specified value on the underlying
* {@link LiveMapInstance}. All queued operations are sent together in a single message once the
* batch function completes.
*
* If the underlying instance at runtime is not a map, this method throws an error.
*
* This does not modify the underlying data of the map. Instead, when the batch function returns, the
* batched operations are sent to Ably. Once accepted, they are applied locally before the
* promise returned by {@link BatchOperations.batch | batch()} resolves.
*
* @param key - The key to set the value for.
* @param value - The value to assign to the key.
*/
set<T extends Record<string, Value> = Record<string, Value>>(key: keyof T & string, value: T[keyof T]): void;
/**
* Adds an operation to the current batch to remove a key from the underlying
* {@link LiveMapInstance}. All queued operations are sent together in a single message once the
* batch function completes.
*
* If the underlying instance at runtime is not a map, this method throws an error.
*
* This does not modify the underlying data of the map. Instead, when the batch function returns, the
* batched operations are sent to Ably. Once accepted, they are applied locally before the
* promise returned by {@link BatchOperations.batch | batch()} resolves.
*
* @param key - The key to remove.
*/
remove<T extends Record<string, Value> = Record<string, Value>>(key: keyof T & string): void;
// LiveCounter operations
/**
* Adds an operation to the current batch to increment the value of the underlying
* {@link LiveCounterInstance}. All queued operations are sent together in a single message once the
* batch function completes.
*
* If the underlying instance at runtime is not a counter, this method throws an error.
*
* This does not modify the underlying data of the counter. Instead, when the batch function returns, the
* batched operations are sent to Ably. Once accepted, they are applied locally before the
* promise returned by {@link BatchOperations.batch | batch()} resolves.
*
* @param amount - The amount by which to increase the counter value. If not provided, defaults to 1.
*/
increment(amount?: number): void;
/**
* An alias for calling {@link BatchContextAnyOperations.increment | increment(-amount)}
*
* @param amount - The amount by which to decrease the counter value. If not provided, defaults to 1.
*/
decrement(amount?: number): void;
}
/**
* Defines batch operations available on {@link LiveObject | LiveObjects}.
*/
interface BatchOperations<T extends LiveObject> {
/**
* Batch multiple operations together using a batch context, which
* wraps the underlying {@link PathObject} or {@link Instance} from which the batch was called.
* The batch context always contains a resolved instance, even when called from a {@link PathObject}.
* If an instance cannot be resolved from the referenced path, or if the instance is not a {@link LiveObject},
* this method throws an error.
*
* Batching enables you to group multiple operations together and send them to the Ably service in a single channel message.
* As a result, other clients will receive the changes in a single channel message once the batch function has completed.
*
* The objects' data is not modified inside the batch function. The batched operations are sent to Ably
* and, once accepted, applied locally. The returned promise resolves after all operations have been applied.
*
* @param fn - A synchronous function that receives a {@link BatchContext} used to group operations together.
* @returns A promise which resolves after all batched operations have been accepted by Ably and applied locally, or rejects with an {@link ErrorInfo} object upon failure.
*/
batch(fn: BatchFunction<T>): Promise<void>;
}
/**
* Defines operations available on {@link LiveMap} objects.
*/
interface LiveMapOperations<T extends Record<string, Value> = Record<string, Value>>
extends BatchOperations<LiveMap<T>> {
/**
* Sends an operation to the Ably system to set a key to a specified value on a given {@link LiveMapInstance},
* or on the map instance resolved from the path when using {@link LiveMapPathObject}.
*
* If called via {@link LiveMapInstance} and the underlying instance at runtime is not a map,
* or if called via {@link LiveMapPathObject} and the map instance at the specified path cannot
* be resolved at the time of the call, this method throws an error.
*
* The operation is sent to Ably and, once accepted, applied locally. The returned promise resolves
* after the operation has been applied.
*
* @param key - The key to set the value for.
* @param value - The value to assign to the key.
* @returns A promise which resolves after the operation has been accepted by Ably and applied locally, or rejects with an {@link ErrorInfo} object upon failure.
*/
set<K extends keyof T & string>(key: K, value: T[K]): Promise<void>;