UNPKG

tiny-electron-essentials

Version:

A lightweight and modular utility library for Electron apps, offering simplified window management, tray support, IPC channels, and custom frameless window styling.

660 lines 31.7 kB
export default TinyElectronRoot; export type WinInitFile = import("./TinyWindowFile.mjs").InitConfig; export type IPCRespondCallback = import("./TinyIpcResponder.mjs").IPCRespondCallback; /** * - Configuration for the new BrowserWindow. */ export type NewBrowserOptions = { /** * - Configuration for the new BrowserWindow. */ config?: Electron.BrowserWindowConstructorOptions | undefined; /** * - Configuration for the browser app details. */ appDetails?: Electron.AppDetailsOptions | undefined; /** * - If you will make all links open with the browser, not with the application. */ openWithBrowser?: boolean | undefined; /** * - The window will appear when the load is finished. */ show?: boolean | undefined; /** * - (Optional) Id file of the window in the manager. */ fileId?: string | undefined; /** * - List of allowed URL protocols to permit external opening. */ urls?: string[] | undefined; /** * - Whether this window is the main application window. */ isMain?: boolean | undefined; /** * - It is necessary to make auto maximize on startup. */ needsMaximize?: boolean | undefined; /** * - Overrides the default behavior to minimize the window instead of closing it. Falls back to `this.getMinimizeOnClose()` if not provided. */ minimizeOnClose?: boolean | undefined; }; /** @typedef {import('./TinyWindowFile.mjs').InitConfig} WinInitFile */ /** @typedef {import('./TinyIpcResponder.mjs').IPCRespondCallback} IPCRespondCallback */ /** * @typedef {Object} NewBrowserOptions - Configuration for the new BrowserWindow. * @property {Electron.BrowserWindowConstructorOptions} [config] - Configuration for the new BrowserWindow. * @property {Electron.AppDetailsOptions} [appDetails={ appId: this.getAppId(), appIconPath: this.getIcon(), relaunchDisplayName: this.getTitle() }] - Configuration for the browser app details. * @property {boolean} [openWithBrowser=this.#openWithBrowser] - If you will make all links open with the browser, not with the application. * @property {boolean} [show=true] - The window will appear when the load is finished. * @property {string} [fileId] - (Optional) Id file of the window in the manager. * @property {string[]} [urls=['https:', 'http:']] - List of allowed URL protocols to permit external opening. * @property {boolean} [isMain=false] - Whether this window is the main application window. * @property {boolean} [needsMaximize=true] - It is necessary to make auto maximize on startup. * @property {boolean} [minimizeOnClose] - Overrides the default behavior to minimize the window instead of closing it. Falls back to `this.getMinimizeOnClose()` if not provided. */ /** * Manages the root context of the Electron application. * * This class acts as the central manager for window instances, * IPC handlers, and global application state. It coordinates * the lifecycle of windows, IPC responders, and shared resources. * * Typically used in the main process to bootstrap and manage the * core behavior of the entire Electron application. * * @class */ declare class TinyElectronRoot { /** * Initializes the core application configuration and sets up essential app behaviors. * * This constructor sets up base application options such as window behavior, * app identification, and URL handling. It also defines internal lifecycle events * for handling window closures, second instance attempts, and macOS dock activations. * * - On **Windows**, it sets the App User Model ID to allow native toast notifications. * - On **macOS**, it recreates the window when the dock icon is clicked and no windows are open. * - When a second instance is started, it focuses the existing window instead of launching a new one. * * @param {Object} [settings={}] - Configuration settings for the application. * @param {AppEvents} [settings.eventNames=this.#AppEvents] - Set of event names for internal messaging. * @param {string} [settings.ipcResponseChannel] - Custom ipc response channel name of TinyIpcResponder instance. * @param {boolean} [settings.openWithBrowser=true] - Whether to allow fallback opening in the system browser. * @param {string} [settings.urlBase=''] - The base URL for loading content if using remote sources. * @param {string} [settings.pathBase] - The local path used for loading static files if not using a URL. * @param {string} [settings.icon] - The icon of the application. * @param {string} [settings.iconFolder] - Path to a folder containing icon assets for the app and tray. * @param {string} [settings.title] - The title of the application. * @param {string} [settings.appId] - The unique App User Model ID (used for Windows notifications). * @param {string} [settings.appDataName] - The appData application name used by folder names. * @param {string} [settings.name=app.getName()] - The internal application name used by Electron APIs. * @param {boolean} [settings.minimizeOnClose=false] - Whether to minimize instead of closing the window. * * @throws {Error} If any required string values are missing or invalid. */ constructor({ eventNames, ipcResponseChannel, openWithBrowser, name, urlBase, icon, pathBase, iconFolder, appId, title, appDataName, minimizeOnClose, }?: { eventNames?: AppEvents | undefined; ipcResponseChannel?: string | undefined; openWithBrowser?: boolean | undefined; urlBase?: string | undefined; pathBase?: string | undefined; icon?: string | undefined; iconFolder?: string | undefined; title?: string | undefined; appId?: string | undefined; appDataName?: string | undefined; name?: string | undefined; minimizeOnClose?: boolean | undefined; }); /** * Checks if a given value exists in the AppEvents values. * * @param {string} value - The value to check for. * @returns {boolean} True if the value exists, false otherwise. */ isValidAppEvent(value: string): boolean; /** * Gets the key (event name) associated with a given AppEvents value. * * @param {string} value - The value to look up. * @returns {string} The matching AppEvents key. * @throws {Error} If the value is not found. */ getAppEventKey(value: string): string; /** * Provides access to a secure internal EventEmitter for subclass use only. * * This method exposes a dedicated EventEmitter instance intended specifically for subclasses * that extend the main class. It prevents subclasses from accidentally or intentionally using * the primary class's public event system (`emit`), which could lead to unpredictable behavior * or interference in the base class's event flow. * * For security and consistency, this method is designed to be accessed only once. * Multiple accesses are blocked to avoid leaks or misuse of the internal event bus. * * @returns {EventEmitter} A special internal EventEmitter instance for subclass use. * @throws {Error} If the method is called more than once. */ getSysEvents(): EventEmitter; /** * @typedef {(...args: any[]) => void} ListenerCallback * A generic callback function used for event listeners. */ /** * Sets the maximum number of listeners for the internal event emitter. * * @param {number} max - The maximum number of listeners allowed. */ setMaxListeners(max: number): void; /** * Emits an event with optional arguments. * @param {string | symbol} event - The name of the event to emit. * @param {...any} args - Arguments passed to event listeners. * @returns {boolean} `true` if the event had listeners, `false` otherwise. */ emit(event: string | symbol, ...args: any[]): boolean; /** * Registers a listener for the specified event. * @param {string | symbol} event - The name of the event to listen for. * @param {ListenerCallback} listener - The callback function to invoke. * @returns {this} The current class instance (for chaining). */ on(event: string | symbol, listener: (...args: any[]) => void): this; /** * Registers a one-time listener for the specified event. * @param {string | symbol} event - The name of the event to listen for once. * @param {ListenerCallback} listener - The callback function to invoke. * @returns {this} The current class instance (for chaining). */ once(event: string | symbol, listener: (...args: any[]) => void): this; /** * Removes a listener from the specified event. * @param {string | symbol} event - The name of the event. * @param {ListenerCallback} listener - The listener to remove. * @returns {this} The current class instance (for chaining). */ off(event: string | symbol, listener: (...args: any[]) => void): this; /** * Alias for `on`. * @param {string | symbol} event - The name of the event. * @param {ListenerCallback} listener - The callback to register. * @returns {this} The current class instance (for chaining). */ addListener(event: string | symbol, listener: (...args: any[]) => void): this; /** * Alias for `off`. * @param {string | symbol} event - The name of the event. * @param {ListenerCallback} listener - The listener to remove. * @returns {this} The current class instance (for chaining). */ removeListener(event: string | symbol, listener: (...args: any[]) => void): this; /** * Removes all listeners for a specific event, or all events if no event is specified. * @param {string | symbol} [event] - The name of the event. If omitted, all listeners from all events will be removed. * @returns {this} The current class instance (for chaining). */ removeAllListeners(event?: string | symbol): this; /** * Returns the number of times the given `listener` is registered for the specified `event`. * If no `listener` is passed, returns how many listeners are registered for the `event`. * @param {string | symbol} eventName - The name of the event. * @param {Function} [listener] - Optional listener function to count. * @returns {number} Number of matching listeners. */ listenerCount(eventName: string | symbol, listener?: Function): number; /** * Adds a listener function to the **beginning** of the listeners array for the specified event. * The listener is called every time the event is emitted. * @param {string | symbol} eventName - The event name. * @param {ListenerCallback} listener - The callback function. * @returns {this} The current class instance (for chaining). */ prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; /** * Adds a **one-time** listener function to the **beginning** of the listeners array. * The next time the event is triggered, this listener is removed and then invoked. * @param {string | symbol} eventName - The event name. * @param {ListenerCallback} listener - The callback function. * @returns {this} The current class instance (for chaining). */ prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; /** * Returns an array of event names for which listeners are currently registered. * @returns {(string | symbol)[]} Array of event names. */ eventNames(): (string | symbol)[]; /** * Gets the current maximum number of listeners allowed for any single event. * @returns {number} The max listener count. */ getMaxListeners(): number; /** * Returns a copy of the listeners array for the specified event. * @param {string | symbol} eventName - The event name. * @returns {Function[]} An array of listener functions. */ listeners(eventName: string | symbol): Function[]; /** * Returns a copy of the internal listeners array for the specified event, * including wrapper functions like those used by `.once()`. * @param {string | symbol} eventName - The event name. * @returns {Function[]} An array of raw listener functions. */ rawListeners(eventName: string | symbol): Function[]; /** * Applies a network proxy configuration to a given BrowserWindow instance. * * This method sets the proxy settings for the session associated with the window's webContents. * Upon completion, it emits events back to the renderer process to indicate success or failure. * * If a callback (`res`) is provided, it will be invoked with `(null)` on success, * or with `(null, Error)` on failure. * * @param {BrowserWindow} win - The target BrowserWindow whose session will receive the proxy configuration. * Must be a valid and active window instance. * * @param {Electron.ProxyConfig} config - The proxy configuration object following Electron's ProxyConfig structure. * Example: `{ proxyRules: 'http=myproxy.com:8080;https=myproxy.com:8080', proxyBypassRules: 'localhost' }` * * @param {IPCRespondCallback} [res] - Optional IPC response callback. Called with: * - `(null)` on success, * - `(null, Error)` on failure, * or `(null, Error('Invalid window type'))` if the window is invalid. * * @throws {Error} Throws an error if the provided window (`win`) is invalid (null, destroyed, or missing webContents). * * @returns {void} */ setProxy(win: BrowserWindow, config: Electron.ProxyConfig, res?: IPCRespondCallback): void; /** * Resolves a safe full path to an icon file inside the icon folder based on the OS. * * - Linux: .png * - Windows: .ico * - macOS: .icns * * @param {string} filename - The base name of the icon (without extension). * @param {string} [iconFolder=this.getIconFolder()] - The root folder where icons are stored. * @returns {string} - The full, safe path to the icon. * @throws {Error} If the filename is invalid, or the file does not exist or escapes the folder. */ resolveSystemIconPath(filename: string, iconFolder?: string): string; /** * Returns the internal TinyWindowFile instance. * @returns {TinyWindowFile} */ getWinFile(): TinyWindowFile; /** * Returns the internal TinyIpcResponder instance. * @returns {TinyIpcResponder} */ getIpcResponder(): TinyIpcResponder; /** * Registers a callback function responsible for providing cache data to be sent * to renderer processes upon request. * * This method can only be called **once** during the application's lifecycle. * Any attempt to register multiple callbacks will result in an error. * * Once set, this callback is triggered when a renderer sends an event * requesting cache values (`ElectronCacheValues`). The response is automatically * sent back to the requesting renderer. * * @param {(data: any) => Record<string, any>} callback - A function that returns the current cache data as an object. * * @throws {Error} Throws an error if a cache request callback is already registered. * Error message: `"Cache request callback has already been set."` * * @returns {void} */ setRequestCache(callback: (data: any) => Record<string, any>): void; /** * Creates a new Electron BrowserWindow and tracks it as a main or secondary window. * * If marked as the main window, it will be assigned to `#win`. Otherwise, it's stored * in the `#wins` map using an auto-incremented index. * * @param {NewBrowserOptions} [settings={}] - Configuration for the new BrowserWindow * @returns {TinyWinInstance} * @throws {TypeError} If settings is not an object. * @throws {Error} If trying to create a second main window. */ createWindow({ config, fileId, show, minimizeOnClose, appDetails, urls, openWithBrowser, needsMaximize, isMain, }?: NewBrowserOptions): TinyWinInstance; /** * Destroys a specific window by key or the main window if no key is provided. * * This will fully close and remove the associated BrowserWindow and clean up its references. * If the window is the main one, it clears the internal main reference. If it’s a secondary * window, it is removed from the internal map. * * @param {string|number} [key] - Optional key to target a secondary window. If omitted, the main window is destroyed. * @throws {Error} If no main window exists or no matching window instance is found. */ destroyWindow(key?: string | number): void; /** * Registers an existing Electron Tray instance under a given key. * * This method does not create a new tray. It simply stores a reference * to an already created Electron Tray so it can be managed later. * * @param {string} key - A unique identifier for the tray. * @param {Electron.Tray} tray - The Electron Tray instance to register. * @throws {Error} If the key is not a string or if the tray is invalid. */ registerTray(key: string, tray: Electron.Tray): void; /** * Registers a tray click callback depending on the platform. * On Linux and macOS, it listens to the `click` event. * On Windows, it listens to the `double-click` event. * * @param {string} key - The identifier of the tray instance. * @param {(event: Electron.KeyboardEvent, bounds: Electron.Rectangle) => void} callback - The callback function to invoke when the event occurs. */ onTrayClick(key: string, callback: (event: Electron.KeyboardEvent, bounds: Electron.Rectangle) => void): void; /** * Unregisters a previously registered tray click callback. * On Linux and macOS, it removes the `click` event listener. * On Windows, it removes the `double-click` event listener. * * @param {string} key - The identifier of the tray instance. * @param {(event: Electron.KeyboardEvent, bounds: Electron.Rectangle) => void} callback - The callback function to remove. */ offTrayClick(key: string, callback: (event: Electron.KeyboardEvent, bounds: Electron.Rectangle) => void): void; /** * Retrieves a registered Tray by its key. * * @param {string} key - The identifier of the tray to retrieve. * @returns {Electron.Tray} * @throws {Error} If the tray is not found. */ getTray(key: string): Electron.Tray; /** * Checks if a tray is registered under the specified key. * * @param {string} key - The key to check. * @returns {boolean} */ hasTray(key: string): boolean; /** * Removes a tray from the registered tray list. * * @param {string} key - The identifier of the tray to delete. * @returns {boolean} True if the tray was found and deleted; false otherwise. */ deleteTray(key: string): boolean; /** * Gets whether the window should minimize instead of close on user request. * @returns {boolean} */ getMinimizeOnClose(): boolean; /** * Sets whether the window should minimize instead of close on user request. * @param {boolean} value */ setMinimizeOnClose(value: boolean): void; /** * Gets the `minimizeOnClose` behavior for a specific window index. * Falls back to the global setting if not explicitly set. * * @param {number} index - The index of the window. * @returns {boolean} */ getMinimizeOnCloseFor(index: number): boolean; /** * Sets the `minimizeOnClose` behavior for a specific window index. * * @param {number} index - The index of the window. * @param {boolean} value - Whether the window should minimize on close. */ setMinimizeOnCloseFor(index: number, value: boolean): void; /** * Removes any custom `minimizeOnClose` override for a specific window. * * @param {number} index - The index of the window. */ removeMinimizeOnCloseFor(index: number): void; /** * Clears all custom `minimizeOnClose` settings for secondary windows. */ clearMinimizeOnCloseOverrides(): void; /** * Checks if a specific CLI argument was provided when starting the application. * * This method scans `process.argv` to determine whether a particular argument * (exact match) was passed via the command line. It's useful for enabling or * disabling behaviors at runtime based on flags. * * @param {string} name - The exact argument name to search for (e.g., "--debug"). * @returns {boolean} `true` if the argument was found; otherwise, `false`. */ hasCliArg(name: string): boolean; /** * Signals the application to quit and sets the internal quit flag. * * This method marks the app as intentionally quitting and then calls `app.quit()`. * If called more than once, it has no additional effect beyond the first invocation. */ quit(): void; /** * Returns a copy of the developer console warning message array. * @returns {string[]} */ getConsoleWarning(): string[]; /** * Sets the warning messages to be displayed in the developer console. * Expects an array of two strings: the message and its CSS style. * @param {string[]} value */ setConsoleWarning(value: string[]): void; /** * Checks if this is the first time the application logic is running. * @returns {boolean} */ isFirstTime(): boolean; /** * Indicates whether the application is ready. * @returns {boolean} */ isAppReady(): boolean; /** * Indicates whether the application is in the process of quitting. * @returns {boolean} */ isQuiting(): boolean; /** * Checks whether a main window or a specific secondary window exists. * * If a `key` is provided, this method will check for the existence of a secondary window * in the internal map of windows. Only string keys are allowed. * * @param {string|number} [key] - Optional key to check existence of a specific secondary window. * @returns {boolean} * @throws {TypeError} If the provided key is not a string. */ existsWin(key?: string | number): boolean; /** * Returns the current main BrowserWindow instance or a specific one by key. * * If a `key` is provided, this method will attempt to retrieve a secondary window * from the internal map of windows. Only string keys are accepted. * * @param {string|number} [key] - Optional key to retrieve a specific secondary window. * @returns {BrowserWindow} * @throws {Error} If no main window exists, key is not a string, or the key does not match any window. */ getWin(key?: string | number): BrowserWindow; /** * Retrieves a window instance by its Electron window ID. * * @param {number} id - The Electron window ID to search for. * @returns {TinyWinInstance} The window instance matching the given ID. * * @throws {TypeError} If the provided ID is not a valid number. * @throws {Error} If no window instance with the given ID is found. */ getWinInstanceById(id: number): TinyWinInstance; /** * Returns the TinyWinInstance object associated with the main window or a specific one by key. * * If a `key` is provided, this method will attempt to retrieve a secondary window * instance from the internal map of windows. Only string keys are supported. * * @param {string|number} [key] - Optional key to retrieve a specific secondary window instance. * @returns {TinyWinInstance} * @throws {Error} If no main window exists, key is not a string, or the key does not match any window. */ getWinInstance(key?: string | number): TinyWinInstance; /** * @typedef {"home"|"appData"|"userData"|"sessionData"|"temp"|"exe"|"module"|"desktop"|"documents"|"downloads"|"music"|"pictures"|"videos"|"recent"|"logs"|"crashDumps"} ElectronPathName */ /** * Returns the full path to a folder inside the Electron app's unpacked directory. * * Useful when accessing files that must remain unpacked (e.g. native binaries). * Validates inputs and throws if any parameter is not a string. * * @param {string|null} [where] - The folder name to append inside the unpacked directory. * @param {string} [packName='app.asar'] - The packed archive filename (usually "app.asar"). * @param {string} [unpackName='app.asar.unpacked'] - The corresponding unpacked folder name (usually "app.asar.unpacked"). * @returns {{ isUnpacked: boolean, unPackedFolder: string }} Object with unpacked folder path and status. * @throws {TypeError} If any parameter is not a valid string. */ getUnpackedFolder(where?: string | null, packName?: string, unpackName?: string): { isUnpacked: boolean; unPackedFolder: string; }; /** * Loads a Chromium extension from a specified folder and extension name. * * This method attempts to load the extension first from the unpacked folder. * If that fails, it tries to load from a fallback path. * * @param {string} extName - The name of the extension's folder. * @param {string} folder - Folder name inside the unpacked app path where the extension is located. * @param {Electron.LoadExtensionOptions} [ops] - Optional Electron extension loading options. * @returns {Promise<Electron.Extension>} A promise that resolves with the loaded extension. * @throws {TypeError} If any required argument is missing or invalid. * @throws {TypeError} If the extension fails to load from both primary and fallback paths. * * @beta */ loadExtension(extName: string, folder: string, ops?: Electron.LoadExtensionOptions): Promise<Electron.Extension>; /** * Initializes the base folder in the given Electron path if not already created. * Throws if the folder was already initialized. * * @param {ElectronPathName} [name] - The Electron path key to use as root. * @returns {string} The absolute path of the created folder. * @throws {Error} If the folder for this path was already initialized. */ initAppDataDir(name?: "module" | "home" | "appData" | "userData" | "sessionData" | "temp" | "exe" | "desktop" | "documents" | "downloads" | "music" | "pictures" | "videos" | "recent" | "logs" | "crashDumps"): string; /** * Retrieves the base folder path previously initialized via `initAppDataDir()`. * * @param {ElectronPathName} [name] - The Electron path key. * @returns {string} The initialized app data folder path. * @throws {Error} If the folder was not yet initialized. */ getAppDataDir(name?: "module" | "home" | "appData" | "userData" | "sessionData" | "temp" | "exe" | "desktop" | "documents" | "downloads" | "music" | "pictures" | "videos" | "recent" | "logs" | "crashDumps"): string; /** * Creates a subdirectory inside the initialized base app data folder. * Throws if the subfolder was already created. * * @param {string} subdir - The name of the subfolder to create. * @param {ElectronPathName} [name] - The Electron path key. * @returns {string} The full path to the created subdirectory. * @throws {Error} If the subdirectory already exists in memory tracking. */ initAppDataSubdir(subdir: string, name?: "module" | "home" | "appData" | "userData" | "sessionData" | "temp" | "exe" | "desktop" | "documents" | "downloads" | "music" | "pictures" | "videos" | "recent" | "logs" | "crashDumps"): string; /** * Retrieves a previously created subdirectory path. * * @param {string} subdir - The name of the subfolder. * @param {ElectronPathName} [name] - The Electron path key. * @returns {string} The absolute path of the subdirectory. * @throws {Error} If the subdirectory was not previously created. */ getAppDataSubdir(subdir: string, name?: "module" | "home" | "appData" | "userData" | "sessionData" | "temp" | "exe" | "desktop" | "documents" | "downloads" | "music" | "pictures" | "videos" | "recent" | "logs" | "crashDumps"): string; /** * Returns the current application appData folder name. * @returns {string} */ getAppDataName(): string; /** * Returns the current application icon path. * @returns {string} */ getIcon(): string; /** * Returns the base folder path where icon assets are stored. * * This is useful when loading tray or window icons using relative paths * from a single shared folder defined in the constructor. * * @returns {string} The path to the icon folder. * @throws {Error} If the icon folder has not been defined. */ getIconFolder(): string; /** * Returns the current application title. * @returns {string} */ getTitle(): string; /** * Returns the current application app id. * @returns {string} */ getAppId(): string; /** * Indicates whether this instance has acquired the lock to run. * Can be null (not yet determined), or a boolean result. * @returns {null|boolean} */ gotTheLock(): null | boolean; /** * Opens the developer tools for the given BrowserWindow. * Also sends the custom console warning message to the devtools console. * @param {Electron.BrowserWindow} win - The target BrowserWindow instance. * @param {Electron.OpenDevToolsOptions} [ops] - The target DevTools config. */ openDevTools(win: Electron.BrowserWindow, ops?: Electron.OpenDevToolsOptions): void; /** * Installs platform-specific protections for Windows systems. * * Currently disables GPU acceleration for Windows 7 (version 6.1). */ installWinProtection(): void; /** * Initializes the application by ensuring a single instance is running. * * If another instance is already running, it exits. Otherwise, * it sets up Electron readiness events and prepares the app. */ init(): void; /** * Loads a page into the given BrowserWindow. * * Depending on configuration, it can load a local file path or a URL. * * @param {BrowserWindow} win - The target BrowserWindow instance. * @param {string|string[]} page - The page or path segments to load. * @param {Electron.LoadFileOptions|Electron.LoadURLOptions} [ops] - Options passed to `loadFile` or `loadURL`. * @throws {TypeError} If the window is not a valid BrowserWindow. * @throws {TypeError} If page is not a string or string[]. * @throws {TypeError} If page contains non-string entries. * @throws {TypeError} If ops is not an object. */ loadPath(win: BrowserWindow, page: string | string[], ops?: Electron.LoadFileOptions | Electron.LoadURLOptions): void; #private; } import { EventEmitter } from 'events'; import { BrowserWindow } from 'electron'; import TinyWindowFile from './TinyWindowFile.mjs'; import TinyIpcResponder from './TinyIpcResponder.mjs'; import TinyWinInstance from './TinyWinInstance.mjs'; import { AppEvents } from '../global/Events.mjs'; //# sourceMappingURL=TinyElectronRoot.d.mts.map