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

ember-artisans

v2.0.0

Published

Small wrapper library for utilizing web workers in ember

Downloads

79

Readme

ember-artisans

NPM Version Build Status semantic-release

Artisans is a tool that makes using web workers in your application a lot more accessible. It offers an easy to use, Promise based API, that lets you break up your business logic to run on other threads, so that client side logic doesn't bog down your application's user experience.

Here's an example of how it might look in your application!

// app/controllers/application.js
import Controller from '@ember/controller'
import { action } from '@ember/object';
import { createWorker } from 'ember-artisans';

export default class ApplicationController extends Controller {
  worker = createWorker('/assets/workers/foo.js');

  @action
  async onFooBar() {
    const result = await this.worker.foo('bar');
    // ...
  }
}
// workers/foo.js
export default class FooBarWorker {
  foo (bar) {
    return `foo${bar}`;
  }
}

That's it! In the above example we're instantiating a worker using the createWorker utility. This returns a proxied Web Worker, that allows for any method you invoke will be delegated to it's corresponding worker.

Migration Guide (1.x -> 2.x)

Starting from version 2, the interface has changed so that the result will no longer have to be unwrapped from the worker response.

Before 🕸

export default class ApplicationController extends Controller {
  worker = createWorker('/assets/workers/foo.js');

  @action
  async onFooBar() {
    const { result }  = await this.worker.foo('bar');
    // ...
  }
}

After ✨

export default class ApplicationController extends Controller {
  worker = createWorker('/assets/workers/foo.js');

  @action
  async onFooBar() {
    const result = await this.worker.foo('bar');
  }
}

This also means if that the worker will no longer silently fail if an exception is thrown. Be sure to properly handle errors if they are present!

Getting Started

Installation 🎉

The first step is installing ember-artisans. This will provide you with the templates for generating your workers, as well as the necessary build steps along the way.

yarn add -D ember-artisans

Creating workers 🛠

Once this has completed, you'll be able to start writing your workers! Running ember g artisan <name> will create your web worker for you in the root of your project inside <root>/workers All changes made to the files in this directory will be automatically picked up by the live reload server, and updated inside your app!

Here's some example input, and the corresponding output:

ember g artisan foo-bar

/**
 * Add your worker description here.
 */
export default class FooBarWorker {
  // Add your worker methods here.

  /**
   * @returns Promise<void>
   */
  async fooBar() {
    
  }
}

API 👩‍💻

There are a couple ways to pull the worker in, and make use of them. I'll walk over each of the available methods of interacting with your workers.

createWorker

import { createWorker } from 'ember-artisans';

createWorker(
  workerPath: string,
  options = {
    timeout: 5000,
  },
) => Proxy<Worker>

Specifying a worker path is done by providing the url that the workers are built at. By default - workers are place inside of dist/assets/workers/<name>.js This means that you would consume them by referencing their public location.

const 🐹 = createWorker('/assets/workers/tomster.js')

createWorkerPool


import { createWorkerPool } from 'ember-artisans';

export function createWorkerPool(
  workerPath: string,
  poolSize: number,
)

createWorkerPool will work the same as createWorker, except that when a method is invoked on a worker pool, it will instead look for the first non-busy worker to delegate your task to.

Using it would look something like this:

// app/controllers/foo.js
import { createWorkerPool } from 'ember-artisans';

const taskPool = createWorkerPool('/assets/workers/task-pool.js', 5);
await taskPool.doSomething();
...
// workers/worker-pool.js
export default class TaskPoolWorker {
  async doSomething () {
    return await something();
  }
}

service('artisans')

This addon also provides a service that lets you instantiate a worker pool to be shared across different parts of your application.

// app/controllers/foo.js
import Controller from '@ember/controller';

import { inject as service } from '@ember/service';
import { task } from 'ember-concurrency';

export default class FooController extends Controller {
  @service('artisans')
  artisanService;

  @(task(function* () {
    const workerPool = this.artisanService.poolFor('/assets/workers/pool.js', 2);
    return workerPool.doSomething();
  }))
  poolTask;
}

Handling Responses

Methods on your Worker will return as such, on successful completion.

import { createWorker } from 'ember-artisans';

const tomsterWorker = createWorker('/assets/workers/tomster.js');

const {
  result, // optional, present if the worker ran successfully!
  error, // optional, present if there was an error encountered by the worker, or in the event of a timeout
  id,   // identifier corresponding to the request instance, used internally to map postMessage to responses
} = await tomsterWorker.runOnWheel();

Notes 📓

Worker Syntax

Currently worker's can be specified as the default export (ESM), or as the module.export (CJS). That means that each of the following is an acceptable way of declaring your workers.

// esm
export default class FoobarWorker {
  async foo() {
    const response = await bar();
    return baz(response);
  }
  ...
}
// cjs
module.exports = {
  async foo() {
    const response = await bar();
    return baz(response);
  }
}

ESM Imports in Workers ✨

You're able to import any of your node_modules/ into your worker, as long as they're able to run in browser context!

Here's a sample worker using the uuid package on npm.

import { v4 as uuidV4 } from 'uuid';

export default class UUIDWorker {
  generateUuid() {
    return uuidV4();
  }
}

Naming Worker Methods

To preserve the native methods present on a worker, avoid naming your Artisan worker methods the same as the native Worker methods.

My Worker Isn't Being Detected 🕵️‍♂️

If you create a new worker after the development server is already running, you might need to restart it for the worker to be properly be built into the public assets directory.