electrobun 0.0.13 → 0.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,402 @@
1
+ import { zigRPC } from "../proc/zig";
2
+ import * as fs from "fs";
3
+ import { execSync } from "child_process";
4
+ import electrobunEventEmitter from "../events/eventEmitter";
5
+ import {
6
+ type RPCSchema,
7
+ type RPCRequestHandler,
8
+ type RPCMessageHandlerFn,
9
+ type WildcardRPCMessageHandlerFn,
10
+ type RPCOptions,
11
+ createRPC,
12
+ } from "rpc-anywhere";
13
+ import { Updater } from "./Updater";
14
+ import type { BuiltinBunToWebviewSchema } from "../../browser/builtinrpcSchema";
15
+
16
+ const BrowserViewMap = {};
17
+ let nextWebviewId = 1;
18
+
19
+ const CHUNK_SIZE = 1024 * 4; // 4KB
20
+
21
+ type BrowserViewOptions<T = undefined> = {
22
+ url: string | null;
23
+ html: string | null;
24
+ preload: string | null;
25
+ partition: string | null;
26
+ frame: {
27
+ x: number;
28
+ y: number;
29
+ width: number;
30
+ height: number;
31
+ };
32
+ rpc: T;
33
+ syncRpc: { [method: string]: (params: any) => any };
34
+ hostWebviewId: number;
35
+ autoResize: boolean;
36
+ };
37
+
38
+ interface ElectrobunWebviewRPCSChema {
39
+ bun: RPCSchema;
40
+ webview: RPCSchema;
41
+ }
42
+
43
+ const defaultOptions: BrowserViewOptions = {
44
+ url: "https://electrobun.dev",
45
+ html: null,
46
+ preload: null,
47
+ frame: {
48
+ x: 0,
49
+ y: 0,
50
+ width: 800,
51
+ height: 600,
52
+ },
53
+ };
54
+
55
+ const internalSyncRpcHandlers = {
56
+ webviewTagInit: ({
57
+ hostWebviewId,
58
+ windowId,
59
+ url,
60
+ html,
61
+ preload,
62
+ partition,
63
+ frame,
64
+ }) => {
65
+ const webviewForTag = new BrowserView({
66
+ url,
67
+ html,
68
+ preload,
69
+ partition,
70
+ frame,
71
+ hostWebviewId,
72
+ autoResize: false,
73
+ });
74
+
75
+ // Note: we have to give it a couple of ticks to fully create the browserview
76
+ // which has a settimout init() which calls rpc that has a settimeout and all the serialization/deserialization
77
+
78
+ // TODO: we really need a better way to handle the whole view creation flow and
79
+ // maybe an onready event or something.
80
+ setTimeout(() => {
81
+ zigRPC.request.addWebviewToWindow({
82
+ windowId: windowId,
83
+ webviewId: webviewForTag.id,
84
+ });
85
+
86
+ if (url) {
87
+ webviewForTag.loadURL(url);
88
+ } else if (html) {
89
+ webviewForTag.loadHTML(html);
90
+ }
91
+ }, 100);
92
+
93
+ return webviewForTag.id;
94
+ },
95
+ };
96
+
97
+ const hash = await Updater.localInfo.hash();
98
+ // Note: we use the build's hash to separate from different apps and different builds
99
+ // but we also want a randomId to separate different instances of the same app
100
+ const randomId = Math.random().toString(36).substring(7);
101
+
102
+ export class BrowserView<T> {
103
+ id: number = nextWebviewId++;
104
+ hostWebviewId?: number;
105
+ url: string | null = null;
106
+ html: string | null = null;
107
+ preload: string | null = null;
108
+ partition: string | null = null;
109
+ autoResize: boolean = true;
110
+ frame: {
111
+ x: number;
112
+ y: number;
113
+ width: number;
114
+ height: number;
115
+ } = {
116
+ x: 0,
117
+ y: 0,
118
+ width: 800,
119
+ height: 600,
120
+ };
121
+ pipePrefix: string;
122
+ inStream: fs.WriteStream;
123
+ outStream: ReadableStream<Uint8Array>;
124
+ rpc?: T;
125
+ syncRpc?: { [method: string]: (params: any) => any };
126
+
127
+ constructor(options: Partial<BrowserViewOptions<T>> = defaultOptions) {
128
+ this.url = options.url || defaultOptions.url;
129
+ this.html = options.html || defaultOptions.html;
130
+ this.preload = options.preload || defaultOptions.preload;
131
+ this.frame = options.frame
132
+ ? { ...defaultOptions.frame, ...options.frame }
133
+ : { ...defaultOptions.frame };
134
+ this.rpc = options.rpc;
135
+ this.syncRpc = { ...(options.syncRpc || {}), ...internalSyncRpcHandlers };
136
+ this.partition = options.partition || null;
137
+ // todo (yoav): since collisions can crash the app add a function that checks if the
138
+ // file exists first
139
+ this.pipePrefix = `/private/tmp/electrobun_ipc_pipe_${hash}_${randomId}_${this.id}`;
140
+ this.hostWebviewId = options.hostWebviewId;
141
+ this.autoResize = options.autoResize === false ? false : true;
142
+
143
+ this.init();
144
+ }
145
+
146
+ init() {
147
+ // TODO: add a then to this that fires an onReady event
148
+ zigRPC.request.createWebview({
149
+ id: this.id,
150
+ hostWebviewId: this.hostWebviewId || null,
151
+ pipePrefix: this.pipePrefix,
152
+ partition: this.partition,
153
+ // TODO: decide whether we want to keep sending url/html
154
+ // here, if we're manually calling loadURL/loadHTML below
155
+ // then we can remove it from the api here
156
+ url: this.url,
157
+ html: this.html,
158
+ preload: this.preload,
159
+ frame: {
160
+ width: this.frame.width,
161
+ height: this.frame.height,
162
+ x: this.frame.x,
163
+ y: this.frame.y,
164
+ },
165
+ autoResize: this.autoResize,
166
+ });
167
+
168
+ this.createStreams();
169
+
170
+ BrowserViewMap[this.id] = this;
171
+ }
172
+
173
+ createStreams() {
174
+ const webviewPipeIn = this.pipePrefix + "_in";
175
+ const webviewPipeOut = this.pipePrefix + "_out";
176
+
177
+ try {
178
+ execSync("mkfifo " + webviewPipeOut);
179
+ } catch (e) {
180
+ console.log("pipe out already exists");
181
+ }
182
+
183
+ try {
184
+ execSync("mkfifo " + webviewPipeIn);
185
+ } catch (e) {
186
+ console.log("pipe in already exists");
187
+ }
188
+
189
+ const inStream = fs.createWriteStream(webviewPipeIn, {
190
+ flags: "r+",
191
+ });
192
+
193
+ // todo: something has to be written to it to open it
194
+ // look into this
195
+ inStream.write("\n");
196
+
197
+ this.inStream = inStream;
198
+
199
+ // Open the named pipe for reading
200
+ const outStream = Bun.file(webviewPipeOut).stream();
201
+ this.outStream = outStream;
202
+
203
+ if (this.rpc) {
204
+ this.rpc.setTransport(this.createTransport());
205
+ }
206
+ }
207
+
208
+ sendMessageToWebview(jsonMessage) {
209
+ const stringifiedMessage =
210
+ typeof jsonMessage === "string"
211
+ ? jsonMessage
212
+ : JSON.stringify(jsonMessage);
213
+ // todo (yoav): make this a shared const with the browser api
214
+ const wrappedMessage = `window.__electrobun.receiveMessageFromBun(${stringifiedMessage})`;
215
+ this.executeJavascript(wrappedMessage);
216
+ }
217
+
218
+ // Note: the OS has a buffer limit on named pipes. If we overflow it
219
+ // it won't trigger the kevent for zig to read the pipe and we'll be stuck.
220
+ // so we have to chunk it
221
+ executeJavascript(js: string) {
222
+ let offset = 0;
223
+ while (offset < js.length) {
224
+ const chunk = js.slice(offset, offset + CHUNK_SIZE);
225
+ this.inStream.write(chunk);
226
+ offset += CHUNK_SIZE;
227
+ }
228
+
229
+ // Ensure the newline is written after all chunks
230
+ this.inStream.write("\n");
231
+ }
232
+
233
+ loadURL(url: string) {
234
+ this.url = url;
235
+ zigRPC.request.loadURL({ webviewId: this.id, url: this.url });
236
+ }
237
+
238
+ loadHTML(html: string) {
239
+ this.html = html;
240
+ zigRPC.request.loadHTML({ webviewId: this.id, html: this.html });
241
+ }
242
+
243
+ // todo (yoav): move this to a class that also has off, append, prepend, etc.
244
+ // name should only allow browserView events
245
+ // Note: normalize event names to willNavigate instead of ['will-navigate'] to save
246
+ // 5 characters per usage and allow minification to be more effective.
247
+ on(
248
+ name:
249
+ | "will-navigate"
250
+ | "did-navigate"
251
+ | "did-navigate-in-page"
252
+ | "did-commit-navigation"
253
+ | "dom-ready",
254
+ handler
255
+ ) {
256
+ const specificName = `${name}-${this.id}`;
257
+ electrobunEventEmitter.on(specificName, handler);
258
+ }
259
+
260
+ createTransport = () => {
261
+ const that = this;
262
+
263
+ return {
264
+ send(message) {
265
+ // todo (yoav): note: this is the same as the zig transport
266
+ try {
267
+ const messageString = JSON.stringify(message);
268
+ that.sendMessageToWebview(messageString);
269
+ } catch (error) {
270
+ console.error("bun: failed to serialize message to webview", error);
271
+ }
272
+ },
273
+ registerHandler(handler) {
274
+ async function readFromPipe(
275
+ reader: ReadableStreamDefaultReader<Uint8Array>
276
+ ) {
277
+ let buffer = "";
278
+ while (true) {
279
+ const { done, value } = await reader.read();
280
+ if (done) break;
281
+
282
+ buffer += new TextDecoder().decode(value);
283
+ let eolIndex;
284
+
285
+ while ((eolIndex = buffer.indexOf("\n")) >= 0) {
286
+ const line = buffer.slice(0, eolIndex).trim();
287
+ buffer = buffer.slice(eolIndex + 1);
288
+ if (line) {
289
+ try {
290
+ const event = JSON.parse(line);
291
+ handler(event);
292
+ } catch (error) {
293
+ console.error("webview: ", line);
294
+ }
295
+ }
296
+ }
297
+ }
298
+ }
299
+
300
+ const reader = that.outStream.getReader();
301
+ readFromPipe(reader);
302
+ },
303
+ };
304
+ };
305
+
306
+ static getById(id: number) {
307
+ return BrowserViewMap[id];
308
+ }
309
+
310
+ static getAll() {
311
+ return Object.values(BrowserViewMap);
312
+ }
313
+
314
+ static defineRPC<
315
+ Schema extends ElectrobunWebviewRPCSChema,
316
+ BunSchema extends RPCSchema = Schema["bun"],
317
+ WebviewSchema extends RPCSchema = Schema["webview"]
318
+ >(config: {
319
+ maxRequestTime?: number;
320
+ handlers: {
321
+ requests?: RPCRequestHandler<BunSchema["requests"]>;
322
+ messages?: {
323
+ [key in keyof BunSchema["messages"]]: RPCMessageHandlerFn<
324
+ BunSchema["messages"],
325
+ key
326
+ >;
327
+ } & {
328
+ "*"?: WildcardRPCMessageHandlerFn<BunSchema["messages"]>;
329
+ };
330
+ };
331
+ }) {
332
+ // Note: RPC Anywhere requires defining the requests that a schema handles and the messages that a schema sends.
333
+ // eg: BunSchema {
334
+ // requests: // ... requests bun handles, sent by webview
335
+ // messages: // ... messages bun sends, handled by webview
336
+ // }
337
+ // In some generlized contexts that makes sense,
338
+ // In the Electrobun context it can feel a bit counter-intuitive so we swap this around a bit. In Electrobun, the
339
+ // webview and bun are known endpoints so we simplify schema definitions by combining them.
340
+ // Schema {
341
+ // bun: BunSchema {
342
+ // requests: // ... requests bun handles, sent by webview,
343
+ // messages: // ... messages bun handles, sent by webview
344
+ // },
345
+ // webview: WebviewSchema {
346
+ // requests: // ... requests webview handles, sent by bun,
347
+ // messages: // ... messages webview handles, sent by bun
348
+ // },
349
+ // }
350
+ // This way from bun, webview.rpc.request.getTitle() and webview.rpc.send.someMessage maps to the schema
351
+ // MySchema.webview.requests.getTitle and MySchema.webview.messages.someMessage
352
+ // and in the webview, Electroview.rpc.request.getFileContents maps to
353
+ // MySchema.bun.requests.getFileContents.
354
+ // electrobun also treats messages as "requests that we don't wait for to complete", and normalizes specifying the
355
+ // handlers for them alongside request handlers.
356
+
357
+ type mixedWebviewSchema = {
358
+ requests: BunSchema["requests"];
359
+ messages: WebviewSchema["messages"];
360
+ };
361
+
362
+ type mixedBunSchema = {
363
+ requests: WebviewSchema["requests"] &
364
+ BuiltinBunToWebviewSchema["requests"];
365
+ messages: BunSchema["messages"];
366
+ };
367
+
368
+ const rpcOptions = {
369
+ maxRequestTime: config.maxRequestTime,
370
+ requestHandler: config.handlers.requests,
371
+ transport: {
372
+ // Note: RPC Anywhere will throw if you try add a message listener if transport.registerHandler is falsey
373
+ registerHandler: () => {},
374
+ },
375
+ } as RPCOptions<mixedWebviewSchema, mixedBunSchema>;
376
+
377
+ const rpc = createRPC<mixedWebviewSchema, mixedBunSchema>(rpcOptions);
378
+
379
+ const messageHandlers = config.handlers.messages;
380
+ if (messageHandlers) {
381
+ // note: this can only be done once there is a transport
382
+ // @ts-ignore - this is due to all the schema mixing we're doing, fine to ignore
383
+ // while types in here are borked, they resolve correctly/bubble up to the defineRPC call site.
384
+ rpc.addMessageListener(
385
+ "*",
386
+ (messageName: keyof BunSchema["messages"], payload) => {
387
+ const globalHandler = messageHandlers["*"];
388
+ if (globalHandler) {
389
+ globalHandler(messageName, payload);
390
+ }
391
+
392
+ const messageHandler = messageHandlers[messageName];
393
+ if (messageHandler) {
394
+ messageHandler(payload);
395
+ }
396
+ }
397
+ );
398
+ }
399
+
400
+ return rpc;
401
+ }
402
+ }
@@ -0,0 +1,178 @@
1
+ import { zigRPC } from "../proc/zig";
2
+ import electrobunEventEmitter from "../events/eventEmitter";
3
+ import { BrowserView } from "./BrowserView";
4
+ import { type RPC } from "rpc-anywhere";
5
+
6
+ let nextWindowId = 1;
7
+
8
+ // todo (yoav): if we default to builtInSchema, we don't want dev to have to define custom handlers
9
+ // for the built-in schema stuff.
10
+ type WindowOptionsType<T = undefined> = {
11
+ title: string;
12
+ frame: {
13
+ x: number;
14
+ y: number;
15
+ width: number;
16
+ height: number;
17
+ };
18
+ url: string | null;
19
+ html: string | null;
20
+ preload: string | null;
21
+ rpc?: T;
22
+ syncRpc?: { [method: string]: (params: any) => any };
23
+ styleMask?: {};
24
+ // TODO: implement all of them
25
+ titleBarStyle: "hiddenInset" | "default";
26
+ };
27
+
28
+ const defaultOptions: WindowOptionsType = {
29
+ title: "Electrobun",
30
+ frame: {
31
+ x: 0,
32
+ y: 0,
33
+ width: 800,
34
+ height: 600,
35
+ },
36
+ url: "https://electrobun.dev",
37
+ html: null,
38
+ preload: null,
39
+ titleBarStyle: "default",
40
+ };
41
+
42
+ const BrowserWindowMap = {};
43
+
44
+ // todo (yoav): do something where the type extends the default schema
45
+ // that way we can provide built-in requests/messages and devs can extend it
46
+
47
+ export class BrowserWindow<T> {
48
+ id: number = nextWindowId++;
49
+ title: string = "Electrobun";
50
+ state: "creating" | "created" = "creating";
51
+ url: string | null = null;
52
+ html: string | null = null;
53
+ preload: string | null = null;
54
+ frame: {
55
+ x: number;
56
+ y: number;
57
+ width: number;
58
+ height: number;
59
+ } = {
60
+ x: 0,
61
+ y: 0,
62
+ width: 800,
63
+ height: 600,
64
+ };
65
+ // todo (yoav): make this an array of ids or something
66
+ webviewId: number;
67
+
68
+ constructor(options: Partial<WindowOptionsType<T>> = defaultOptions) {
69
+ this.title = options.title || "New Window";
70
+ this.frame = options.frame
71
+ ? { ...defaultOptions.frame, ...options.frame }
72
+ : { ...defaultOptions.frame };
73
+ this.url = options.url || null;
74
+ this.html = options.html || null;
75
+ this.preload = options.preload || null;
76
+
77
+ this.init(options);
78
+ }
79
+
80
+ init({
81
+ rpc,
82
+ syncRpc,
83
+ styleMask,
84
+ titleBarStyle,
85
+ }: Partial<WindowOptionsType<T>>) {
86
+ zigRPC.request.createWindow({
87
+ id: this.id,
88
+ title: this.title,
89
+ url: this.url,
90
+ html: this.html,
91
+ frame: {
92
+ width: this.frame.width,
93
+ height: this.frame.height,
94
+ x: this.frame.x,
95
+ y: this.frame.y,
96
+ },
97
+ styleMask: {
98
+ Borderless: false,
99
+ Titled: true,
100
+ Closable: true,
101
+ Miniaturizable: true,
102
+ Resizable: true,
103
+ UnifiedTitleAndToolbar: false,
104
+ FullScreen: false,
105
+ FullSizeContentView: false,
106
+ UtilityWindow: false,
107
+ DocModalWindow: false,
108
+ NonactivatingPanel: false,
109
+ HUDWindow: false,
110
+ ...(styleMask || {}),
111
+ ...(titleBarStyle === "hiddenInset"
112
+ ? {
113
+ Titled: true,
114
+ FullSizeContentView: true,
115
+ }
116
+ : {}),
117
+ },
118
+ titleBarStyle: titleBarStyle || "default",
119
+ });
120
+
121
+ // todo (yoav): user should be able to override this and pass in their
122
+ // own webview instance, or instances for attaching to the window.
123
+ const webview = new BrowserView({
124
+ // TODO: decide whether we want to keep sending url/html
125
+ // here, if we're manually calling loadURL/loadHTML below
126
+ // then we can remove it from the api here
127
+ url: this.url,
128
+ html: this.html,
129
+ preload: this.preload,
130
+ // frame: this.frame,
131
+ frame: {
132
+ x: 0,
133
+ y: 0,
134
+ width: this.frame.width,
135
+ height: this.frame.height,
136
+ },
137
+ rpc,
138
+ syncRpc,
139
+ });
140
+
141
+ this.webviewId = webview.id;
142
+
143
+ zigRPC.request.addWebviewToWindow({
144
+ windowId: this.id,
145
+ webviewId: webview.id,
146
+ });
147
+
148
+ if (this.url) {
149
+ webview.loadURL(this.url);
150
+ } else if (this.html) {
151
+ webview.loadHTML(this.html);
152
+ }
153
+
154
+ BrowserWindowMap[this.id] = this;
155
+ }
156
+
157
+ get webview() {
158
+ // todo (yoav): we don't want this to be undefined, so maybe we should just
159
+ // link directly to the browserview object instead of a getter
160
+ return BrowserView.getById(this.webviewId) as BrowserView<T>;
161
+ }
162
+
163
+ setTitle(title: string) {
164
+ this.title = title;
165
+ return zigRPC.request.setTitle({ winId: this.id, title });
166
+ }
167
+
168
+ close() {
169
+ return zigRPC.request.closeWindow({ winId: this.id });
170
+ }
171
+
172
+ // todo (yoav): move this to a class that also has off, append, prepend, etc.
173
+ // name should only allow browserWindow events
174
+ on(name, handler) {
175
+ const specificName = `${name}-${this.id}`;
176
+ electrobunEventEmitter.on(specificName, handler);
177
+ }
178
+ }
@@ -0,0 +1,67 @@
1
+ // TODO: have a context specific menu that excludes role
2
+ import { zigRPC, type ApplicationMenuItemConfig } from "../proc/zig";
3
+ import electrobunEventEmitter from "../events/eventEmitter";
4
+
5
+ export const showContextMenu = (menu: Array<ApplicationMenuItemConfig>) => {
6
+ const menuWithDefaults = menuConfigWithDefaults(menu);
7
+ zigRPC.request.showContextMenu({
8
+ menuConfig: JSON.stringify(menuWithDefaults),
9
+ });
10
+ };
11
+
12
+ export const on = (name: "context-menu-clicked", handler) => {
13
+ const specificName = `${name}`;
14
+ electrobunEventEmitter.on(specificName, handler);
15
+ };
16
+
17
+ // todo: Consolidate Application menu, context menu, and tray menus can all have roles.
18
+ const roleLabelMap = {
19
+ quit: "Quit",
20
+ hide: "Hide",
21
+ hideOthers: "Hide Others",
22
+ showAll: "Show All",
23
+ undo: "Undo",
24
+ redo: "Redo",
25
+ cut: "Cut",
26
+ copy: "Copy",
27
+ paste: "Paste",
28
+ pasteAndMatchStyle: "Paste And Match Style",
29
+ delete: "Delete",
30
+ selectAll: "Select All",
31
+ startSpeaking: "Start Speaking",
32
+ stopSpeaking: "Stop Speaking",
33
+ enterFullScreen: "Enter FullScreen",
34
+ exitFullScreen: "Exit FullScreen",
35
+ toggleFullScreen: "Toggle Full Screen",
36
+ minimize: "Minimize",
37
+ zoom: "Zoom",
38
+ bringAllToFront: "Bring All To Front",
39
+ close: "Close",
40
+ cycleThroughWindows: "Cycle Through Windows",
41
+ showHelp: "Show Help",
42
+ };
43
+
44
+ const menuConfigWithDefaults = (
45
+ menu: Array<ApplicationMenuItemConfig>
46
+ ): Array<ApplicationMenuItemConfig> => {
47
+ return menu.map((item) => {
48
+ if (item.type === "divider" || item.type === "separator") {
49
+ return { type: "divider" };
50
+ } else {
51
+ return {
52
+ label: item.label || roleLabelMap[item.role] || "",
53
+ type: item.type || "normal",
54
+ // application menus can either have an action or a role. not both.
55
+ ...(item.role ? { role: item.role } : { action: item.action || "" }),
56
+ // default enabled to true unless explicitly set to false
57
+ enabled: item.enabled === false ? false : true,
58
+ checked: Boolean(item.checked),
59
+ hidden: Boolean(item.hidden),
60
+ tooltip: item.tooltip || undefined,
61
+ ...(item.submenu
62
+ ? { submenu: menuConfigWithDefaults(item.submenu) }
63
+ : {}),
64
+ };
65
+ }
66
+ });
67
+ };
@@ -0,0 +1,5 @@
1
+ import { resolve } from "path";
2
+
3
+ const RESOURCES_FOLDER = resolve("../Resources/");
4
+
5
+ export const VIEWS_FOLDER = resolve(RESOURCES_FOLDER, "app/views");