feat: add Gelectron compatibility layer for Electron modules

- Introduced contextBridge module for exposing APIs to the main world.
- Added dialog module for handling open, save, and message dialogs.
- Created index module as a drop-in replacement for Electron's main API.
- Implemented ipcMain and ipcRenderer modules for inter-process communication.
- Developed menu and menu item modules for creating application menus.
- Added nativeImage module for handling images in various formats.
- Implemented notification module for displaying system notifications.
- Created preload-loader for injecting preload scripts into the renderer process.
- Developed runtime module for running Electron apps in a Node.js environment.
- Added safe-storage module for basic string encryption and decryption.
- Implemented shell module for opening external URLs and managing file paths.
- Created tray module for managing system tray icons and menus.
- Developed webContents utilities for interacting with browser windows.
This commit is contained in:
miles committed 2026-07-26 17:12:47 -05:00
1 parent 4af8378d72
commit 86c19b0012
39 files changed
+4687 -2

No files matched your search

+209
View File
@@ -0,0 +1,209 @@
'use strict';
/**
* Gelectron - app module (Electron compatible)
*/
const { EventEmitter } = require('events');
const path = require('path');
class App extends EventEmitter {
constructor() {
super();
this._ready = false;
this._paths = {
home: require('os').homedir(),
appData: path.join(require('os').homedir(), '.config', 'gelectron'),
userData: path.join(require('os').homedir(), '.config', 'gelectron'),
desktop: path.join(require('os').homedir(), 'Desktop'),
documents: path.join(require('os').homedir(), 'Documents'),
downloads: path.join(require('os').homedir(), 'Downloads'),
temp: require('os').tmpdir(),
exe: process.execPath,
module: __dirname,
crashDumps: path.join(require('os').homedir(), '.config', 'gelectron', 'crashDumps'),
logs: path.join(require('os').homedir(), '.config', 'gelectron', 'logs'),
};
this._commandLine = new Map();
this._dock = process.platform === 'darwin' ? {
setIcon: (icon) => {
console.log('[gelectron] dock.setIcon called');
},
bounce: () => 0,
cancelBounce: () => {},
setBadge: () => {},
getBadge: () => '',
hide: () => {},
show: () => {},
isVisible: () => true,
setMenu: () => {},
setBadgeCount: () => {},
getBadgeCount: () => 0,
setThumbnail: () => {},
setThumbnailClip: () => {},
setThumbnailToolTip: () => {},
setMenu: () => {},
} : null;
this._argv = process.argv.slice();
}
get commandLine() {
return {
appendSwitch: (name, value) => {
this._commandLine.set(name, value || '');
},
removeSwitch: (name) => {
this._commandLine.delete(name);
},
getSwitch: (name) => {
return this._commandLine.get(name) || '';
},
hasSwitch: (name) => {
return this._commandLine.has(name);
},
};
}
get dock() {
return this._dock;
}
get argv() {
return this._argv;
}
get isPackaged() {
return !process.argv[0].includes('node') && !process.argv[0].includes('gelectron');
}
get name() {
return 'Gelectron App';
}
set name(val) {
// no-op
}
get version() {
return process.env.GELECTRON_VERSION || '0.1.0';
}
getPath(name) {
return this._paths[name] || this._paths.userData;
}
setPath(name, path) {
this._paths[name] = path;
}
getName() {
return this.name;
}
getVersion() {
return this.version;
}
getLocale() {
return Intl.DateTimeFormat().resolvedOptions().locale || 'en-US';
}
getUserAgent() {
return `Gelectron/${this.version} (${process.platform} ${process.arch}) Node.js/${process.versions.node}`;
}
getPathForProtocol(protocol) {
return null;
}
async whenReady() {
if (this._ready) return;
return new Promise((resolve) => {
this.once('ready', resolve);
});
}
async requestSingleInstanceLock() {
this._ready = true;
process.nextTick(() => this.emit('ready'));
return true;
}
acquireSingleInstanceLock() {
return true;
}
releaseSingleInstanceLock() {}
async quit(exitCode = 0) {
this.emit('before-quit');
process.exit(exitCode);
}
exit(exitCode = 0) {
process.exit(exitCode);
}
relaunch(options = {}) {
process.exit(0);
}
isReady() {
return this._ready;
}
addRecentDocument(path) {}
clearRecentDocuments() {}
setAppUserModelId(id) {}
getAppUserModelId() {
return '';
}
async showCertificateTrustDialog() {}
on(eventName, listener) {
super.on(eventName, listener);
return this;
}
once(eventName, listener) {
super.once(eventName, listener);
return this;
}
getLoginItemSettings() {
return { openAtLogin: false, openAsHidden: false };
}
setLoginItemSettings() {}
isInApplicationsFolder() {
return true;
}
moveToApplicationsFolder() {}
getFileIcon(path, options, callback) {
if (typeof options === 'function') {
callback = options;
}
callback(null, null);
}
focus(options) {}
hide() {}
show() {}
isVisible() {
return true;
}
isHidden() {
return false;
}
setAboutPanelOptions() {}
}
const app = new App();
module.exports = { app, App };
+336
View File
@@ -0,0 +1,336 @@
'use strict';
/**
* Gelectron - BrowserWindow module (Electron compatible)
*/
const { EventEmitter } = require('events');
const path = require('path');
class WebContents extends EventEmitter {
constructor(id) {
super();
this.id = id;
this._url = '';
this._title = '';
this._isLoading = false;
this._zoomFactor = 1.0;
this._zoomLevel = 0;
this._userAgent = '';
this._audioMuted = false;
}
get URL() { return this._url; }
get isLoading() { return this._isLoading; }
get title() { return this._title; }
get session() {
return {
id: `session-${this.id}`,
cookies: {
get: async () => [],
set: async () => {},
remove: async () => {},
},
protocol: {
registerFileProtocol: () => {},
registerHttpProtocol: () => {},
unregisterProtocol: () => {},
isProtocolRegistered: () => false,
},
setPermissionRequestHandler: () => {},
setPermissionCheckHandler: () => {},
webRequest: { onBeforeRequest: () => {}, onHeadersReceived: () => {} },
setUserAgent: () => {},
getUserAgent: () => '',
};
}
get processId() { return process.pid; }
loadURL(targetUrl) {
this._url = targetUrl;
this._isLoading = true;
this.emit('did-start-loading');
setTimeout(() => {
this._isLoading = false;
this.emit('did-stop-loading');
this.emit('did-finish-load');
this.emit('dom-ready');
}, 100);
return Promise.resolve();
}
loadFile(filePath) {
return this.loadURL(`file://${path.resolve(filePath)}`);
}
reload() {
this._isLoading = true;
this.emit('did-start-loading');
setTimeout(() => {
this._isLoading = false;
this.emit('did-stop-loading');
this.emit('did-finish-load');
}, 50);
return Promise.resolve();
}
canGoBack() { return false; }
canGoForward() { return false; }
goBack() {}
goForward() {}
executeJavaScript(code, userGesture = true) {
return Promise.resolve(null);
}
insertCSS(css) { return Promise.resolve(0); }
insertJS(code, hasUserGesture = true) { return this.executeJavaScript(code, hasUserGesture); }
send(channel, ...args) {
console.log(`[gelectron] webContents.send('${channel}')`);
}
sendInputEvent() {}
setZoomFactor(factor) { this._zoomFactor = factor; }
getZoomFactor() { return this._zoomFactor; }
setZoomLevel(level) { this._zoomLevel = level; }
getZoomLevel() { return this._zoomLevel; }
setUserAgent(ua) { this._userAgent = ua; }
getUserAgent() { return this._userAgent; }
setAudioMuted(muted) { this._audioMuted = muted; }
isAudioMuted() { return this._audioMuted; }
openDevTools() { console.log('[gelectron] openDevTools'); }
closeDevTools() {}
isDevToolsOpened() { return false; }
toggleDevTools() {}
inspectElement() {}
setIgnoreMenuShortcuts() {}
setWindowOpenHandler() { return { action: 'deny' }; }
setPermissionRequestHandler() {}
setCertificateVerifyProc() {}
setBackgroundColor() {}
isCrashed() { return false; }
capturePage() { return Promise.resolve(null); }
getResourceUsage() { return { images: 0, scripts: 0, css: 0, xhr: 0, webgl: 0 }; }
type() { return 'backgroundPage'; }
focused() { return false; }
isFocused() { return false; }
destroy() {}
}
class BrowserWindow extends EventEmitter {
static _windows = new Map();
static _nextId = 1;
constructor(options = {}) {
super();
this.id = BrowserWindow._nextId++;
this._options = {
width: options.width || 800,
height: options.height || 600,
minWidth: options.minWidth || 0,
minHeight: options.minHeight || 0,
maxWidth: options.maxWidth || 0,
maxHeight: options.maxHeight || 0,
title: options.title || 'Gelectron',
backgroundColor: options.backgroundColor || '#ffffff',
show: options.show !== false,
frame: options.frame !== false,
resizable: options.resizable !== false,
minimizable: options.minimizable !== false,
maximizable: options.maximizable !== false,
closable: options.closable !== false,
fullscreen: options.fullscreen || false,
alwaysOnTop: options.alwaysOnTop || false,
transparent: options.transparent || false,
decorations: options.decorations !== false,
icon: options.icon || null,
titleBarStyle: options.titleBarStyle || 'default',
trafficLightPosition: options.trafficLightPosition || null,
vibrancy: options.vibrancy || null,
webPreferences: {
preload: options.webPreferences?.preload || null,
contextIsolation: options.webPreferences?.contextIsolation !== false,
nodeIntegration: options.webPreferences?.nodeIntegration || false,
sandbox: options.webPreferences?.sandbox || false,
devTools: options.webPreferences?.devTools !== false,
webSecurity: options.webPreferences?.webSecurity !== false,
allowRunningInsecureContent: options.webPreferences?.allowRunningInsecureContent || false,
experimentalFeatures: options.webPreferences?.experimentalFeatures || false,
...options.webPreferences,
},
};
this._url = '';
this._isDestroyed = false;
this._isVisible = this._options.show;
this._isMinimized = false;
this._isMaximized = false;
this._isFullScreen = this._options.fullscreen;
this.webContents = new WebContents(this.id);
BrowserWindow._windows.set(this.id, this);
if (this._options.show) {
process.nextTick(() => {
if (!this._isDestroyed) {
this.emit('ready-to-show');
this.show();
}
});
}
}
static fromWebContents(webContents) {
for (const win of BrowserWindow._windows.values()) {
if (win.webContents && win.webContents.id === webContents.id) return win;
}
return null;
}
static getAllWindows() {
return Array.from(BrowserWindow._windows.values()).filter((w) => !w.isDestroyed());
}
static getFocusedWindow() { return null; }
static fromId(id) { return BrowserWindow._windows.get(id) || null; }
static addExtension() {}
static removeExtension() {}
static getExtensions() { return {}; }
loadURL(targetUrl) {
this._url = targetUrl;
return this.webContents.loadURL(targetUrl);
}
loadFile(filePath) {
return this.loadURL(`file://${path.resolve(filePath)}`);
}
show() {
if (this._isDestroyed) return;
this._isVisible = true;
this._isMinimized = false;
this.emit('show');
}
hide() {
if (this._isDestroyed) return;
this._isVisible = false;
this.emit('hide');
}
close() {
if (this._isDestroyed) return;
this.emit('close');
this.destroy();
}
destroy() {
if (this._isDestroyed) return;
this._isDestroyed = true;
BrowserWindow._windows.delete(this.id);
this.emit('closed');
}
focus() { if (!this._isDestroyed) this.emit('focus'); }
blur() {}
minimize() { if (!this._isDestroyed) { this._isMinimized = true; this.emit('minimize'); } }
maximize() { if (!this._isDestroyed) { this._isMaximized = true; this.emit('maximize'); } }
unmaximize() { if (!this._isDestroyed) { this._isMaximized = false; this.emit('unmaximize'); } }
restore() { if (!this._isDestroyed) { this._isMinimized = false; this._isMaximized = false; this.emit('restore'); } }
setFullScreen(flag) { this._isFullScreen = flag; this.emit('enter-full-screen'); }
isFullScreen() { return this._isFullScreen; }
isMinimized() { return this._isMinimized; }
isMaximized() { return this._isMaximized; }
isVisible() { return this._isVisible; }
isDestroyed() { return this._isDestroyed; }
isFocused() { return false; }
isNormal() { return !this._isMinimized && !this._isMaximized && !this._isFullScreen; }
setAlwaysOnTop(flag) { this._options.alwaysOnTop = flag; }
isAlwaysOnTop() { return this._options.alwaysOnTop; }
setPosition(x, y) {}
getPosition() { return [0, 0]; }
setSize(w, h) { this._options.width = w; this._options.height = h; }
getSize() { return [this._options.width, this._options.height]; }
setMinimumSize(w, h) { this._options.minWidth = w; this._options.minHeight = h; }
getMinimumSize() { return [this._options.minWidth, this._options.minHeight]; }
setMaximumSize(w, h) { this._options.maxWidth = w; this._options.maxHeight = h; }
getMaximumSize() { return [this._options.maxWidth, this._options.maxHeight]; }
setResizable(v) { this._options.resizable = v; }
isResizable() { return this._options.resizable; }
setMovable() {}
isMovable() { return true; }
setMinimizable(v) { this._options.minimizable = v; }
isMinimizable() { return this._options.minimizable; }
setMaximizable(v) { this._options.maximizable = v; }
isMaximizable() { return this._options.maximizable; }
setClosable(v) { this._options.closable = v; }
isClosable() { return this._options.closable; }
setTitle(title) { this._options.title = title; this.webContents._title = title; }
getTitle() { return this._options.title; }
setSkipTaskbar() {}
setKiosk() {}
isKiosk() { return false; }
center() {}
setBounds() {}
getBounds() { return { x: 0, y: 0, width: this._options.width, height: this._options.height }; }
setSimpleFullScreen() {}
isSimpleFullScreen() { return false; }
setAutoHideCursor() {}
setContentBounds() {}
getContentBounds() { return this.getBounds(); }
isEnabled() { return true; }
setEnabled() {}
setProgressBar() {}
setOverlayIcon() {}
setVisibleOnAllWorkspaces() {}
isVisibleOnAllWorkspaces() { return false; }
setVibrancy() {}
getNativeWindowHandle() { return Buffer.alloc(0); }
setHasShadow() {}
hasShadow() { return true; }
setOpacity() {}
getOpacity() { return 1.0; }
setThumbarButtons() {}
setThumbnailClip() {}
setThumbnailToolTip() {}
setAppDetails() {}
setForeground() {}
flashFrame() {}
setIcon() {}
setBackgroundColor(c) { this._options.backgroundColor = c; }
getBackgroundColor() { return this._options.backgroundColor; }
capturePage() { return this.webContents.capturePage(); }
print() { console.log('[gelectron] print called'); }
printToPDF() { return Promise.resolve(Buffer.alloc(0)); }
setParentWindow() {}
getParentWindow() { return null; }
getChildWindows() { return []; }
selectPreviousTab() {}
selectNextTab() {}
mergeAllWindows() {}
moveTabToNewWindow() {}
toggleTabBar() {}
addTabbedWindow() {}
}
module.exports = { BrowserWindow, WebContents };
+33
View File
@@ -0,0 +1,33 @@
'use strict';
/**
* Gelectron - contextBridge module (Electron compatible)
*/
const contextBridge = {
exposeInMainWorld(key, api) {
if (typeof globalThis.window === 'undefined') {
return;
}
// Create a frozen copy of the API
const safeApi = deepFreeze(JSON.parse(JSON.stringify(api)));
globalThis.window[key] = safeApi;
console.log(`[gelectron] contextBridge: exposed '${key}' to main world`);
},
};
function deepFreeze(obj) {
if (typeof obj !== 'object' || obj === null) return obj;
Object.freeze(obj);
Object.keys(obj).forEach((key) => {
if (typeof obj[key] === 'object' && obj[key] !== null && !Object.isFrozen(obj[key])) {
deepFreeze(obj[key]);
}
});
return obj;
}
module.exports = contextBridge;
+70
View File
@@ -0,0 +1,70 @@
'use strict';
/**
* Gelectron - dialog module (Electron compatible)
*/
const dialog = {
showOpenDialog(browserWindowOrOptions, options) {
let opts = options || browserWindowOrOptions || {};
if (browserWindowOrOptions && browserWindowOrOptions.webContents) {
opts = options || {};
}
// Route through native if available
if (typeof globalThis.__gelectron_dialog_open === 'function') {
return globalThis.__gelectron_dialog_open(opts);
}
return Promise.resolve({ canceled: true, filePaths: [] });
},
showSaveDialog(browserWindowOrOptions, options) {
let opts = options || browserWindowOrOptions || {};
if (browserWindowOrOptions && browserWindowOrOptions.webContents) {
opts = options || {};
}
if (typeof globalThis.__gelectron_dialog_save === 'function') {
return globalThis.__gelectron_dialog_save(opts);
}
return Promise.resolve({ canceled: true, filePath: undefined });
},
showMessageBox(browserWindowOrOptions, options) {
let opts = options || browserWindowOrOptions || {};
if (browserWindowOrOptions && browserWindowOrOptions.webContents) {
opts = options || {};
}
if (typeof globalThis.__gelectron_dialog_message === 'function') {
return globalThis.__gelectron_dialog_message(opts);
}
return Promise.resolve({ response: 0, checkboxChecked: false });
},
showErrorBox(title, content) {
console.error(`[gelectron] ${title}: ${content}`);
},
showMessageBoxSync(browserWindowOrOptions, options) {
let opts = options || browserWindowOrOptions || {};
if (browserWindowOrOptions && browserWindowOrOptions.webContents) {
opts = options || {};
}
if (typeof globalThis.__gelectron_dialog_message_sync === 'function') {
return globalThis.__gelectron_dialog_message_sync(opts);
}
return 0;
},
showCertificateTrustDialog(browserWindowOrOptions, options) {
return Promise.resolve();
},
};
module.exports = dialog;
+121
View File
@@ -0,0 +1,121 @@
'use strict';
/**
* Gelectron - Electron compatibility layer.
* Drop-in replacement for require('electron').
*/
const { app } = require('./app');
const { BrowserWindow } = require('./browser-window');
const ipcMain = require('./ipc-main');
const { Menu, MenuItem } = require('./menu');
const { Tray } = require('./tray');
const dialog = require('./dialog');
const shell = require('./shell');
const { Notification } = require('./notification');
const nativeImage = require('./native-image');
const safeStorage = require('./safe-storage');
const contextBridge = require('./context-bridge');
const webContents = require('./web-contents');
module.exports = {
app,
BrowserWindow,
ipcMain,
Menu,
MenuItem,
Tray,
dialog,
shell,
Notification,
nativeImage,
safeStorage,
contextBridge,
webContents,
// Aliases for common imports
clipboard: {
readText: () => '',
writeText: () => {},
readImage: () => nativeImage.createEmpty(),
writeImage: () => {},
},
screen: {
getPrimaryDisplay: () => ({
id: 0,
label: '',
bounds: { x: 0, y: 0, width: 1920, height: 1080 },
workArea: { x: 0, y: 0, width: 1920, height: 1040 },
size: { width: 1920, height: 1080 },
workAreaSize: { width: 1920, height: 1040 },
scaleFactor: 1.0,
rotation: 0,
internal: false,
touchSupport: 'unknown',
}),
getAllDisplays: () => [],
getDisplayMatching: () => null,
},
systemPreferences: {
isDarkMode: () => false,
getAccentColor: () => '#007AFF',
getColor: () => '#ffffff',
isSwipeTrackingFromScrollEventsEnabled: () => false,
subscribeNotification: () => () => {},
unsubscribeNotification: () => {},
subscribeLocalNotification: () => () => {},
unsubscribeLocalNotification: () => {},
getUserDefault: () => null,
setUserDefault: () => {},
removeUserDefault: () => {},
},
powerMonitor: {
on: () => {},
off: () => {},
once: () => {},
getSystemIdleState: () => 'active',
getSystemIdleTime: () => 0,
isInLowPowerMode: () => false,
},
globalShortcut: {
register: () => true,
unregister: () => {},
unregisterAll: () => {},
isRegistered: () => false,
},
session: {
defaultSession: {
cookies: {
get: async () => [],
set: async () => {},
remove: async () => {},
getSession: () => null,
},
protocol: {
registerFileProtocol: () => {},
registerHttpProtocol: () => {},
unregisterProtocol: () => {},
isProtocolRegistered: () => false,
},
setPermissionRequestHandler: () => {},
setPermissionCheckHandler: () => {},
webRequest: {
onBeforeRequest: () => {},
onHeadersReceived: () => {},
},
setUserAgent: () => {},
getUserAgent: () => '',
},
},
net: {
fetch: globalThis.fetch || require('node-fetch'),
},
// Constants
IPCRenderer: {
invoke: () => Promise.resolve(),
send: () => {},
on: () => () => {},
removeListener: () => {},
},
};
+107
View File
@@ -0,0 +1,107 @@
'use strict';
/**
* Gelectron - ipcMain module (Electron compatible)
*/
const { EventEmitter } = require('events');
class IpcMain extends EventEmitter {
constructor() {
super();
this._handlers = new Map();
this._onceHandlers = new Map();
}
handle(channel, handler) {
if (typeof handler !== 'function') {
throw new TypeError(`Expected function for channel '${channel}'`);
}
this._handlers.set(channel, handler);
return this;
}
handleOnce(channel, handler) {
if (typeof handler !== 'function') {
throw new TypeError(`Expected function for channel '${channel}'`);
}
this._onceHandlers.set(channel, handler);
return this;
}
on(channel, listener) {
if (typeof listener !== 'function') {
throw new TypeError(`Expected function for channel '${channel}'`);
}
super.on(channel, listener);
return this;
}
once(channel, listener) {
if (typeof listener !== 'function') {
throw new TypeError(`Expected function for channel '${channel}'`);
}
super.once(channel, listener);
return this;
}
removeHandler(channel) {
this._handlers.delete(channel);
return this;
}
removeListener(channel, listener) {
super.removeListener(channel, listener);
return this;
}
removeAllListeners(channel) {
super.removeAllListeners(channel);
return this;
}
listenerCount(channel) {
return super.listenerCount(channel);
}
rawListeners(channel) {
return super.rawListeners(channel);
}
eventNames() {
return super.eventNames();
}
_invoke(channel, ...args) {
const handler = this._handlers.get(channel);
if (!handler) {
return Promise.reject(new Error(`No handler registered for channel '${channel}'`));
}
try {
const result = handler(...args);
if (result instanceof Promise) {
return result;
}
return Promise.resolve(result);
} catch (err) {
return Promise.reject(err);
}
}
_emit(channel, ...args) {
return this.emit(channel, ...args);
}
_emitOnce(channel, ...args) {
const handler = this._onceHandlers.get(channel);
if (handler) {
this._onceHandlers.delete(channel);
return handler(...args);
}
return this.emit(channel, ...args);
}
}
const ipcMain = new IpcMain();
module.exports = ipcMain;
+145
View File
@@ -0,0 +1,145 @@
'use strict';
/**
* Gelectron - ipcRenderer module (Electron compatible)
*/
const { EventEmitter } = require('events');
class IpcRendererEvent {
constructor(sender, channel) {
this.sender = sender;
this.channel = channel;
this._returnValue = undefined;
this._defaultPrevented = false;
}
preventDefault() {
this._defaultPrevented = true;
}
get defaultPrevented() {
return this._defaultPrevented;
}
}
class IpcRenderer extends EventEmitter {
constructor() {
super();
this._requestId = 0;
this._pending = new Map();
this._listeners = new Map();
}
async invoke(channel, ...args) {
const requestId = `ipc-${++this._requestId}-${Date.now()}`;
const argsJson = JSON.stringify(args);
// In full integration, this calls the native ipc_renderer_invoke
// For now, route through the global IPC bridge if available
if (typeof globalThis.__gelectron_ipc === 'function') {
return globalThis.__gelectron_ipc(channel, ...args);
}
// Fallback: emit event for main process handling
return new Promise((resolve, reject) => {
this._pending.set(requestId, { resolve, reject });
// Emit for any registered handlers
this.emit(`invoke:${channel}`, ...args);
// Timeout after 30 seconds
setTimeout(() => {
if (this._pending.has(requestId)) {
this._pending.delete(requestId);
reject(new Error(`IPC invoke timed out for channel '${channel}'`));
}
}, 30000);
});
}
send(channel, ...args) {
const argsJson = JSON.stringify(args);
if (typeof globalThis.__gelectron_send === 'function') {
globalThis.__gelectron_send(channel, ...args);
}
this.emit(`send:${channel}`, ...args);
}
sendSync(channel, ...args) {
// Synchronous IPC is deprecated in Electron; return undefined
return undefined;
}
postMessage(channel, message, transfer) {
this.send(channel, message);
}
on(channel, listener) {
const wrappedListener = (event, ...args) => {
listener(event, ...args);
};
// Store wrapped reference for removeListener
if (!this._listeners.has(channel)) {
this._listeners.set(channel, new Map());
}
this._listeners.get(channel).set(listener, wrappedListener);
return super.on(channel, wrappedListener);
}
once(channel, listener) {
const wrappedListener = (event, ...args) => {
listener(event, ...args);
};
return super.once(channel, wrappedListener);
}
removeListener(channel, listener) {
const channelListeners = this._listeners.get(channel);
if (channelListeners) {
const wrapped = channelListeners.get(listener);
if (wrapped) {
channelListeners.delete(listener);
return super.removeListener(channel, wrapped);
}
}
return super.removeListener(channel, listener);
}
removeAllListeners(channel) {
this._listeners.delete(channel);
return super.removeAllListeners(channel);
}
// Internal method to receive messages from main process
_receiveMessage(channel, data) {
const event = new IpcRendererEvent(this, channel);
this.emit(channel, event, data);
}
// Internal method to resolve a pending invoke
_resolveInvoke(requestId, result) {
const pending = this._pending.get(requestId);
if (pending) {
this._pending.delete(requestId);
pending.resolve(result);
}
}
// Internal method to reject a pending invoke
_rejectInvoke(requestId, error) {
const pending = this._pending.get(requestId);
if (pending) {
this._pending.delete(requestId);
pending.reject(new Error(error));
}
}
}
const ipcRenderer = new IpcRenderer();
module.exports = { ipcRenderer, IpcRendererEvent };
+119
View File
@@ -0,0 +1,119 @@
'use strict';
/**
* Gelectron - menu module (Electron compatible)
*/
const { EventEmitter } = require('events');
class MenuItem extends EventEmitter {
constructor(options = {}) {
super();
this.id = options.id || '';
this.label = options.label || '';
this.type = options.type || 'normal';
this.role = options.role || '';
this.accelerator = options.accelerator || '';
this.enabled = options.enabled !== false;
this.visible = options.visible !== false;
this.checked = options.checked || false;
this.submenu = options.submenu || null;
this.toolTip = options.toolTip || '';
this.icon = options.icon || null;
this._click = options.click || null;
}
click() {
if (this._click) {
this._click(this, null);
}
this.emit('click');
}
}
class Menu extends EventEmitter {
constructor() {
super();
this.items = [];
this._id = Menu._nextId++;
}
static _nextId = 1;
static buildFromTemplate(template) {
const menu = new Menu();
if (Array.isArray(template)) {
menu.items = template.map((item) => {
if (item instanceof MenuItem) return item;
if (item.type === 'separator') {
return new MenuItem({ type: 'separator' });
}
return new MenuItem(item);
});
}
return menu;
}
static getApplicationMenu() {
return Menu._applicationMenu || null;
}
static setApplicationMenu(menu) {
Menu._applicationMenu = menu;
}
append(menuItem) {
if (menuItem instanceof MenuItem) {
this.items.push(menuItem);
} else {
this.items.push(new MenuItem(menuItem));
}
return this;
}
insert(menuItem, position) {
if (menuItem instanceof MenuItem) {
this.items.splice(position, 0, menuItem);
} else {
this.items.splice(position, 0, new MenuItem(menuItem));
}
return this;
}
popup(options = {}) {
console.log('[gelectron] Menu.popup called');
}
closePopup() {
console.log('[gelectron] Menu.closePopup called');
}
getMenuItemById(id) {
return this._findMenuItemById(this.items, id);
}
_findMenuItemById(items, id) {
for (const item of items) {
if (item.id === id) return item;
if (item.submenu) {
const found = this._findMenuItemById(item.submenu.items || item.submenu, id);
if (found) return found;
}
}
return null;
}
items() {
return this.items;
}
getApplicationMenu() {
return Menu._applicationMenu;
}
setApplicationMenu(menu) {
Menu._applicationMenu = menu;
}
}
module.exports = { Menu, MenuItem };
+117
View File
@@ -0,0 +1,117 @@
'use strict';
/**
* Gelectron - nativeImage module (Electron compatible)
*/
class NativeImage {
constructor() {
this._isEmpty = true;
this._width = 0;
this._height = 0;
this._data = null;
}
static createFromPath(path) {
const img = new NativeImage();
try {
const fs = require('fs');
const data = fs.readFileSync(path);
// Basic PNG header parsing for dimensions
if (data.length > 24 && data[0] === 0x89 && data[1] === 0x50) {
img._width = data.readUInt32BE(16);
img._height = data.readUInt32BE(20);
img._data = data;
img._isEmpty = false;
}
} catch (err) {
console.error(`[gelectron] Failed to load image: ${path}`, err.message);
}
return img;
}
static createFromBuffer(buffer, options = {}) {
const img = new NativeImage();
if (buffer && buffer.length > 0) {
img._data = buffer;
img._isEmpty = false;
img._width = options.width || 0;
img._height = options.height || 0;
// Try to detect PNG dimensions
if (buffer.length > 24 && buffer[0] === 0x89 && buffer[1] === 0x50) {
img._width = buffer.readUInt32BE(16);
img._height = buffer.readUInt32BE(20);
}
}
return img;
}
static createFromDataURL(dataURL) {
const matches = dataURL.match(/^data:[^;]+;base64,(.+)$/);
if (matches) {
return NativeImage.createFromBuffer(Buffer.from(matches[1], 'base64'));
}
return NativeImage.createEmpty();
}
static createEmpty() {
return new NativeImage();
}
toPNG(options = {}) {
return this._data || Buffer.alloc(0);
}
toJPEG(quality) {
return this._data || Buffer.alloc(0);
}
toBitmap(options = {}) {
return this._data || Buffer.alloc(0);
}
toDataURL() {
if (!this._data) return 'data:,';
const base64 = this._data.toString('base64');
return `data:image/png;base64,${base64}`;
}
resize(options) {
const resized = new NativeImage();
resized._width = options.width || this._width;
resized._height = options.height || this._height;
resized._data = this._data;
resized._isEmpty = this._isEmpty;
return resized;
}
crop(rect) {
return this.resize({ width: rect.width, height: rect.height });
}
getBitmap(options = {}) {
return this._data || Buffer.alloc(0);
}
getSize() {
return { width: this._width, height: this._height };
}
isEmpty() {
return this._isEmpty;
}
setTemplateImage(template) {
this._isTemplate = template;
}
isTemplateImage() {
return this._isTemplate || false;
}
toPNG(options) { return this.toPNG(options); }
toJPEG(quality) { return this.toJPEG(quality); }
}
module.exports = NativeImage;
+59
View File
@@ -0,0 +1,59 @@
'use strict';
/**
* Gelectron - Notification module (Electron compatible)
*/
const { EventEmitter } = require('events');
class Notification extends EventEmitter {
static _notifications = new Map();
static _nextId = 1;
constructor(options = {}) {
super();
this.id = Notification._nextId++;
this.title = options.title || '';
this.body = options.body || '';
this.subtitle = options.subtitle || '';
this.silent = options.silent || false;
this.icon = options.icon || null;
this.urgency = options.urgency || 'normal';
this.timeoutType = options.timeoutType || 'default';
this.closeButtonText = options.closeButtonText || '';
this.toastXml = options.toastXml || '';
this.actions = options.actions || [];
this.replyPlaceholder = options.replyPlaceholder || '';
Notification._notifications.set(this.id, this);
}
static isSupported() {
return true;
}
show() {
if (typeof Notification !== 'undefined' && Notification.permission === 'granted') {
new globalThis.Notification(this.title, {
body: this.body,
icon: this.icon,
});
}
console.log(`[gelectron] Notification shown: ${this.title}`);
this.emit('show');
return true;
}
close() {
Notification._notifications.delete(this.id);
console.log(`[gelectron] Notification ${this.id} closed`);
this.emit('close');
}
static fromNotification(notification) {
return notification;
}
}
module.exports = { Notification };
+156
View File
@@ -0,0 +1,156 @@
'use strict';
/**
* Gelectron - Preload script injection
*
* This script is injected into the renderer process before the page loads.
* It provides the ipcRenderer and contextBridge APIs to preload scripts.
*/
function getPreloadScript() {
return `
(function() {
'use strict';
// Expose gelectron preload APIs
window.__gelectron = window.__gelectron || {};
// IPC Renderer stub
window.__gelectron.ipcRenderer = {
_requestId: 0,
_pending: {},
invoke: function(channel) {
var args = Array.prototype.slice.call(arguments, 1);
var requestId = 'ipc-' + (++this._requestId) + '-' + Date.now();
var message = {
type: 'invoke',
requestId: requestId,
channel: channel,
args: args
};
if (typeof window.__gelectron_send === 'function') {
window.__gelectron_send(JSON.stringify(message));
}
return new Promise(function(resolve, reject) {
window.__gelectron.ipcRenderer._pending[requestId] = { resolve: resolve, reject: reject };
setTimeout(function() {
if (window.__gelectron.ipcRenderer._pending[requestId]) {
delete window.__gelectron.ipcRenderer._pending[requestId];
reject(new Error('IPC invoke timed out for channel: ' + channel));
}
}, 30000);
});
},
send: function(channel) {
var args = Array.prototype.slice.call(arguments, 1);
var message = {
type: 'send',
channel: channel,
args: args
};
if (typeof window.__gelectron_send === 'function') {
window.__gelectron_send(JSON.stringify(message));
}
},
sendSync: function() { return undefined; },
postMessage: function(channel, message) { this.send(channel, message); },
on: function(channel, listener) {
var wrappedListener = function(event) {
listener(event, Array.prototype.slice.call(arguments, 1));
};
window.addEventListener('message', function(event) {
if (event.data && event.data.__gelectron_channel === channel) {
wrappedListener(event, event.data.args);
}
});
return this;
},
once: function(channel, listener) {
var self = this;
var wrappedListener = function(event) {
listener(event, Array.prototype.slice.call(arguments, 1));
self.removeListener(channel, listener);
};
return this.on(channel, wrappedListener);
},
removeListener: function(channel, listener) {
return this;
},
removeAllListeners: function(channel) {
return this;
},
_resolveInvoke: function(requestId, result) {
var pending = this._pending[requestId];
if (pending) {
delete this._pending[requestId];
pending.resolve(result);
}
},
_rejectInvoke: function(requestId, error) {
var pending = this._pending[requestId];
if (pending) {
delete this._pending[requestId];
pending.reject(new Error(error));
}
}
};
// Context Bridge API
window.__gelectron.contextBridge = {
exposeInMainWorld: function(key, api) {
if (typeof window[key] !== 'undefined') {
console.warn('[gelectron] contextBridge: window.' + key + ' already exists, skipping');
return;
}
Object.defineProperty(window, key, {
value: Object.freeze(JSON.parse(JSON.stringify(api))),
writable: false,
configurable: false,
enumerable: true
});
}
};
// Receive messages from main process
window.addEventListener('message', function(event) {
if (event.data && event.data.__gelectron_channel) {
var channel = event.data.__gelectron_channel;
var args = event.data.args;
// Resolve pending invoke
if (channel === '__gelectron_ipc_resolve') {
var requestId = args[0];
var result = args[1];
window.__gelectron.ipcRenderer._resolveInvoke(requestId, result);
} else if (channel === '__gelectron_ipc_reject') {
var requestId = args[0];
var error = args[1];
window.__gelectron.ipcRenderer._rejectInvoke(requestId, error);
} else {
// Regular IPC message from main process
window.__gelectron.ipcRenderer._receiveMessage(channel, args);
}
}
});
// Expose as global for preload scripts
window.electron = window.electron || {};
window.electron.ipcRenderer = window.__gelectron.ipcRenderer;
window.electron.contextBridge = window.__gelectron.contextBridge;
})();
`;
}
module.exports = { getPreloadScript };
+45
View File
@@ -0,0 +1,45 @@
'use strict';
/**
* Gelectron Runtime - Node.js fallback when native binary is not available.
* Loads and runs an Electron app's main process using the JS compatibility layer.
*/
const path = require('path');
const Module = require('module');
function run(mainScript, env) {
// Set up the environment
Object.assign(process.env, env);
// Patch require so that 'electron' resolves to gelectron's compat layer
const electronCompatPath = path.join(__dirname, 'index.js');
const originalResolveFilename = Module._resolveFilename;
Module._resolveFilename = function (request, parent, isMain, options) {
if (request === 'electron') {
return electronCompatPath;
}
if (request === 'electron/main') {
return electronCompatPath;
}
if (request === 'electron/renderer') {
return path.join(__dirname, 'ipc-renderer.js');
}
if (request === 'electron/common') {
return electronCompatPath;
}
return originalResolveFilename.call(this, request, parent, isMain, options);
};
// Require the app's main script
try {
require(mainScript);
} catch (err) {
console.error(`[gelectron] Error loading main script: ${mainScript}`);
console.error(err);
process.exit(1);
}
}
module.exports = { run };
+30
View File
@@ -0,0 +1,30 @@
'use strict';
/**
* Gelectron - safeStorage module (Electron compatible)
*/
const safeStorage = {
isAvailable() {
return true;
},
async encryptString(plaintext) {
// Basic obfuscation; in production, this routes through the native keyring
return Buffer.from(plaintext).toString('base64');
},
async decryptString(encrypted) {
return Buffer.from(encrypted, 'base64').toString('utf-8');
},
async encryptBuffer(buffer) {
return Buffer.from(buffer).toString('base64');
},
async decryptBuffer(encrypted) {
return Buffer.from(encrypted, 'base64');
},
};
module.exports = safeStorage;
+100
View File
@@ -0,0 +1,100 @@
'use strict';
/**
* Gelectron - shell module (Electron compatible)
*/
const { exec } = require('child_process');
const path = require('path');
const os = require('os');
const shell = {
openExternal(url, options = {}) {
const platform = os.platform();
let cmd;
if (platform === 'darwin') {
cmd = `open "${url}"`;
} else if (platform === 'win32') {
cmd = `start "" "${url}"`;
} else {
cmd = `xdg-open "${url}"`;
}
return new Promise((resolve, reject) => {
exec(cmd, (error) => {
if (error) reject(error);
else resolve();
});
});
},
openPath(path) {
return new Promise((resolve, reject) => {
const platform = os.platform();
let cmd;
if (platform === 'darwin') {
cmd = `open "${path}"`;
} else if (platform === 'win32') {
cmd = `start "" "${path}"`;
} else {
cmd = `xdg-open "${path}"`;
}
exec(cmd, (error) => {
if (error) reject(error.message);
else resolve('');
});
});
},
showItemInFolder(fullPath) {
const platform = os.platform();
let cmd;
if (platform === 'darwin') {
cmd = `open -R "${fullPath}"`;
} else if (platform === 'win32') {
cmd = `explorer /select,"${fullPath}"`;
} else {
const dir = path.dirname(fullPath);
cmd = `xdg-open "${dir}"`;
}
exec(cmd);
},
moveItemToTrash(fullPath) {
// Use fs.rm or platform-specific trash command
const fs = require('fs');
try {
fs.rmSync(fullPath, { recursive: true, force: true });
return Promise.resolve('');
} catch (err) {
return Promise.reject(err.message);
}
},
beep() {
process.stdout.write('\x07');
},
writeShortcutLink(shortcutPath, options = {}) {
console.log('[gelectron] writeShortcutLink called');
return true;
},
readShortcutLink(shortcutPath) {
return {
target: '',
cwd: '',
args: '',
description: '',
icon: '',
iconIndex: 0,
};
},
};
module.exports = shell;
+74
View File
@@ -0,0 +1,74 @@
'use strict';
/**
* Gelectron - Tray module (Electron compatible)
*/
const { EventEmitter } = require('events');
class Tray extends EventEmitter {
static _trays = new Map();
static _nextId = 1;
constructor(image) {
super();
this.id = Tray._nextId++;
this._image = image;
this._tooltip = '';
this._menu = null;
this._isDestroyed = false;
Tray._trays.set(this.id, this);
console.log(`[gelectron] Tray ${this.id} created`);
}
setToolTip(tooltip) {
this._tooltip = tooltip;
}
getToolTip() {
return this._tooltip;
}
setImage(image) {
this._image = image;
}
setPressedImage(image) {}
setContextMenu(menu) {
this._menu = menu;
}
getContextMenu() {
return this._menu;
}
popupContextMenu(options) {
console.log('[gelectron] Tray.popupContextMenu');
}
isDestroyed() {
return this._isDestroyed;
}
destroy() {
this._isDestroyed = true;
Tray._trays.delete(this.id);
this.emit('destroy');
}
getBounds() {
return { x: 0, y: 0, width: 22, height: 22 };
}
static fromId(id) {
return Tray._trays.get(id) || null;
}
static getAllTrays() {
return Array.from(Tray._trays.values());
}
}
module.exports = { Tray };
+25
View File
@@ -0,0 +1,25 @@
'use strict';
/**
* Gelectron - webContents utilities (Electron compatible)
*/
const { BrowserWindow } = require('./browser-window');
const webContents = {
getAllWebContents() {
return BrowserWindow.getAllWindows().map((win) => win.webContents);
},
getFocusedWebContents() {
const focused = BrowserWindow.getFocusedWindow();
return focused ? focused.webContents : null;
},
fromId(id) {
const win = BrowserWindow.fromId(id);
return win ? win.webContents : null;
},
};
module.exports = webContents;