@instantdb/core
Version:
Instant's core local abstraction
397 lines • 15.6 kB
TypeScript
export namespace STATUS {
let CONNECTING: string;
let OPENED: string;
let AUTHENTICATED: string;
let CLOSED: string;
let ERRORED: string;
}
/**
* @template {import('./presence.ts').RoomSchemaShape} [RoomSchema = {}]
*/
export default class Reactor<RoomSchema extends import("./presence.ts").RoomSchemaShape = {}> {
constructor(config: any, Storage: typeof IndexedDBStorage | undefined, NetworkListener: typeof WindowNetworkListener | undefined, versions: any, EventSourceConstructor: any);
/** @type {s.AttrsStore | undefined} */
attrs: s.AttrsStore | undefined;
_isOnline: boolean;
_isShutdown: boolean;
status: string;
/** @type {PersistedObject<string, QuerySub, QuerySubInStorage>} */
querySubs: PersistedObject<string, QuerySub, QuerySubInStorage>;
/** @type {PersistedObject} */
kv: PersistedObject<any, any, any>;
/** @type {SyncTable} */
_syncTable: SyncTable;
/** @type {InstantStream} */
_instantStream: InstantStream;
/** @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;
mutationDeferredStore: Map<any, any>;
_reconnectTimeoutId: null;
_reconnectTimeoutMs: number;
/** @type {Connection} */
_transport: Connection;
/** @type {TransportType} */
_transportType: TransportType;
/** @type {EventSourceConstructor} */
_EventSource: EventSourceConstructor;
/** @type {boolean | null} */
_wsOk: boolean | null;
_localIdPromises: {};
_errorMessage: null;
/** @type {Promise<null | {error: {message: string}}> | null}**/
_oauthCallbackResponse: Promise<null | {
error: {
message: string;
};
}> | null;
/** @type {null | import('./utils/linkIndex.ts').LinkIndex}} */
_linkIndex: null | import("./utils/linkIndex.ts").LinkIndex;
/** @type BroadcastChannel | undefined */
_broadcastChannel: BroadcastChannel | undefined;
/** @type {Record<string, {roomType: string; isConnected: boolean; error: any}>} */
_rooms: Record<string, {
roomType: string;
isConnected: boolean;
error: any;
}>;
/** @type {Record<string, boolean>} */
_roomsPendingLeave: Record<string, boolean>;
_presence: {};
_broadcastQueue: any[];
_broadcastSubs: {};
/** @type {{isLoading: boolean; error: any | undefined, user: any | undefined}} */
_currentUserCached: {
isLoading: boolean;
error: any | undefined;
user: any | undefined;
};
_beforeUnloadCbs: any[];
_dataForQueryCache: {};
/** @type {Logger} */
_log: Logger;
_pendingTxCleanupTimeout: any;
_pendingMutationCleanupThreshold: any;
_inFlightMutationEventIds: Set<any>;
/** @type FrameworkClient | null */
_frameworkClient: FrameworkClient | null;
queryCacheLimit: any;
versions: any;
_beforeUnload(): void;
getFrameworkClient(): import("./framework.ts").FrameworkClient | null;
/** @param {FrameworkClient} client */
setFrameworkClient(client: FrameworkClient): void;
ensureAttrs(): s.AttrsStore;
updateSchema(schema: any): void;
_reactorStats(): {
inFlightMutationCount: number;
storedMutationCount: any;
transportType: import("./Connection.ts").TransportType;
};
_onQuerySubLoaded(hash: any): void;
_initStorage(Storage: any): void;
/**
* @param {'enqueued' | 'pending' | 'synced' | 'timeout' | 'error' } status
* @param {string} eventId
* @param {{message?: string, type?: string, status?: number, hint?: unknown}} [errorMsg]
*/
_finishTransaction(status: "enqueued" | "pending" | "synced" | "timeout" | "error", eventId: string, errorMsg?: {
message?: string;
type?: string;
status?: number;
hint?: unknown;
}): void;
_setStatus(status: any, err: any): void;
_onMergeKv: (key: any, storageV: any, inMemoryV: any) => any;
_flushEnqueuedRoomData(roomId: any): void;
/**
* Does the same thing as add-query-ok
* but called as a result of receiving query info from ssr
* @param {any} q
* @param {{ triples: any; pageInfo: any; }} result
* @param {boolean} enableCardinalityInference
*/
_addQueryData(q: any, result: {
triples: any;
pageInfo: any;
}, enableCardinalityInference: boolean): void;
_handleReceive(connId: any, msg: any): void;
_sessionId: any;
createWriteStream(opts: any): import("./Stream.ts").InstantWritableStream<string>;
createReadStream(opts: any): ReadableStream<string>;
_pendingMutations(): any;
_updatePendingMutations(f: any): void;
/**
* @param {'timeout' | 'error'} status
* @param {string} eventId
* @param {{message?: string, type?: string, status?: number, hint?: unknown}} errorMsg
*/
_handleMutationError(status: "timeout" | "error", eventId: string, errorMsg: {
message?: string;
type?: string;
status?: number;
hint?: unknown;
}): 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;
subscribeTable(q: any, cb: any): (opts?: {
keepSubscription?: boolean | null | undefined;
} | null | undefined) => void;
/**
* 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;
_hasQueryListeners(hash: any): boolean;
_cleanupQuery(q: any, hash: any): void;
/**
*
* @param {s.AttrsStore} attrs
* @param {any} muts
* @param {number} [processedTxId]
*/
_rewriteMutations(attrs: s.AttrsStore, muts: any, processedTxId?: number): any;
_rewriteMutationsSorted(attrs: any, muts: any): any[];
/**
* @returns {s.AttrsStore}
*/
optimisticAttrs(): s.AttrsStore;
/** Runs instaql on a query and a store */
dataForQuery(hash: any, applyOptimistic?: boolean): any;
_applyOptimisticUpdates(store: any, attrsStore: any, mutations: any, processedTxId: any): {
store: any;
attrsStore: 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;
_transportOnOpen: (e: any) => void;
_transportOnMessage: (e: any) => void;
_transportOnError: (e: any) => void;
_scheduleReconnect: () => void;
_transportOnClose: (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.
*
*/
getLocalId(name: any): Promise<any>;
_replaceUrlAfterOAuth(): void;
/**
*
* @returns Promise<null | {error: {message: string}}>
*/
_oauthLoginInit(): Promise<{
error: {
message: any;
};
} | null>;
_waitForOAuthCallbackResponse(): Promise<{
error: {
message: string;
};
} | null>;
__subscribeMutationErrors(cb: any): () => void;
subscribeAuth(cb: any): () => void;
getAuth(): Promise<import("./clientTypes.ts").User | null>;
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 | undefined;
user: any | undefined;
};
/**
* @param {{ forceReadFromStorage?: boolean }} [opts]
* @returns {Promise<User | undefined>}
*/
_getCurrentUser(opts?: {
forceReadFromStorage?: boolean;
}): Promise<User | undefined>;
/**
* @param {{ forceReadFromStorage?: boolean }} [opts]
* @returns {Promise<AuthState>}
*/
getCurrentUser(opts?: {
forceReadFromStorage?: boolean;
}): Promise<AuthState>;
_hasCurrentUser(): Promise<boolean>;
changeCurrentUser(newUser: any): Promise<void>;
syncUserToEndpoint(user: any): Promise<void>;
updateUser(newUser: any): Promise<void>;
sendMagicCode({ email }: {
email: any;
}): Promise<authAPI.SendMagicCodeResponse>;
signInWithMagicCode({ email, code }: {
email: any;
code: any;
}): Promise<authAPI.VerifyResponse>;
signInWithCustomToken(authToken: any): Promise<authAPI.VerifyResponse>;
signInAsGuest(): 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 | undefined;
}): 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} roomType
* @param {string} roomId
* @param {any | null | undefined} [initialPresence] -- initial presence data to send when joining the room
* @returns () => void
*/
joinRoom(roomType: string, roomId: string, initialPresence?: 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;
}) | undefined;
peers: {
[peerId: string]: Pick<any, string | number | symbol> & {
peerId: string;
};
};
} | null;
publishPresence(roomType: any, roomId: any, partialData: any): void;
_trySetPresence(roomId: any, data: any): void;
_tryJoinRoom(roomType: any, roomId: any, data: any): void;
_tryLeaveRoom(roomId: any): void;
_trySetRoomConnected(roomId: any, isConnected: 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(roomType: any, 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;
export type Connection = import("./Connection.ts").Connection<any>;
export type TransportType = import("./Connection.ts").TransportType;
export type EventSourceConstructor = import("./Connection.ts").EventSourceConstructor;
export type QuerySub = import("./reactorTypes.ts").QuerySub;
export type QuerySubInStorage = import("./reactorTypes.ts").QuerySubInStorage;
export type User = import("./clientTypes.ts").User;
export type AuthState = import("./clientTypes.ts").AuthState;
export type FrameworkClient = import("./framework.ts").FrameworkClient;
import * as s from './store.ts';
import { PersistedObject } from './utils/PersistedObject.ts';
import { SyncTable } from './SyncTable.ts';
import { InstantStream } from './Stream.ts';
import { Deferred } from './utils/Deferred.ts';
import * as authAPI from './authAPI.ts';
import * as StorageApi from './StorageAPI.ts';
import IndexedDBStorage from './IndexedDBStorage.ts';
import WindowNetworkListener from './WindowNetworkListener.js';
//# sourceMappingURL=Reactor.d.ts.map