thread-stream 2.0.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.husky/pre-commit CHANGED
@@ -1,4 +1,4 @@
1
- #!/bin/sh
2
- . "$(dirname "$0")/_/husky.sh"
1
+ #!/usr/bin/env sh
2
+ . "$(dirname -- "$0")/_/husky.sh"
3
3
 
4
4
  npm test
package/.taprc CHANGED
@@ -1,3 +1,4 @@
1
1
  jobs: 1
2
2
  check-coverage: false
3
- timeout: 60000
3
+ # in seconds
4
+ timeout: 60
package/README.md CHANGED
@@ -84,6 +84,31 @@ stream.end()
84
84
 
85
85
  This module works with `yarn` in PnP (plug'n play) mode too!
86
86
 
87
+ ### Emit events
88
+
89
+ You can emit events on the ThreadStream from your worker using [`worker.parentPort.postMessage()`](https://nodejs.org/api/worker_threads.html#workerparentport).
90
+ The message (JSON object) must have the following data structure:
91
+
92
+ ```js
93
+ parentPort.postMessage({
94
+ code: 'EVENT',
95
+ name: 'eventName',
96
+ args: ['list', 'of', 'args', 123, new Error('Boom')]
97
+ })
98
+ ```
99
+
100
+ On your ThreadStream, you can add a listener function for this event name:
101
+
102
+ ```js
103
+ const stream = new ThreadStream({
104
+ filename: join(__dirname, 'worker.js'),
105
+ workerData: {},
106
+ })
107
+ stream.on('eventName', function (a, b, c, n, err) {
108
+ console.log('received:', a, b, c, n, err) // received: list of args 123 Error: Boom
109
+ })
110
+ ```
111
+
87
112
  ## License
88
113
 
89
114
  MIT
package/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  'use strict'
2
2
 
3
+ const { version } = require('./package.json')
3
4
  const { EventEmitter } = require('events')
4
5
  const { Worker } = require('worker_threads')
5
6
  const { join } = require('path')
@@ -29,6 +30,7 @@ class FakeWeakRef {
29
30
 
30
31
  const FinalizationRegistry = global.FinalizationRegistry || class FakeFinalizationRegistry {
31
32
  register () {}
33
+
32
34
  unregister () {}
33
35
  }
34
36
 
@@ -55,7 +57,12 @@ function createWorker (stream, opts) {
55
57
  : pathToFileURL(filename).href,
56
58
  dataBuf: stream[kImpl].dataBuf,
57
59
  stateBuf: stream[kImpl].stateBuf,
58
- workerData
60
+ workerData: {
61
+ $context: {
62
+ threadStreamVersion: version
63
+ },
64
+ ...workerData
65
+ }
59
66
  }
60
67
  })
61
68
 
@@ -163,6 +170,13 @@ function onWorkerMessage (msg) {
163
170
  case 'ERROR':
164
171
  destroy(stream, msg.err)
165
172
  break
173
+ case 'EVENT':
174
+ if (Array.isArray(msg.args)) {
175
+ stream.emit(msg.name, ...msg.args)
176
+ } else {
177
+ stream.emit(msg.name, msg.args)
178
+ }
179
+ break
166
180
  default:
167
181
  destroy(stream, new Error('this should not happen: ' + msg.code))
168
182
  }
package/lib/worker.js CHANGED
@@ -17,7 +17,7 @@ const state = new Int32Array(stateBuf)
17
17
  const data = Buffer.from(dataBuf)
18
18
 
19
19
  async function start () {
20
- let fn
20
+ let worker
21
21
  try {
22
22
  if (filename.endsWith('.ts') || filename.endsWith('.cts')) {
23
23
  // TODO: add support for the TSM modules loader ( https://github.com/lukeed/tsm ).
@@ -28,9 +28,9 @@ async function start () {
28
28
  }
29
29
  // TODO: Support ES imports once tsc, tap & ts-node provide better compatibility guarantees.
30
30
  // Remove extra forwardslash on Windows
31
- fn = realRequire(decodeURIComponent(filename.replace(process.platform === 'win32' ? 'file:///' : 'file://', '')))
31
+ worker = realRequire(decodeURIComponent(filename.replace(process.platform === 'win32' ? 'file:///' : 'file://', '')))
32
32
  } else {
33
- fn = (await realImport(filename))
33
+ worker = (await realImport(filename))
34
34
  }
35
35
  } catch (error) {
36
36
  // A yarn user that tries to start a ThreadStream for an external module
@@ -43,7 +43,10 @@ async function start () {
43
43
  // The error codes may change based on the node.js version (ENOTDIR > 12, ERR_MODULE_NOT_FOUND <= 12 )
44
44
  if ((error.code === 'ENOTDIR' || error.code === 'ERR_MODULE_NOT_FOUND') &&
45
45
  filename.startsWith('file://')) {
46
- fn = realRequire(decodeURIComponent(filename.replace('file://', '')))
46
+ worker = realRequire(decodeURIComponent(filename.replace('file://', '')))
47
+ } else if (error.code === undefined) {
48
+ // When bundled with pkg, an undefined error is thrown when called with realImport
49
+ worker = realRequire(decodeURIComponent(filename.replace(process.platform === 'win32' ? 'file:///' : 'file://', '')))
47
50
  } else {
48
51
  throw error
49
52
  }
@@ -52,10 +55,10 @@ async function start () {
52
55
  // Depending on how the default export is performed, and on how the code is
53
56
  // transpiled, we may find cases of two nested "default" objects.
54
57
  // See https://github.com/pinojs/pino/issues/1243#issuecomment-982774762
55
- if (typeof fn === 'object') fn = fn.default
56
- if (typeof fn === 'object') fn = fn.default
58
+ if (typeof worker === 'object') worker = worker.default
59
+ if (typeof worker === 'object') worker = worker.default
57
60
 
58
- destination = await fn(workerData.workerData)
61
+ destination = await worker(workerData.workerData)
59
62
 
60
63
  destination.on('error', function (err) {
61
64
  Atomics.store(state, WRITE_INDEX, -2)
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "thread-stream",
3
- "version": "2.0.0",
3
+ "version": "2.2.0",
4
4
  "description": "A streaming way to send data to a Node.js Worker Thread",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
7
7
  "dependencies": {
8
- "real-require": "^0.1.0"
8
+ "real-require": "^0.2.0"
9
9
  },
10
10
  "devDependencies": {
11
11
  "@types/node": "^18.0.0",
@@ -5,7 +5,7 @@ const { join } = require('path')
5
5
  const { file } = require('./helper')
6
6
  const ThreadStream = require('..')
7
7
 
8
- test('bundlers support', function (t) {
8
+ test('bundlers support with .js file', function (t) {
9
9
  t.plan(1)
10
10
 
11
11
  globalThis.__bundlerPathsOverrides = {
@@ -31,3 +31,30 @@ test('bundlers support', function (t) {
31
31
 
32
32
  stream.end()
33
33
  })
34
+
35
+ test('bundlers support with .mjs file', function (t) {
36
+ t.plan(1)
37
+
38
+ globalThis.__bundlerPathsOverrides = {
39
+ 'thread-stream-worker': join(__dirname, 'custom-worker.js')
40
+ }
41
+
42
+ const dest = file()
43
+
44
+ process.on('uncaughtException', error => {
45
+ console.log(error)
46
+ })
47
+
48
+ const stream = new ThreadStream({
49
+ filename: join(__dirname, 'to-file.mjs'),
50
+ workerData: { dest },
51
+ sync: true
52
+ })
53
+
54
+ stream.worker.removeAllListeners('message')
55
+ stream.worker.once('message', message => {
56
+ t.equal(message.code, 'CUSTOM-WORKER-CALLED')
57
+ })
58
+
59
+ stream.end()
60
+ })
@@ -0,0 +1,21 @@
1
+ 'use strict'
2
+
3
+ const { test } = require('tap')
4
+ const { join } = require('path')
5
+ const ThreadStream = require('..')
6
+ const { version } = require('../package.json')
7
+ require('why-is-node-running')
8
+
9
+ test('get context', (t) => {
10
+ const stream = new ThreadStream({
11
+ filename: join(__dirname, 'get-context.js'),
12
+ workerData: {},
13
+ sync: true
14
+ })
15
+ t.on('end', () => stream.end())
16
+ stream.on('context', (ctx) => {
17
+ t.same(ctx.threadStreamVersion, version)
18
+ t.end()
19
+ })
20
+ stream.write('hello')
21
+ })
@@ -0,0 +1,22 @@
1
+ 'use strict'
2
+
3
+ const { Writable } = require('stream')
4
+ const parentPort = require('worker_threads').parentPort
5
+
6
+ async function run () {
7
+ return new Writable({
8
+ autoDestroy: true,
9
+ write (chunk, enc, cb) {
10
+ if (parentPort) {
11
+ parentPort.postMessage({
12
+ code: 'EVENT',
13
+ name: 'socketError',
14
+ args: ['list', 'of', 'args', 123, new Error('unable to write data to the TCP socket')]
15
+ })
16
+ }
17
+ cb()
18
+ }
19
+ })
20
+ }
21
+
22
+ module.exports = run
@@ -0,0 +1,24 @@
1
+ 'use strict'
2
+
3
+ const { test } = require('tap')
4
+ const { join } = require('path')
5
+ const ThreadStream = require('..')
6
+ require('why-is-node-running')
7
+
8
+ test('event propagate', (t) => {
9
+ const stream = new ThreadStream({
10
+ filename: join(__dirname, 'emit-event.js'),
11
+ workerData: {},
12
+ sync: true
13
+ })
14
+ t.on('end', () => stream.end())
15
+ stream.on('socketError', function (a, b, c, n, error) {
16
+ t.same(a, 'list')
17
+ t.same(b, 'of')
18
+ t.same(c, 'args')
19
+ t.same(n, 123)
20
+ t.same(error, new Error('unable to write data to the TCP socket'))
21
+ t.end()
22
+ })
23
+ stream.write('hello')
24
+ })
@@ -0,0 +1,22 @@
1
+ 'use strict'
2
+
3
+ const { Writable } = require('stream')
4
+ const parentPort = require('worker_threads').parentPort
5
+
6
+ async function run (opts) {
7
+ return new Writable({
8
+ autoDestroy: true,
9
+ write (chunk, enc, cb) {
10
+ if (parentPort) {
11
+ parentPort.postMessage({
12
+ code: 'EVENT',
13
+ name: 'context',
14
+ args: opts.$context
15
+ })
16
+ }
17
+ cb()
18
+ }
19
+ })
20
+ }
21
+
22
+ module.exports = run
@@ -1,6 +1,6 @@
1
1
  'use strict'
2
2
 
3
- const test = require('tape')
3
+ const { test } = require('tap')
4
4
  const indexes = require('../lib/indexes')
5
5
 
6
6
  for (const index of Object.keys(indexes)) {