feat(sandbox) implement sandbox functionality for lazy loaded plugins

This commit is contained in:
Benjamin Wegener
2024-01-11 23:23:01 +00:00
parent 1421a6c3a8
commit 01d49e4c6a
2 changed files with 221 additions and 0 deletions

View File

@@ -0,0 +1,71 @@
export default class SandboxMessenger {
constructor() {
this.messageQueue = [];
this.responseQueue = [];
this.isProcessing = false;
}
async sendMessage(message) {
return new Promise((resolve, reject) => {
this.messageQueue.push({ message, resolve, reject });
this.processMessages();
});
}
async receiveMessage() {
return new Promise((resolve) => {
this.responseQueue.push(resolve);
this.processMessages();
});
}
async processMessages() {
if (this.isProcessing) {
return;
}
this.isProcessing = true;
while (this.messageQueue.length > 0 && this.responseQueue.length > 0) {
const { message, resolve, reject } = this.messageQueue.shift();
const responseCallback = this.responseQueue.shift();
try {
// Send the message to the Main Thread and wait for the response
const response = await this.sendMessageToMainThread(message);
// Resolve the promise with the response
resolve(response);
// Call the response callback with the response
responseCallback(response);
} catch (error) {
// Reject the promise with the error
reject(error);
}
}
this.isProcessing = false;
}
async sendMessageToMainThread(message) {
return new Promise((resolve, reject) => {
// Send the message to the Main Thread
postMessage(message);
// Listen for the response from the Main Thread
const messageHandler = (event) => {
const response = event.data;
// Remove the event listener
removeEventListener('message', messageHandler);
// Resolve the promise with the response
resolve(response);
};
// Add the event listener for the response
addEventListener('message', messageHandler, { once: true });
});
}
}