through2 4.0.1 → 5.0.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/test/web.js ADDED
@@ -0,0 +1,191 @@
1
+ import { transform } from '../web.js'
2
+
3
+ const decoder = new TextDecoder('ascii')
4
+ const encoder = new TextEncoder()
5
+
6
+ const eq = (actual, expected, msg) => {
7
+ if (actual !== expected) {
8
+ throw new Error(`${msg || 'eq'}: expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`)
9
+ }
10
+ }
11
+
12
+ const deepEq = (actual, expected, msg) => {
13
+ if (JSON.stringify(actual) !== JSON.stringify(expected)) {
14
+ throw new Error(`${msg || 'deepEq'}: expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`)
15
+ }
16
+ }
17
+
18
+ const concat = (chunks) => {
19
+ let total = 0
20
+ for (const c of chunks) total += c.length
21
+ const out = new Uint8Array(total)
22
+ let i = 0
23
+ for (const c of chunks) { out.set(c, i); i += c.length }
24
+ return out
25
+ }
26
+
27
+ const collect = async (readable) => {
28
+ const reader = readable.getReader()
29
+ const out = []
30
+ while (true) {
31
+ const { value, done } = await reader.read()
32
+ if (done) return out
33
+ out.push(value)
34
+ }
35
+ }
36
+
37
+ const pipeThrough = (input, ts) => {
38
+ const r = new ReadableStream({
39
+ start (controller) {
40
+ for (const chunk of input) controller.enqueue(chunk)
41
+ controller.close()
42
+ }
43
+ })
44
+ return collect(r.pipeThrough(ts))
45
+ }
46
+
47
+ export async function classicControllerEnqueue () {
48
+ const ts = transform((chunk, controller) => {
49
+ controller.enqueue(chunk)
50
+ controller.enqueue(chunk)
51
+ })
52
+ const out = await pipeThrough([encoder.encode('a'), encoder.encode('b')], ts)
53
+ eq(decoder.decode(concat(out)), 'aabb')
54
+ }
55
+
56
+ export async function asyncReturnedValueEnqueued () {
57
+ const ts = transform(async (chunk) => chunk % 2 === 0 ? chunk : undefined)
58
+ const out = await pipeThrough([0, 1, 2, 3, 4], ts)
59
+ deepEq(out, [0, 2, 4])
60
+ }
61
+
62
+ export async function asyncgenFanOut () {
63
+ const ts = transform(async function * (source) {
64
+ for await (const chunk of source) {
65
+ yield chunk
66
+ yield chunk
67
+ }
68
+ })
69
+ const out = await pipeThrough(['a', 'b'], ts)
70
+ deepEq(out, ['a', 'a', 'b', 'b'])
71
+ }
72
+
73
+ export async function asyncgenFilter () {
74
+ const ts = transform(async function * (source) {
75
+ for await (const chunk of source) if (chunk % 2 === 0) yield chunk
76
+ })
77
+ const out = await pipeThrough([0, 1, 2, 3, 4, 5], ts)
78
+ deepEq(out, [0, 2, 4])
79
+ }
80
+
81
+ export async function flushClassic () {
82
+ const ts = transform(
83
+ (chunk, controller) => controller.enqueue(chunk),
84
+ (controller) => controller.enqueue('END')
85
+ )
86
+ const out = await pipeThrough(['a', 'b'], ts)
87
+ deepEq(out, ['a', 'b', 'END'])
88
+ }
89
+
90
+ export async function flushAsync () {
91
+ const ts = transform(
92
+ async (chunk) => chunk,
93
+ async () => 'END'
94
+ )
95
+ const out = await pipeThrough(['x'], ts)
96
+ deepEq(out, ['x', 'END'])
97
+ }
98
+
99
+ export async function asyncRejectedPropagates () {
100
+ const ts = transform(async () => { throw new Error('boom') })
101
+ const r = new ReadableStream({
102
+ start (controller) { controller.enqueue('x'); controller.close() }
103
+ })
104
+ let err
105
+ try { await collect(r.pipeThrough(ts)) } catch (e) { err = e }
106
+ if (!err) throw new Error('expected error')
107
+ eq(err.message, 'boom')
108
+ }
109
+
110
+ export async function asyncgenThrownPropagates () {
111
+ const ts = transform(async function * () { throw new Error('gen-boom') })
112
+ const r = new ReadableStream({
113
+ start (controller) { controller.enqueue('x'); controller.close() }
114
+ })
115
+ let err
116
+ try { await collect(r.pipeThrough(ts)) } catch (e) { err = e }
117
+ if (!err) throw new Error('expected error')
118
+ eq(err.message, 'gen-boom')
119
+ }
120
+
121
+ export async function noopDefault () {
122
+ const ts = transform()
123
+ const out = await pipeThrough(['a', 'b', 'c'], ts)
124
+ deepEq(out, ['a', 'b', 'c'])
125
+ }
126
+
127
+ // Memory backpressure: a slow async generator with many fast upstream chunks
128
+ // must not let the internal queue grow unbounded. The transform method holds
129
+ // when its queue is full, propagating backpressure through pipeThrough.
130
+ export async function asyncgenWritableBackpressure () {
131
+ const ts = transform(async function * (source) {
132
+ for await (const x of source) {
133
+ await new Promise((resolve) => setTimeout(resolve, 2))
134
+ yield x
135
+ }
136
+ })
137
+ const N = 200
138
+ const r = new ReadableStream({
139
+ start (controller) {
140
+ for (let i = 0; i < N; i++) controller.enqueue(i)
141
+ controller.close()
142
+ }
143
+ })
144
+ const out = await collect(r.pipeThrough(ts))
145
+ deepEq(out, Array.from({ length: N }, (_, i) => i))
146
+ }
147
+
148
+ // Reader cancel must finalize the user's async generator: its `finally`
149
+ // block must run so resources can be released.
150
+ export async function asyncgenCancelRunsFinally () {
151
+ let finalized = false
152
+ const ts = transform(async function * (source) {
153
+ try {
154
+ for await (const x of source) yield x
155
+ } finally {
156
+ finalized = true
157
+ }
158
+ })
159
+ const r = new ReadableStream({
160
+ start (controller) { controller.enqueue('a') }
161
+ // intentionally never closes; reader will cancel
162
+ })
163
+ const out = r.pipeThrough(ts)
164
+ const reader = out.getReader()
165
+ await reader.read()
166
+ await new Promise((resolve) => setTimeout(resolve, 20))
167
+ await reader.cancel()
168
+ await new Promise((resolve) => setTimeout(resolve, 20))
169
+ if (!finalized) throw new Error('generator finally must run on cancel')
170
+ }
171
+
172
+ // Downstream backpressure: a fast generator emitting many chunks, with a
173
+ // slow reader, must not flood the readable buffer unboundedly.
174
+ export async function asyncgenReaderBackpressure () {
175
+ const ts = transform(async function * (source) {
176
+ // eslint-disable-next-line no-unused-vars
177
+ for await (const _ of source) for (let i = 0; i < 50; i++) yield i
178
+ })
179
+ const r = new ReadableStream({
180
+ start (controller) { controller.enqueue('go'); controller.close() }
181
+ })
182
+ const reader = r.pipeThrough(ts).getReader()
183
+ const out = []
184
+ while (true) {
185
+ const { value, done } = await reader.read()
186
+ if (done) break
187
+ out.push(value)
188
+ await new Promise((resolve) => setTimeout(resolve, 1)) // slow reader
189
+ }
190
+ deepEq(out, Array.from({ length: 50 }, (_, i) => i))
191
+ }
package/through2.js CHANGED
@@ -1,83 +1,293 @@
1
- const { Transform } = require('readable-stream')
1
+ /**
2
+ * @file Tiny utilities for inserting transformation logic into Node.js stream
3
+ * pipelines without subclassing `Transform`. Exports `transform`,
4
+ * `objectTransform`, `transformer`. See `through2/web` for the Web Streams
5
+ * variant.
6
+ */
2
7
 
3
- function inherits (fn, sup) {
4
- fn.super_ = sup
5
- fn.prototype = Object.create(sup.prototype, {
6
- constructor: { value: fn, enumerable: false, writable: true, configurable: true }
7
- })
8
- }
8
+ import { Transform } from 'readable-stream'
9
9
 
10
- // create a new export function, used by both the main export and
11
- // the .ctor export, contains common logic for dealing with arguments
12
- function through2 (construct) {
13
- return (options, transform, flush) => {
14
- if (typeof options === 'function') {
15
- flush = transform
16
- transform = options
17
- options = {}
18
- }
10
+ /** @typedef {(chunk: any, encoding: BufferEncoding, callback: (err?: Error | null, data?: any) => void) => void} ClassicTransformFn */
11
+ /** @typedef {(chunk: any, encoding: BufferEncoding) => any | Promise<any>} AsyncTransformFn */
12
+ /** @typedef {(source: AsyncIterable<any>) => AsyncGenerator<any, void, void>} AsyncGenTransformFn */
13
+ /** @typedef {ClassicTransformFn | AsyncTransformFn | AsyncGenTransformFn} TransformFn */
14
+ /** @typedef {(callback: (err?: Error | null) => void) => void} ClassicFlushFn */
15
+ /** @typedef {() => any | Promise<any>} AsyncFlushFn */
16
+ /** @typedef {ClassicFlushFn | AsyncFlushFn} FlushFn */
17
+ /** @typedef {import('readable-stream').TransformOptions} TransformOptions */
19
18
 
20
- if (typeof transform !== 'function') {
21
- // noop
22
- transform = (chunk, enc, cb) => cb(null, chunk)
23
- }
19
+ const AsyncFunction = async function () {}.constructor
20
+ const AsyncGeneratorFunction = async function * () {}.constructor
24
21
 
25
- if (typeof flush !== 'function') {
26
- flush = null
27
- }
22
+ /**
23
+ * @param {Function} fn
24
+ * @returns {'async' | 'asyncgen' | 'classic'}
25
+ */
26
+ function fnKind (fn) {
27
+ if (fn instanceof AsyncGeneratorFunction) return 'asyncgen'
28
+ if (fn instanceof AsyncFunction) return 'async'
29
+ return 'classic'
30
+ }
28
31
 
29
- return construct(options, transform, flush)
32
+ /**
33
+ * @param {TransformOptions | TransformFn} [options]
34
+ * @param {TransformFn} [transform]
35
+ * @param {FlushFn} [flush]
36
+ * @returns {{ options: TransformOptions, transform: TransformFn, flush: FlushFn | null }}
37
+ */
38
+ function resolveArgs (options, transform, flush) {
39
+ if (typeof options === 'function') {
40
+ flush = /** @type {FlushFn} */ (transform)
41
+ transform = options
42
+ options = {}
43
+ }
44
+ if (typeof transform !== 'function') {
45
+ /** @type {ClassicTransformFn} */
46
+ const passthrough = (chunk, _enc, cb) => cb(null, chunk)
47
+ transform = passthrough
30
48
  }
49
+ return { options: options || {}, transform, flush: typeof flush === 'function' ? flush : null }
31
50
  }
32
51
 
33
- // main export, just make me a transform stream!
34
- const make = through2((options, transform, flush) => {
35
- const t2 = new Transform(options)
52
+ /**
53
+ * @param {import('readable-stream').Transform} t
54
+ * @param {TransformFn} transformFn
55
+ * @param {FlushFn | null} flushFn
56
+ */
57
+ function setupTransform (t, transformFn, flushFn) {
58
+ const tKind = fnKind(transformFn)
36
59
 
37
- t2._transform = transform
38
-
39
- if (flush) {
40
- t2._flush = flush
60
+ if (tKind === 'asyncgen') {
61
+ setupAsyncGen(t, /** @type {AsyncGenTransformFn} */ (transformFn), flushFn)
62
+ return
41
63
  }
42
64
 
43
- return t2
44
- })
65
+ if (tKind === 'async') {
66
+ const fn = /** @type {AsyncTransformFn} */ (transformFn)
67
+ t._transform = function (chunk, enc, cb) {
68
+ ;(async () => fn.call(this, chunk, enc))().then(
69
+ (out) => cb(null, out),
70
+ (err) => cb(err)
71
+ )
72
+ }
73
+ } else {
74
+ t._transform = /** @type {ClassicTransformFn} */ (transformFn)
75
+ }
45
76
 
46
- // make me a reusable prototype that I can `new`, or implicitly `new`
47
- // with a constructor call
48
- const ctor = through2((options, transform, flush) => {
49
- function Through2 (override) {
50
- if (!(this instanceof Through2)) {
51
- return new Through2(override)
77
+ if (flushFn) {
78
+ if (fnKind(flushFn) === 'async') {
79
+ const fn = /** @type {AsyncFlushFn} */ (flushFn)
80
+ t._flush = function (cb) {
81
+ ;(async () => fn.call(this))().then(
82
+ (out) => { if (out !== undefined) this.push(out); cb() },
83
+ (err) => cb(err)
84
+ )
85
+ }
86
+ } else {
87
+ t._flush = /** @type {ClassicFlushFn} */ (flushFn)
52
88
  }
89
+ }
90
+ }
53
91
 
54
- this.options = Object.assign({}, options, override)
92
+ /**
93
+ * Drive an async-generator transform. Incoming chunks are queued and exposed
94
+ * as an async-iterable source; yielded values are pushed downstream. Honours
95
+ * backpressure on both sides: writes pause when the queue reaches the
96
+ * writable HWM; the consumer pauses when `t.push()` reports a full readable
97
+ * buffer (resumed by the next `_read()` call).
98
+ *
99
+ * @param {import('readable-stream').Transform} t
100
+ * @param {AsyncGenTransformFn} gen
101
+ * @param {FlushFn | null} flushFn
102
+ */
103
+ function setupAsyncGen (t, gen, flushFn) {
104
+ /** @type {any[]} */
105
+ const queue = []
106
+ /** @type {Array<(value?: any) => void>} */
107
+ const sourceWakeups = []
108
+ /** @type {Array<(value?: any) => void>} */
109
+ const writeWaiters = []
110
+ /** @type {Array<(value?: any) => void>} */
111
+ const readWaiters = []
112
+ let writableEnded = false
113
+ /** @type {{ cb: Function | null }} */
114
+ const flushState = { cb: null }
55
115
 
56
- Transform.call(this, this.options)
116
+ const writableHWM = t.writableHighWaterMark ?? 16
57
117
 
58
- this._transform = transform
59
- if (flush) {
60
- this._flush = flush
118
+ const wakeOne = (/** @type {Array<(value?: any) => void>} */ arr) => {
119
+ const w = arr.shift()
120
+ if (w) w()
121
+ }
122
+ const wakeAll = (/** @type {Array<(value?: any) => void>} */ arr) => {
123
+ while (arr.length) /** @type {(value?: any) => void} */ (arr.shift())()
124
+ }
125
+
126
+ const source = (async function * () {
127
+ while (true) {
128
+ while (queue.length > 0) {
129
+ yield queue.shift()
130
+ wakeOne(writeWaiters)
131
+ }
132
+ if (writableEnded) return
133
+ await new Promise((resolve) => { sourceWakeups.push(resolve) })
61
134
  }
135
+ })()
136
+
137
+ t._transform = function (chunk, _enc, cb) {
138
+ queue.push(chunk)
139
+ wakeOne(sourceWakeups)
140
+ if (queue.length >= writableHWM) writeWaiters.push(cb)
141
+ else cb()
62
142
  }
63
143
 
64
- inherits(Through2, Transform)
144
+ t._flush = function (cb) {
145
+ flushState.cb = cb
146
+ writableEnded = true
147
+ wakeOne(sourceWakeups)
148
+ }
149
+
150
+ // Default Transform._read drives _transform pull semantics, which we
151
+ // bypass. We use it solely as the "downstream wants more" signal.
152
+ t._read = function () { wakeAll(readWaiters) }
153
+
154
+ // On destroy/close, end the source iterable so the user's `for await`
155
+ // unwinds (running its `finally`) and our consumer loop exits.
156
+ t.once('close', () => {
157
+ writableEnded = true
158
+ wakeAll(sourceWakeups); wakeAll(readWaiters); wakeAll(writeWaiters)
159
+ })
65
160
 
66
- return Through2
67
- })
161
+ ;(async () => {
162
+ try {
163
+ for await (const out of gen(source)) {
164
+ if (t.destroyed) return
165
+ if (!t.push(out)) {
166
+ await new Promise((resolve) => { readWaiters.push(resolve) })
167
+ }
168
+ }
169
+ if (t.destroyed) return
170
+ if (flushFn) {
171
+ if (fnKind(flushFn) === 'async') {
172
+ const out = await /** @type {AsyncFlushFn} */ (flushFn).call(t)
173
+ if (out !== undefined && !t.push(out)) {
174
+ await new Promise((resolve) => { readWaiters.push(resolve) })
175
+ }
176
+ } else {
177
+ await new Promise((resolve, reject) => {
178
+ /** @type {ClassicFlushFn} */ (flushFn).call(t, (err) => err ? reject(err) : resolve(undefined))
179
+ })
180
+ }
181
+ }
182
+ if (flushState.cb) flushState.cb()
183
+ } catch (err) {
184
+ if (flushState.cb) flushState.cb(/** @type {Error} */ (err))
185
+ else t.destroy(/** @type {Error} */ (err))
186
+ }
187
+ })()
188
+ }
68
189
 
69
- const obj = through2(function (options, transform, flush) {
70
- const t2 = new Transform(Object.assign({ objectMode: true, highWaterMark: 16 }, options))
190
+ /**
191
+ * Build a Transform around a transformation function (classic / async / async
192
+ * generator; auto-dispatched).
193
+ *
194
+ * @example Classic
195
+ * transform(function (chunk, _enc, cb) { this.push(chunk); cb() })
196
+ * @example Async
197
+ * transform(async (chunk) => chunk.toString().toUpperCase())
198
+ * @example Async generator (1-to-many; cross-chunk state is just a local var)
199
+ * transform(async function * (source) {
200
+ * let buf = ''
201
+ * for await (const chunk of source) {
202
+ * buf += chunk.toString()
203
+ * const lines = buf.split('\n')
204
+ * buf = lines.pop()
205
+ * for (const line of lines) yield line
206
+ * }
207
+ * if (buf) yield buf
208
+ * })
209
+ *
210
+ * @param {TransformOptions | TransformFn} [options]
211
+ * @param {TransformFn} [transformFn]
212
+ * @param {FlushFn} [flushFn]
213
+ * @returns {import('readable-stream').Transform}
214
+ */
215
+ export function transform (options, transformFn, flushFn) {
216
+ const args = resolveArgs(options, transformFn, flushFn)
217
+ const t = new Transform(args.options)
218
+ setupTransform(t, args.transform, args.flush)
219
+ return t
220
+ }
71
221
 
72
- t2._transform = transform
222
+ /**
223
+ * Like {@link transform}, with `objectMode: true` by default.
224
+ *
225
+ * @example Filter
226
+ * objectTransform(async (item) => predicate(item) ? item : undefined)
227
+ * @example Batch
228
+ * objectTransform(async function * (source) {
229
+ * let batch = []
230
+ * for await (const item of source) {
231
+ * batch.push(item)
232
+ * if (batch.length >= 100) { yield batch; batch = [] }
233
+ * }
234
+ * if (batch.length) yield batch
235
+ * })
236
+ *
237
+ * @param {TransformOptions | TransformFn} [options]
238
+ * @param {TransformFn} [transformFn]
239
+ * @param {FlushFn} [flushFn]
240
+ * @returns {import('readable-stream').Transform}
241
+ */
242
+ export function objectTransform (options, transformFn, flushFn) {
243
+ const args = resolveArgs(options, transformFn, flushFn)
244
+ const t = new Transform({ objectMode: true, highWaterMark: 16, ...args.options })
245
+ setupTransform(t, args.transform, args.flush)
246
+ return t
247
+ }
73
248
 
74
- if (flush) {
75
- t2._flush = flush
249
+ /**
250
+ * Build a reusable factory. The returned function works with or without
251
+ * `new`; per-call options merge over the configured defaults and are exposed
252
+ * as `this.options` inside the transform.
253
+ *
254
+ * Note: in v5 this returns a Transform instance directly, not a true
255
+ * constructor; `instanceof FactoryFn` no longer holds (`instanceof Transform`
256
+ * still does).
257
+ *
258
+ * @example
259
+ * const Counter = transformer({ objectMode: true }, function (chunk, _enc, cb) {
260
+ * this.count = (this.count || 0) + 1
261
+ * this.push(chunk); cb()
262
+ * })
263
+ * const a = Counter()
264
+ * const b = new Counter({ highWaterMark: 32 })
265
+ *
266
+ * @param {TransformOptions | TransformFn} [options]
267
+ * @param {TransformFn} [transformFn]
268
+ * @param {FlushFn} [flushFn]
269
+ * @returns {(override?: TransformOptions) => import('readable-stream').Transform & { options: TransformOptions }}
270
+ */
271
+ export function transformer (options, transformFn, flushFn) {
272
+ const args = resolveArgs(options, transformFn, flushFn)
273
+ return function make (override) {
274
+ const merged = { ...args.options, ...override }
275
+ const t = /** @type {import('readable-stream').Transform & { options: TransformOptions }} */ (
276
+ new Transform(merged)
277
+ )
278
+ t.options = merged
279
+ setupTransform(t, args.transform, args.flush)
280
+ return t
76
281
  }
282
+ }
77
283
 
78
- return t2
79
- })
284
+ /**
285
+ * Default export: `transform` with legacy `.obj` / `.ctor` for v4
286
+ * back-compatibility.
287
+ * @type {typeof transform & { obj: typeof objectTransform, ctor: typeof transformer }}
288
+ */
289
+ const through2 = /** @type {any} */ (transform)
290
+ through2.obj = objectTransform
291
+ through2.ctor = transformer
80
292
 
81
- module.exports = make
82
- module.exports.ctor = ctor
83
- module.exports.obj = obj
293
+ export default through2
package/tsconfig.json ADDED
@@ -0,0 +1,25 @@
1
+ {
2
+ "compilerOptions": {
3
+ "allowJs": true,
4
+ "checkJs": true,
5
+ "strict": true,
6
+ "esModuleInterop": true,
7
+ "target": "ESNext",
8
+ "module": "nodenext",
9
+ "moduleResolution": "nodenext",
10
+ "skipLibCheck": true,
11
+ "types": ["node"],
12
+ "declaration": true,
13
+ "declarationMap": true,
14
+ "emitDeclarationOnly": true,
15
+ "outDir": "types"
16
+ },
17
+ "include": [
18
+ "through2.js",
19
+ "web.js"
20
+ ],
21
+ "exclude": [
22
+ "node_modules",
23
+ "test"
24
+ ]
25
+ }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Build a Transform around a transformation function (classic / async / async
3
+ * generator; auto-dispatched).
4
+ *
5
+ * @example Classic
6
+ * transform(function (chunk, _enc, cb) { this.push(chunk); cb() })
7
+ * @example Async
8
+ * transform(async (chunk) => chunk.toString().toUpperCase())
9
+ * @example Async generator (1-to-many; cross-chunk state is just a local var)
10
+ * transform(async function * (source) {
11
+ * let buf = ''
12
+ * for await (const chunk of source) {
13
+ * buf += chunk.toString()
14
+ * const lines = buf.split('\n')
15
+ * buf = lines.pop()
16
+ * for (const line of lines) yield line
17
+ * }
18
+ * if (buf) yield buf
19
+ * })
20
+ *
21
+ * @param {TransformOptions | TransformFn} [options]
22
+ * @param {TransformFn} [transformFn]
23
+ * @param {FlushFn} [flushFn]
24
+ * @returns {import('readable-stream').Transform}
25
+ */
26
+ export function transform(options?: TransformOptions | TransformFn, transformFn?: TransformFn, flushFn?: FlushFn): import("readable-stream").Transform;
27
+ /**
28
+ * Like {@link transform}, with `objectMode: true` by default.
29
+ *
30
+ * @example Filter
31
+ * objectTransform(async (item) => predicate(item) ? item : undefined)
32
+ * @example Batch
33
+ * objectTransform(async function * (source) {
34
+ * let batch = []
35
+ * for await (const item of source) {
36
+ * batch.push(item)
37
+ * if (batch.length >= 100) { yield batch; batch = [] }
38
+ * }
39
+ * if (batch.length) yield batch
40
+ * })
41
+ *
42
+ * @param {TransformOptions | TransformFn} [options]
43
+ * @param {TransformFn} [transformFn]
44
+ * @param {FlushFn} [flushFn]
45
+ * @returns {import('readable-stream').Transform}
46
+ */
47
+ export function objectTransform(options?: TransformOptions | TransformFn, transformFn?: TransformFn, flushFn?: FlushFn): import("readable-stream").Transform;
48
+ /**
49
+ * Build a reusable factory. The returned function works with or without
50
+ * `new`; per-call options merge over the configured defaults and are exposed
51
+ * as `this.options` inside the transform.
52
+ *
53
+ * Note: in v5 this returns a Transform instance directly, not a true
54
+ * constructor; `instanceof FactoryFn` no longer holds (`instanceof Transform`
55
+ * still does).
56
+ *
57
+ * @example
58
+ * const Counter = transformer({ objectMode: true }, function (chunk, _enc, cb) {
59
+ * this.count = (this.count || 0) + 1
60
+ * this.push(chunk); cb()
61
+ * })
62
+ * const a = Counter()
63
+ * const b = new Counter({ highWaterMark: 32 })
64
+ *
65
+ * @param {TransformOptions | TransformFn} [options]
66
+ * @param {TransformFn} [transformFn]
67
+ * @param {FlushFn} [flushFn]
68
+ * @returns {(override?: TransformOptions) => import('readable-stream').Transform & { options: TransformOptions }}
69
+ */
70
+ export function transformer(options?: TransformOptions | TransformFn, transformFn?: TransformFn, flushFn?: FlushFn): (override?: TransformOptions) => import("readable-stream").Transform & {
71
+ options: TransformOptions;
72
+ };
73
+ export default through2;
74
+ export type ClassicTransformFn = (chunk: any, encoding: BufferEncoding, callback: (err?: Error | null, data?: any) => void) => void;
75
+ export type AsyncTransformFn = (chunk: any, encoding: BufferEncoding) => any | Promise<any>;
76
+ export type AsyncGenTransformFn = (source: AsyncIterable<any>) => AsyncGenerator<any, void, void>;
77
+ export type TransformFn = ClassicTransformFn | AsyncTransformFn | AsyncGenTransformFn;
78
+ export type ClassicFlushFn = (callback: (err?: Error | null) => void) => void;
79
+ export type AsyncFlushFn = () => any | Promise<any>;
80
+ export type FlushFn = ClassicFlushFn | AsyncFlushFn;
81
+ export type TransformOptions = import("readable-stream").TransformOptions;
82
+ /**
83
+ * Default export: `transform` with legacy `.obj` / `.ctor` for v4
84
+ * back-compatibility.
85
+ * @type {typeof transform & { obj: typeof objectTransform, ctor: typeof transformer }}
86
+ */
87
+ declare const through2: typeof transform & {
88
+ obj: typeof objectTransform;
89
+ ctor: typeof transformer;
90
+ };
91
+ //# sourceMappingURL=through2.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"through2.d.ts","sourceRoot":"","sources":["../through2.js"],"names":[],"mappings":"AA6LA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,oCALW,gBAAgB,GAAG,WAAW,gBAC9B,WAAW,YACX,OAAO,GACL,OAAO,iBAAiB,EAAE,SAAS,CAO/C;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,0CALW,gBAAgB,GAAG,WAAW,gBAC9B,WAAW,YACX,OAAO,GACL,OAAO,iBAAiB,EAAE,SAAS,CAO/C;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,sCALW,gBAAgB,GAAG,WAAW,gBAC9B,WAAW,YACX,OAAO,GACL,CAAC,QAAQ,CAAC,EAAE,gBAAgB,KAAK,OAAO,iBAAiB,EAAE,SAAS,GAAG;IAAE,OAAO,EAAE,gBAAgB,CAAA;CAAE,CAahH;;iCAhRa,CAAC,KAAK,EAAE,GAAG,EAAE,QAAQ,EAAE,cAAc,EAAE,QAAQ,EAAE,CAAC,GAAG,CAAC,EAAE,KAAK,GAAG,IAAI,EAAE,IAAI,CAAC,EAAE,GAAG,KAAK,IAAI,KAAK,IAAI;+BAClG,CAAC,KAAK,EAAE,GAAG,EAAE,QAAQ,EAAE,cAAc,KAAK,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC;kCAC5D,CAAC,MAAM,EAAE,aAAa,CAAC,GAAG,CAAC,KAAK,cAAc,CAAC,GAAG,EAAE,IAAI,EAAE,IAAI,CAAC;0BAC/D,kBAAkB,GAAG,gBAAgB,GAAG,mBAAmB;6BAC3D,CAAC,QAAQ,EAAE,CAAC,GAAG,CAAC,EAAE,KAAK,GAAG,IAAI,KAAK,IAAI,KAAK,IAAI;2BAChD,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC;sBACxB,cAAc,GAAG,YAAY;+BAC7B,OAAO,iBAAiB,EAAE,gBAAgB;AA2QxD;;;;GAIG;AACH,wBAFU,OAAO,SAAS,GAAG;IAAE,GAAG,EAAE,OAAO,eAAe,CAAC;IAAC,IAAI,EAAE,OAAO,WAAW,CAAA;CAAE,CAEvC"}