A tiny utility to asynchronously drive a namespace exposed through a Worker.

Overview

proxied-worker

Social Media Photo by Ricardo Gomez Angel on Unsplash

A tiny utility to asynchronously drive a namespace exposed through a Shared/Service/Worker:

  • property access
  • functions invokes
  • instances creation ...
  • ... and instances methods invokes, or properties access

Instances reflected on the client are automatically cleared up on the worker though a dedicated FinalizationRegistry.

It is also possible, since v0.5.0, to use functions as arguments, although these are stored "forever", so use this feature with caution. Bear in mind, the context is currently not propagated from the Worker, so if it's strictly needed, bind the listener before passing it as-is.

Related

This module is a modern simplification of workway, heavily inspired, and possibly fueling in the future, electroff too.

Compatibility / Requirements

This module works with latest browsers, as long as the following APIs are available:

Live Demo

API

The exported namespace provides a mechanism to await any part of it, including a top level addEventListener and removeEventListener, to allow listening to custom postMessage notifications from the Service/Shared/Worker.

See worker.js to better understand how this works.

Example

// client.js
import ProxiedWorker from 'https://unpkg.com/proxied-worker/client';

// point at the file that exports a namespace
const nmsp = ProxiedWorker('./worker.js');

// custom notifications from the Worker
nmsp.addEventListener('message', ({data: {action}}) => {
  if (action === 'greetings')
    console.log('Worker said hello 👋');
});

// v0.5.0+ use listenres like features
nmsp.on('listener', (action, type) => {
  console.log(action, 'called with type', type);
});

// access its properties
console.log(await nmsp.test);

// or its helpers
console.log(await nmsp.sum(1, 2));
await nmsp.delayed();

// or create instances
const instance = await new nmsp.Class('🍻');
// and invoke their methods
console.log(await instance.sum(1, 2));

// - - - - - - - - - - - - - - - - - - - - - - 

// worker.js
importScripts('https://unpkg.com/proxied-worker/server');

ProxiedWorker({
  test: 'OK',
  sum(a, b) {
    return a + b;
  },
  on(type, callback) {
    setTimeout(() => {
      callback('Event', type);
    });
  },
  async delayed() {
    console.log('context', this.test);
    postMessage({action: 'greetings'});
    return await new Promise($ => setTimeout($, 500, Math.random()));
  },
  Class: class {
    constructor(name) {
      this.name = name;
    }
    sum(a, b) {
      console.log(this.name, a, b);
      return a + b;
    }
  }
});

Alternatively, if the browser supports workers as module:

// client.js
import ProxiedWorker from 'https://unpkg.com/proxied-worker/client';
const nmsp = ProxiedWorker('./worker.js', {type: 'module'});

// worker.js
import ProxiedWorker from 'https://unpkg.com/proxied-worker/module';
ProxiedWorker({
  // ...
});

As SharedWorker

The ProxiedWorker signature is similar to a Worker one, plus an extra third argument that is the constructor to use.

In order to have a SharedWorker, this code might be used:

// client.js
import ProxiedWorker from 'https://unpkg.com/proxied-worker/client';
const nmsp = ProxiedWorker('./shared-worker.js', {type: 'module'}, SharedWorker);

// shared-worker.js
import ProxiedWorker from 'https://unpkg.com/proxied-worker/module';
ProxiedWorker({
  // ...
});

As ServiceWorker

Similarly to a SharedWorker, it is also possible to register and use a ServiceWorker to compute heavy tasks.

// client.js
import ProxiedWorker from 'https://unpkg.com/proxied-worker/client';
const nmsp = ProxiedWorker('./service-worker.js', {scope: '/'}, ServiceWorker);

// service-worker.js
importScripts('https://unpkg.com/proxied-worker/server');

ProxiedWorker({
  // ...
});
You might also like...

This is a simple script to upload Multiple files into google drive using google drive API and Nodejs.

Welcome to gDrive Multiple File Upload 👋 This is a simple script to upload Multiple files into google drive using google drive API and Nodejs Install

Dec 29, 2021

A postgraphile plugin that allows you to expose only a single direction of connections exposed by foreign key constraints

A postgraphile plugin that allows you to expose only a single direction of connections exposed by foreign key constraints

Mar 13, 2022

A TypeScript namespace declaration for KeyboardEvent.key strings, just in case your code is allergic to enums.

ts-key-namespace A TypeScript namespace declaration for KeyboardEvent.key strings, just in case you prefer namespaces to enums. Largely based on ts-ke

Apr 5, 2022

Monitor your code for exposed API keys, tokens, credentials, and high-risk security IaC misconfigurations

Monitor your code for exposed API keys, tokens, credentials, and high-risk security IaC misconfigurations

Spectral VS Code extension The Spectral VS Code extension is a tool for developers that want to catch security issues (such as credentials, tokens and

Dec 19, 2022

NoExGen is a node.js express application generator with modern folder structure, namespace/project mapping and much more! It contains preconfigured Settings and Routing files, ready to be used in any project.

Installation $ npm install -g noexgen Quick Start You can use Node Package Execution to create your node-express application as shown below: Create th

Oct 8, 2022

The iofod SDK provides developers with the ability to interact with the main iofod interface within the Web worker, enabling rapid development of iofod extensions through the SDK.

iofod-sdk English | 简体中文 The iofod SDK provides developers with the ability to interact with the main iofod interface within the Web worker, enabling

Oct 17, 2022

Journeys is a django based community-focused website that allows users to bookmark URLs (through chrome extension) and share their journeys through timelines.

Journeys is a django based community-focused website that allows users to bookmark URLs (through chrome extension) and share their journeys through timelines.

Journeys is a django based community-focused website that allows users to bookmark URLs (through chrome extension) and share their journeys through timelines. A timeline is a collection of links that share a common topic or a journey of building and learning something new. Users can create timelines, share them publicly, and explore resources.

Jun 13, 2022

Using a RPI 3b+ to create a PT camera accessible through Windows browser and controllable through MQTT

web-camera_PT A Web flask server converts the MJPEG stream from RPI to JPG img using opencv, then display in browser. Controls added to move Camera in

Dec 20, 2022

CLI utility that broadcasts BTC, ETH, SOL, ZEC & XMR transactions through TOR using public block explorers

tx-tor-broadcaster CLI utility that broadcasts BTC, ETH, SOL, ZEC & XMR transactions through TOR using public block explorers. Provides a great degree

Dec 25, 2022

A light-weight, no-dependency, vanilla JavaScript engine to drive the user's focus across the page

A light-weight, no-dependency, vanilla JavaScript engine to drive the user's focus across the page

Driver.js Powerful, highly customizable vanilla JavaScript engine to drive the user's focus across the page No external dependencies, supports all maj

Jan 4, 2023

MyDrive is an Open Source cloud file storage server (Similar To Google Drive)

MyDrive is an Open Source cloud file storage server (Similar To Google Drive)

MyDrive is an Open Source cloud file storage server (Similar To Google Drive). Host myDrive on your own server or trusted platform and then access myDrive through your web browser. MyDrive uses mongoDB to store file/folder metadata, and supports multiple databases to store the file chunks, such as Amazon S3, the Filesystem, or just MongoDB. MyDrive is built using Node.js, and Typescript. The service now even supports Docker images!

Dec 30, 2022

Index your Google Drive Easily and Free.

Index your Google Drive Easily and Free.

Google Personal/Shared Drive Index Full White label and Customizable Index | One of a kind Supports Both My and Team/Shared Drives with Dark Mode. Cli

Sep 22, 2021

replacement for comma.ai backend and useradmin dashboard. comes bundled with a modified cabana instance for seamless drive reviewing.

replacement for comma.ai backend and useradmin dashboard. comes bundled with a modified cabana instance for seamless drive reviewing.

retropilot-server Replacement for comma.ai backend and useradmin dashboard. Bundled with a modified version of comma's cabana to allow viewing & analy

Dec 4, 2022

Use the Google Drive API as a Content Management System

Google Drive CMS This shared Google Drive folder serves as the backend for this sample webpage. Quick links: Github / NPM / Dockerhub / Heroku NPM npm

Nov 22, 2022

Todas as aulas da Semana JS Expert 5.0 - Google Drive Clone

Todas as aulas da Semana JS Expert 5.0 - Google Drive Clone

Google Drive Clone - Semana JS Expert 5.0 Seja bem vindo(a) à quinta Semana Javascript Expert. Este é o código inicial para iniciar nossa jornada. Mar

Dec 29, 2022

A helper to use immer as Solid.js Signal to drive state

Solid Immer A helper to use immer as Solid.js Signal to drive state. Installation $ npm install solid-immer Usage Use createImmerSignal to create a im

Nov 22, 2022

This extension injects a button to the Google Drive WebUI.

This extension injects a button to the Google Drive WebUI.

This extension injects a button to the Google Drive WebUI. When clicking on it the current folder id is send to your gogdl-ng instance. It was developed and tested on the latest version of Mozilla Firefox and Chrome.

Jul 13, 2022

🔻 Generate a Google Drive direct download link based on the URL or ID

Drive Link Generate a Google Drive direct download link based on the URL or ID. Usage The API is the same on all this platforms ✔️ Deno 🦕 import { dr

Nov 1, 2022
Comments
  • Added implicit context to callbacks

    Added implicit context to callbacks

    This MR fixes the context issue but the client size is now around 900 bytes instead of 800 bytes + it's not clear how useful this feature would be in the real-world, as listeners should be actually pretty rare and it's trivial to access to the same namespace.

    I'll keep this parked for the time being.

    enhancement 
    opened by WebReflection 0
Owner
Andrea Giammarchi
Web, Mobile, IoT and all Web & JS things since 00's
Andrea Giammarchi
Redirect requests of current origin to another domain with Service Worker.

Service Worker to Redirect Origin This is a tool for your static website which could intercept all GET requests of the origin domain and redirect them

Menci 9 Aug 28, 2022
A tool library for handling window && iframe && worker communication based on the JSON RPC specification

rpc-shooter A tool library for handling window && iframe && worker communication based on the JSON RPC specification 一个基于 JSON-RPC 规范用于处理 window && if

臼犀 89 Dec 20, 2022
⚙️ Offline-capable Astro apps via SWSR (Service Worker Side Rendering)

Astro-service-worker ⚙️ Offline-capable Astro apps via SWSR (Service Worker Side Rendering) astro-service-worker will take your Astro SSR project, and

Pascal Schilp 41 Dec 4, 2022
Cloudflare Worker that will allow you to progressively migrate files from an S3-compatible object store to Cloudflare R2.

A Cloudflare Worker for Progressive S3 to R2 Blog Post: https://kian.org.uk/progressive-s3-to-cloudflare-r2-migration-using-workers/ This is a Cloudfl

Kian 29 Dec 30, 2022
Send emails using Cloudflare Worker, for free.

Email API for Proselog. Not intended for use outside of Proselog, but it should work with any worker, without any configuration. import { sendEmail }

Proselog 65 Nov 7, 2022
Cloudflare Worker to make a R2 Bucket public!

r2-public-worker A Cloudflare Worker to make your R2 bucket public! Minimum Requirements Cloudflare Account wrangler >= 2.0.2 Note: Ensure you are usi

Cole Mackenzie 20 Sep 19, 2022
Type-safe and Promisified API for Web Worker and Iframe

?? You can help the author become a full-time open-source maintainer by sponsoring him on GitHub. typed-worker Install npm i typed-worker Usage Create

EGOIST 189 Dec 31, 2022
Using Cloudflare worker to generate host list from firebog to keep updated.

AdGuardCloudflareHostGenerator Use a cloudflare worker to generate a up to date list from FireBog's ticked list found at https://v.firebog.net/hosts/l

Jake Steele 14 Nov 30, 2022
Google-Drive-Directory-Index | Combining the power of Cloudflare Workers and Google Drive API will allow you to index your Google Drive files on the browser.

?? Google-Drive-Directory-Index Combining the power of Cloudflare Workers and Google Drive will allow you to index your Google Drive files on the brow

Aicirou 127 Jan 2, 2023
Warp drive is a lightweight jQuery plugin that helps you create a cool, interactive, configurable, HTML5 canvas based warp drive/starfield effect.

Warp drive jQuery plugin (jquery-warpdrive-plugin) Preview Description Warp drive is a lightweight jQuery plugin that helps you create a cool, interac

Niklas 51 Nov 15, 2022