import { Database } from './utils'; import { BehaviorSubject } from 'rxjs'; import { Auth } from './auth'; import { PWA } from './pwa'; import { Files } from './files'; import { Meta } from './meta'; import { Pdf } from './pdf'; import { ApiCall, Slice } from './slice'; import { Socket } from './socket'; import { Superuser } from './superuser'; import { WebRtc } from './webrtc'; import { Gps, GpsOptions } from './gps'; import { Chat } from './chat'; import { ChatGuiOptions, ChatWindow } from './chat-gui'; export type JwtPayload = { aud: string; email: string; exp: number; iat: number; iss: string; jti: string; payload: any; realm: string; timezone: string; uid: number; }; /** * Api connection options */ export type ApiOptions = { /** Bundle requests together that happen in quick succession */ bundleTime?: number; /** Use legacy dates by default */ legacyDates?: boolean; /** PWA manifest overrides */ manifest?: any; /** Name of application */ name?: string; /** * Slice IDs to persist in the local IndexedDB cache for offline use. * * These slices can fall back to local data when the browser loses network * connectivity or when Datalynk enters an `unavailable` recovery state. */ offline?: number[]; /** @deprecated Connectivity banners are no longer rendered by the SDK. Retained as a no-op for compatibility. */ offlineBanner?: boolean | 'top' | 'bottom'; /** Website hostname */ origin?: string; /** Save session token to localStorage to persist logins */ saveSession?: boolean; /** Manage token expiry, session cleanup, and page reloads. Disable when a host application owns authentication. */ manageSession?: boolean; /** Replay the IndexedDB pending queue when authenticated connectivity returns. Disable in service-worker helper instances. */ replayOfflineQueue?: boolean; /** Watch JWT expiry. This is always disabled on development hosts. */ watchTokenExpiry?: boolean; /** Service worker URL */ serviceWorker?: string; /** Disable sockets with false or override socket URL */ socket?: false | string; /** Socket authentication mode. Existing clients use token authentication unless ticket mode is explicitly enabled. */ socketAuthentication?: 'token' | 'ticket'; /** Optional realm for legacy socket authentication. */ socketRealm?: string; /** Lazy chat module URL. Defaults to the adjacent chat.mjs package artifact. */ chatModule?: string; /** Show an opt-in floating chat launcher. Chat code and network activity remain lazy until it is opened. */ chat?: boolean; /** GPS live tracking over socket-server/Redis */ gps?: GpsOptions; /** WebRTC TURN server URL */ webrtc?: { /** Additional ICE servers */ ice?: RTCIceServer[]; /** Auxilium WebRTC STUN/TURN server URL override */ url: string; /** TURN server username */ username?: string; /** TURN server password */ password?: string; }; /** Progressive Web App settings */ pwaSettings?: { /** How long to wait before showing the installation prompt (seconds). Default is 30 seconds */ timeout?: number; /** Days until the dismissed prompt can show again. If set to `0` it will trigger every refresh. (Default is 7 days) */ dismissExpiry?: number; /** Show PWA install link on login screen. Default is False */ loginLink?: boolean; /** Hide/disable the in-app PWA install popup entirely */ hidePWAPrompt?: boolean; /** Optional: override the installed-app icon (should be a PNG, ideally 512x512) */ icon?: string; }; }; /** * Possible options for API calls */ export interface ApiRequestOptions { /** Skip bundling & caching */ noOptimize?: boolean; /** * Allow this request to be queued while normal API access is unavailable. * * Queued requests do not receive an immediate response payload. If a token * expires while Datalynk is offline, queued work is preserved and replay is * deferred until the same user successfully reauthenticates. */ offline?: boolean; /** Skip the token translating step */ raw?: boolean; /** Set request token */ token?: string; } /** API error response */ export interface ApiError { /** Error message */ message: string; /** Source of error */ request: any; /** Extra debugging information */ debug?: any; /** Stack trace */ trace?: any; } /** * Current ability to communicate with the Datalynk API. * * - `online` - normal API requests are available. * - `offline` - the API could not be reached over the network. * - `unauthorized` - the current token is expired or was rejected. * - `unavailable` - the API responded with a recoverable server/API failure and * the exact failed request owns recovery until it succeeds again. * * `offline` and `unavailable` are intentionally distinct. A browser may still * have Internet access while Datalynk is `unavailable` because, for example, * MySQL or an API route is failing. */ export type ApiConnectionStatus = 'online' | 'offline' | 'unauthorized' | 'unavailable'; /** The server answered, but not with a valid Datalynk API response. */ export declare class UnexpectedApiResponseError extends Error { readonly response: Response; readonly body: string; constructor(response: Response, body: string); } /** * Connect to Datalynk & send requests */ export declare class Api { readonly origin: string; /** Client library version */ static version: string; /** Current requests bundle */ private bundle; /** Bundle lifecycle tracking */ private bundleOngoing; /** Track online state */ private heartbeat; private authenticationInvalid; /** Token reached exp while the client could not reach Datalynk; keep the offline session alive until reconnect. */ private offlineAuthenticationExpired; private tokenExpiryTimeout; private unauthorizedLogout; private replayingPending; /** If replay is requested while a replay pass is already active, run another pass when it finishes. */ private pendingReplayRequested; private offlineSessionOwner; /** Request-specific recovery after a server response proves an API call is broken. */ private recovery; /** Retry the failed request twice immediately, then this long after each failed recovery response. */ private recoveryRetryInterval; private readonly recoveryImmediateRetries; /** LocalStorage key for persisting logins */ private localStorageKey; /** Persisted owner of an offline queue so another login cannot inherit queued writes. */ private offlineSessionOwnerKey; private tokenStorageListener; /** Pending requests cache */ private pending; private chatModulePromise; private chatInstance; private chatLauncherHost; private chatLauncherButton; /** Helpers */ /** Authentication */ readonly auth: Auth; /** File */ readonly files: Files; /** PDF */ readonly pdf: Pdf; /** PWA setup & prompt */ readonly pwa: PWA; /** Socket */ readonly socket: Socket; /** GPS */ readonly gps: Gps; /** Superuser */ readonly superuser: Superuser; /** WebRTC */ readonly webrtc: WebRtc; /** Offline database */ database?: Database; /** Options */ options: ApiOptions; /** Created slices */ sliceCache: Map; /** API URL */ url: string; /** Client library version */ version: string; /** Is token expired */ get expired(): boolean; /** Whether authentication expired while offline and must be renewed before replaying queued work. */ get reauthenticationPending(): boolean; /** Get session info from JWT payload */ get jwtPayload(): JwtPayload | null; private onlineOverride; private initialOnline; /** * Detailed API connection state. * * Subscribe to this when callers need to distinguish physical/network * offline state from authentication failure or server/API unavailability. */ status$: BehaviorSubject; /** * Backwards-compatible boolean connection state. * * `false` includes `offline`, `unauthorized`, and `unavailable` states. */ online$: BehaviorSubject; /** Current detailed Datalynk API connection state. */ get status(): ApiConnectionStatus; /** * Whether normal Datalynk network requests are currently available. * * This becomes `false` for network outages, rejected/expired sessions, and * request-owned server recovery. It therefore describes Datalynk * availability rather than only `navigator.onLine`. */ get online(): boolean | null; /** * Whether normal Datalynk API access is currently unavailable. * * This is the inverse of {@link online}. It can be `true` while the browser * still has Internet access, for example during MySQL/HTTP 5xx recovery. */ get offline(): boolean; /** * Override the boolean connection state. * * Set `true` or `false` to force the corresponding state. Set `null` to * remove the override and resume normal connection checking. This is a * manual override and can supersede the current recovery state, so normal * applications should generally observe {@link status} instead of forcing it. */ set online(value: boolean | null); /** Logged in spoke */ get spoke(): string; /** API Session token */ token$: BehaviorSubject; get token(): string | null; set token(token: string | null); /** * Connect to Datalynk & send requests * * @example * ```ts * const api = new Api('https://spoke.auxiliumgroup.com'); * ``` * * @param {string} origin API URL * @param {ApiOptions} options */ constructor(origin: string, options?: ApiOptions); /** Mount the optional launcher without loading or initializing the chat bundle. */ private setupChatLauncher; private openChatFromLauncher; private restoreChatLauncher; /** Lazily load and construct chat. No chat code or requests run before this call. */ chat(): Promise; /** Lazily load, authorize, and open the reusable chat window. */ openChat(options?: ChatGuiOptions): Promise; private loadChatModule; private _request; /** Execute exactly one HTTP API attempt. Recovery uses this directly to avoid recursive retry loops. */ private _requestOnce; /** * Only failures which indicate Datalynk as a service is unavailable own global * recovery. A request-specific application failure must not take the whole * client offline: another unrelated API request may still be perfectly healthy. */ private isRecoverableResponseError; /** Any API error returned in PDO SQLSTATE form uses the offline/recovery path. */ private isSqlStateError; /** * A returned server failure immediately makes the client unavailable. The exact * failed request is then retried twice back-to-back. After that, retries are * scheduled 30 seconds after each completed failed attempt, never with overlap. */ private beginRecovery; private runImmediateRecovery; private tryRecoveryOnce; private scheduleRecovery; private finishRecovery; private cancelRecovery; private checkConnection; private isGatewayUnavailableStatus; private isTokenExpired; private isDevelopmentEnvironment; private canAdoptToken; /** Adopt a newer canonical token written by another auth path before expiring this session. */ private adoptStoredToken; private scheduleTokenExpiry; /** Handle local JWT expiry without treating an offline device like a rejected online session. */ private expireToken; private shouldDeferLocalExpiry; private deferOfflineExpiry; private markUnauthorized; private finishUnauthorizedLogout; private clearOfflineSessionCache; private tokenIdentity; private readOfflineSessionOwner; private ownersMatch; private rememberOfflineSessionOwner; private ensureOfflineSessionOwner; private hasOwnedOfflineSession; private clearOfflineSessionOwner; /** Replay queued writes only after a matching authenticated session is online. */ private replayPendingQueue; private setConnectionStatus; private startHeartbeat; private stopHeartbeat; /** * Get list of slices * @return {Promise} */ getSlices(): Promise; /** * Parses API request/response object for special Datalynk tokens & converts them to native JS objects * * @param obj An API request or response * @return {Object} Api request or response with translated tokens * @private */ private static translateTokens; /** * Chain multiple requests to execute together * @param {Slice} requests List of requests to chain * @return {Promise} API Response */ chain(...requests: (any | ApiCall)[]): Promise; /** * Organize multiple requests into a single mapped request * @param {{[p: string]: any}} request Map of requests * @return {Promise} Map of API Responses */ chainMap(request: { [key: string]: any; }): Promise; /** * Exact same as the `request` method, but logs the response in the console automatically * * @param {object | string} data Datalynk request as object or string * @param {ApiRequestOptions} options * @returns {Promise} Datalynk response */ debug(data: any, options?: ApiRequestOptions): Promise; debug(data: any, options: { offline: true; } & ApiRequestOptions): Promise; /** * Send a request to Datalynk * * @example * ```ts * const response = await api.request('$/auth/current'); * ``` * * @param {object} data Request using Datalynk API syntax. Strings will be converted: '$/auth/current' -> {'$/auth/current': {}} * @param {ApiRequestOptions} options * @returns {Promise} Datalynk response or error */ request(data: any, options?: ApiRequestOptions): Promise; request(data: any, options: { offline: true; } & ApiRequestOptions): Promise; /** * Create a slice object using the API * * @example * ```ts * const contactsSlice = api.slice(12345); * const allContacts = await contactsSlice.select().exec().rows(); * const unsubscribe = contactsSlice.sync().subscribe(rows => console.log(rows)); * ``` * * @param {number} id Slice ID the object will target * @returns {Slice} Object for making requests & caching rows */ slice(id: number | string): Slice; } //# sourceMappingURL=api.d.ts.map