@instantdb/core
Version:
Instant's core local abstraction
314 lines • 12.1 kB
TypeScript
/**
* @template {import('./presence.ts').RoomSchemaShape} [RoomSchema = {}]
*/
export default class Reactor<RoomSchema extends import("./presence.ts").RoomSchemaShape = {}> {
constructor(config: any, Storage: typeof IndexedDBStorage, NetworkListener: typeof WindowNetworkListener, versions: any);
attrs: any;
_isOnline: boolean;
_isShutdown: boolean;
status: string;
/** @type {PersistedObject} */
querySubs: PersistedObject;
/** @type {PersistedObject} */
pendingMutations: PersistedObject;
/** @type {Record<string, Array<{ q: any, cb: (data: any) => any }>>} */
queryCbs: Record<string, Array<{
q: any;
cb: (data: any) => any;
}>>;
/** @type {Record<string, Array<{ q: any, eventId: string, dfd: Deferred }>>} */
queryOnceDfds: Record<string, Array<{
q: any;
eventId: string;
dfd: Deferred;
}>>;
authCbs: any[];
attrsCbs: any[];
mutationErrorCbs: any[];
connectionStatusCbs: any[];
config: any;
_persister: any;
mutationDeferredStore: Map<any, any>;
_reconnectTimeoutId: any;
_reconnectTimeoutMs: number;
_ws: any;
_localIdPromises: {};
_errorMessage: any;
/** @type {Promise<null | {error: {message: string}}>}**/
_oauthCallbackResponse: Promise<null | {
error: {
message: string;
};
}>;
/** @type {null | import('./utils/linkIndex.ts').LinkIndex}} */
_linkIndex: null | import("./utils/linkIndex.ts").LinkIndex;
/** @type BroadcastChannel | undefined */
_broadcastChannel: BroadcastChannel | undefined;
/** @type {Record<string, {isConnected: boolean; error: any}>} */
_rooms: Record<string, {
isConnected: boolean;
error: any;
}>;
/** @type {Record<string, boolean>} */
_roomsPendingLeave: Record<string, boolean>;
_presence: {};
_broadcastQueue: any[];
_broadcastSubs: {};
_currentUserCached: {
isLoading: boolean;
error: any;
user: any;
};
_beforeUnloadCbs: any[];
_dataForQueryCache: {};
/** @type {Logger} */
_log: Logger;
queryCacheLimit: any;
versions: any;
_beforeUnload(): void;
updateSchema(schema: any): void;
_initStorage(Storage: any): void;
/**
* @param {'enqueued' | 'pending' | 'synced' | 'timeout' | 'error' } status
* @param string eventId
* @param {{message?: string, hint?: string, error?: Error}} [errDetails]
*/
_finishTransaction(status: "enqueued" | "pending" | "synced" | "timeout" | "error", eventId: any, errDetails?: {
message?: string;
hint?: string;
error?: Error;
}): void;
_setStatus(status: any, err: any): void;
/**
* merge querySubs from storage and in memory. Has the following side
* effects:
* - We notify all queryCbs because results may been added during merge
*/
_onMergeQuerySubs: (_storageSubs: any, inMemorySubs: any) => void;
/**
* merge pendingMutations from storage and in memory. Has a side effect of
* sending mutations that were stored but not acked
*/
_onMergePendingMutations: (storageMuts: any, inMemoryMuts: any) => void;
_flushEnqueuedRoomData(roomId: any): void;
_handleReceive(wsId: any, msg: any): void;
_sessionId: any;
/**
* @param {'timeout' | 'error'} status
* @param {string} eventId
* @param {{message?: string, hint?: string, error?: Error}} errDetails
*/
_handleMutationError(status: "timeout" | "error", eventId: string, errDetails: {
message?: string;
hint?: string;
error?: Error;
}): void;
_handleReceiveError(msg: any): void;
notifyQueryOnceError(q: any, hash: any, eventId: any, e: any): void;
_setAttrs(attrs: any): void;
getPreviousResult: (q: any) => any;
_startQuerySub(q: any, hash: any): string;
/**
* When a user subscribes to a query the following side effects occur:
*
* - We update querySubs to include the new query
* - We update queryCbs to include the new cb
* - If we already have a result for the query we call cb immediately
* - We send the server an `add-query` message
*
* Returns an unsubscribe function
*/
subscribeQuery(q: any, cb: any, opts: any): () => void;
queryOnce(q: any, opts: any): Promise<any>;
_completeQueryOnce(q: any, hash: any, dfd: any): void;
_unsubQuery(q: any, hash: any, cb: any): void;
_cleanupQuery(q: any, hash: any): void;
_rewriteMutations(attrs: any, muts: any, processedTxId: any): any;
_rewriteMutationsSorted(attrs: any, muts: any): any[];
optimisticAttrs(): any;
/** Runs instaql on a query and a store */
dataForQuery(hash: any): any;
_applyOptimisticUpdates(store: any, mutations: any, processedTxId: any): any;
/** Re-run instaql and call all callbacks with new data */
notifyOne: (hash: any) => void;
notifyOneQueryOnce: (hash: any) => void;
notifyQueryError: (hash: any, error: any) => void;
/** Re-compute all subscriptions */
notifyAll(): void;
loadedNotifyAll(): void;
/** Applies transactions locally and sends transact message to server */
pushTx: (chunks: any) => Promise<any>;
/**
* @param {*} txSteps
* @param {*} [error]
* @returns
*/
pushOps: (txSteps: any, error?: any) => Promise<any>;
shutdown(): void;
/**
* Sends mutation to server and schedules a timeout to cancel it if
* we don't hear back in time.
* Note: If we're offline we don't schedule a timeout, we'll schedule it
* later once we're back online and send the mutation again
*
*/
_sendMutation(eventId: any, mutation: any): void;
/** Send messages we accumulated while we were connecting */
_flushPendingMessages(): void;
/**
* Clean up pendingMutations that all queries have seen
*/
_cleanupPendingMutationsQueries(): void;
/**
* After mutations is confirmed by server, we give each query 30 sec
* to update its results. If that doesn't happen, we assume query is
* unaffected by this mutation and it’s safe to delete it from local queue
*/
_cleanupPendingMutationsTimeout(): void;
_trySendAuthed(...args: any[]): void;
_trySend(eventId: any, msg: any, opts: any): void;
_wsOnOpen: (e: any) => void;
_wsOnMessage: (e: any) => void;
_wsOnError: (e: any) => void;
_wsOnClose: (e: any) => void;
_startSocket(): void;
/**
* Given a key, returns a stable local id, unique to this device and app.
*
* This can be useful if you want to create guest ids for example.
*
* Note: If the user deletes their local storage, this id will change.
*
* We use this._localIdPromises to ensure that we only generate a local
* id once, even if multiple callers call this function concurrently.
*/
getLocalId(name: any): Promise<any>;
_replaceUrlAfterOAuth(): void;
/**
*
* @returns Promise<null | {error: {message: string}}>
*/
_oauthLoginInit(): Promise<{
error: {
message: any;
};
}>;
_waitForOAuthCallbackResponse(): Promise<{
error: {
message: string;
};
}>;
__subscribeMutationErrors(cb: any): () => void;
subscribeAuth(cb: any): () => void;
getAuth(): Promise<any>;
subscribeConnectionStatus(cb: any): () => void;
subscribeAttrs(cb: any): () => void;
notifyAuthSubs(user: any): void;
notifyMutationErrorSubs(error: any): void;
notifyAttrsSubs(): void;
notifyConnectionStatusSubs(status: any): void;
setCurrentUser(user: any): Promise<void>;
getCurrentUserCached(): {
isLoading: boolean;
error: any;
user: any;
};
getCurrentUser(): Promise<{
user: any;
error: any;
}>;
_hasCurrentUser(): Promise<boolean>;
changeCurrentUser(newUser: any): Promise<void>;
updateUser(newUser: any): void;
sendMagicCode({ email }: {
email: any;
}): Promise<authAPI.SendMagicCodeResponse>;
signInWithMagicCode({ email, code }: {
email: any;
code: any;
}): Promise<authAPI.VerifyResponse>;
signInWithCustomToken(authToken: any): Promise<authAPI.VerifyResponse>;
potentiallyInvalidateToken(currentUser: any, opts: any): void;
signOut(opts: any): Promise<void>;
/**
* Creates an OAuth authorization URL.
* @param {Object} params - The parameters to create the authorization URL.
* @param {string} params.clientName - The name of the client requesting authorization.
* @param {string} params.redirectURL - The URL to redirect users to after authorization.
* @returns {string} The created authorization URL.
*/
createAuthorizationURL({ clientName, redirectURL }: {
clientName: string;
redirectURL: string;
}): string;
/**
* @param {Object} params
* @param {string} params.code - The code received from the OAuth service.
* @param {string} [params.codeVerifier] - The code verifier used to generate the code challenge.
*/
exchangeCodeForToken({ code, codeVerifier }: {
code: string;
codeVerifier?: string;
}): Promise<authAPI.VerifyResponse>;
issuerURI(): string;
/**
* @param {Object} params
* @param {string} params.clientName - The name of the client requesting authorization.
* @param {string} params.idToken - The id_token from the external service
* @param {string | null | undefined} [params.nonce] - The nonce used when requesting the id_token from the external service
*/
signInWithIdToken({ idToken, clientName, nonce }: {
clientName: string;
idToken: string;
nonce?: string | null | undefined;
}): Promise<authAPI.VerifyResponse>;
/**
* @param {string} roomId
* @param {any | null | undefined} [initialData] -- initial presence data to send when joining the room
* @returns () => void
*/
joinRoom(roomId: string, initialData?: any | null | undefined): () => void;
_cleanupRoom(roomId: any): void;
getPresence(roomType: any, roomId: any, opts?: {}): {
isLoading: boolean;
error: any;
user?: Pick<any, string | number | symbol> & {
peerId: string;
};
peers: {
[peerId: string]: Pick<any, string | number | symbol> & {
peerId: string;
};
};
};
publishPresence(roomType: any, roomId: any, partialData: any): void;
_trySetPresence(roomId: any, data: any): void;
_tryJoinRoom(roomId: any, data: any): void;
_tryLeaveRoom(roomId: any): void;
subscribePresence(roomType: any, roomId: any, opts: any, cb: any): () => void;
_notifyPresenceSubs(roomId: any): void;
_notifyPresenceSub(roomId: any, handler: any): void;
_patchPresencePeers(roomId: any, edits: any): void;
_setPresencePeers(roomId: any, data: any): void;
publishTopic({ roomType, roomId, topic, data }: {
roomType: any;
roomId: any;
topic: any;
data: any;
}): void;
_tryBroadcast(roomId: any, roomType: any, topic: any, data: any): void;
subscribeTopic(roomId: any, topic: any, cb: any): () => void;
_notifyBroadcastSubs(room: any, topic: any, msg: any): void;
uploadFile(path: any, file: any, opts: any): Promise<StorageApi.UploadFileResponse>;
deleteFile(path: any): Promise<StorageApi.DeleteFileResponse>;
upload(path: any, file: any): Promise<boolean>;
getDownloadUrl(path: any): Promise<any>;
}
export type Logger = import("./utils/log.ts").Logger;
import { PersistedObject } from './utils/PersistedObject.js';
import { Deferred } from './utils/Deferred.js';
import * as authAPI from './authAPI.ts';
import * as StorageApi from './StorageAPI.ts';
import IndexedDBStorage from './IndexedDBStorage.js';
import WindowNetworkListener from './WindowNetworkListener.js';
//# sourceMappingURL=Reactor.d.ts.map