extensions/types.tstypescript
import type { ExtensionHost } from "./ExtensionHost";

/**
 * Extension state in the host.
 */
export type ExtensionState = "registered" | "activating" | "active" | "failed" | "disposed";

/**
 * Options passed to {@link IExtension.activate}.
 * @property {AbortSignal} signal - Aborted when the extension is removed or the renderer is destroyed during activation.
 */
export interface IActivateOptions {
    signal: AbortSignal;
}

/**
 * Extension description.
 * @property {string} id - Unique id, e.g. "author.name".
 * @property {string} [version] - Extension version.
 * @property {string} [og] - Supported openglobus versions, e.g. "^1.2.0".
 * @property {string} extensionApi - Extension API range, e.g. "^1".
 * @property {Record<string, string> | IExtension[]} [requires] - Extensions it can't work without, id to version range
 * or the extensions themselves, then they are added too.
 * @property {Record<string, string>} [optional] - Extensions it works with when they are added, id to version range.
 * @property {Function} activate - Called with the host when the renderer is ready, returns the extension exports.
 * @property {Function} [deactivate] - Called with the host when the extension is removed.
 * @example
 * export default defineExtension({
 *     id: "demo.hello",
 *     extensionApi: "^1",
 *     requires: { "demo.measure": "^1.0.0" }, // or [measure]
 *     activate(host) {
 *         alert("hello world");
 *     }
 * });
 */
export interface IExtension<T = any> {
    id: string;
    version?: string;
    og?: string;
    extensionApi: string;
    requires?: Record<string, string> | IExtension[];
    optional?: Record<string, string>;
    activate(host: ExtensionHost, options: IActivateOptions): T | void | Promise<T | void>;
    deactivate?(host: ExtensionHost): void | Promise<void>;
}

/**
 * Extension record in the host.
 * @property {string} id - Extension id.
 * @property {IExtension} extension - Extension description.
 * @property {ExtensionState} state - Current state.
 * @property {*} exports - What activate returned.
 * @property {Error | null} error - Activation error.
 */
export interface IExtensionInfo<T = any> {
    readonly id: string;
    readonly extension: IExtension<T>;
    readonly state: ExtensionState;
    readonly exports: T | undefined;
    readonly error: Error | null;
}