/** * Type representing a JSON serializable object. */ import {ErrorWithContext} from '../error/ErrorWithContext' import {Awaitable} from './types' export type JSONState = { [key: string]: string | boolean | number | undefined | JSONState | Array } /** * An error thrown when the state passed into a class is invalid for that class. */ export class InvalidJSONStateError extends ErrorWithContext {} /** * Returns true if the given object can be JSON serialized. * @param what * @return boolean */ export function isJSONState(what: unknown): what is JSONState { try { JSON.stringify(what) return true } catch (e) { return false } } /** * Base interface for a class that can be rehydrated and restored. */ export interface Rehydratable { /** * Dehydrate this class' state and get it. * @return JSONState|Promise */ dehydrate(): Awaitable /** * Rehydrate a state into this class. * @param {JSONState} state * @return void|Promise */ rehydrate(state: JSONState): Awaitable }