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,10 @@
1
+ // consider just makeing a shared types file
2
+
3
+ export type BuiltinBunToWebviewSchema = {
4
+ requests: {
5
+ evaluateJavascriptWithResponse: {
6
+ params: { script: string };
7
+ response: any;
8
+ };
9
+ };
10
+ };
@@ -0,0 +1,404 @@
1
+ import {
2
+ type RPCSchema,
3
+ type RPCRequestHandler,
4
+ type RPCOptions,
5
+ type RPCMessageHandlerFn,
6
+ type WildcardRPCMessageHandlerFn,
7
+ type RPCTransport,
8
+ createRPC,
9
+ } from "rpc-anywhere";
10
+ import { ConfigureWebviewTags } from "./webviewtag";
11
+ // todo: should this just be injected as a preload script?
12
+ import { isAppRegionDrag } from "./stylesAndElements";
13
+ import type { BuiltinBunToWebviewSchema } from "./builtinrpcSchema";
14
+
15
+ interface ElectrobunWebviewRPCSChema {
16
+ bun: RPCSchema;
17
+ webview: RPCSchema;
18
+ }
19
+
20
+ const WEBVIEW_ID = window.__electrobunWebviewId;
21
+
22
+ // todo (yoav): move this stuff to browser/rpc/webview.ts
23
+ type ZigWebviewHandlers = RPCSchema<{
24
+ requests: {
25
+ webviewTagCallAsyncJavaScript: {
26
+ params: {
27
+ messageId: string;
28
+ webviewId: number;
29
+ hostWebviewId: number;
30
+ script: string;
31
+ };
32
+ response: void;
33
+ };
34
+ };
35
+ }>;
36
+
37
+ type WebviewTagHandlers = RPCSchema<{
38
+ requests: {};
39
+ messages: {
40
+ webviewTagResize: {
41
+ id: number;
42
+ frame: {
43
+ x: number;
44
+ y: number;
45
+ width: number;
46
+ height: number;
47
+ };
48
+ masks: string;
49
+ };
50
+ webviewTagUpdateSrc: {
51
+ id: number;
52
+ url: string;
53
+ };
54
+ webviewTagGoBack: {
55
+ id: number;
56
+ };
57
+ webviewTagGoForward: {
58
+ id: number;
59
+ };
60
+ webviewTagReload: {
61
+ id: number;
62
+ };
63
+ webviewTagRemove: {
64
+ id: number;
65
+ };
66
+ startWindowMove: {
67
+ id: number;
68
+ };
69
+ stopWindowMove: {
70
+ id: number;
71
+ };
72
+ moveWindowBy: {
73
+ id: number;
74
+ x: number;
75
+ y: number;
76
+ };
77
+ webviewTagSetTransparent: {
78
+ id: number;
79
+ transparent: boolean;
80
+ };
81
+ webviewTagToggleMirroring: {
82
+ id: number;
83
+ enable: boolean;
84
+ };
85
+ webviewTagSetPassthrough: {
86
+ id: number;
87
+ enablePassthrough: boolean;
88
+ };
89
+ webviewTagSetHidden: {
90
+ id: number;
91
+ hidden: boolean;
92
+ };
93
+ };
94
+ }>;
95
+
96
+ class Electroview<T> {
97
+ // user's custom rpc browser <-> bun
98
+ rpc?: T;
99
+ rpcHandler?: (msg: any) => void;
100
+ // electrobun rpc browser <-> zig
101
+ zigRpc?: any;
102
+ zigRpcHandler?: (msg: any) => void;
103
+ // give it a default function
104
+ syncRpc: (params: any) => any = () => {
105
+ console.log("syncRpc not initialized");
106
+ };
107
+
108
+ constructor(config: { rpc: T }) {
109
+ this.rpc = config.rpc;
110
+ this.init();
111
+ }
112
+
113
+ init() {
114
+ // todo (yoav): should init webviewTag by default when src is local
115
+ // and have a setting that forces it enabled or disabled
116
+ this.initZigRpc();
117
+ // Note:
118
+ // syncRPC messages doesn't need to be defined since there's no need for sync 1-way message
119
+ // just use non-blocking async rpc for that, we just need sync requests
120
+ // We don't need request ids either since we're not receiving the response on a different pipe
121
+ if (true) {
122
+ // TODO: define sync requests on schema (separate from async reqeusts and messages)
123
+ this.syncRpc = (msg: { method: string; params: any }) => {
124
+ try {
125
+ const messageString = JSON.stringify(msg);
126
+ return this.bunBridgeSync(messageString);
127
+ } catch (error) {
128
+ console.error(
129
+ "bun: failed to serialize message to webview syncRpc",
130
+ error
131
+ );
132
+ }
133
+ };
134
+ }
135
+ ConfigureWebviewTags(true, this.zigRpc, this.syncRpc);
136
+
137
+ this.initElectrobunListeners();
138
+
139
+ window.__electrobun = {
140
+ receiveMessageFromBun: this.receiveMessageFromBun.bind(this),
141
+ receiveMessageFromZig: this.receiveMessageFromZig.bind(this),
142
+ };
143
+
144
+ if (this.rpc) {
145
+ this.rpc.setTransport(this.createTransport());
146
+ }
147
+ }
148
+
149
+ initZigRpc() {
150
+ this.zigRpc = createRPC<WebviewTagHandlers, ZigWebviewHandlers>({
151
+ transport: this.createZigTransport(),
152
+ // requestHandler: {
153
+
154
+ // },
155
+ maxRequestTime: 1000,
156
+ });
157
+ }
158
+
159
+ // This will be attached to the global object, zig can rpc reply by executingJavascript
160
+ // of that global reference to the function
161
+ receiveMessageFromZig(msg: any) {
162
+ if (this.zigRpcHandler) {
163
+ this.zigRpcHandler(msg);
164
+ }
165
+ }
166
+
167
+ // TODO: implement proper rpc-anywhere style rpc here
168
+ // todo: this is duplicated in webviewtag.ts and should be DRYed up
169
+ sendToZig(message: {}) {
170
+ window.webkit.messageHandlers.webviewTagBridge.postMessage(
171
+ JSON.stringify(message)
172
+ );
173
+ }
174
+
175
+ initElectrobunListeners() {
176
+ document.addEventListener("mousedown", (e) => {
177
+ if (isAppRegionDrag(e)) {
178
+ this.zigRpc?.send.startWindowMove({ id: WEBVIEW_ID });
179
+ }
180
+ });
181
+
182
+ document.addEventListener("mouseup", (e) => {
183
+ if (isAppRegionDrag(e)) {
184
+ this.zigRpc?.send.stopWindowMove({ id: WEBVIEW_ID });
185
+ }
186
+ });
187
+ }
188
+
189
+ createTransport() {
190
+ const that = this;
191
+ return {
192
+ send(message) {
193
+ try {
194
+ const messageString = JSON.stringify(message);
195
+ that.bunBridge(messageString);
196
+ } catch (error) {
197
+ console.error("bun: failed to serialize message to webview", error);
198
+ }
199
+ },
200
+ registerHandler(handler) {
201
+ that.rpcHandler = handler;
202
+ },
203
+ };
204
+ }
205
+
206
+ createZigTransport(): RPCTransport {
207
+ const that = this;
208
+ return {
209
+ send(message) {
210
+ window.webkit.messageHandlers.webviewTagBridge.postMessage(
211
+ JSON.stringify(message)
212
+ );
213
+ },
214
+ registerHandler(handler) {
215
+ that.zigRpcHandler = handler;
216
+ // webview tag doesn't handle any messages from zig just yet
217
+ },
218
+ };
219
+ }
220
+
221
+ // call any of your bun syncrpc methods in a way that appears synchronous from the browser context
222
+ bunBridgeSync(msg: string) {
223
+ var xhr = new XMLHttpRequest();
224
+ // Note: setting false here makes the xhr request blocking. This completely
225
+ // blocks the main thread which is terrible. You can use this safely from a webworker.
226
+ // There are also cases where exposing bun sync apis (eg: existsSync) is useful especially
227
+ // on a first pass when migrating from Electron to Electrobun.
228
+ // This mechanism is designed to make any rpc call over the bridge into a sync blocking call
229
+ // from the browser context while bun asynchronously replies. Use it sparingly from the main thread.
230
+ xhr.open("POST", "views://syncrpc", false); // Synchronous call
231
+ xhr.send(msg);
232
+ if (!xhr.responseText) {
233
+ return xhr.responseText;
234
+ }
235
+
236
+ try {
237
+ return JSON.parse(xhr.responseText);
238
+ } catch {
239
+ return xhr.responseText;
240
+ }
241
+ }
242
+
243
+ bunBridge(msg: string) {
244
+ // Note: messageHandlers seem to freeze when sending large messages
245
+ // but xhr to views://rpc can run into CORS issues on non views://
246
+ // loaded content (eg: when writing extensions/preload scripts for
247
+ // remote content).
248
+
249
+ // Since most messages--especially those on remote content, are small
250
+ // we can solve most use cases by having a fallback to xhr for
251
+ // large messages
252
+
253
+ // TEMP: disable the fallback for now. for some reason suddenly can't
254
+ // repro now that other places are chunking messages and laptop restart
255
+ if (true || msg.length < 8 * 1024) {
256
+ window.webkit.messageHandlers.bunBridge.postMessage(msg);
257
+ } else {
258
+ var xhr = new XMLHttpRequest();
259
+
260
+ // Note: we're only using synchronouse http on this async
261
+ // call to get around CORS for now
262
+ // Note: DO NOT use postMessage handlers since it
263
+ // freezes the process when sending lots of large messages
264
+
265
+ xhr.open("POST", "views://rpc", false); // sychronous call
266
+ xhr.send(msg);
267
+ }
268
+ }
269
+
270
+ receiveMessageFromBun(msg) {
271
+ // NOTE: in the webview messages are passed by executing ElectrobunView.receiveMessageFromBun(object)
272
+ // so they're already parsed into an object here
273
+ if (this.rpcHandler) {
274
+ this.rpcHandler(msg);
275
+ }
276
+ }
277
+ // todo (yoav): This is mostly just the reverse of the one in BrowserView.ts on the bun side. Should DRY this up.
278
+ static defineRPC<
279
+ Schema extends ElectrobunWebviewRPCSChema,
280
+ BunSchema extends RPCSchema = Schema["bun"],
281
+ WebviewSchema extends RPCSchema = Schema["webview"]
282
+ >(config: {
283
+ maxRequestTime?: number;
284
+ handlers: {
285
+ requests?: RPCRequestHandler<WebviewSchema["requests"]>;
286
+ messages?: {
287
+ [key in keyof WebviewSchema["messages"]]: RPCMessageHandlerFn<
288
+ WebviewSchema["messages"],
289
+ key
290
+ >;
291
+ } & {
292
+ "*"?: WildcardRPCMessageHandlerFn<WebviewSchema["messages"]>;
293
+ };
294
+ };
295
+ }) {
296
+ // Note: RPC Anywhere requires defining the requests that a schema handles and the messages that a schema sends.
297
+ // eg: BunSchema {
298
+ // requests: // ... requests bun handles, sent by webview
299
+ // messages: // ... messages bun sends, handled by webview
300
+ // }
301
+ // In some generlized contexts that makes sense,
302
+ // In the Electrobun context it can feel a bit counter-intuitive so we swap this around a bit. In Electrobun, the
303
+ // webview and bun are known endpoints so we simplify schema definitions by combining them.
304
+ // Schema {
305
+ // bun: BunSchema {
306
+ // requests: // ... requests bun sends, handled by webview,
307
+ // messages: // ... messages bun sends, handled by webview
308
+ // },
309
+ // webview: WebviewSchema {
310
+ // requests: // ... requests webview sends, handled by bun,
311
+ // messages: // ... messages webview sends, handled by bun
312
+ // },
313
+ // }
314
+ // electrobun also treats messages as "requests that we don't wait for to complete", and normalizes specifying the
315
+ // handlers for them alongside request handlers.
316
+
317
+ const builtinHandlers: {
318
+ requests: RPCRequestHandler<BuiltinBunToWebviewSchema["requests"]>;
319
+ } = {
320
+ requests: {
321
+ evaluateJavascriptWithResponse: ({ script }) => {
322
+ return new Promise((resolve) => {
323
+ try {
324
+ const resultFunction = new Function(script);
325
+ const result = resultFunction();
326
+
327
+ if (result instanceof Promise) {
328
+ result
329
+ .then((resolvedResult) => {
330
+ resolve(resolvedResult);
331
+ })
332
+ .catch((error) => {
333
+ console.error("bun: async script execution failed", error);
334
+ resolve(String(error));
335
+ });
336
+ } else {
337
+ resolve(result);
338
+ }
339
+ } catch (error) {
340
+ console.error("bun: failed to eval script", error);
341
+ resolve(String(error));
342
+ }
343
+ });
344
+ },
345
+ },
346
+ };
347
+
348
+ type mixedWebviewSchema = {
349
+ requests: BunSchema["requests"];
350
+ messages: WebviewSchema["messages"];
351
+ };
352
+
353
+ type mixedBunSchema = {
354
+ requests: WebviewSchema["requests"] &
355
+ BuiltinBunToWebviewSchema["requests"];
356
+ messages: BunSchema["messages"];
357
+ };
358
+
359
+ const rpcOptions = {
360
+ maxRequestTime: config.maxRequestTime,
361
+ requestHandler: {
362
+ ...config.handlers.requests,
363
+ ...builtinHandlers.requests,
364
+ },
365
+ transport: {
366
+ // Note: RPC Anywhere will throw if you try add a message listener if transport.registerHandler is falsey
367
+ registerHandler: () => {},
368
+ },
369
+ } as RPCOptions<mixedBunSchema, mixedWebviewSchema>;
370
+
371
+ const rpc = createRPC<mixedBunSchema, mixedWebviewSchema>(rpcOptions);
372
+
373
+ const messageHandlers = config.handlers.messages;
374
+ if (messageHandlers) {
375
+ // note: this can only be done once there is a transport
376
+ // @ts-ignore - this is due to all the schema mixing we're doing, fine to ignore
377
+ // while types in here are borked, they resolve correctly/bubble up to the defineRPC call site.
378
+ rpc.addMessageListener(
379
+ "*",
380
+ (messageName: keyof WebviewSchema["messages"], payload) => {
381
+ const globalHandler = messageHandlers["*"];
382
+ if (globalHandler) {
383
+ globalHandler(messageName, payload);
384
+ }
385
+
386
+ const messageHandler = messageHandlers[messageName];
387
+ if (messageHandler) {
388
+ messageHandler(payload);
389
+ }
390
+ }
391
+ );
392
+ }
393
+
394
+ return rpc;
395
+ }
396
+ }
397
+
398
+ export { type RPCSchema, createRPC, Electroview };
399
+
400
+ const Electrobun = {
401
+ Electroview,
402
+ };
403
+
404
+ export default Electrobun;
@@ -0,0 +1,3 @@
1
+ export const isAppRegionDrag = (e: MouseEvent) => {
2
+ return e.target?.classList.contains("electrobun-webkit-app-region-drag");
3
+ };