@lark-sh/client 0.1.11 → 0.1.13

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.d.mts CHANGED
@@ -209,9 +209,10 @@ declare class DatabaseReference {
209
209
  setWithPriority(value: unknown, priority: number | string): Promise<void>;
210
210
  /**
211
211
  * Set the priority of the data at this location.
212
- * Fetches current value and sets it with the new priority.
212
+ * Uses cached value for optimistic behavior (local effects are immediate).
213
+ * The optimistic update happens synchronously, Promise resolves after server ack.
213
214
  */
214
- setPriority(priority: number | string): Promise<void>;
215
+ setPriority(priority: number | string | null): Promise<void>;
215
216
  /**
216
217
  * Atomically modify the data at this location using optimistic concurrency.
217
218
  *
@@ -238,10 +239,14 @@ declare class DatabaseReference {
238
239
  /**
239
240
  * Read the data at this location once.
240
241
  *
241
- * @param eventType - The event type (only 'value' is supported)
242
+ * For 'value' events, this fetches data directly from the server.
243
+ * For child events ('child_added', 'child_changed', 'child_removed', 'child_moved'),
244
+ * this subscribes, waits for the first event, then unsubscribes.
245
+ *
246
+ * @param eventType - The event type
242
247
  * @returns Promise that resolves to the DataSnapshot
243
248
  */
244
- once(eventType?: 'value'): Promise<DataSnapshot>;
249
+ once(eventType?: EventType): Promise<DataSnapshot>;
245
250
  /**
246
251
  * Subscribe to events at this location.
247
252
  * Returns an unsubscribe function.
@@ -344,6 +349,11 @@ declare class DatabaseReference {
344
349
  * Format: https://db.lark.sh/project/database/path/to/data
345
350
  */
346
351
  toString(): string;
352
+ /**
353
+ * Returns the URL for JSON serialization.
354
+ * This allows refs to be serialized with JSON.stringify().
355
+ */
356
+ toJSON(): string;
347
357
  }
348
358
  /**
349
359
  * A reference that is also a Promise - returned by push().
@@ -462,6 +472,7 @@ declare class DataSnapshot {
462
472
  val<T = any>(): T;
463
473
  /**
464
474
  * Check if data exists at this location (is not null/undefined).
475
+ * Returns false for priority-only nodes (only .priority, no actual value).
465
476
  */
466
477
  exists(): boolean;
467
478
  /**
@@ -609,7 +620,16 @@ interface TransactionConditionOp {
609
620
  type TransactionOp = TransactionSetOp | TransactionUpdateOp | TransactionDeleteOp | TransactionConditionOp;
610
621
  /** Object syntax for transactions: path -> value (null = delete) */
611
622
  type TransactionObject = Record<string, unknown>;
612
- type ConnectionState = 'disconnected' | 'connecting' | 'connected' | 'reconnecting';
623
+ /**
624
+ * Connection state machine:
625
+ * - 'disconnected': Not connected
626
+ * - 'connecting': Initial connection in progress
627
+ * - 'connected': WebSocket open
628
+ * - 'joined': Join complete (database identified)
629
+ * - 'authenticated': Auth complete (ready to operate)
630
+ * - 'reconnecting': Attempting to reconnect after disconnect
631
+ */
632
+ type ConnectionState = 'disconnected' | 'connecting' | 'connected' | 'joined' | 'authenticated' | 'reconnecting';
613
633
  /**
614
634
  * Server values that are resolved by the server when a write is committed.
615
635
  * Use these with set(), update(), or push() to have the server fill in values.
@@ -695,6 +715,8 @@ declare class LarkDatabase {
695
715
  private _coordinatorUrl;
696
716
  private _volatilePaths;
697
717
  private _transportType;
718
+ private _currentToken;
719
+ private _isAnonymous;
698
720
  private _connectionId;
699
721
  private _connectOptions;
700
722
  private _intentionalDisconnect;
@@ -708,11 +730,15 @@ declare class LarkDatabase {
708
730
  private disconnectCallbacks;
709
731
  private errorCallbacks;
710
732
  private reconnectingCallbacks;
733
+ private authStateChangedCallbacks;
711
734
  private infoSubscriptions;
735
+ private authenticationPromise;
736
+ private authenticationResolve;
712
737
  private _serverTimeOffset;
713
738
  constructor();
714
739
  /**
715
- * Whether the database is currently connected.
740
+ * Whether the database is fully connected and authenticated.
741
+ * Returns true when ready to perform database operations.
716
742
  */
717
743
  get connected(): boolean;
718
744
  /**
@@ -769,6 +795,10 @@ declare class LarkDatabase {
769
795
  connect(databaseId: string, options?: ConnectOptions): Promise<void>;
770
796
  /**
771
797
  * Internal connect implementation used by both initial connect and reconnect.
798
+ * Implements the Join → Auth flow:
799
+ * 1. Connect WebSocket
800
+ * 2. Send join (identifies database)
801
+ * 3. Send auth (authenticates user - required even for anonymous)
772
802
  */
773
803
  private performConnect;
774
804
  /**
@@ -901,9 +931,50 @@ declare class LarkDatabase {
901
931
  * Returns an unsubscribe function.
902
932
  */
903
933
  onReconnecting(callback: () => void): () => void;
934
+ /**
935
+ * Register a callback for auth state changes.
936
+ * Fires when user signs in, signs out, or auth changes.
937
+ * Returns an unsubscribe function.
938
+ */
939
+ onAuthStateChanged(callback: (auth: AuthInfo | null) => void): () => void;
940
+ /**
941
+ * Sign in with a new auth token while connected.
942
+ * Changes the authenticated user without disconnecting.
943
+ *
944
+ * Note: Some subscriptions may be revoked if the new user doesn't have
945
+ * permission. Listen for 'permission_denied' errors on your subscriptions.
946
+ *
947
+ * @param token - The auth token for the new user
948
+ * @throws Error if not connected (must call connect() first)
949
+ */
950
+ signIn(token: string): Promise<void>;
951
+ /**
952
+ * Sign out the current user.
953
+ * Reverts to anonymous authentication.
954
+ *
955
+ * Note: Some subscriptions may be revoked if anonymous users don't have
956
+ * permission. Listen for 'permission_denied' errors on your subscriptions.
957
+ */
958
+ signOut(): Promise<void>;
904
959
  private handleMessage;
905
960
  private handleClose;
906
961
  private handleError;
962
+ /**
963
+ * Check if authenticated synchronously.
964
+ * Returns true if authenticated, false if connecting (should wait), throws if disconnected.
965
+ */
966
+ private isAuthenticatedOrThrow;
967
+ /**
968
+ * Wait for authentication to complete before performing an operation.
969
+ * If already authenticated, returns immediately (synchronously).
970
+ * If connecting/reconnecting, waits for auth to complete.
971
+ * If disconnected and no connect in progress, throws.
972
+ *
973
+ * IMPORTANT: This returns a Promise only if waiting is needed.
974
+ * Callers should use: `if (!this.isAuthenticatedOrThrow()) if (!this.isAuthenticatedOrThrow()) await this.waitForAuthenticated();`
975
+ * to preserve synchronous execution when already authenticated.
976
+ */
977
+ private waitForAuthenticated;
907
978
  private send;
908
979
  /**
909
980
  * @internal Send a set operation.
@@ -962,6 +1033,14 @@ declare class LarkDatabase {
962
1033
  * @internal Send an onDisconnect operation.
963
1034
  */
964
1035
  _sendOnDisconnect(path: string, action: string, value?: unknown): Promise<void>;
1036
+ /**
1037
+ * @internal Get a cached value from the subscription manager.
1038
+ * Used for optimistic writes where we need the current value without a network fetch.
1039
+ */
1040
+ _getCachedValue(path: string): {
1041
+ value: unknown;
1042
+ found: boolean;
1043
+ };
965
1044
  /**
966
1045
  * @internal Send a subscribe message to server.
967
1046
  * Includes tag for non-default queries to enable proper event routing.
package/dist/index.d.ts CHANGED
@@ -209,9 +209,10 @@ declare class DatabaseReference {
209
209
  setWithPriority(value: unknown, priority: number | string): Promise<void>;
210
210
  /**
211
211
  * Set the priority of the data at this location.
212
- * Fetches current value and sets it with the new priority.
212
+ * Uses cached value for optimistic behavior (local effects are immediate).
213
+ * The optimistic update happens synchronously, Promise resolves after server ack.
213
214
  */
214
- setPriority(priority: number | string): Promise<void>;
215
+ setPriority(priority: number | string | null): Promise<void>;
215
216
  /**
216
217
  * Atomically modify the data at this location using optimistic concurrency.
217
218
  *
@@ -238,10 +239,14 @@ declare class DatabaseReference {
238
239
  /**
239
240
  * Read the data at this location once.
240
241
  *
241
- * @param eventType - The event type (only 'value' is supported)
242
+ * For 'value' events, this fetches data directly from the server.
243
+ * For child events ('child_added', 'child_changed', 'child_removed', 'child_moved'),
244
+ * this subscribes, waits for the first event, then unsubscribes.
245
+ *
246
+ * @param eventType - The event type
242
247
  * @returns Promise that resolves to the DataSnapshot
243
248
  */
244
- once(eventType?: 'value'): Promise<DataSnapshot>;
249
+ once(eventType?: EventType): Promise<DataSnapshot>;
245
250
  /**
246
251
  * Subscribe to events at this location.
247
252
  * Returns an unsubscribe function.
@@ -344,6 +349,11 @@ declare class DatabaseReference {
344
349
  * Format: https://db.lark.sh/project/database/path/to/data
345
350
  */
346
351
  toString(): string;
352
+ /**
353
+ * Returns the URL for JSON serialization.
354
+ * This allows refs to be serialized with JSON.stringify().
355
+ */
356
+ toJSON(): string;
347
357
  }
348
358
  /**
349
359
  * A reference that is also a Promise - returned by push().
@@ -462,6 +472,7 @@ declare class DataSnapshot {
462
472
  val<T = any>(): T;
463
473
  /**
464
474
  * Check if data exists at this location (is not null/undefined).
475
+ * Returns false for priority-only nodes (only .priority, no actual value).
465
476
  */
466
477
  exists(): boolean;
467
478
  /**
@@ -609,7 +620,16 @@ interface TransactionConditionOp {
609
620
  type TransactionOp = TransactionSetOp | TransactionUpdateOp | TransactionDeleteOp | TransactionConditionOp;
610
621
  /** Object syntax for transactions: path -> value (null = delete) */
611
622
  type TransactionObject = Record<string, unknown>;
612
- type ConnectionState = 'disconnected' | 'connecting' | 'connected' | 'reconnecting';
623
+ /**
624
+ * Connection state machine:
625
+ * - 'disconnected': Not connected
626
+ * - 'connecting': Initial connection in progress
627
+ * - 'connected': WebSocket open
628
+ * - 'joined': Join complete (database identified)
629
+ * - 'authenticated': Auth complete (ready to operate)
630
+ * - 'reconnecting': Attempting to reconnect after disconnect
631
+ */
632
+ type ConnectionState = 'disconnected' | 'connecting' | 'connected' | 'joined' | 'authenticated' | 'reconnecting';
613
633
  /**
614
634
  * Server values that are resolved by the server when a write is committed.
615
635
  * Use these with set(), update(), or push() to have the server fill in values.
@@ -695,6 +715,8 @@ declare class LarkDatabase {
695
715
  private _coordinatorUrl;
696
716
  private _volatilePaths;
697
717
  private _transportType;
718
+ private _currentToken;
719
+ private _isAnonymous;
698
720
  private _connectionId;
699
721
  private _connectOptions;
700
722
  private _intentionalDisconnect;
@@ -708,11 +730,15 @@ declare class LarkDatabase {
708
730
  private disconnectCallbacks;
709
731
  private errorCallbacks;
710
732
  private reconnectingCallbacks;
733
+ private authStateChangedCallbacks;
711
734
  private infoSubscriptions;
735
+ private authenticationPromise;
736
+ private authenticationResolve;
712
737
  private _serverTimeOffset;
713
738
  constructor();
714
739
  /**
715
- * Whether the database is currently connected.
740
+ * Whether the database is fully connected and authenticated.
741
+ * Returns true when ready to perform database operations.
716
742
  */
717
743
  get connected(): boolean;
718
744
  /**
@@ -769,6 +795,10 @@ declare class LarkDatabase {
769
795
  connect(databaseId: string, options?: ConnectOptions): Promise<void>;
770
796
  /**
771
797
  * Internal connect implementation used by both initial connect and reconnect.
798
+ * Implements the Join → Auth flow:
799
+ * 1. Connect WebSocket
800
+ * 2. Send join (identifies database)
801
+ * 3. Send auth (authenticates user - required even for anonymous)
772
802
  */
773
803
  private performConnect;
774
804
  /**
@@ -901,9 +931,50 @@ declare class LarkDatabase {
901
931
  * Returns an unsubscribe function.
902
932
  */
903
933
  onReconnecting(callback: () => void): () => void;
934
+ /**
935
+ * Register a callback for auth state changes.
936
+ * Fires when user signs in, signs out, or auth changes.
937
+ * Returns an unsubscribe function.
938
+ */
939
+ onAuthStateChanged(callback: (auth: AuthInfo | null) => void): () => void;
940
+ /**
941
+ * Sign in with a new auth token while connected.
942
+ * Changes the authenticated user without disconnecting.
943
+ *
944
+ * Note: Some subscriptions may be revoked if the new user doesn't have
945
+ * permission. Listen for 'permission_denied' errors on your subscriptions.
946
+ *
947
+ * @param token - The auth token for the new user
948
+ * @throws Error if not connected (must call connect() first)
949
+ */
950
+ signIn(token: string): Promise<void>;
951
+ /**
952
+ * Sign out the current user.
953
+ * Reverts to anonymous authentication.
954
+ *
955
+ * Note: Some subscriptions may be revoked if anonymous users don't have
956
+ * permission. Listen for 'permission_denied' errors on your subscriptions.
957
+ */
958
+ signOut(): Promise<void>;
904
959
  private handleMessage;
905
960
  private handleClose;
906
961
  private handleError;
962
+ /**
963
+ * Check if authenticated synchronously.
964
+ * Returns true if authenticated, false if connecting (should wait), throws if disconnected.
965
+ */
966
+ private isAuthenticatedOrThrow;
967
+ /**
968
+ * Wait for authentication to complete before performing an operation.
969
+ * If already authenticated, returns immediately (synchronously).
970
+ * If connecting/reconnecting, waits for auth to complete.
971
+ * If disconnected and no connect in progress, throws.
972
+ *
973
+ * IMPORTANT: This returns a Promise only if waiting is needed.
974
+ * Callers should use: `if (!this.isAuthenticatedOrThrow()) if (!this.isAuthenticatedOrThrow()) await this.waitForAuthenticated();`
975
+ * to preserve synchronous execution when already authenticated.
976
+ */
977
+ private waitForAuthenticated;
907
978
  private send;
908
979
  /**
909
980
  * @internal Send a set operation.
@@ -962,6 +1033,14 @@ declare class LarkDatabase {
962
1033
  * @internal Send an onDisconnect operation.
963
1034
  */
964
1035
  _sendOnDisconnect(path: string, action: string, value?: unknown): Promise<void>;
1036
+ /**
1037
+ * @internal Get a cached value from the subscription manager.
1038
+ * Used for optimistic writes where we need the current value without a network fetch.
1039
+ */
1040
+ _getCachedValue(path: string): {
1041
+ value: unknown;
1042
+ found: boolean;
1043
+ };
965
1044
  /**
966
1045
  * @internal Send a subscribe message to server.
967
1046
  * Includes tag for non-default queries to enable proper event routing.