[
  {
    "path": ".gitignore",
    "content": ".DS_Store\nnode_modules/\npackage-lock.json\n^worker.js\n"
  },
  {
    "path": ".npmignore",
    "content": "node_modules/*\nexamples/*\npartial/*\ntest/*\n.DS_Store\n.gitignore\n.travis.yml\npackage-lock.json\n"
  },
  {
    "path": ".travis.yml",
    "content": "language: node_js\nnode_js:\n  - stable\ngit:\n  depth: 1\nbranches:\n  only:\n    - master\n"
  },
  {
    "path": "LICENSE",
    "content": "ISC License\n\nCopyright (c) 2018, Andrea Giammarchi, @WebReflection\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted, provided that the above\ncopyright notice and this permission notice appear in all copies.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE\nOR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# workway DEPRECATED - See [coincident](https://github.com/WebReflection/coincident#coincidentserver)\n\nA general purpose, Web Worker driven, remote namespace with classes and methods.\n\n\n- - -\n\n## Announcement: Meet proxied-worker & proxied-node\n\nThere is a new, very similar, yet different, project, in case you're looking to simply drive generic Workers instances, or namespaces, from a client/main thread: [proxied-worker](https://github.com/WebReflection/proxied-worker#readme).\n\nIt has [a NodeJS counterpart module](https://github.com/WebReflection/proxied-node#readme) too!\n\nThe main difference with these projects is:\n\n  * classes have a working constructor\n  * heap is automatically cleaned on both client/server\n  * it uses *Proxy* and *FinalizationRegistry* so these are not as compatible as *workway* is with legacy browsers\n\n- - -\n\n\n## Key Features\n\n  * no eval at all, no scope issues, 100% CSP friendly\n  * no Proxy at all neither, compatible with IE 10, iOS 8, Android 4.4, BB OS 10, and [every other browser](https://webreflection.github.io/workway/test/)\n  * 100LOC client squeezed in about 0.5K once compressed\n  * you expose non blocking namespaces to the main thread, not the other way around\n  * it **works on NodeJS** too 🎉\n\n\n\n## Example <sup><sub>(client side only)</sub></sup>\nA basic **firebase.js** client to show the user name.\n```js\nworkway('/workers/firebase.js').then(\n  async function ({worker, namespace}) {\n    await namespace.initializeApp({\n      apiKey: \"<API_KEY>\",\n      authDomain: \"<PROJECT_ID>.firebaseapp.com\",\n      databaseURL: \"https://<DATABASE_NAME>.firebaseio.com\",\n      projectId: \"<PROJECT_ID>\",\n      storageBucket: \"<BUCKET>.appspot.com\",\n      messagingSenderId: \"<SENDER_ID>\"\n    });\n    const fb = new namespace.FirebaseUser();\n    const name = await fb.name();\n    console.log(name); // will log the user name, if any\n\n    // the worker can be regularly used like any other worker\n    worker.postMessage('all good');\n  }\n);\n\n// you can also pass in an existing Worker instance (useful if you're using\n// Webpack's worker-loader and don't have access to the output file path):\nimport Worker from 'worker-loader!./Worker.js';\nworkway(new Worker()).then(...\n```\n\nThe **workers/firebase.js** worker that exposes some info.\n```js\n// top import to ensure a transparent communication channel\nimportScripts('https://unpkg.com/workway/worker.js');\n\n// any other needed import for this worker\nimportScripts(...[\n  'app', 'auth', 'database', 'firestore', 'messaging', 'functions'\n].map(name => `https://www.gstatic.com/firebasejs/5.0.1/firebase-${name}.js`));\n\n// expose a namespaces as an object\n// with any sort of serializable value\n// and also methods or classes\nworkway({\n\n  // any serializable data is OK (nested too)\n  timestamp: Date.now(),\n\n  // methods are OK too, each method\n  // accepts serializable arguments and\n  // can return a value and/or a promise\n  initializeApp(config) {\n    firebase.initializeApp(config);\n  },\n\n  // classes are also fine, as long as\n  // these respect RemoteClass conventions\n  FirebaseUser: class FirebaseUser {\n    constructor() {\n      this.uid = firebase.auth().currentUser.uid;\n    }\n    name() {\n      return firebase.database()\n                .ref('/users/' + this.uid)\n                .once('value')\n                .then(snapshot => ((\n                  snapshot.val() && snapshot.val().username\n                ) || 'Anonymous'));\n    }\n  }\n});\n\n// this worker can be regularly used like any other worker\n// the passed event will never be one handled by `workway`\nself.onmessage = event => {\n  console.log(event.data);\n};\n```\n\n## Example <sup><sub>(NodeJS)</sub></sup>\n\nTo have NodeJS driven workers you need the regular client side `workway.js` file, plus `/pocket.io/pocket.io.js` and `/workway@node.js` that are both handled by this module.\n\n```html\n<script src=\"/workway.js\">/* regular workway client file */</script>\n<script src=\"/pocket.io/pocket.io.js\">/* automatically provided by the server */</script>\n<script src=\"/workway@node.js\">/* automatically provided by the server */</script>\n```\n\nThis is a `js/os.js` file for the client side.\n```js\nworkway('node://os.js').then(({worker, namespace:os}) => {\n  os.getNetworkInterfaces().then(console.log);\n});\n```\n\nPlease note the client file needs EventTarget, Promise, and WeakMap constructors.\nIf your target browsers don't have these features, you can use the following polyfills on top of your HTML file.\n\n```html\n<script>\nif(!this.Promise)document.write('<script src=\"https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.auto.min.js\"><'+'/script>');\nif(!this.WeakMap)document.write('<script src=\"https://unpkg.com/poorlyfills@0.1.1/min.js\"><'+'/script>');\ntry{new EventTarget}catch(e){document.write('<script src=\"https://unpkg.com/event-target@1.2.2/min.js\"><'+'/script>')}\n</script>\n```\n\n\nFollowing a `workers/os.js` file to serve via NodeJS.\n```js\n// note: you require a facade here via 'workway'\nvar workway = require('workway');\nworkway(require('os'));\n```\n\nAn express / node based bootstrap.\n```js\nvar express = require('express');\n\n// note: you require the real module as 'workway/node'\nvar workway = require('workway/node');\n// authorize / expose a specific folder\n// that contains web driven workers\nworkway.authorize(__dirname + '/workers');\n\nvar app = workway.app(express());\napp.use(express.static(__dirname + '/www'));\napp.listen(8080);\n```\n\n### NodeJS extra features & gotchas\n\n  * exact same API (actually exact same code) of the real Web Worker based client side\n  * circular objects are supported out of the box via [flatted](https://github.com/WebReflection/flatted#flatted) on both ways\n  * the `self` global (but sandboxed) variable points at the global\n  * the `self.workway` method is already there, feel free to use it instead of requiring it from workers\n  * the `self.addEventListener` and `self.remoteEventListener` are normalized to work like on the front end side: do not use emitter methods directly with your node workers or messages and errors might not be signaled as expected\n\n\n## The RemoteClass convention\n\nClasses exposed through `workway` namespace must follow these rules:\n\n  * no constructor arguments; use methods to eventually forward extra details from the client\n  * methods can accept only serializable arguments and can return either a serializable value or a promise that will resolve as serializable data\n  * properties set on the **client** side must be serializable and will be **reflected** into related worker instances whenever methods are invoked\n  * properties set in the **worker** will **not** be **reflected** on the client side so that what's defined in the worker, stays in the worker\n  * every method invocation returns a Promise, even if the method returned value is not\n  * multiple methods invocation at once are possible, but there is no guarantee of the order. Use promises features or `await` each call if sequential methods calls depend on previous results.\n\n\n\n## Compatibility\n\nThe code is written in a ES5 friendly syntax, and it's guaranteed to work in IE 10 or above, and mostly every mobile browser on platforms such iOS 8+, Android 4.4+, Blackberry OS 10+, or Windows Phone 8+.\n\nYou can test live your browser through the **[live test page](https://webreflection.github.io/workway/test/index.html)**.\n\nPlease note in IE 10/11 or other old browser cases, you might need to provide polyfills on both client and worker side.\n\nFeel free to choose the polyfill you prefer.\n\nFollowing just as example:\n\n```html\n<!doctype html>\n<script>\n// needed for IE11\nif(!this.Promise)document.write('<script src=\"https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.auto.min.js\"><'+'/script>');\n// needed for IE10\nif(!this.WeakMap)document.write('<script src=\"https://unpkg.com/poorlyfills@0.1.1/min.js\"><'+'/script>');\n</script>\n<script src=\"https://unpkg.com/workway\"></script>\n<script src=\"firebase.js\"></script>\n```\n\nOr on top of your generic worker.\n```js\n// import the polyfill you prefer for either IE11 or IE10\nif (!self.Promise) importScripts('https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.auto.min.js');\nif (!self.WeakMap) importScripts('https://unpkg.com/poorlyfills@0.1.1/min.js');\n\n// now import workway/worker.js before any other worker script\nimportScripts('https://unpkg.com/workway/worker.js');\n\n// ... the rest of the code ... \n```\n\n\n\n## About Recursive data\n\nIf you need to invoke a method passing an object that might contain recursive data you can serialize it upfront and parse it once received.\n\n```js\n// main thread app.js side\nimport workway from 'https://unpkg.com/workway/esm';\nimport {stringify} from 'https://unpkg.com/flatted/esm';\n\nworkway('analyzer.js').then(({namespace}) => {\n  const data = {arr: []};\n  data.arr.push(data);\n  data.data = data;\n  namespace.analyze(stringify(data))\n            .then(\n              state => document.body.textContent = state,\n              console.error\n            );\n});\n\n\n\n// worker side: analyzer.js\nimportScripts(\n  'https://unpkg.com/workway/worker.js',\n  'https://unpkg.com/flatted'\n);\n\nworkway({\n  analyze(circular) {\n    const data = Flatted.parse(circular);\n    return 'OK';\n  }\n});\n```\n\nYou can [test above example right here](https://webreflection.github.io/workway/test/circular/).\n\n\n\n### Extra Info\n\n  * the client side of this package fits in just 100 LOC\n  * the client side of this project weights 0.5K via brotli, 0.6K via gzip\n  * the client side source of truth of this project is its root `./index.js`\n  * the only worker related code is in `./worker.js` root file\n  * the ESM version of this module is in `esm/index.js`\n  * the CJS version of this module is in `cjs/index.js`\n  * the browser version of this module is in `min.js`\n"
  },
  {
    "path": "cjs/index.js",
    "content": "function workway(file) {'use strict';\n  /*! (c) 2018 Andrea Giammarchi (ISC) */\n  return new Promise(function (res) {\n    function uid() { return ++i + Math.random(); }\n    var i = 0;\n    var channel = uid();\n    var messages = {};\n    var worker = typeof file === 'string' ? new Worker(file) : file;\n    worker.addEventListener('message', function (event) {\n      if (event.data.channel !== channel) return;\n      event.stopImmediatePropagation();\n      var namespace = event.data.namespace;\n      if (namespace) {\n        var Class = function (info) {\n          var path = info.path;\n          var methods = info.methods;\n          var statics = info.statics;\n          var wm = new WeakMap;\n          function RemoteClass() { wm.set(this, uid()); }\n          methods.forEach(function (method) {\n            RemoteClass.prototype[method] = function () {\n              return send({\n                args: slice.call(arguments),\n                path: path,\n                method: method,\n                object: {\n                  id: wm.get(this),\n                  value: this\n                }\n              });\n            };\n          });\n          statics.methods.forEach(function (method) {\n            RemoteClass[method] = function () {\n              return send({\n                args: slice.call(arguments),\n                path: path,\n                method: method\n              });\n            };\n          });\n          statics.values.forEach(function (pair) {\n            RemoteClass[pair[0]] = pair[1];\n          });\n          return RemoteClass;\n        };\n        var callback = function (path) {\n          return function remoteCallback() {\n            return send({\n              args: slice.call(arguments),\n              path: path\n            });\n          };\n        };\n        var send = function (message) {\n          var resolve, reject;\n          var promise = new Promise(function (res, rej) {\n            resolve = res;\n            reject = rej;\n          });\n          promise.resolve = resolve;\n          promise.reject = reject;\n          messages[message.id = uid()] = promise;\n          worker.postMessage({\n            channel: channel,\n            message: message\n          });\n          return promise;\n        };\n        var slice = [].slice;\n        (function update(namespace) {\n          Object.keys(namespace).forEach(function (key) {\n            var info = namespace[key];\n            switch (info.type) {\n              case 'class': namespace[key] = Class(info); break;\n              case 'function': namespace[key] = callback(info.path); break;\n              case 'object': update(namespace[key] = info.value); break;\n              default: namespace[key] = info.value;\n            }\n          });\n        }(namespace));\n        res({\n          worker: worker,\n          namespace: namespace\n        });\n      } else {\n        var message = event.data.message;\n        var id = message.id;\n        var promise = messages[id];\n        delete messages[id];\n        if (message.hasOwnProperty('error')) {\n          var error, facade = message.error;\n          if (facade.hasOwnProperty('source'))\n            error = facade.source;\n          else {\n            error = new Error(facade.message);\n            error.stack = facade.stack;\n          }\n          promise.reject(error);\n        }\n        else\n          promise.resolve(message.result);\n      }\n    });\n    worker.postMessage({channel: channel});\n  });\n}\nmodule.exports = workway;\n"
  },
  {
    "path": "cjs/remoted.js",
    "content": "function remoted(object) {\n  return function $(object, current, remote) {\n    Object.keys(object).forEach(function (key) {\n      var value = object[key];\n      var path = current.concat(key);\n      if (typeof value === 'function') {\n        remote[key] = /^[A-Z]/.test(key) ?\n          {\n            type: 'class',\n            path: path,\n            methods: Object.getOwnPropertyNames(value.prototype)\n                            .filter(no(['constructor']))\n                            .concat('destroy'),\n            statics: Object.getOwnPropertyNames(value)\n                            .filter(no([\n                              'arguments', 'callee', 'caller',\n                              'length', 'name', 'prototype'\n                            ]))\n                            .reduce(\n                              function (info, key) {\n                                if (typeof value[key] === 'function') {\n                                  info.methods.push(key);\n                                } else {\n                                  info.values.push([key, value[key]]);\n                                }\n                                return info;\n                              },\n                              {\n                                methods: [],\n                                values: []\n                              }\n                            )\n          } :\n          {\n            type: 'function',\n            path: path\n          };\n      } else if (remote.toString.call(value) === '[object Object]') {\n        remote[key] = {\n          type: 'object',\n          path: path,\n          value: {}\n        };\n        $(value, path, remote[key].value);\n      } else if (value !== void 0) {\n        remote[key] = {\n          type: 'any',\n          path: path,\n          value: value\n        };\n      }\n    });\n    return remote;\n  }(object, [], {});\n  function no(within) {\n    return function (what) {\n      return within.indexOf(what) < 0;\n    };\n  }\n}\nmodule.exports = remoted;\n"
  },
  {
    "path": "esm/index.js",
    "content": "function workway(file) {'use strict';\n  /*! (c) 2018 Andrea Giammarchi (ISC) */\n  return new Promise(function (res) {\n    function uid() { return ++i + Math.random(); }\n    var i = 0;\n    var channel = uid();\n    var messages = {};\n    var worker = typeof file === 'string' ? new Worker(file) : file;\n    worker.addEventListener('message', function (event) {\n      if (event.data.channel !== channel) return;\n      event.stopImmediatePropagation();\n      var namespace = event.data.namespace;\n      if (namespace) {\n        var Class = function (info) {\n          var path = info.path;\n          var methods = info.methods;\n          var statics = info.statics;\n          var wm = new WeakMap;\n          function RemoteClass() { wm.set(this, uid()); }\n          methods.forEach(function (method) {\n            RemoteClass.prototype[method] = function () {\n              return send({\n                args: slice.call(arguments),\n                path: path,\n                method: method,\n                object: {\n                  id: wm.get(this),\n                  value: this\n                }\n              });\n            };\n          });\n          statics.methods.forEach(function (method) {\n            RemoteClass[method] = function () {\n              return send({\n                args: slice.call(arguments),\n                path: path,\n                method: method\n              });\n            };\n          });\n          statics.values.forEach(function (pair) {\n            RemoteClass[pair[0]] = pair[1];\n          });\n          return RemoteClass;\n        };\n        var callback = function (path) {\n          return function remoteCallback() {\n            return send({\n              args: slice.call(arguments),\n              path: path\n            });\n          };\n        };\n        var send = function (message) {\n          var resolve, reject;\n          var promise = new Promise(function (res, rej) {\n            resolve = res;\n            reject = rej;\n          });\n          promise.resolve = resolve;\n          promise.reject = reject;\n          messages[message.id = uid()] = promise;\n          worker.postMessage({\n            channel: channel,\n            message: message\n          });\n          return promise;\n        };\n        var slice = [].slice;\n        (function update(namespace) {\n          Object.keys(namespace).forEach(function (key) {\n            var info = namespace[key];\n            switch (info.type) {\n              case 'class': namespace[key] = Class(info); break;\n              case 'function': namespace[key] = callback(info.path); break;\n              case 'object': update(namespace[key] = info.value); break;\n              default: namespace[key] = info.value;\n            }\n          });\n        }(namespace));\n        res({\n          worker: worker,\n          namespace: namespace\n        });\n      } else {\n        var message = event.data.message;\n        var id = message.id;\n        var promise = messages[id];\n        delete messages[id];\n        if (message.hasOwnProperty('error')) {\n          var error, facade = message.error;\n          if (facade.hasOwnProperty('source'))\n            error = facade.source;\n          else {\n            error = new Error(facade.message);\n            error.stack = facade.stack;\n          }\n          promise.reject(error);\n        }\n        else\n          promise.resolve(message.result);\n      }\n    });\n    worker.postMessage({channel: channel});\n  });\n}\nexport default workway;\n"
  },
  {
    "path": "esm/remoted.js",
    "content": "function remoted(object) {\n  return function $(object, current, remote) {\n    Object.keys(object).forEach(function (key) {\n      var value = object[key];\n      var path = current.concat(key);\n      if (typeof value === 'function') {\n        remote[key] = /^[A-Z]/.test(key) ?\n          {\n            type: 'class',\n            path: path,\n            methods: Object.getOwnPropertyNames(value.prototype)\n                            .filter(no(['constructor']))\n                            .concat('destroy'),\n            statics: Object.getOwnPropertyNames(value)\n                            .filter(no([\n                              'arguments', 'callee', 'caller',\n                              'length', 'name', 'prototype'\n                            ]))\n                            .reduce(\n                              function (info, key) {\n                                if (typeof value[key] === 'function') {\n                                  info.methods.push(key);\n                                } else {\n                                  info.values.push([key, value[key]]);\n                                }\n                                return info;\n                              },\n                              {\n                                methods: [],\n                                values: []\n                              }\n                            )\n          } :\n          {\n            type: 'function',\n            path: path\n          };\n      } else if (remote.toString.call(value) === '[object Object]') {\n        remote[key] = {\n          type: 'object',\n          path: path,\n          value: {}\n        };\n        $(value, path, remote[key].value);\n      } else if (value !== void 0) {\n        remote[key] = {\n          type: 'any',\n          path: path,\n          value: value\n        };\n      }\n    });\n    return remote;\n  }(object, [], {});\n  function no(within) {\n    return function (what) {\n      return within.indexOf(what) < 0;\n    };\n  }\n}\nexport default remoted;\n"
  },
  {
    "path": "examples/workway-node/README.md",
    "content": "# Node.js workway demo\n\nThis demo shows CPUs and current memory consumption.\n\n```sh\nnpm install\n# now open that localhost page\n```\n"
  },
  {
    "path": "examples/workway-node/index.js",
    "content": "const path = require('path');\nconst express = require('express');\nconst workway = require('workway/node');\n\n// which folder should be reachable from the Web ?\nworkway.authorize(path.join(__dirname, 'workers'));\n\n// create an app through workway\nconst app = workway.app(express());\napp.use(express.static(path.join(__dirname, 'www')));\napp.listen(process.env.PORT || 8080, function () {\n  console.log(`http://localhost:${this.address().port}/`);\n});\n"
  },
  {
    "path": "examples/workway-node/package.json",
    "content": "{\n  \"private\": true,\n  \"description\": \"A basic workway driven NodeJS example\",\n  \"scripts\": {\n    \"postinstall\": \"npm start\",\n    \"start\": \"node index.js\"\n  },\n  \"author\": \"Andrea Giammarchi\",\n  \"license\": \"ISC\",\n  \"dependencies\": {\n    \"express\": \"^4.16.3\",\n    \"workway\": \"^0.5.2\"\n  }\n}\n"
  },
  {
    "path": "examples/workway-node/workers/os.js",
    "content": "const workway = require('workway');\n\n// export any namespace or even modules\nworkway(require('os'));\n"
  },
  {
    "path": "examples/workway-node/www/index.html",
    "content": "<!doctype html>\n<html>\n  <head>\n    <title>workway meets NodeJS</title>\n    <style>body { font-family: sans-serif; }</style>\n    <script>\n    if(!this.Promise)document.write('<script src=\"/js/poly/es6-promise.js\"><'+'/script>');\n    if(!this.WeakMap)document.write('<script src=\"/js/poly/poorlyfills.js\"><'+'/script>');\n    try{new EventTarget}catch(e){document.write('<script src=\"/js/poly/event-target.js\"><'+'/script>')}\n    </script>\n    <script src=\"/js/3rd/hyperhtml.js\"></script>\n    <script src=\"/js/3rd/workway.js\"></script>\n    <script src=\"/pocket.io/pocket.io.js\"></script>\n    <script src=\"/workway@node.js\"></script>\n    <script src=\"/js/index.js\"></script>\n  </head>\n  <body></body>\n</html>"
  },
  {
    "path": "examples/workway-node/www/js/3rd/hyperhtml.js",
    "content": "/*! (c) Andrea Giammarchi (ISC) */var hyperHTML=function(e){\"use strict\";var t=document.defaultView,r=/^area|base|br|col|embed|hr|img|input|keygen|link|menuitem|meta|param|source|track|wbr$/i,l=\"ownerSVGElement\",c=\"http://www.w3.org/2000/svg\",s=\"connected\",f=\"dis\"+s,d=/^style|textarea$/i,b=\"_hyper: \"+(Math.random()*new Date|0)+\";\",h=\"\\x3c!--\"+b+\"--\\x3e\",v=t.Event;try{new v(\"Event\")}catch(e){v=function(e){var t=document.createEvent(\"Event\");return t.initEvent(e,!1,!1),t}}var n,i=t.Map||function(){var n=[],r=[];return{get:function(e){return r[n.indexOf(e)]},set:function(e,t){r[n.push(e)-1]=t}}},o=0,p=t.WeakMap||function(){var n=b+o++;return{get:function(e){return e[n]},set:function(e,t){Object.defineProperty(e,n,{configurable:!0,value:t})}}},a=t.WeakSet||function(){var t=new p;return{add:function(e){t.set(e,!0)},has:function(e){return!0===t.get(e)}}},u=Array.isArray||(n={}.toString,function(e){return\"[object Array]\"===n.call(e)}),m=b.trim||function(){return this.replace(/^\\s+|\\s+$/g,\"\")};function g(){return this}var w=function(e,t){var n=\"_\"+e+\"$\";return{get:function(){return this[n]||(this[e]=t.call(this,e))},set:function(e){Object.defineProperty(this,n,{configurable:!0,value:e})}}},y={},N=[],x=y.hasOwnProperty,E=0,C=function(e,t){e in y||(E=N.push(e)),y[e]=t},j=function(e,t){for(var n=0;n<E;n++){var r=N[n];if(x.call(e,r))return y[r](e[r],t)}},A=function(e,t){return S(e).createElement(t)},S=function(e){return e.ownerDocument||e},T=function(e){return S(e).createDocumentFragment()},L=function(e,t){return S(e).createTextNode(t)},O=\" \\\\f\\\\n\\\\r\\\\t\",k=\"[^ \"+O+\"\\\\/>\\\"'=]+\",M=\"[ \"+O+\"]+\"+k,D=\"<([A-Za-z]+[A-Za-z0-9:_-]*)((?:\",$=\"(?:=(?:'[^']*?'|\\\"[^\\\"]*?\\\"|<[^>]*?>|\"+k+\"))?)\",P=new RegExp(D+M+$+\"+)([ \"+O+\"]*/?>)\",\"g\"),B=new RegExp(D+M+$+\"*)([ \"+O+\"]*/>)\",\"g\"),R=T(document),H=\"append\"in R,_=\"content\"in A(document,\"template\");R.appendChild(L(R,\"g\")),R.appendChild(L(R,\"\"));var z=1===R.cloneNode(!0).childNodes.length,F=\"importNode\"in document,Z=H?function(e,t){e.append.apply(e,t)}:function(e,t){for(var n=t.length,r=0;r<n;r++)e.appendChild(t[r])},I=new RegExp(\"(\"+M+\"=)(['\\\"]?)\"+h+\"\\\\2\",\"gi\"),V=function(e,t,n,r){return\"<\"+t+n.replace(I,W)+r},W=function(e,t,n){return t+(n||'\"')+b+(n||'\"')},q=function(e,t){return(l in e?Y:X)(e,t.replace(P,V))},G=z?function(e){for(var t=e.cloneNode(),n=e.childNodes||[],r=n.length,i=0;i<r;i++)t.appendChild(G(n[i]));return t}:function(e){return e.cloneNode(!0)},J=F?function(e,t){return e.importNode(t,!0)}:function(e,t){return G(t)},K=[].slice,Q=function(e){return U(e)},U=function(e){if(e.propertyIsEnumerable(\"raw\")||/Firefox\\/(\\d+)/.test((t.navigator||{}).userAgent)&&parseFloat(RegExp.$1)<55){var n={};U=function(e){var t=\"^\"+e.join(\"^\");return n[t]||(n[t]=e)}}else U=function(e){return e};return U(e)},X=_?function(e,t){var n=A(e,\"template\");return n.innerHTML=t,n.content}:function(e,t){var n=A(e,\"template\"),r=T(e);if(/^[^\\S]*?<(col(?:group)?|t(?:head|body|foot|r|d|h))/i.test(t)){var i=RegExp.$1;n.innerHTML=\"<table>\"+t+\"</table>\",Z(r,K.call(n.querySelectorAll(i)))}else n.innerHTML=t,Z(r,K.call(n.childNodes));return r},Y=_?function(e,t){var n=T(e),r=S(e).createElementNS(c,\"svg\");return r.innerHTML=t,Z(n,K.call(r.childNodes)),n}:function(e,t){var n=T(e),r=A(e,\"div\");return r.innerHTML='<svg xmlns=\"'+c+'\">'+t+\"</svg>\",Z(n,K.call(r.firstChild.childNodes)),n};function ee(e){this.childNodes=e,this.length=e.length,this.first=e[0],this.last=e[this.length-1]}ee.prototype.insert=function(){var e=T(this.first);return Z(e,this.childNodes),e},ee.prototype.remove=function(){var e=this.first,t=this.last;if(2===this.length)t.parentNode.removeChild(t);else{var n=S(e).createRange();n.setStartBefore(this.childNodes[1]),n.setEndAfter(t),n.deleteContents()}return e};var te=function(e,t,n){e.unshift(e.indexOf.call(t.childNodes,n))},ne=function(e,t,n){return{type:e,name:n,node:t,path:function(e){var t=[],n=void 0;switch(e.nodeType){case 1:case 11:n=e;break;case 8:n=e.parentNode,te(t,n,e);break;default:n=e.ownerElement}for(e=n;n=n.parentNode;e=n)te(t,n,e);return t}(t)}},re=function(e,t){for(var n=t.length,r=0;r<n;r++)e=e.childNodes[t[r]];return e},ie=/acit|ex(?:s|g|n|p|$)|rph|ows|mnc|ntw|ine[ch]|zoo|^ord/i,oe=function(o,a){var u=void 0,l=void 0;return function(e){switch(typeof e){case\"object\":if(e){if(\"object\"===u){if(!a&&l!==e)for(var t in l)t in e||(o[t]=\"\")}else a?o.value=\"\":o.cssText=\"\";var n=a?{}:o;for(var r in e){var i=e[r];n[r]=\"number\"!=typeof i||ie.test(r)?i:i+\"px\"}u=\"object\",a?o.value=le(l=n):l=e;break}default:l!=e&&(u=\"string\",l=e,a?o.value=e||\"\":o.cssText=e||\"\")}}},ae=/([^A-Z])([A-Z]+)/g,ue=function(e,t,n){return t+\"-\"+n.toLowerCase()},le=function(e){var t=[];for(var n in e)t.push(n.replace(ae,ue),\":\",e[n],\";\");return t.join(\"\")},ce=function(e){return e},se=function(e,t,n,r){if(null==r)t.removeChild(e(n,-1));else{var i=t.ownerDocument.createRange();i.setStartBefore(e(n,-1)),i.setEndAfter(e(r,-1)),i.deleteContents()}},fe=function(e,t,n,r,i){for(var o=r||ce,a=null==i?null:o(i,0),u=0,l=0,c=t.length-1,s=t[0],f=t[c],d=n.length-1,h=n[0],v=n[d];u<=c&&l<=d;)if(null==s)s=t[++u];else if(null==f)f=t[--c];else if(null==h)h=n[++l];else if(null==v)v=n[--d];else if(s==h)s=t[++u],h=n[++l];else if(f==v)f=t[--c],v=n[--d];else if(s==v)e.insertBefore(o(s,1),o(f,-0).nextSibling),s=t[++u],v=n[--d];else if(f==h)e.insertBefore(o(f,1),o(s,0)),f=t[--c],h=n[++l];else{var p=t.indexOf(h);if(p<0)e.insertBefore(o(h,1),o(s,0)),h=n[++l];else{for(var m=p,g=l;m<=c&&g<=d&&t[m]===n[g];)m++,g++;if(1<m-p)--p===u?e.removeChild(o(s,-1)):se(o,e,s,t[p]),l=g,s=t[u=m],h=n[g];else{var b=t[p];t[p]=null,e.insertBefore(o(b,1),o(s,0)),h=n[++l]}}}if(u<=c||l<=d)if(c<u){var w=n[d+1],y=null==w?a:o(w,0);if(l===d)e.insertBefore(o(n[l],1),y);else{for(var N=e.ownerDocument.createDocumentFragment();l<=d;)N.appendChild(o(n[l++],1));e.insertBefore(N,y)}}else null==t[u]&&u++,u===c?e.removeChild(o(t[u],-1)):se(o,e,t[u],t[c]);return n},de=new a;function he(){}he.prototype=Object.create(null);var ve=function(e){return{html:e}},pe=function e(t,n){return\"ELEMENT_NODE\"in t?t:t.constructor===ee?1/n<0?n?t.remove():t.last:n?t.insert():t.first:e(t.render(),n)},me=function(e,t,n){for(var r=new he,i=e.attributes,o=K.call(i),a=[],u=o.length,l=0;l<u;l++){var c=o[l];if(c.value===b){var s=c.name;if(!(s in r)){var f=n.shift().replace(/^(?:|[\\S\\s]*?\\s)(\\S+?)=['\"]?$/,\"$1\");r[s]=i[f]||i[f.toLowerCase()],t.push(ne(\"attr\",r[s],f))}a.push(c)}}for(var d=a.length,h=0;h<d;h++){var v=a[h];/^id$/i.test(v.name)?e.removeAttribute(v.name):e.removeAttributeNode(a[h])}var p=e.nodeName;if(/^script$/i.test(p)){for(var m=document.createElement(p),g=0;g<i.length;g++)m.setAttributeNode(i[g].cloneNode(!0));m.textContent=e.textContent,e.parentNode.replaceChild(m,e)}},ge=function(e,t){t(e.placeholder),\"text\"in e?Promise.resolve(e.text).then(String).then(t):\"any\"in e?Promise.resolve(e.any).then(t):\"html\"in e?Promise.resolve(e.html).then(ve).then(t):Promise.resolve(j(e,t)).then(t)},be=function(e){return null!=e&&\"then\"in e},we=function(r,i){var o=!1,a=void 0;return function e(t){switch(typeof t){case\"string\":case\"number\":case\"boolean\":o?a!==t&&(a=t,i[0].textContent=t):(o=!0,a=t,i=fe(r.parentNode,i,[L(r,t)],pe,r));break;case\"object\":case\"undefined\":if(null==t){o=!1,i=fe(r.parentNode,i,[],pe,r);break}default:if(o=!1,u(a=t))if(0===t.length)i.length&&(i=fe(r.parentNode,i,[],pe,r));else switch(typeof t[0]){case\"string\":case\"number\":case\"boolean\":e({html:t});break;case\"object\":if(u(t[0])&&(t=t.concat.apply([],t)),be(t[0])){Promise.all(t).then(e);break}default:i=fe(r.parentNode,i,t,pe,r)}else\"ELEMENT_NODE\"in(n=t)||n instanceof ee||n instanceof g?i=fe(r.parentNode,i,11===t.nodeType?K.call(t.childNodes):[t],pe,r):be(t)?t.then(e):\"placeholder\"in t?ge(t,e):\"text\"in t?e(String(t.text)):\"any\"in t?e(t.any):\"html\"in t?i=fe(r.parentNode,i,K.call(q(r,[].concat(t.html).join(\"\")).childNodes),pe,r):e(\"length\"in t?K.call(t):j(t,e))}var n}},ye=function(t,n,e){var r=l in t,i=void 0;if(\"style\"===n)return function(e,t,n){if(n){var r=t.cloneNode(!0);return r.value=\"\",e.setAttributeNode(r),oe(r,n)}return oe(e.style,n)}(t,e,r);if(/^on/.test(n)){var o=n.slice(2);return o===s||o===f?(Ee&&(Ee=!1,function(){var i=function(e,t){for(var n=new v(t),r=e.length,i=0;i<r;i++){var o=e[i];1===o.nodeType&&a(o,n)}},a=function e(t,n){de.has(t)&&t.dispatchEvent(n);for(var r=t.children,i=r.length,o=0;o<i;o++)e(r[o],n)};try{new MutationObserver(function(e){for(var t=e.length,n=0;n<t;n++){var r=e[n];i(r.removedNodes,f),i(r.addedNodes,s)}}).observe(document,{subtree:!0,childList:!0})}catch(e){document.addEventListener(\"DOMNodeRemoved\",function(e){i([e.target],f)},!1),document.addEventListener(\"DOMNodeInserted\",function(e){i([e.target],s)},!1)}}()),de.add(t)):n.toLowerCase()in t&&(o=o.toLowerCase()),function(e){i!==e&&(i&&t.removeEventListener(o,i,!1),(i=e)&&t.addEventListener(o,e,!1))}}if(\"data\"===n||!r&&n in t)return function(e){i!==e&&(i=e,t[n]!==e&&null==(t[n]=e)&&t.removeAttribute(n))};var a=!1,u=e.cloneNode(!0);return function(e){i!==e&&(i=e,u.value!==e&&(null==e?(a&&(a=!1,t.removeAttributeNode(u)),u.value=e):(u.value=e,a||(a=!0,t.setAttributeNode(u)))))}},Ne=function(n){var r=void 0;return function e(t){r!==t&&(\"object\"==typeof(r=t)&&t?be(t)?t.then(e):\"placeholder\"in t?ge(t,e):e(\"text\"in t?String(t.text):\"any\"in t?t.any:\"html\"in t?[].concat(t.html).join(\"\"):\"length\"in t?K.call(t).join(\"\"):j(t,e)):n.textContent=null==t?\"\":t)}},xe={create:function(e,t){for(var n=[],r=t.length,i=0;i<r;i++){var o=t[i],a=re(e,o.path);switch(o.type){case\"any\":n.push(we(a,[]));break;case\"attr\":n.push(ye(a,o.name,o.node));break;case\"text\":n.push(Ne(a)),a.textContent=\"\"}}return n},find:function e(t,n,r){for(var i=t.childNodes,o=i.length,a=0;a<o;a++){var u=i[a];switch(u.nodeType){case 1:me(u,n,r),e(u,n,r);break;case 8:u.textContent===b&&(r.shift(),n.push(d.test(t.nodeName)?ne(\"text\",t):ne(\"any\",u)));break;case 3:d.test(t.nodeName)&&m.call(u.textContent)===h&&(r.shift(),n.push(ne(\"text\",t)))}}}},Ee=!0;var Ce=new p,je=function(){try{var e=new p,t=Object.freeze([]);if(e.set(t,!0),!e.get(t))throw t;return e}catch(t){return new i}}();function Ae(e){var t=Ce.get(this);return t&&t.template===Q(e)?Se.apply(t.updates,arguments):function(e){e=Q(e);var t=je.get(e)||function(e){var t=[],n=e.join(h).replace(Me,De),r=q(this,n);xe.find(r,t,e.slice());var i={fragment:r,paths:t};return je.set(e,i),i}.call(this,e),n=J(this.ownerDocument,t.fragment),r=xe.create(n,t.paths);Ce.set(this,{template:e,updates:r}),Se.apply(r,arguments),this.textContent=\"\",this.appendChild(n)}.apply(this,arguments),this}function Se(){for(var e=arguments.length,t=1;t<e;t++)this[t-1](arguments[t])}var Te,Le,Oe,ke,Me=B,De=function(e,t,n){return r.test(t)?e:\"<\"+t+n+\"></\"+t+\">\"},$e=new p,Pe=function(n){var r=void 0,i=void 0,o=void 0,a=void 0,u=void 0;return function(e){e=Q(e);var t=a!==e;return t&&(a=e,o=T(document),i=\"svg\"===n?document.createElementNS(c,\"svg\"):o,u=Ae.bind(i)),u.apply(null,arguments),t&&(\"svg\"===n&&Z(o,K.call(i.childNodes)),r=Re(o)),r}},Be=function(e,t){var n=t.indexOf(\":\"),r=$e.get(e),i=t;return-1<n&&(i=t.slice(n+1),t=t.slice(0,n)||\"html\"),r||$e.set(e,r={}),r[i]||(r[i]=Pe(t))},Re=function(e){for(var t=e.childNodes,n=t.length,r=[],i=0;i<n;i++){var o=t[i];1!==o.nodeType&&0===m.call(o.textContent).length||r.push(o)}return 1===r.length?r[0]:new ee(r)},He=C;function _e(e){return arguments.length<2?null==e?Pe(\"html\"):\"string\"==typeof e?_e.wire(null,e):\"raw\"in e?Pe(\"html\")(e):\"nodeType\"in e?_e.bind(e):Be(e,\"html\"):(\"raw\"in e?Pe(\"html\"):_e.wire).apply(null,arguments)}return _e.Component=g,_e.bind=function(e){return Ae.bind(e)},_e.define=He,_e.diff=fe,(_e.hyper=_e).wire=function(e,t){return null==e?Pe(t||\"html\"):Be(e,t||\"html\")},Te=Pe,Le=new p,Oe=Object.create,ke=function(e,t){var n={w:null,p:null};return t.set(e,n),n},Object.defineProperties(g,{for:{configurable:!0,value:function(e,t){return function(e,t,n,r){var i,o,a,u=t.get(e)||ke(e,t);switch(typeof r){case\"object\":case\"function\":var l=u.w||(u.w=new p);return l.get(r)||(i=l,o=r,a=new e(n),i.set(o,a),a);default:var c=u.p||(u.p=Oe(null));return c[r]||(c[r]=new e(n))}}(this,Le.get(e)||(n=e,r=new i,Le.set(n,r),r),e,null==t?\"default\":t);var n,r}}}),Object.defineProperties(g.prototype,{handleEvent:{value:function(e){var t=e.currentTarget;this[\"getAttribute\"in t&&t.getAttribute(\"data-call\")||\"on\"+e.type](e)}},html:w(\"html\",Te),svg:w(\"svg\",Te),state:w(\"state\",function(){return this.defaultState}),defaultState:{get:function(){return{}}},setState:{value:function(e,t){var n=this.state,r=\"function\"==typeof e?e.call(this,n):e;for(var i in r)n[i]=r[i];return!1!==t&&this.render(),this}}}),_e}(window);"
  },
  {
    "path": "examples/workway-node/www/js/3rd/workway.js",
    "content": "function workway(a){\"use strict\";\n/*! (c) 2018 Andrea Giammarchi (ISC) */return new Promise(function(u,e){function f(){return++t+Math.random()}var t=0,h=f(),l={},p=new Worker(a);p.addEventListener(\"message\",function(e){if(e.data.channel===h){e.stopImmediatePropagation();var t=e.data.namespace;if(t){var o=function(e){var a,r,t=new Promise(function(e,t){a=e,r=t});return t.resolve=a,t.reject=r,l[e.id=f()]=t,p.postMessage({channel:h,message:e}),t},c=[].slice;!function r(n){Object.keys(n).forEach(function(e){var t,a=n[e];switch(a.type){case\"class\":n[e]=function(e){var t=e.path,a=e.methods,r=e.statics,n=new WeakMap;function s(){n.set(this,f())}return a.forEach(function(e){s.prototype[e]=function(){return o({args:c.call(arguments),path:t,method:e,object:{id:n.get(this),value:this}})}}),r.methods.forEach(function(e){s[e]=function(){return o({args:c.call(arguments),path:t,method:e})}}),r.values.forEach(function(e){s[e[0]]=e[1]}),s}(a);break;case\"function\":n[e]=(t=a.path,function(){return o({args:c.call(arguments),path:t})});break;case\"object\":r(n[e]=a.value);break;default:n[e]=a.value}})}(t),u({worker:p,namespace:t})}else{var a=e.data.message,r=a.id,n=l[r];if(delete l[r],a.hasOwnProperty(\"error\")){var s,i=a.error;i.hasOwnProperty(\"source\")?s=i.source:(s=new Error(i.message)).stack=i.stack,n.reject(s)}else n.resolve(a.result)}}}),p.postMessage({channel:h})})}"
  },
  {
    "path": "examples/workway-node/www/js/index.js",
    "content": "workway('node://os.js').then(async ({worker, namespace:os}) => {\n  // cpus are not going to change (not the showed part)\n  const cpus = await os.cpus();\n  // grab other info and render the view\n  grabAndShow();\n  function grabAndShow() {\n    Promise.all([\n      os.freemem(),\n      os.totalmem()\n    ]).then(render);\n  }\n  // show all the details\n  function render([freemem, totalmem]) {\n    hyperHTML(document.body)`\n    <strong>Summary of ${cpus.length}\n            CPU${cpus.length === 1 ? '' : 's'}</strong>\n    <ul>\n      ${cpus.map(cpu => hyperHTML(cpu)`\n      <li>${cpu.model}</li>`)}\n    </ul>\n    <hr>\n    <p>Using ${\n      ((100 * (totalmem - freemem)) / totalmem).toFixed(2)\n    }% of memory</p>`;\n    // update the same view in a second\n    setTimeout(grabAndShow, 1000);\n  }\n});"
  },
  {
    "path": "examples/workway-node/www/js/poly/es6-promise.js",
    "content": "!function(t,e){\"object\"==typeof exports&&\"undefined\"!=typeof module?module.exports=e():\"function\"==typeof define&&define.amd?define(e):t.ES6Promise=e()}(this,function(){\"use strict\";function t(t){var e=typeof t;return null!==t&&(\"object\"===e||\"function\"===e)}function e(t){return\"function\"==typeof t}function n(t){B=t}function r(t){G=t}function o(){return function(){return process.nextTick(a)}}function i(){return\"undefined\"!=typeof z?function(){z(a)}:c()}function s(){var t=0,e=new J(a),n=document.createTextNode(\"\");return e.observe(n,{characterData:!0}),function(){n.data=t=++t%2}}function u(){var t=new MessageChannel;return t.port1.onmessage=a,function(){return t.port2.postMessage(0)}}function c(){var t=setTimeout;return function(){return t(a,1)}}function a(){for(var t=0;t<W;t+=2){var e=V[t],n=V[t+1];e(n),V[t]=void 0,V[t+1]=void 0}W=0}function f(){try{var t=Function(\"return this\")().require(\"vertx\");return z=t.runOnLoop||t.runOnContext,i()}catch(e){return c()}}function l(t,e){var n=this,r=new this.constructor(p);void 0===r[Z]&&O(r);var o=n._state;if(o){var i=arguments[o-1];G(function(){return P(o,r,i,n._result)})}else E(n,r,t,e);return r}function h(t){var e=this;if(t&&\"object\"==typeof t&&t.constructor===e)return t;var n=new e(p);return g(n,t),n}function p(){}function v(){return new TypeError(\"You cannot resolve a promise with itself\")}function d(){return new TypeError(\"A promises callback cannot return that same promise.\")}function _(t){try{return t.then}catch(e){return nt.error=e,nt}}function y(t,e,n,r){try{t.call(e,n,r)}catch(o){return o}}function m(t,e,n){G(function(t){var r=!1,o=y(n,e,function(n){r||(r=!0,e!==n?g(t,n):S(t,n))},function(e){r||(r=!0,j(t,e))},\"Settle: \"+(t._label||\" unknown promise\"));!r&&o&&(r=!0,j(t,o))},t)}function b(t,e){e._state===tt?S(t,e._result):e._state===et?j(t,e._result):E(e,void 0,function(e){return g(t,e)},function(e){return j(t,e)})}function w(t,n,r){n.constructor===t.constructor&&r===l&&n.constructor.resolve===h?b(t,n):r===nt?(j(t,nt.error),nt.error=null):void 0===r?S(t,n):e(r)?m(t,n,r):S(t,n)}function g(e,n){e===n?j(e,v()):t(n)?w(e,n,_(n)):S(e,n)}function A(t){t._onerror&&t._onerror(t._result),T(t)}function S(t,e){t._state===$&&(t._result=e,t._state=tt,0!==t._subscribers.length&&G(T,t))}function j(t,e){t._state===$&&(t._state=et,t._result=e,G(A,t))}function E(t,e,n,r){var o=t._subscribers,i=o.length;t._onerror=null,o[i]=e,o[i+tt]=n,o[i+et]=r,0===i&&t._state&&G(T,t)}function T(t){var e=t._subscribers,n=t._state;if(0!==e.length){for(var r=void 0,o=void 0,i=t._result,s=0;s<e.length;s+=3)r=e[s],o=e[s+n],r?P(n,r,o,i):o(i);t._subscribers.length=0}}function M(t,e){try{return t(e)}catch(n){return nt.error=n,nt}}function P(t,n,r,o){var i=e(r),s=void 0,u=void 0,c=void 0,a=void 0;if(i){if(s=M(r,o),s===nt?(a=!0,u=s.error,s.error=null):c=!0,n===s)return void j(n,d())}else s=o,c=!0;n._state!==$||(i&&c?g(n,s):a?j(n,u):t===tt?S(n,s):t===et&&j(n,s))}function x(t,e){try{e(function(e){g(t,e)},function(e){j(t,e)})}catch(n){j(t,n)}}function C(){return rt++}function O(t){t[Z]=rt++,t._state=void 0,t._result=void 0,t._subscribers=[]}function k(){return new Error(\"Array Methods must be provided an Array\")}function F(t){return new ot(this,t).promise}function Y(t){var e=this;return new e(U(t)?function(n,r){for(var o=t.length,i=0;i<o;i++)e.resolve(t[i]).then(n,r)}:function(t,e){return e(new TypeError(\"You must pass an array to race.\"))})}function q(t){var e=this,n=new e(p);return j(n,t),n}function D(){throw new TypeError(\"You must pass a resolver function as the first argument to the promise constructor\")}function K(){throw new TypeError(\"Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.\")}function L(){var t=void 0;if(\"undefined\"!=typeof global)t=global;else if(\"undefined\"!=typeof self)t=self;else try{t=Function(\"return this\")()}catch(e){throw new Error(\"polyfill failed because global object is unavailable in this environment\")}var n=t.Promise;if(n){var r=null;try{r=Object.prototype.toString.call(n.resolve())}catch(e){}if(\"[object Promise]\"===r&&!n.cast)return}t.Promise=it}var N=void 0;N=Array.isArray?Array.isArray:function(t){return\"[object Array]\"===Object.prototype.toString.call(t)};var U=N,W=0,z=void 0,B=void 0,G=function(t,e){V[W]=t,V[W+1]=e,W+=2,2===W&&(B?B(a):X())},H=\"undefined\"!=typeof window?window:void 0,I=H||{},J=I.MutationObserver||I.WebKitMutationObserver,Q=\"undefined\"==typeof self&&\"undefined\"!=typeof process&&\"[object process]\"==={}.toString.call(process),R=\"undefined\"!=typeof Uint8ClampedArray&&\"undefined\"!=typeof importScripts&&\"undefined\"!=typeof MessageChannel,V=new Array(1e3),X=void 0;X=Q?o():J?s():R?u():void 0===H&&\"function\"==typeof require?f():c();var Z=Math.random().toString(36).substring(2),$=void 0,tt=1,et=2,nt={error:null},rt=0,ot=function(){function t(t,e){this._instanceConstructor=t,this.promise=new t(p),this.promise[Z]||O(this.promise),U(e)?(this.length=e.length,this._remaining=e.length,this._result=new Array(this.length),0===this.length?S(this.promise,this._result):(this.length=this.length||0,this._enumerate(e),0===this._remaining&&S(this.promise,this._result))):j(this.promise,k())}return t.prototype._enumerate=function(t){for(var e=0;this._state===$&&e<t.length;e++)this._eachEntry(t[e],e)},t.prototype._eachEntry=function(t,e){var n=this._instanceConstructor,r=n.resolve;if(r===h){var o=_(t);if(o===l&&t._state!==$)this._settledAt(t._state,e,t._result);else if(\"function\"!=typeof o)this._remaining--,this._result[e]=t;else if(n===it){var i=new n(p);w(i,t,o),this._willSettleAt(i,e)}else this._willSettleAt(new n(function(e){return e(t)}),e)}else this._willSettleAt(r(t),e)},t.prototype._settledAt=function(t,e,n){var r=this.promise;r._state===$&&(this._remaining--,t===et?j(r,n):this._result[e]=n),0===this._remaining&&S(r,this._result)},t.prototype._willSettleAt=function(t,e){var n=this;E(t,void 0,function(t){return n._settledAt(tt,e,t)},function(t){return n._settledAt(et,e,t)})},t}(),it=function(){function t(e){this[Z]=C(),this._result=this._state=void 0,this._subscribers=[],p!==e&&(\"function\"!=typeof e&&D(),this instanceof t?x(this,e):K())}return t.prototype[\"catch\"]=function(t){return this.then(null,t)},t.prototype[\"finally\"]=function(t){var e=this,n=e.constructor;return e.then(function(e){return n.resolve(t()).then(function(){return e})},function(e){return n.resolve(t()).then(function(){throw e})})},t}();return it.prototype.then=l,it.all=F,it.race=Y,it.resolve=h,it.reject=q,it._setScheduler=n,it._setAsap=r,it._asap=G,it.polyfill=L,it.Promise=it,it.polyfill(),it});"
  },
  {
    "path": "examples/workway-node/www/js/poly/event-targe.js",
    "content": "/*! (c) 2017 Andrea Giammarchi (ISC) */\nvar EventTarget=function(){\"use strict\";var t=\"object\"==typeof global?global:self,e=[].findIndex||function(t,e){for(var n=this.length;n--;)if(t.call(e,this[n]))return n;return n},n=Object.defineProperty,r=\"__event-target__\"+Math.random(),i=t.WeakMap||function(){return{get:function(t){return t[r]},set:function(t,e){n(t,r,{configurable:!0,value:e})}}},a=t.EventTarget;try{new a}catch(o){a=function(){function t(){}function r(t){var e=t.options;e&&e.once&&u.call(t.target,this.type,t.listener,t.options),\"function\"==typeof t.listener?t.listener.call(t.target,this):t.listener.handleEvent(this)}function a(t){return this===t.listener}function o(t,n,r){var i=f(this),o=i[t]||(i[t]=[]);e.call(o,a,n)<0&&o.push({target:this,listener:n,options:r})}function c(t){var e=f(this),n=e[t.type];return n&&(h(t,{currentTarget:this,target:this}),n.forEach(r,t),delete t.currentTarget,delete t.target),!0}function u(t,n,r){var i=f(this),o=i[t];if(o){var c=e.call(o,a,n);-1<c&&o.splice(c,1)}}function l(){}var s=new i,f=function(t){return s.get(t)||v(t)},v=function(t){var e=new l;return s.set(t,e),e},h=function(t,e){for(var r in e)n(t,r,{configurable:!0,value:e[r]})};return h(t.prototype,{addEventListener:o,dispatchEvent:c,removeEventListener:u}),l.prototype=Object.create(null),t}()}return a}();"
  },
  {
    "path": "examples/workway-node/www/js/poly/poorlyfills.js",
    "content": "\"use strict\";!function(e){/*! (c) 2017 Andrea Giammarchi @WebReflection, (ISC) */\ne.Map=e.Map||function(){var e=void 0,t=void 0,n=void 0,r=function(){t=[],n=[]},u=function(n){return-1<(e=t.indexOf(n))};return r(),{get size(){return t.length},has:u,clear:r,get:function(e){return n[t.indexOf(e)]},keys:function(){return t.slice()},values:function(){return n.slice()},entries:function(){return t.map(function(e,t){return[e,n[t]]})},delete:function(r){return u(r)&&t.splice(e,1)&&!!n.splice(e,1)},forEach:function(e,r){var u=this;n.forEach(function(n,i){return e.call(r,n,t[i],u)})},set:function(r,i){return u(r)?n[e]=i:n[t.push(r)-1]=i,this}}},e.Set=e.Set||function(){var t=new e.Map,n=t.set;return delete t.get,delete t.set,t.add=function(e){return n.call(t,e,e)},t};var t=0,n={}.hasOwnProperty;e.WeakMap=e.WeakMap||function(){var e=\"__\"+[t++,Math.random()],r=function(t){return n.call(t,e)};return{has:r,get:function(t){return t[e]},delete:function(t){return r(t)&&delete t[e]},set:function(t,n){return Object.defineProperty(t,e,{configurable:!0,value:n}),this}}},e.WeakSet=e.WeakSet||function(){var t=new e.WeakMap;return{has:function(e){return!0===t.get(e)},delete:t.delete,add:function(e){return t.set(e,!0),this}}}}(this);"
  },
  {
    "path": "examples/workway-promise-reject/README.md",
    "content": "# Promise reject from Node.js\n\nThis demo shows results when a Promise fails.\n\n```sh\nnpm install\n# now open that localhost page\n```\n"
  },
  {
    "path": "examples/workway-promise-reject/index.html",
    "content": "<!doctype html>\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n<script>\nif(!this.Promise)document.write('<script src=\"https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.auto.min.js\"><'+'/script>');\nif(!this.WeakMap)document.write('<script src=\"https://unpkg.com/poorlyfills@0.1.1/min.js\"><'+'/script>');\ntry{new EventTarget}catch(e){document.write('<script src=\"https://unpkg.com/event-target@1.2.2/min.js\"><'+'/script>')}\n</script>\n<script src=\"https://unpkg.com/workway\"></script>\n<script src=\"/pocket.io/pocket.io.js\"></script>\n<script src=\"/workway@node.js\"></script>\n<script>\nworkway('node://index.js').then(async ({worker, namespace:foo}) => {\n  foo.fooPromisified(\"unused\")\n    .then(res => console.log(\"then\", res))\n    .catch(err => console.log(\"catch\", err));\n});\n</script>\n"
  },
  {
    "path": "examples/workway-promise-reject/index.js",
    "content": "var PORT = process.env.PORT || 3000;\n\nvar path = require('path');\nvar express = require('express');\nvar workway = require('workway/node').authorize(\n  path.resolve(__dirname, 'workers')\n);\n\nvar app = workway.app(express());\napp.get('/', function (req, res) {\n  res.writeHead(200, 'OK', {\n    'Content-Type': 'text/html; charset=utf-8'\n  });\n  res.end(require('fs').readFileSync(path.resolve(__dirname, 'index.html')));\n});\napp.listen(PORT, () => {\n  console.log('listening on http://localhost:' + PORT);\n});\n"
  },
  {
    "path": "examples/workway-promise-reject/package.json",
    "content": "{\n  \"name\": \"workway-demo\",\n  \"private\": true,\n  \"dependencies\": {\n    \"express\": \"^4.16.3\",\n    \"workway\": \"^0.5.2\"\n  },\n  \"scripts\": {\n    \"start\": \"node index.js\",\n    \"postinstall\": \"npm start\"\n  },\n  \"author\": \"Andrea Giammarchi\",\n  \"license\": \"ISC\"\n}\n"
  },
  {
    "path": "examples/workway-promise-reject/workers/index.js",
    "content": "const util = require('util');\n\nconst workway = require('workway');\n\nfunction foo(message, callback) {\n    callback(42); // forcing always an error\n}\n\nconst fooPromisified = util.promisify(foo);\n\nworkway({\n    fooPromisified\n});\n"
  },
  {
    "path": "index.js",
    "content": "function workway(file) {'use strict';\n  /*! (c) 2018 Andrea Giammarchi (ISC) */\n  return new Promise(function (res) {\n    function uid() { return ++i + Math.random(); }\n    var i = 0;\n    var channel = uid();\n    var messages = {};\n    var worker = typeof file === 'string' ? new Worker(file) : file;\n    worker.addEventListener('message', function (event) {\n      if (event.data.channel !== channel) return;\n      event.stopImmediatePropagation();\n      var namespace = event.data.namespace;\n      if (namespace) {\n        var Class = function (info) {\n          var path = info.path;\n          var methods = info.methods;\n          var statics = info.statics;\n          var wm = new WeakMap;\n          function RemoteClass() { wm.set(this, uid()); }\n          methods.forEach(function (method) {\n            RemoteClass.prototype[method] = function () {\n              return send({\n                args: slice.call(arguments),\n                path: path,\n                method: method,\n                object: {\n                  id: wm.get(this),\n                  value: this\n                }\n              });\n            };\n          });\n          statics.methods.forEach(function (method) {\n            RemoteClass[method] = function () {\n              return send({\n                args: slice.call(arguments),\n                path: path,\n                method: method\n              });\n            };\n          });\n          statics.values.forEach(function (pair) {\n            RemoteClass[pair[0]] = pair[1];\n          });\n          return RemoteClass;\n        };\n        var callback = function (path) {\n          return function remoteCallback() {\n            return send({\n              args: slice.call(arguments),\n              path: path\n            });\n          };\n        };\n        var send = function (message) {\n          var resolve, reject;\n          var promise = new Promise(function (res, rej) {\n            resolve = res;\n            reject = rej;\n          });\n          promise.resolve = resolve;\n          promise.reject = reject;\n          messages[message.id = uid()] = promise;\n          worker.postMessage({\n            channel: channel,\n            message: message\n          });\n          return promise;\n        };\n        var slice = [].slice;\n        (function update(namespace) {\n          Object.keys(namespace).forEach(function (key) {\n            var info = namespace[key];\n            switch (info.type) {\n              case 'class': namespace[key] = Class(info); break;\n              case 'function': namespace[key] = callback(info.path); break;\n              case 'object': update(namespace[key] = info.value); break;\n              default: namespace[key] = info.value;\n            }\n          });\n        }(namespace));\n        res({\n          worker: worker,\n          namespace: namespace\n        });\n      } else {\n        var message = event.data.message;\n        var id = message.id;\n        var promise = messages[id];\n        delete messages[id];\n        if (message.hasOwnProperty('error')) {\n          var error, facade = message.error;\n          if (facade.hasOwnProperty('source'))\n            error = facade.source;\n          else {\n            error = new Error(facade.message);\n            error.stack = facade.stack;\n          }\n          promise.reject(error);\n        }\n        else\n          promise.resolve(message.result);\n      }\n    });\n    worker.postMessage({channel: channel});\n  });\n}\n"
  },
  {
    "path": "min.js",
    "content": "function workway(t){\"use strict\";\n/*! (c) 2018 Andrea Giammarchi (ISC) */return new Promise(function(u){function f(){return++e+Math.random()}var e=0,h=f(),l={},p=\"string\"==typeof t?new Worker(t):t;p.addEventListener(\"message\",function(e){if(e.data.channel===h){e.stopImmediatePropagation();var t=e.data.namespace;if(t){var o=function(e){var a,r,t=new Promise(function(e,t){a=e,r=t});return t.resolve=a,t.reject=r,l[e.id=f()]=t,p.postMessage({channel:h,message:e}),t},c=[].slice;!function a(r){Object.keys(r).forEach(function(e){var t=r[e];switch(t.type){case\"class\":r[e]=function(e){var t=e.path,a=e.methods,r=e.statics,n=new WeakMap;function s(){n.set(this,f())}return a.forEach(function(e){s.prototype[e]=function(){return o({args:c.call(arguments),path:t,method:e,object:{id:n.get(this),value:this}})}}),r.methods.forEach(function(e){s[e]=function(){return o({args:c.call(arguments),path:t,method:e})}}),r.values.forEach(function(e){s[e[0]]=e[1]}),s}(t);break;case\"function\":r[e]=function(e){return function(){return o({args:c.call(arguments),path:e})}}(t.path);break;case\"object\":a(r[e]=t.value);break;default:r[e]=t.value}})}(t),u({worker:p,namespace:t})}else{var a=e.data.message,r=a.id,n=l[r];if(delete l[r],a.hasOwnProperty(\"error\")){var s,i=a.error;i.hasOwnProperty(\"source\")?s=i.source:(s=new Error(i.message)).stack=i.stack,n.reject(s)}else n.resolve(a.result)}}}),p.postMessage({channel:h})})}"
  },
  {
    "path": "node/client.js",
    "content": "window.workway = (function (Worker, workway, SECRET) {\n\n  /*! Copyright 2018 Andrea Giammarchi - @WebReflection\n   *\n   * Permission to use, copy, modify, and/or distribute this software\n   * for any purpose with or without fee is hereby granted,\n   * provided that the above copyright notice\n   * and this permission notice appear in all copies.\n   * \n   * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS\n   * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING\n   * ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.\n   * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,\n   * DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR\n   * ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,\n   * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,\n   * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n   * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n   */\n\n  // ${JSON}\n\n  var instances = [];\n  var sockets = new WeakMap();\n\n  addEventListener(\n    'beforeunload',\n    function () {\n      while (instances.length) instances[0].terminate();\n    },\n    false\n  );\n\n  function NodeWorker(ep) {\n    var socket = io({JSON: Flatted});\n    var self = new EventTarget;\n    self.postMessage = this.postMessage;\n    self.terminate = this.terminate;\n    instances.push(self);\n    sockets.set(self, socket);\n    socket.on(SECRET + ':error', this.onerror.bind(self));\n    socket.on(SECRET + ':message', this.onmessage.bind(self));\n    socket.emit(SECRET + ':setup', ep);\n    return self;\n  }\n\n  function createEvent(type) {\n    var event = document.createEvent('Event');\n    event.initEvent(type, false, true);\n    event.stopImmediatePropagation = event.stopImmediatePropagation ||\n                                      event.stopPropagation;\n    return event;\n  }\n\n  NodeWorker.prototype = {\n\n    onerror: function (error) {\n      var event = createEvent('error');\n      event.message = error.message;\n      event.stack = error.stack;\n      this.dispatchEvent(event);\n      if (this.onerror) this.onerror(event);\n    },\n\n    onmessage: function (data) {\n      var event = createEvent('message');\n      event.data = data;\n      this.dispatchEvent(event);\n      if (this.onmessage) this.onmessage(event);\n    },\n\n    postMessage: function (message) {\n      sockets.get(this).emit(SECRET, message);\n    },\n\n    terminate: function () {\n      instances.splice(instances.indexOf(this), 1);\n      sockets.get(this).disconnect();\n    }\n\n  };\n\n  return function (file) {\n    if (/^node:\\/\\/([\\w._-]+)/.test(file)) {\n      file = RegExp.$1;\n      window.Worker = NodeWorker;\n      var promise = workway(file);\n      window.Worker = Worker;\n      return promise;\n    } else\n      return workway(file);\n  };\n\n}(Worker, workway, '${SECRET}'));\n"
  },
  {
    "path": "node/index.js",
    "content": "\"use strict\";\n\n// used core modules\nvar EventEmitter = require('events').EventEmitter;\nvar crypto = require('crypto');\nvar fs = require('fs');\nvar http = require('http');\nvar path = require('path');\nvar vm = require('vm');\n\n// extra dependencies\nvar Flatted = require('flatted');\nvar pocketIO = require('pocket.io');\nvar workerjs = fs.readFileSync(\n  path.resolve(__dirname, '..', 'worker.js')\n).toString();\n\n// used as communication channel\nvar SECRET = crypto.randomBytes(32).toString('hex');\n\n// the client side is enriched at runtime\nvar jsContent = fs.readFileSync(path.join(__dirname, 'client.js'))\n                  .toString()\n                  .replace(\n                    /\\$\\{(SECRET|JSON)\\}/g,\n                    function ($0, $1) { return this[$1]; }.bind({\n                      SECRET: SECRET,\n                      JSON: fs.readFileSync(require.resolve('flatted/min.js')).toString()\n                    })\n                  );\n\nvar workers = '';\n\nprocess.on('unhandledRejection', uncaught);\nprocess.on('uncaughtException', uncaught);\n\n// return a new Worker sandbox\nfunction createSandbox(filename, socket) {\n  var self = new EventEmitter;\n  var listeners = new WeakMap;\n  self.addEventListener = function (type, listener) {\n    if (!listeners.has(listener)) {\n      var facade = function (event) {\n        if (!event.canceled) listener.apply(this, arguments);\n      };\n      listeners.set(listener, facade);\n      self.on(type, facade);\n    }\n  };\n  self.removeEventListener = function (type, listener) {\n    self.removeListener(type, listeners.get(listener));\n  };\n  self.__filename = filename;\n  self.__dirname = path.dirname(filename);\n  self.postMessage = function postMessage(data) { message(socket, data); };\n  self.console = console;\n  self.process = process;\n  self.Buffer = Buffer;\n  self.clearImmediate = clearImmediate;\n  self.clearInterval = clearInterval;\n  self.clearTimeout = clearTimeout;\n  self.setImmediate = setImmediate;\n  self.setInterval = setInterval;\n  self.setTimeout = setTimeout;\n  self.module = module;\n  self.global = self;\n  self.self = self;\n  self.require = function (file) {\n    switch (true) {\n      case file === 'workway':\n        return self.workway;\n      case /^[./]/.test(file):\n        file = path.resolve(self.__dirname, file);\n      default:\n        return require(file);\n    }\n  };\n  return self;\n}\n\nfunction cleanedStack(stack) {\n  return ''.replace.call(stack, /:uid-\\d+-[a-f0-9]{16}/g, '');\n}\n\n// notify the socket there was an error\nfunction error(socket, err) {\n  socket.emit(SECRET + ':error', {\n    message: err.message,\n    stack: cleanedStack(err.stack)\n  });\n}\n\n// send serialized data to the client\nfunction message(socket, data) {\n  socket.emit(SECRET + ':message', data);\n}\n\n// used to send /node-worker.js client file\nfunction responder(request, response, next) {\n  response.writeHead(200, 'OK', {\n    'Content-Type': 'application/javascript'\n  });\n  response.end(jsContent);\n  if (next) next();\n}\n\nuid.i = 0;\nuid.map = Object.create(null);\nuid.delete = function (sandbox) {\n  Object.keys(uid.map).some(function (key) {\n    var found = uid.map[key] === sandbox;\n    if (found) delete uid.map[key];\n    return found;\n  });\n};\n\nfunction uid(filename, socket) {\n  var id = filename + ':uid-'.concat(++uid.i, '-', crypto.randomBytes(8).toString('hex'));\n  uid.map[id] = socket;\n  return id;\n}\n\nfunction uncaught(err) {\n  console.error(err);\n  if (/([\\S]+?(:uid-\\d+-[a-f0-9]{16}))/.test(err.stack)) {\n    var socket = uid.map[RegExp.$1];\n    if (socket) error(socket, err);\n  }\n}\n\nfunction Event(data) {\n  this.canceled = false;\n  this.data = data;\n}\n\nEvent.prototype.stopImmediatePropagation = function () {\n  this.canceled = true;\n};\n\nmodule.exports = {\n  authorize: function (folder) {\n    if (workers.length) throw new Error('workway already authorized');\n    workers = folder;\n    return this;\n  },\n  app: function (app) {\n    var io;\n    var native = app instanceof http.Server;\n    if (native) {\n      io = pocketIO(app, {JSON: Flatted});\n      var request = app._events.request;\n      app._events.request = function (req) {\n        return /^\\/workway@node\\.js(?:\\?|$)/.test(req.url) ?\n          responder.apply(this, arguments) :\n          request.apply(this, arguments);\n      };\n    } else {\n      var wrap = http.Server(app);\n      io = pocketIO(wrap, {JSON: Flatted});\n      app.get('/workway@node.js', responder);\n      Object.defineProperty(app, 'listen', {\n        configurable: true,\n        value: function () {\n          wrap.listen.apply(wrap, arguments);\n          return app;\n        }\n      });\n    }\n    io.on('connection', function (socket) {\n      var sandbox;\n      var queue = [];\n      function message(data) {\n        if (sandbox) {\n          try {\n            var event = new Event(data);\n            sandbox.emit('message', event);\n            if ('onmessage' in sandbox && !event.canceled) {\n              sandbox.onmessage(event);\n            }\n          } catch(err) {\n            error(socket, err);\n          }\n        }\n        else queue.push(data);\n      }\n      socket.on(SECRET, message);\n      socket.on(SECRET + ':setup', function (worker) {\n        var filename = path.resolve(path.join(workers, worker));\n        if (filename.indexOf(workers)) {\n          error(socket, {\n            message: 'Unauthorized worker: ' + worker,\n            stack: ''\n          });\n        } else {\n          fs.readFile(filename, function (err, content) {\n            if (err) {\n              error(socket, {\n                message: 'Worker not found: ' + worker,\n                stack: err.stack\n              });\n            } else {\n              sandbox = createSandbox(filename, socket);\n              vm.createContext(sandbox);\n              vm.runInContext(workerjs, sandbox);\n              vm.runInContext(content, sandbox, {\n                filename: uid(worker, socket),\n                displayErrors: true\n              });\n              while (queue.length) {\n                setTimeout(message, queue.length * 100, queue.pop());\n              }\n            }\n          });\n        }\n      });\n      socket.on('disconnect', function () {\n        uid.delete(socket);\n        sandbox = null;\n      });\n    });\n    return app;\n  }\n};\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"workway\",\n  \"version\": \"0.5.5\",\n  \"description\": \"A general purpose, Web Worker driven, remote namespace with classes and methods.\",\n  \"unpkg\": \"min.js\",\n  \"main\": \"cjs/index.js\",\n  \"module\": \"esm/index.js\",\n  \"scripts\": {\n    \"$\": \"npm-dollar\",\n    \"build\": \"npm-dollar build\",\n    \"bundle\": \"npm-dollar bundle\",\n    \"size\": \"npm-dollar size\",\n    \"test\": \"npm-dollar test\"\n  },\n  \"$\": {\n    \"build\": [\n      \"$ remoted\",\n      \"$ bundle\",\n      \"$ test\",\n      \"$ size\"\n    ],\n    \"bundle\": {\n      \"cjs\": [\n        \"cp index.js cjs/\",\n        \"echo 'module.exports = workway;' >> cjs/index.js\"\n      ],\n      \"esm\": [\n        \"cp index.js esm/\",\n        \"echo 'export default workway;' >> esm/index.js\"\n      ],\n      \"min\": \"uglifyjs index.js --comments=/^!/ -m -c -o min.js\",\n      \"node\": [\n        [\n          \"node -e 'fs.writeFileSync(\\\"worker.js\\\",\",\n          \"fs.readFileSync(\\\"partial/worker.js\\\").toString().replace(/^(\\\\s*)\\\\/\\\\/js:(\\\\w+)/gm,\",\n          \"(o,s,k)=>fs.readFileSync(k+\\\".js\\\").toString().trim().replace(/^/gm,s)))'\"\n        ]\n      ]\n    },\n    \"remoted\": {\n      \"cjs\": [\n        \"cp remoted.js cjs/\",\n        \"echo 'module.exports = remoted;' >> cjs/remoted.js\"\n      ],\n      \"esm\": [\n        \"cp remoted.js esm/\",\n        \"echo 'export default remoted;' >> esm/remoted.js\"\n      ]\n    },\n    \"size\": [\n      [\n        \"cat index.js |\",\n        \"wc -c;cat min.js |\",\n        \"wc -c;gzip -c9 min.js |\",\n        \"wc -c;cat min.js |\",\n        \"brotli |\",\n        \"wc -c && rm -f min.js.br\"\n      ]\n    ],\n    \"test\": [\n      \"cd test\",\n      \"node index.js\",\n      \"echo $(tput bold)OK$(tput sgr0)\"\n    ]\n  },\n  \"author\": \"Andrea Giammarchi\",\n  \"license\": \"ISC\",\n  \"devDependencies\": {\n    \"express\": \"^4.17.1\",\n    \"npm-dollar\": \"^2.2.1\",\n    \"uglify-js\": \"^3.6.0\"\n  },\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/WebReflection/workway.git\"\n  },\n  \"keywords\": [\n    \"web\",\n    \"worker\",\n    \"remote\",\n    \"namespace\",\n    \"driven\"\n  ],\n  \"bugs\": {\n    \"url\": \"https://github.com/WebReflection/workway/issues\"\n  },\n  \"homepage\": \"https://github.com/WebReflection/workway#readme\",\n  \"dependencies\": {\n    \"flatted\": \"^2.0.0\",\n    \"pocket.io\": \"^0.1.4\"\n  }\n}\n"
  },
  {
    "path": "partial/worker.js",
    "content": "(function () {'use strict';\n  /*! (c) 2018 Andrea Giammarchi (ISC) */\n  function walkThrough(O, K) { return O[K]; }\n  var namespace;\n  var channels = {};\n  var instances = {};\n  var onceExposed = new Promise(function (resolve) {\n    self.workway = function workway(exposed) {\n      return Promise.resolve(exposed).then(function (result) {\n        namespace = result;\n        resolve(remoted(result));\n      });\n    };\n    //js:remoted\n  });\n  self.addEventListener('message', function (event) {\n    var method;\n    var data = event.data;\n    var channel = data.channel;\n    var message = data.message;\n    if (channels[channel]) {\n      event.stopImmediatePropagation();\n      var id = message.id;\n      var path = message.path;\n      var args = message.args;\n      var resolved = function (result) { send({result: result}); };\n      var rejected = function (error) {\n        if (\n          error != null &&\n          typeof error === 'object' &&\n          'message' in error\n        )\n          send({error: {\n            stack: error.stack,\n            message: error.message\n          }});\n        else\n          send({error: {source: error}});\n      };\n      var send = function (message) {\n        message.id = id;\n        self.postMessage({\n          channel: channel,\n          message: message\n        });\n      };\n      try {\n        if (message.hasOwnProperty('method')) {\n          method = message.method;\n          var Class = path.reduce(walkThrough, namespace);\n          if (!Class)\n            return rejected('Unknown Class ' + path.join('.'));\n          if (message.hasOwnProperty('object')) {\n            var object = message.object;\n            var instance = instances[object.id] ||\n                            (instances[object.id] = new Class);\n            if (method === 'destroy')\n              delete instances[object.id];\n            else {\n              Object.keys(object.value)\n                    .forEach(function (key) {\n                      instance[key] = object.value[key];\n                    });\n              Promise.resolve(instance[method].apply(instance, args))\n                      .then(resolved, rejected);\n            }\n          } else {\n            Promise.resolve(Class[method].apply(Class, args))\n                    .then(resolved, rejected);\n          }\n        } else {\n          var context = path.slice(0, -1).reduce(walkThrough, namespace);\n          if (!context)\n            return rejected('Unknown namespace ' + path.slice(0, -1).join('.'));\n          method = path[path.length - 1];\n          if (typeof context[method] !== 'function')\n            return rejected('Unknown method ' + path.join('.'));\n          Promise.resolve(context[method].apply(context, args))\n                  .then(resolved, rejected);\n        }\n      } catch(error) {\n        rejected(error);\n      }\n    } else if (/^(-?\\d+\\.\\d+)$/.test(channel)) {\n      channels[channel] = true;\n      event.stopImmediatePropagation();\n      onceExposed.then(function (namespace) {\n        self.postMessage({\n          channel: channel,\n          namespace: namespace\n        });\n      });\n    }\n  });\n}());\n"
  },
  {
    "path": "remoted.js",
    "content": "function remoted(object) {\n  return function $(object, current, remote) {\n    Object.keys(object).forEach(function (key) {\n      var value = object[key];\n      var path = current.concat(key);\n      if (typeof value === 'function') {\n        remote[key] = /^[A-Z]/.test(key) ?\n          {\n            type: 'class',\n            path: path,\n            methods: Object.getOwnPropertyNames(value.prototype)\n                            .filter(no(['constructor']))\n                            .concat('destroy'),\n            statics: Object.getOwnPropertyNames(value)\n                            .filter(no([\n                              'arguments', 'callee', 'caller',\n                              'length', 'name', 'prototype'\n                            ]))\n                            .reduce(\n                              function (info, key) {\n                                if (typeof value[key] === 'function') {\n                                  info.methods.push(key);\n                                } else {\n                                  info.values.push([key, value[key]]);\n                                }\n                                return info;\n                              },\n                              {\n                                methods: [],\n                                values: []\n                              }\n                            )\n          } :\n          {\n            type: 'function',\n            path: path\n          };\n      } else if (remote.toString.call(value) === '[object Object]') {\n        remote[key] = {\n          type: 'object',\n          path: path,\n          value: {}\n        };\n        $(value, path, remote[key].value);\n      } else if (value !== void 0) {\n        remote[key] = {\n          type: 'any',\n          path: path,\n          value: value\n        };\n      }\n    });\n    return remote;\n  }(object, [], {});\n  function no(within) {\n    return function (what) {\n      return within.indexOf(what) < 0;\n    };\n  }\n}\n"
  },
  {
    "path": "test/background.js",
    "content": "// a Blackberry gotcha, no console in workers\nif (!self.console) self.console = {log: function () {}, error: function () {}};\n// import the polyfill you prefer for IE11 or IE10\nif (!self.Promise) importScripts('https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.auto.min.js');\nif (!self.WeakMap) importScripts('https://unpkg.com/poorlyfills@0.1.1/min.js');\n\n// to avoid any possible issue with messages\n// import the remote utility n the top of your worker\nimportScripts('../worker.js');\n\n// ES2015 classes would work too\n// ( not using class for IE11 tests )\nfunction Test() {}\nTest.method = function () {\n  console.log('Test.method');\n  console.log('arguments', [].slice.call(arguments));\n  return Math.random();\n};\nTest.prototype.method = function () {\n  console.log('Test.prototype.method');\n  console.log('instance', JSON.stringify(this));\n  console.log('arguments', [].slice.call(arguments));\n  return Math.random();\n};\n\n// expose a namespace with serializable data\n// but also classes and utilities as methods/functions\nworkway({\n  test: 123,\n  array: [1, 2, 3],\n  object: {a: 'a'},\n  nested: {\n    method: function () {\n      console.log('method');\n      console.log('arguments', [].slice.call(arguments));\n      return Math.random();\n    },\n    Test: Test\n  }\n});\n\n// you can regularly post any sort of message, or listen\n// to anything you want to\nself.addEventListener('message', function (event) {\n  console.log(event.type, event.data);\n  if (event.data.hasOwnProperty('echo'))\n    self.postMessage(event.data.echo);\n});\n"
  },
  {
    "path": "test/circular/analyzer.js",
    "content": "importScripts('https://unpkg.com/workway/worker.js');\n\nworkway({\n  analyze(circular) {\n    return circular;\n  }\n});\n"
  },
  {
    "path": "test/circular/index.html",
    "content": "<!doctype html>\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n<script type=\"module\">\nimport workway from 'https://unpkg.com/workway/esm';\n\nworkway('analyzer.js').then(({namespace}) => {\n  const data = {arr: []};\n  data.arr.push(data);\n  data.data = data;\n  namespace.analyze(data)\n            .then(\n              data => {\n                if (\n                  data &&\n                  data.arr &&\n                  data.arr[0] === data &&\n                  data.arr.length === 1 &&\n                  data.data === data\n                )\n                  document.body.textContent = 'it works 🎉';\n                else\n                  throw new Error('unable to solve recursion');\n              },\n              console.error\n            );\n});\n</script>\n"
  },
  {
    "path": "test/client.js",
    "content": "workway('./background.js').then(function (info) {\n  // {worker, namespace}\n  var worker = info.worker;\n  var namespace = info.namespace;\n\n  // you can either use addEventListener\n  // or onmessage and onerror and\n  // these will never receive remote events,\n  // only user messages, and same goes if you post messages\n  // the remote logic won't ever be affected\n  worker.onmessage = function (event) { showData(event.data); };\n  worker.addEventListener('message', console.log.bind(console));\n\n  // you can also send regular messages\n  // without affecting namespace operations\n  worker.postMessage({echo: 'hello remote'});\n\n  // classes can have static methods\n  // static values, and regular prototypal methods\n  // however there are few limitations such inheritance\n  // and constructor arguments, which is always, and only\n  // the unique identifier used to pair local/remote instances\n  var instance = new namespace.nested.Test;\n\n  // properties can be added, as long as these are serializable\n  instance.test = Math.random();\n\n  // and every method of the class returns a Promise\n  // that will resolve once the instance has been updated\n  // (properties) and the method invoked,\n  // with serializable arguments\n  instance.method(1, 2, 3)\n          .then(showData, console.error.bind(console))\n          .then(function () { instance.destroy(); });\n\n  function showData(data) {\n    document.body.appendChild(\n      document.createElement('pre')\n    ).textContent = JSON.stringify(data, null, '  ');\n  }\n\n});\n"
  },
  {
    "path": "test/foo.html",
    "content": "<!doctype html>\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n<script>\nif(!this.Promise)document.write('<script src=\"https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.auto.min.js\"><'+'/script>');\nif(!this.WeakMap)document.write('<script src=\"https://unpkg.com/poorlyfills@0.1.1/min.js\"><'+'/script>');\ntry{new EventTarget}catch(e){document.write('<script src=\"https://unpkg.com/event-target@1.2.2/min.js\"><'+'/script>')}\n</script>\n<script src=\"/workway.js\"></script>\n<script src=\"/pocket.io/pocket.io.js\"></script>\n<script src=\"/workway@node.js\"></script>\n<script>\nworkway('node://foo.js').then(async ({worker, namespace:foo}) => {\n  foo.fooPromisified(\"unused\")\n    .then(console.info, console.error);\n});\n</script>"
  },
  {
    "path": "test/foo.js",
    "content": "var PORT = process.env.PORT || 3000;\n\nvar path = require('path');\nvar express = require('express');\nvar workway = require('../node').authorize(\n  path.resolve(__dirname, 'workers')\n);\n\nvar app = workway.app(express());\napp.get('/', function (req, res) {\n  res.writeHead(200, 'OK', {\n    'Content-Type': 'text/html; charset=utf-8'\n  });\n  res.end(require('fs').readFileSync(path.resolve(__dirname, 'foo.html')));\n});\napp.get('/workway.js', function (req, res) {\n  res.writeHead(200, 'OK', {\n    'Content-Type': 'application/javascript; charset=utf-8'\n  });\n  res.end(require('fs').readFileSync(path.resolve(__dirname, '..', 'min.js')));\n});\napp.listen(PORT, () => {\n  console.log('listening on http://localhost:' + PORT);\n});\n"
  },
  {
    "path": "test/index.html",
    "content": "<!doctype html>\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n<script>\nif(!this.Promise)document.write('<script src=\"https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.auto.min.js\"><'+'/script>');\nif(!this.WeakMap)document.write('<script src=\"https://unpkg.com/poorlyfills@0.1.1/min.js\"><'+'/script>');\n</script>\n<script src=\"../index.js\"></script>\n<script src=\"./client.js\"></script>\n"
  },
  {
    "path": "test/index.js",
    "content": "require('./webworker');\nglobal.workway = require('../cjs/index');\nrequire('./client');\n"
  },
  {
    "path": "test/node.html",
    "content": "<!doctype html>\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n<script>\nif(!this.Promise)document.write('<script src=\"https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.auto.min.js\"><'+'/script>');\nif(!this.WeakMap)document.write('<script src=\"https://unpkg.com/poorlyfills@0.1.1/min.js\"><'+'/script>');\ntry{new EventTarget}catch(e){document.write('<script src=\"https://unpkg.com/event-target@1.2.2/min.js\"><'+'/script>')}\n</script>\n<script src=\"/workway.js\"></script>\n<script src=\"/pocket.io/pocket.io.js\"></script>\n<script src=\"/workway@node.js\"></script>\n<script>\n// handy protocol to differentiate between client-side workers\n// and NodeJS driven workers (must be authorized on nodejs side)\nworkway('node://test.js').then(({worker, namespace}) => {\n  // workers have regular methods\n  worker.addEventListener('message', event => {\n    console.info(event.data);\n  });\n  worker.addEventListener('error', event => {\n    console.error(event.message);\n    console.error(event.stack);\n  });\n  // here I have exported require('os') directly\n  namespace.os.platform().then(console.log);\n  // but also some other custom method\n  namespace.ping();\n  // workers on the NodeJS side can listen too\n  worker.postMessage('hello from the Web');\n});\n</script>"
  },
  {
    "path": "test/node.js",
    "content": "var PORT = process.env.PORT || 3000;\n\nvar path = require('path');\nvar express = require('express');\nvar workway = require('../node').authorize(\n  path.resolve(__dirname, 'workers')\n);\n\nvar app = workway.app(express());\napp.get('/', function (req, res) {\n  res.writeHead(200, 'OK', {\n    'Content-Type': 'text/html; charset=utf-8'\n  });\n  res.end(require('fs').readFileSync(path.resolve(__dirname, 'node.html')));\n});\napp.get('/workway.js', function (req, res) {\n  res.writeHead(200, 'OK', {\n    'Content-Type': 'application/javascript; charset=utf-8'\n  });\n  res.end(require('fs').readFileSync(path.resolve(__dirname, '..', 'index.js')));\n});\napp.listen(PORT, () => {\n  console.log('listening on http://localhost:' + PORT);\n});\n"
  },
  {
    "path": "test/webworker.js",
    "content": "const workers = [];\n\nclass Event {\n  constructor(data) {\n    this._stopImmediatePropagation = false;\n    this.type = 'message';\n    this.data = data;\n  }\n  stopImmediatePropagation() {\n    this._stopImmediatePropagation = true;\n  }\n}\n\nglobal.Worker = class Worker extends require('events').EventEmitter {\n  constructor(file) {\n    workers.push(super());\n    require(file);\n  }\n  addEventListener(type, listener) {\n    this.on(type, listener);\n  }\n  postMessage(data) {\n    process.emit('message', new Event(data));\n  }\n};\n\nglobal.document = {\n  body: {\n    appendChild: Object\n  },\n  createElement() {\n    return {set textContent(value) {\n      console.log(value);\n    }};\n  }\n};\nglobal.importScripts = require;\nglobal.self = new Proxy(\n  {\n    addEventListener(type, listener) {\n      process.on(type, listener);\n    },\n    postMessage(data) {\n      workers.forEach(worker => worker.emit('message', new Event(data)));\n    }\n  },\n  {\n    get: (self, key) => self[key] || global[key],\n    set: (self, key, value) => {\n      global[key] = value;\n      return true;\n    }\n  }\n);\n"
  },
  {
    "path": "test/workers/foo.js",
    "content": "const util = require('util');\n\nconst workway = require('workway');\n\nfunction foo(message, callback) {\n    callback(42); // forcing always an error\n}\n\nconst fooPromisified = util.promisify(foo);\n\nworkway({\n    fooPromisified\n});"
  },
  {
    "path": "test/workers/other.js",
    "content": "console.log(__filename);\n"
  },
  {
    "path": "test/workers/test.js",
    "content": "var workway = require('workway');\n\n// require('./other');\n\nworkway({\n  os: require('os'),\n  ping: function () {\n    self.postMessage('pong');\n  }\n});\n\nself.addEventListener('message', function (event) {\n  console.log(event.data);\n});\n"
  },
  {
    "path": "worker.js",
    "content": "(function () {'use strict';\n  /*! (c) 2018 Andrea Giammarchi (ISC) */\n  function walkThrough(O, K) { return O[K]; }\n  var namespace;\n  var channels = {};\n  var instances = {};\n  var onceExposed = new Promise(function (resolve) {\n    self.workway = function workway(exposed) {\n      return Promise.resolve(exposed).then(function (result) {\n        namespace = result;\n        resolve(remoted(result));\n      });\n    };\n    function remoted(object) {\n      return function $(object, current, remote) {\n        Object.keys(object).forEach(function (key) {\n          var value = object[key];\n          var path = current.concat(key);\n          if (typeof value === 'function') {\n            remote[key] = /^[A-Z]/.test(key) ?\n              {\n                type: 'class',\n                path: path,\n                methods: Object.getOwnPropertyNames(value.prototype)\n                                .filter(no(['constructor']))\n                                .concat('destroy'),\n                statics: Object.getOwnPropertyNames(value)\n                                .filter(no([\n                                  'arguments', 'callee', 'caller',\n                                  'length', 'name', 'prototype'\n                                ]))\n                                .reduce(\n                                  function (info, key) {\n                                    if (typeof value[key] === 'function') {\n                                      info.methods.push(key);\n                                    } else {\n                                      info.values.push([key, value[key]]);\n                                    }\n                                    return info;\n                                  },\n                                  {\n                                    methods: [],\n                                    values: []\n                                  }\n                                )\n              } :\n              {\n                type: 'function',\n                path: path\n              };\n          } else if (remote.toString.call(value) === '[object Object]') {\n            remote[key] = {\n              type: 'object',\n              path: path,\n              value: {}\n            };\n            $(value, path, remote[key].value);\n          } else if (value !== void 0) {\n            remote[key] = {\n              type: 'any',\n              path: path,\n              value: value\n            };\n          }\n        });\n        return remote;\n      }(object, [], {});\n      function no(within) {\n        return function (what) {\n          return within.indexOf(what) < 0;\n        };\n      }\n    }\n  });\n  self.addEventListener('message', function (event) {\n    var method;\n    var data = event.data;\n    var channel = data.channel;\n    var message = data.message;\n    if (channels[channel]) {\n      event.stopImmediatePropagation();\n      var id = message.id;\n      var path = message.path;\n      var args = message.args;\n      var resolved = function (result) { send({result: result}); };\n      var rejected = function (error) {\n        if (\n          error != null &&\n          typeof error === 'object' &&\n          'message' in error\n        )\n          send({error: {\n            stack: error.stack,\n            message: error.message\n          }});\n        else\n          send({error: {source: error}});\n      };\n      var send = function (message) {\n        message.id = id;\n        self.postMessage({\n          channel: channel,\n          message: message\n        });\n      };\n      try {\n        if (message.hasOwnProperty('method')) {\n          method = message.method;\n          var Class = path.reduce(walkThrough, namespace);\n          if (!Class)\n            return rejected('Unknown Class ' + path.join('.'));\n          if (message.hasOwnProperty('object')) {\n            var object = message.object;\n            var instance = instances[object.id] ||\n                            (instances[object.id] = new Class);\n            if (method === 'destroy')\n              delete instances[object.id];\n            else {\n              Object.keys(object.value)\n                    .forEach(function (key) {\n                      instance[key] = object.value[key];\n                    });\n              Promise.resolve(instance[method].apply(instance, args))\n                      .then(resolved, rejected);\n            }\n          } else {\n            Promise.resolve(Class[method].apply(Class, args))\n                    .then(resolved, rejected);\n          }\n        } else {\n          var context = path.slice(0, -1).reduce(walkThrough, namespace);\n          if (!context)\n            return rejected('Unknown namespace ' + path.slice(0, -1).join('.'));\n          method = path[path.length - 1];\n          if (typeof context[method] !== 'function')\n            return rejected('Unknown method ' + path.join('.'));\n          Promise.resolve(context[method].apply(context, args))\n                  .then(resolved, rejected);\n        }\n      } catch(error) {\n        rejected(error);\n      }\n    } else if (/^(-?\\d+\\.\\d+)$/.test(channel)) {\n      channels[channel] = true;\n      event.stopImmediatePropagation();\n      onceExposed.then(function (namespace) {\n        self.postMessage({\n          channel: channel,\n          namespace: namespace\n        });\n      });\n    }\n  });\n}());\n"
  }
]