{"name":"gatsby-worker","version":"2.16.0","keywords":["gatsby","worker"],"author":{"name":"Michal Piechowiak","email":"misiek.piechowiak@gmail.com"},"license":"MIT","_id":"gatsby-worker@2.16.0","maintainers":[{"name":"pieh","email":"misiek.piechowiak@gmail.com"},{"name":"mlgualtieri-gatsby","email":"mike.gualtieri@netlify.com"},{"name":"gatsby_integrations","email":"integrations-collab-squad@gatsbyjs.com"},{"name":"kathmbeck","email":"katherine.beck@netlify.com"},{"name":"seanroberts","email":"sean.roberts90@gmail.com"},{"name":"serhalp-netlify","email":"philippe.serhal@netlify.com"},{"name":"wardpeet","email":"ward@coding-tech.com"}],"homepage":"https://github.com/gatsbyjs/gatsby/tree/master/packages/gatsby-worker#readme","bugs":{"url":"https://github.com/gatsbyjs/gatsby/issues"},"dist":{"shasum":"d62a8e521fb69866b90be9ef18dd73e547359aee","tarball":"http://registry-npm.ywwl.com/gatsby-worker/download/gatsby-worker-2.16.0.tgz","fileCount":14,"integrity":"sha512-1C36ZFvhN3rX/HkO3H4hT3NMoFeaEPNjhK7rPrGU9IX3+Vm+/ry1LyYMziC3wKEeeWHNmCs2NFCBZYoBw1SzJQ==","signatures":[{"sig":"MEUCIHhIm/NJncNNbjIowA0xDLqE0mUjGdSfpt4XN3Q9ienNAiEAm4yGqznJY2TUQ/3IZ059l/c7TqfvBeC319Z/vLPeWi0=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":52217,"size":14460,"noattachment":false,"key":"/gatsby-worker/-/gatsby-worker-2.16.0.tgz"},"main":"dist/index.js","engines":{"node":">=18.0.0 <26"},"gitHead":"92d6c67dcf10b641adf5fcc81ebeec5f50b75e40","scripts":{"build":"babel src --out-dir dist/ --ignore \"**/__tests__\" --extensions \".ts,.js\"","watch":"babel -w src --out-dir dist/ --ignore \"**/__tests__\"  --extensions \".ts,.js\"","prepare":"cross-env NODE_ENV=production npm run build && npm run typegen","typegen":"rimraf --glob \"dist/**/*.d.ts\" && tsc --emitDeclarationOnly --declaration --declarationDir dist/"},"_npmUser":{"name":"serhalp-netlify","email":"philippe.serhal@netlify.com"},"repository":{"url":"git+https://github.com/gatsbyjs/gatsby.git","type":"git","directory":"packages/gatsby-worker"},"_npmVersion":"lerna/3.22.1/node@v22.19.0+arm64 (darwin)","description":"Utility to create worker pools","directories":{},"_nodeVersion":"22.19.0","dependencies":{"fs-extra":"^11.2.0","@babel/core":"^7.20.12","signal-exit":"^3.0.7","@babel/runtime":"^7.20.13"},"_hasShrinkwrap":false,"devDependencies":{"rimraf":"^5.0.5","cross-env":"^7.0.3","@babel/cli":"^7.20.7","typescript":"^5.1.6","@babel/register":"^7.18.9","babel-preset-gatsby-package":"^3.16.0"},"_npmOperationalInternal":{"tmp":"tmp/gatsby-worker_2.16.0_1769459242560_0.23764814494401398","host":"s3://npm-registry-packages-npm-production"},"readme":"# gatsby-worker\n\nUtility to execute tasks in forked processes. Highly inspired by [`jest-worker`](https://www.npmjs.com/package/jest-worker).\n\n## Example\n\nFile `worker.ts`:\n\n```ts\nexport async function heavyTask(param: string): Promise<string> {\n  // using workers is ideal for CPU intensive tasks\n  return await heavyProcessing(param)\n}\n\nexport async function setupStep(param: string): Promise<void> {\n  await heavySetup(param)\n}\n```\n\nFile `parent.ts`:\n\n```ts\nimport { WorkerPool } from \"gatsby-worker\"\n\nconst workerPool = new WorkerPool<typeof import(\"./worker\")>(\n  require.resolve(`./worker`),\n  {\n    numWorkers: 5,\n    env: {\n      CUSTOM_ENV_VAR_TO_SET_IN_WORKER: `foo`,\n    },\n    silent: false,\n  }\n)\n\n// queue a task on all workers\nconst arrayOfPromises = workerPool.all.setupStep(`bar`)\n\n// queue a task on single worker\nconst singlePromise = workerPool.single.heavyTask(`baz`)\n```\n\n## API\n\n### Constructor\n\n```ts\n// TypeOfWorkerModule allows to type exposed functions ensuring type safety.\n// It will convert sync methods to async and discard/disallow usage of exports\n// that are not functions. Recommended to use with `<typeof import(\"path_to_worker_module\")>`.\nconst workerPool = new WorkerPool<TypeOfWorkerModule>(\n  // Absolute path to worker module. Recommended to use with `require.resolve`\n  workerPath: string,\n  // Not required options\n  options?: {\n    // Number of workers to spawn. Defaults to `1` if not defined.\n    numWorkers?: number\n    // Additional env vars to set in worker. Worker will inherit env vars of parent process\n    // as well as additional `GATSBY_WORKER_ID` env var (starting with \"1\" for first worker)\n    env?: Record<string, string>,\n    // Whether or not the output from forked process should ignored. Defaults to `false` if not defined.\n    silent?: boolean,\n  }\n)\n```\n\n### `.single`\n\n```ts\n// Exports of the worker module become available under `.single` property of `WorkerPool` instance.\n// Calling those will either start executing immediately if there are any idle workers or queue them\n// to be executed once a worker become idle.\nconst singlePromise = workerPool.single.heavyTask(`baz`)\n```\n\n### `.all`\n\n```ts\n// Exports of the worker module become available under `.all` property of `WorkerPool` instance.\n// Calling those will ensure a function is executed on all workers. Best usage for this is performing\n// setup/bootstrap of workers.\nconst arrayOfPromises = workerPool.all.setupStep(`baz`)\n```\n\n### `.end`\n\n```ts\n// Used to shutdown `WorkerPool`. If there are any in progress or queued tasks, promises for those will be rejected as they won't be able to complete.\nconst arrayOfPromises = workerPool.end()\n```\n\n### `isWorker`\n\n```ts\n// Determine if current context is executed in worker context. Useful for conditional handling depending on context.\nimport { isWorker } from \"gatsby-worker\"\n\nif (isWorker) {\n  // this is executed in worker context\n} else {\n  // this is NOT executed in worker context\n}\n```\n\n### Messaging\n\n`gatsby-worker` allows sending messages from worker to main and from main to worker at any time.\n\n#### Sending messages from worker\n\nFile `message-types.ts`:\n\n```ts\n// `gatsby-worker` supports message types. Creating common module that centralize possible messages\n// that is shared by worker and parent will ensure messages type safety.\ninterface IPingMessage {\n  type: `PING`\n}\n\ninterface IAnotherMessageFromChild {\n  type: `OTHER_MESSAGE_FROM_CHILD`\n  payload: {\n    foo: string\n  }\n}\n\nexport type MessagesFromChild = IPingMessage | IAnotherMessageFromChild\n\ninterface IPongMessage {\n  type: `PONG`\n}\n\ninterface IAnotherMessageFromParent {\n  type: `OTHER_MESSAGE_FROM_PARENT`\n  payload: {\n    foo: string\n  }\n}\n\nexport type MessagesFromParent = IPongMessage | IAnotherMessageFromParent\n```\n\nFile `worker.ts`:\n\n```ts\nimport { getMessenger } from \"gatsby-worker\"\n\nimport { MessagesFromParent, MessagesFromChild } from \"./message-types\"\n\nconst messenger = getMessenger<MessagesFromParent, MessagesFromChild>()\n// messenger might be `undefined` if `getMessenger`\n// is called NOT in worker context\nif (messenger) {\n  // send a message to a parent\n  messenger.send({ type: `PING` })\n  messenger.send({\n    type: `OTHER_MESSAGE_FROM_CHILD`,\n    payload: {\n      foo: `bar`,\n    },\n  })\n\n  // following would cause type error as message like that is\n  // not part of MessagesFromChild type union\n  // messenger.send({ type: `NOT_PART_OF_TYPES` })\n\n  // start listening to messages from parent\n  messenger.onMessage(msg => {\n    switch (msg.type) {\n      case `PONG`: {\n        // handle PONG message\n        break\n      }\n      case `OTHER_MESSAGE_FROM_PARENT`: {\n        // msg.payload.foo will be typed as `string` here\n        // handle\n        break\n      }\n\n      // following would cause type error as there is no msg with\n      // given type as part of MessagesFromParent type union\n      // case `NOT_PART_OF_TYPES`: {}\n    }\n  })\n}\n```\n\nFile `parent.ts`:\n\n```ts\nimport { getMessenger } from \"gatsby-worker\"\n\nimport { MessagesFromParent, MessagesFromChild } from \"./message-types\"\n\nconst workerPool = new WorkerPool<\n  typeof import(\"./worker\"),\n  MessagesFromParent,\n  MessagesFromChild\n>(\n  workerPath: require.resolve(`./worker`)\n)\n\n// `sendMessage` on WorkerPool instance requires second parameter\n// `workerId` to specify to which worker to send message to\n// (`workerId` starts at 1 for first worker).\nworkerPool.sendMessage(\n  {\n    type: `OTHER_MESSAGE_FROM_PARENT`,\n    payload: {\n      foo: `baz`\n    }\n  },\n  1\n)\n\n// start listening to messages from child\n// `onMessage` callback will be called with message sent from worker\n// and `workerId` (to identify which worker send this message)\nworkerPool.onMessage((msg: MessagesFromChild, workerId: number): void => {\n  switch(msg.type) {\n    case: `PING`: {\n      // send message back making sure we send it back to same worker\n      // that sent `PING` message\n      workerPool.sendMessage({ type: `PONG` }, workerId)\n      break\n    }\n  }\n})\n```\n\n## Usage with unit tests\n\nIf you are working with source files that need transpilation, you will need to make it possible to load untranspiled modules in child processes.\nThis can be done with `@babel/register` (or similar depending on your build toolchain). Example setup:\n\n```ts\nconst testWorkerPool = new WorkerPool<WorkerModuleType>(workerModule, {\n  numWorkers,\n  env: {\n    NODE_OPTIONS: `--require ${require.resolve(`./ts-register`)}`,\n  },\n})\n```\n\nThis will execute additional module before allowing adding runtime support for new JavaScript syntax or support for TypeScript. Example `ts-register.js`:\n\n```js\n// spawned process won't use jest config (or other testing framework equivalent) to support TS, so we need to add support ourselves\nrequire(`@babel/register`)({\n  extensions: [`.js`, `.ts`],\n  configFile: require.resolve(relativePathToYourBabelConfig),\n  ignore: [/node_modules/],\n})\n```\n","publish_time":1769459242693,"_cnpm_publish_time":1769459242693,"dist-tags":{"alpha-9689ff":"1.23.0-alpha-9689ff.25","alpha-pqr-bootstrap":"0.1.0-alpha-pqr-bootstrap.18664","alpha-pqr-debug":"0.1.0-alpha-pqr-debug.18666","alpha-qe-sm":"0.5.0-alpha-qe-sm.46","alpha-ssr":"0.0.0-next.0","alpha-transformer-json":"1.14.0-alpha-transformer-json.26","alpha-ts-jit":"1.6.0-alpha-ts-jit.48","alpha-v5":"2.0.0-alpha-v5.d20221012t101120.57","drupal-proxyurl":"2.0.0-alpha-drupal-proxyurl.14","drupal-self-reference":"1.18.0-alpha-drupal-self-reference.18","image-service":"1.8.0-alpha-image-service.24","latest":"2.16.0","latest-v3":"0.6.0","latest-v4":"1.25.0","next":"2.17.0-next.0","preview-gh-api":"1.23.0-alpha-preview-gh-api.26","wp-image-cdn-auth":"1.15.0-alpha-wp-image-cdn-auth.48"}}