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 🙏

© 2024 – Pkg Stats / Ryan Hefner

webext-rpc

v1.0.4

Published

A type-safe RPC for all webextension, client side code does not contain the actual called code, supports async generator functions

Downloads

16

Readme

webext-rpc

A type-safe RPC for all webextension, client side code does not contain the actual called code, supports async generator functions

This is a library for making RPC calls to a web extension from a web page. It uses the webextension-polyfill API to communicate with the extension, supports all browsers (Chrome, Firefox, Safari).

Supports normal functions, async functions, generator functions, and async generator functions.

Usage

To use this library, you need to install webext-rpc in your project. You can install it using npm with the following command:

pnpm install webext-rpc
  1. Create a router
// webext-rpc/router/index.ts
import { readerToAsyncGenerator } from 'webext-rpc/utils'

const generateGroup = {
  *generatorFunction() {
    yield 'this is generatorFunction 1'
    yield 'this is generatorFunction 2'
  },
  async *asyncGeneratorFunction(count: number) {
    for (let i = 0; i < count; i++) {
      await new Promise((resolve) => setTimeout(() => resolve(void 0), 1000))
      yield `this is asyncGeneratorFunction, count:${i} ,time:${Date.now()}`
    }
  },
}
export const router = {
  normalFunction(id: number, msg: string) {
    return `this is normalFunction, id:${id}, msg:${msg}`
  },
  async asyncFunction() {
    return 'this is asyncFunction'
  },
  generateGroup,
  async *fetchStream(api_key: string, prompt: string) {
    const response = await fetch(`...`)
    const reader = response.body?.getReader()
    yield* readerToAsyncGenerator(reader, (value) => {
      const text = new TextDecoder().decode(value)
      return text
    })
  },
}

// only type
export type AppRouter = typeof router
  1. Register the router in background
// entrypoints/background.ts
import { router } from '@/webext-rpc/router'
import { createBackgroundHandler } from 'webext-rpc'

createBackgroundHandler(router)
  1. Create a client and use it in the UI
// webext-rpc/client.ts
import { createWebextRpcCaller } from 'webext-rpc'
import type { AppRouter } from './router'

// only use type
export const client = createWebextRpcCaller<AppRouter>()
// entrypoints/content/app.ts
import { client } from '@/webext-rpc/client'
const a = await client.normalFunction(1, 'hello')
const b = await client.asyncFunction()
const c = await client.generatorFunction()
const iter = await client.asyncGeneratorFunction(3)
const d = []
for await (const i of iter) {
  d.push(i)
}
let e = ''
const fetch_iter = await client.fetchStream('api_key', 'prompt')
for await (const i of fetch_iter) {
  e += i
}

Check out the demo

Generate utils

readerToAsyncGenerator

This function converts a ReadableStreamDefaultReader to an AsyncGenerator.

import { readerToAsyncGenerator } from 'webext-rpc/utils'
const response = await fetch(`...`)
const reader = response.body?.getReader()
yield *
  readerToAsyncGenerator(reader, (value) => {
    const text = new TextDecoder().decode(value)
    return text
  })

MessageStream

MessageStream allows for handling message streams. It provides a mechanism to add messages and signal the end of the stream. Consumers can then utilize an AsyncGenerator to process the stream

import { ExposedPromise } from 'webext-rpc/utils'

async function testForCallback(callback: (message: string) => Promise<void>) {
  for (let i = 0; i < 3; i++) {
    callback(`message ${i}`)
  }
}

const stream = new MessageStream<string>()
testForCallback(async (message) => {
  stream.addMessage(message)
})
stream.close()

const messageGenerator: AsyncGenerator<string> = stream.getMessages()

expect((await messageGenerator.next()).value).toBe('message 0')
expect((await messageGenerator.next()).value).toBe('message 1')
expect((await messageGenerator.next()).value).toBe('message 2')
expect((await messageGenerator.next()).done).toBe(true)

Inspiration

This library was inspired by two excellent libraries:

tRPC

@webext-core/proxy-service