npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

sw-worker

v0.0.8

Published

Librería para comunicación entre cliente y worker en entornos de navegador y extensiones.

Readme

sw-worker

npm License

🌐 Landing page

sw-worker es una librería que facilita la comunicación entre un cliente y un trabajador (worker) en entornos de navegador o extensiones. Proporciona una arquitectura modular y flexible para manejar rutas, solicitudes y respuestas.

Tabla de Contenido

Instalación

Usa el siguiente comando para instalar la dependencia:

npm install sw-worker

O si usas pnpm:

pnpm add sw-worker

Uso

Cliente

El cliente (SWWorkerClient) permite realizar solicitudes al trabajador. Puedes inicializarlo con diferentes configuraciones dependiendo del entorno.

Ejemplo de uso:

import { SWWorkerClient } from 'sw-worker/client';

const client = new SWWorkerClient({
  runtime: 'browser',
  url: new URL('./worker.js', import.meta.url),
});

// Realizar una solicitud GET
client.get('/ruta')
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => console.error('Error:', error))
  .finally(() => console.log('Finalizado'));

// Realizar una solicitud POST
client.post('/ruta', { key: 'value' })
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => console.error('Error:', error))
  .finally(() => console.log('Finalizado'));

// Terminar el worker cuando ya no sea necesario
client.terminate();

Trabajador

El trabajador (SWWorker) permite definir rutas y manejar solicitudes desde el cliente.

Ejemplo de uso:

import SWWorker from 'sw-worker/worker';

const worker = new SWWorker('browser');

// Definir rutas
worker.get('/ruta', (req, res) => {
  res.send({ mensaje: 'Hola desde el worker' });
});

worker.post('/ruta', (req, res) => {
  const { key } = req.body;
  res.send({ mensaje: `Recibido: ${key}` });
});

// Escuchar solicitudes
worker.listen();

Uso en Entorno de Extensión

El cliente y el trabajador también pueden ser utilizados en un entorno de extensión. A continuación, se muestra un ejemplo con rutas CRUD para /tabs y /bookmarks:

Cliente en Extensión:

import { SWWorkerClient } from 'sw-worker/client';

const client = new SWWorkerClient({
  runtime: 'extension',
});

// Obtener todas las pestañas
client.get('/tabs')
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => console.error('Error:', error))
  .finally(() => console.log('Finalizado'));

// Crear un marcador
client.post('/bookmarks', { title: 'Nuevo Marcador', url: 'https://example.com' })
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => console.error('Error:', error))
  .finally(() => console.log('Finalizado'));

Trabajador en Extensión:

import SWWorker from 'sw-worker/worker';

const worker = new SWWorker('extension');

// Rutas para pestañas
worker.get('/tabs', async (req, res) => {
  const tabs = await chrome.tabs.query({});
  res.send({ tabs });
});

worker.post('/tabs', async (req, res) => {
  const { url } = req.body;
  const tab = await chrome.tabs.create({ url });
  res.send({ tab });
});

// Rutas para marcadores
worker.get('/bookmarks', async (req, res) => {
  const bookmarks = await chrome.bookmarks.getTree();
  res.send({ bookmarks });
});

worker.post('/bookmarks', async (req, res) => {
  const { title, url } = req.body;
  const bookmark = await chrome.bookmarks.create({ title, url });
  res.send({ bookmark });
});

// Escuchar solicitudes
worker.listen();

Estructura del Proyecto

La librería sigue una arquitectura modular:

sw-worker/
├── src/
│   ├── client/
│   │   └── index.ts
│   ├── worker/
│   │   └── index.ts
│   ├── managers/
│   │   ├── RequestHandler.ts
│   │   ├── ResponseManager.ts
│   │   └── RouteManager.ts
│   ├── types/
│   │   └── types.d.ts
│   └── utils/
│       └── pathUtils.ts
├── tests/
│   ├── client.test.ts
│   └── worker.test.ts
├── package.json
├── tsconfig.json
├── LICENSE
└── README.md

API

SWWorkerClient

Métodos

  • get(route: string, headers?: HeadersInit): Promise<ClientResponse>
  • post(route: string, body?: StructuredCloneable, headers?: HeadersInit): Promise<ClientResponse>
  • put(route: string, body?: StructuredCloneable, headers?: HeadersInit): Promise<ClientResponse>
  • delete(route: string, body?: StructuredCloneable, headers?: HeadersInit): Promise<ClientResponse>
  • terminate(): void

SWWorker

Métodos

  • get(path: string, handler: Handler): void
  • post(path: string, handler: Handler): void
  • put(path: string, handler: Handler): void
  • delete(path: string, handler: Handler): void
  • route(path: string, app: SWWorker): void
  • listen(): void

Contribución

¡Las contribuciones son bienvenidas! Si deseas colaborar, sigue estos pasos:

  1. Haz un fork del repositorio.
  2. Crea una rama para tu funcionalidad (git checkout -b feature/nueva-funcionalidad). No envíes tus cambios a la rama master, utiliza la rama develop.
  3. Realiza tus cambios y haz un commit (git commit -m 'feat: agrega nueva funcionalidad').
  4. Sube tus cambios a tu rama (git push origin feature/nueva-funcionalidad).
  5. Abre un Pull Request en el repositorio principal.

Nota: El flujo de trabajo de GitHub Actions solo se ejecutará en la rama master.

Licencia

Este proyecto está licenciado bajo la Licencia MIT. Consulta el archivo LICENSE para más detalles.


Repositorio: sw-worker