documonster 0.20.2 → 0.21.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.
Files changed (144) hide show
  1. package/README.md +1 -1
  2. package/README_zh.md +1 -1
  3. package/THIRD_PARTY_NOTICES.md +34 -2
  4. package/dist/esm/modules/archive/core/byte-queue.js +2 -1
  5. package/dist/esm/modules/archive/unzip/stream.browser.js +6 -0
  6. package/dist/esm/modules/csv/parse/async.js +2 -1
  7. package/dist/esm/modules/excel/bridge/csv-bridge.js +1 -1
  8. package/dist/esm/modules/excel/core/xlsx-io.browser.js +5 -9
  9. package/dist/esm/modules/excel/core/xlsx-io.js +1 -3
  10. package/dist/esm/modules/excel/core/xlsx-stream.js +3 -1
  11. package/dist/esm/modules/excel/stream/workbook-reader.browser.js +10 -10
  12. package/dist/esm/modules/excel/stream/workbook-reader.js +30 -6
  13. package/dist/esm/modules/stream/browser/collector.js +3 -5
  14. package/dist/esm/modules/stream/browser/compose.js +13 -228
  15. package/dist/esm/modules/stream/browser/duplex-pair.js +71 -0
  16. package/dist/esm/modules/stream/browser/factories.js +35 -217
  17. package/dist/esm/modules/stream/browser/pipeline.js +43 -478
  18. package/dist/esm/modules/stream/browser/utils.js +21 -247
  19. package/dist/esm/modules/stream/browser/web.js +25 -0
  20. package/dist/esm/modules/stream/buffered-stream.js +8 -6
  21. package/dist/esm/modules/stream/core/factories.js +166 -0
  22. package/dist/esm/modules/stream/core/pipeline-api.js +32 -0
  23. package/dist/esm/modules/stream/core/sink-adapter.js +94 -24
  24. package/dist/esm/modules/stream/core/stream-helpers.js +160 -0
  25. package/dist/esm/modules/stream/core/utils.js +0 -23
  26. package/dist/esm/modules/stream/core/web-conversions.js +31 -0
  27. package/dist/esm/modules/stream/core/web-pipeline.js +90 -0
  28. package/dist/esm/modules/stream/index.base.js +2 -2
  29. package/dist/esm/modules/stream/index.browser.js +13 -19
  30. package/dist/esm/modules/stream/index.js +6 -10
  31. package/dist/esm/modules/stream/kernel/classes.js +618 -0
  32. package/dist/esm/modules/stream/kernel/compose-impl.js +225 -0
  33. package/dist/esm/modules/stream/kernel/destroy.js +255 -0
  34. package/dist/esm/modules/stream/kernel/duplexify.js +355 -0
  35. package/dist/esm/modules/stream/kernel/end-of-stream.js +212 -0
  36. package/dist/esm/modules/stream/kernel/errors.js +215 -0
  37. package/dist/esm/modules/stream/kernel/from.js +202 -0
  38. package/dist/esm/modules/stream/kernel/legacy.js +35 -0
  39. package/dist/esm/modules/stream/kernel/operators.js +285 -0
  40. package/dist/esm/modules/stream/kernel/pipeline-impl.js +561 -0
  41. package/dist/esm/modules/stream/kernel/readable-impl.js +963 -0
  42. package/dist/esm/modules/stream/kernel/state.js +253 -0
  43. package/dist/esm/modules/stream/kernel/stream-utils.js +212 -0
  44. package/dist/esm/modules/stream/kernel/web-adapters.js +584 -0
  45. package/dist/esm/modules/stream/kernel/writable.js +651 -0
  46. package/dist/esm/modules/stream/node/collector.js +7 -1
  47. package/dist/esm/modules/stream/node/compose.js +21 -206
  48. package/dist/esm/modules/stream/node/factories.js +34 -238
  49. package/dist/esm/modules/stream/node/pipeline.js +40 -94
  50. package/dist/esm/modules/stream/node/utils.js +15 -239
  51. package/dist/esm/modules/stream/node/web.js +27 -0
  52. package/dist/esm/modules/stream/pull-stream.js +15 -9
  53. package/dist/esm/modules/word/writer/streaming-writer.js +3 -0
  54. package/dist/iife/THIRD_PARTY_NOTICES.md +34 -2
  55. package/dist/iife/documonster.archive.iife.min.js +4 -4
  56. package/dist/iife/documonster.csv.iife.min.js +19 -19
  57. package/dist/iife/documonster.draw.iife.min.js +1 -1
  58. package/dist/iife/documonster.excel.iife.min.js +50 -50
  59. package/dist/iife/documonster.formula.iife.min.js +1 -1
  60. package/dist/iife/documonster.markdown.iife.min.js +1 -1
  61. package/dist/iife/documonster.mermaid.iife.min.js +1 -1
  62. package/dist/iife/documonster.pdf.iife.min.js +1 -1
  63. package/dist/iife/documonster.stream.iife.min.js +2 -2
  64. package/dist/iife/documonster.word.iife.min.js +60 -60
  65. package/dist/iife/documonster.xml.iife.min.js +1 -1
  66. package/dist/types/modules/excel/core/xlsx-io.browser.d.ts +5 -9
  67. package/dist/types/modules/excel/core/xlsx-io.d.ts +1 -3
  68. package/dist/types/modules/excel/core/xlsx-stream.d.ts +3 -2
  69. package/dist/types/modules/excel/stream/workbook-reader.browser.d.ts +2 -1
  70. package/dist/types/modules/excel/stream/workbook-reader.d.ts +2 -1
  71. package/dist/types/modules/stream/browser/collector.d.ts +1 -1
  72. package/dist/types/modules/stream/browser/compose.d.ts +14 -15
  73. package/dist/types/modules/stream/browser/duplex-pair.d.ts +10 -0
  74. package/dist/types/modules/stream/browser/factories.d.ts +22 -79
  75. package/dist/types/modules/stream/browser/pipeline.d.ts +8 -40
  76. package/dist/types/modules/stream/browser/utils.d.ts +6 -47
  77. package/dist/types/modules/stream/browser/web.d.ts +18 -0
  78. package/dist/types/modules/stream/core/add-abort-signal.d.ts +2 -1
  79. package/dist/types/modules/stream/core/consumers.d.ts +1 -1
  80. package/dist/types/modules/stream/core/event-utils.d.ts +2 -1
  81. package/dist/types/modules/stream/core/factories.d.ts +129 -0
  82. package/dist/types/modules/stream/core/pipeline-api.d.ts +10 -0
  83. package/dist/types/modules/stream/core/sink-adapter.d.ts +18 -1
  84. package/dist/types/modules/stream/core/stream-helpers.d.ts +76 -0
  85. package/dist/types/modules/stream/core/utils.d.ts +0 -9
  86. package/dist/types/modules/stream/core/web-conversions.d.ts +68 -0
  87. package/dist/types/modules/stream/core/web-pipeline.d.ts +27 -0
  88. package/dist/types/modules/stream/index.base.d.ts +6 -4
  89. package/dist/types/modules/stream/index.browser.d.ts +13 -14
  90. package/dist/types/modules/stream/index.d.ts +7 -10
  91. package/dist/types/modules/stream/kernel/classes.d.ts +220 -0
  92. package/dist/types/modules/stream/kernel/compose-impl.d.ts +10 -0
  93. package/dist/types/modules/stream/kernel/destroy.d.ts +21 -0
  94. package/dist/types/modules/stream/kernel/duplexify.d.ts +31 -0
  95. package/dist/types/modules/stream/kernel/end-of-stream.d.ts +28 -0
  96. package/dist/types/modules/stream/kernel/errors.d.ts +42 -0
  97. package/dist/types/modules/stream/kernel/from.d.ts +17 -0
  98. package/dist/types/modules/stream/kernel/legacy.d.ts +20 -0
  99. package/dist/types/modules/stream/kernel/operators.d.ts +44 -0
  100. package/dist/types/modules/stream/kernel/pipeline-impl.d.ts +32 -0
  101. package/dist/types/modules/stream/kernel/readable-impl.d.ts +34 -0
  102. package/dist/types/modules/stream/kernel/state.d.ts +223 -0
  103. package/dist/types/modules/stream/kernel/stream-utils.d.ts +34 -0
  104. package/dist/types/modules/stream/kernel/web-adapters.d.ts +65 -0
  105. package/dist/types/modules/stream/kernel/writable.d.ts +107 -0
  106. package/dist/types/modules/stream/node/collector.d.ts +7 -2
  107. package/dist/types/modules/stream/node/compose.d.ts +31 -5
  108. package/dist/types/modules/stream/node/factories.d.ts +22 -85
  109. package/dist/types/modules/stream/node/pipeline.d.ts +4 -15
  110. package/dist/types/modules/stream/node/utils.d.ts +9 -49
  111. package/dist/types/modules/stream/node/web.d.ts +18 -0
  112. package/dist/types/modules/stream/pull-stream.d.ts +2 -2
  113. package/dist/types/modules/stream/types.d.ts +24 -6
  114. package/package.json +5 -3
  115. package/dist/esm/modules/stream/browser/_lazy.js +0 -30
  116. package/dist/esm/modules/stream/browser/chunk-buffer.js +0 -223
  117. package/dist/esm/modules/stream/browser/duplex.js +0 -979
  118. package/dist/esm/modules/stream/browser/helpers.js +0 -44
  119. package/dist/esm/modules/stream/browser/microtask-context.js +0 -60
  120. package/dist/esm/modules/stream/browser/passthrough.js +0 -16
  121. package/dist/esm/modules/stream/browser/pipe-manager.js +0 -161
  122. package/dist/esm/modules/stream/browser/readable.js +0 -2208
  123. package/dist/esm/modules/stream/browser/transform.js +0 -1241
  124. package/dist/esm/modules/stream/browser/writable.js +0 -1316
  125. package/dist/esm/modules/stream/core/end-args.js +0 -24
  126. package/dist/esm/modules/stream/node/writable.js +0 -125
  127. package/dist/esm/modules/stream/utils.base.js +0 -126
  128. package/dist/esm/modules/stream/utils.browser.js +0 -80
  129. package/dist/esm/modules/stream/utils.js +0 -81
  130. package/dist/types/modules/stream/browser/_lazy.d.ts +0 -20
  131. package/dist/types/modules/stream/browser/chunk-buffer.d.ts +0 -61
  132. package/dist/types/modules/stream/browser/duplex.d.ts +0 -299
  133. package/dist/types/modules/stream/browser/helpers.d.ts +0 -13
  134. package/dist/types/modules/stream/browser/microtask-context.d.ts +0 -44
  135. package/dist/types/modules/stream/browser/passthrough.d.ts +0 -11
  136. package/dist/types/modules/stream/browser/pipe-manager.d.ts +0 -38
  137. package/dist/types/modules/stream/browser/readable.d.ts +0 -379
  138. package/dist/types/modules/stream/browser/transform.d.ts +0 -314
  139. package/dist/types/modules/stream/browser/writable.d.ts +0 -238
  140. package/dist/types/modules/stream/core/end-args.d.ts +0 -20
  141. package/dist/types/modules/stream/node/writable.d.ts +0 -53
  142. package/dist/types/modules/stream/utils.base.d.ts +0 -63
  143. package/dist/types/modules/stream/utils.browser.d.ts +0 -23
  144. package/dist/types/modules/stream/utils.d.ts +0 -24
@@ -1,979 +0,0 @@
1
- /**
2
- * Browser Stream - Duplex
3
- */
4
- import { addEmitterListener, createListenerRegistry } from "./helpers.js";
5
- import { deferTask, inDeferredContext } from "./microtask-context.js";
6
- import { Readable } from "./readable.js";
7
- import { Writable } from "./writable.js";
8
- import { parseEndArgs } from "../core/end-args.js";
9
- import { StreamTypeError } from "../errors.js";
10
- import { createAbortError } from "../../../utils/errors.js";
11
- import { EventEmitter } from "../../../utils/event-emitter.js";
12
- /**
13
- * A duplex stream that combines readable and writable
14
- */
15
- export class Duplex extends EventEmitter {
16
- /**
17
- * Allow duck-typed instanceof checks.
18
- * Browser Duplex composes Readable + Writable, so we use Symbol.hasInstance
19
- * to check for key Duplex-like methods/properties (both readable and writable).
20
- * This makes `transform instanceof Duplex` return true.
21
- */
22
- static [Symbol.hasInstance](instance) {
23
- if (instance == null || typeof instance !== "object") {
24
- return false;
25
- }
26
- // Fast path: actual Duplex prototype
27
- if (Object.prototype.isPrototypeOf.call(Duplex.prototype, instance)) {
28
- return true;
29
- }
30
- // Duck-type: must have both Readable and Writable characteristics + stream brand
31
- const o = instance;
32
- return (o.__documonster_stream === true &&
33
- typeof o.read === "function" &&
34
- typeof o.pipe === "function" &&
35
- typeof o.write === "function" &&
36
- typeof o.end === "function" &&
37
- typeof o.on === "function" &&
38
- "readableFlowing" in instance &&
39
- "writableFinished" in instance);
40
- }
41
- /**
42
- * Check if a stream has been disturbed (data read or piped).
43
- * Delegates to Readable.isDisturbed, checking internal _readable for Duplex/Transform.
44
- */
45
- static isDisturbed(stream) {
46
- if (stream && typeof stream === "object") {
47
- const inner = stream._readable;
48
- if (inner instanceof Readable) {
49
- return Readable.isDisturbed(inner);
50
- }
51
- }
52
- return Readable.isDisturbed(stream);
53
- }
54
- /**
55
- * Create a Duplex stream from various sources
56
- */
57
- static from(source) {
58
- // If it's already a Duplex, return as-is
59
- if (source instanceof Duplex) {
60
- return source;
61
- }
62
- const forwardReadableToDuplex = (readable, duplex) => {
63
- const sink = new Writable({
64
- objectMode: duplex.readableObjectMode,
65
- write(chunk, _encoding, callback) {
66
- // Boundary: the source stream is known by construction to emit
67
- // chunks assignable to the duplex read type.
68
- duplex.push(chunk);
69
- callback();
70
- },
71
- final(callback) {
72
- duplex.push(null);
73
- callback();
74
- }
75
- });
76
- const onError = (err) => {
77
- duplex.emit("error", err);
78
- };
79
- const cleanupError = addEmitterListener(readable, "error", onError);
80
- addEmitterListener(readable, "end", cleanupError, { once: true });
81
- addEmitterListener(readable, "close", cleanupError, { once: true });
82
- addEmitterListener(sink, "finish", cleanupError, { once: true });
83
- readable.pipe(sink);
84
- };
85
- // Promise source — resolve and recursively call from()
86
- if (source instanceof Promise) {
87
- const duplex = new Duplex({ objectMode: true });
88
- source
89
- .then(value => {
90
- const inner = Duplex.from(value);
91
- forwardReadableToDuplex(inner, duplex);
92
- })
93
- .catch(err => {
94
- duplex.destroy(err instanceof Error ? err : new Error(String(err)));
95
- });
96
- return duplex;
97
- }
98
- // String source — wrap as a single-chunk readable
99
- if (typeof source === "string") {
100
- const readable = Readable.from([source]);
101
- const duplex = new Duplex({ objectMode: true });
102
- forwardReadableToDuplex(readable, duplex);
103
- return duplex;
104
- }
105
- // Blob source — convert to ReadableStream then to Readable
106
- if (typeof Blob !== "undefined" && source instanceof Blob) {
107
- const readable = Readable.fromWeb(source.stream());
108
- const duplex = new Duplex();
109
- forwardReadableToDuplex(readable, duplex);
110
- return duplex;
111
- }
112
- // If it has readable and/or writable properties
113
- if (typeof source === "object" &&
114
- source !== null &&
115
- "readable" in source &&
116
- "writable" in source) {
117
- const pair = source;
118
- // Create one duplex that can bridge both sides.
119
- // (Previous behavior returned a new writable-only Duplex and dropped the readable side.)
120
- const duplex = new Duplex({
121
- readableObjectMode: pair.readable?.readableObjectMode,
122
- writableObjectMode: pair.writable?.writableObjectMode,
123
- write: pair.writable
124
- ? (chunk, encoding, callback) => {
125
- pair.writable.write(chunk, encoding, callback);
126
- }
127
- : undefined,
128
- final: pair.writable
129
- ? callback => {
130
- pair.writable.end(callback);
131
- }
132
- : undefined,
133
- destroy: (error, callback) => {
134
- // Propagate destroy to the original source streams so they are cleaned
135
- // up when the wrapping Duplex is destroyed. Node.js does this too.
136
- if (pair.readable && !pair.readable.destroyed) {
137
- pair.readable.destroy(error ?? undefined);
138
- }
139
- if (pair.writable && !pair.writable.destroyed) {
140
- pair.writable.destroy(error ?? undefined);
141
- }
142
- callback(error);
143
- }
144
- });
145
- if (pair.readable) {
146
- forwardReadableToDuplex(pair.readable, duplex);
147
- }
148
- return duplex;
149
- }
150
- // Web ReadableStream — wrap as readable-only Duplex (matches Node.js Duplex.from(ReadableStream))
151
- if (typeof source === "object" &&
152
- source !== null &&
153
- typeof source.getReader === "function" &&
154
- typeof source.cancel === "function") {
155
- // Boundary: Web ReadableStream interop — chunk type is supplied by the caller.
156
- const readable = Readable.fromWeb(source);
157
- const duplex = new Duplex({
158
- objectMode: readable.readableObjectMode
159
- });
160
- forwardReadableToDuplex(readable, duplex);
161
- return duplex;
162
- }
163
- // Web WritableStream — wrap as writable-only Duplex (matches Node.js Duplex.from(WritableStream))
164
- if (typeof source === "object" &&
165
- source !== null &&
166
- typeof source.getWriter === "function" &&
167
- typeof source.close === "function") {
168
- // Boundary: Web WritableStream interop — chunk type is supplied by the caller.
169
- const writable = Writable.fromWeb(source);
170
- return new Duplex({
171
- objectMode: writable.writableObjectMode,
172
- write(chunk, encoding, callback) {
173
- writable.write(chunk, encoding, callback);
174
- },
175
- final(callback) {
176
- writable.end(callback);
177
- },
178
- destroy(error, callback) {
179
- if (!writable.destroyed) {
180
- writable.destroy(error ?? undefined);
181
- }
182
- callback(error);
183
- }
184
- });
185
- }
186
- // If it's an iterable
187
- if (typeof source === "object" &&
188
- source !== null &&
189
- (Symbol.asyncIterator in source || Symbol.iterator in source)) {
190
- const readable = Readable.from(source);
191
- const duplex = new Duplex({
192
- objectMode: readable.readableObjectMode
193
- });
194
- forwardReadableToDuplex(readable, duplex);
195
- return duplex;
196
- }
197
- // If it's a Readable
198
- if (source instanceof Readable) {
199
- const duplex = new Duplex({
200
- objectMode: source.readableObjectMode
201
- });
202
- forwardReadableToDuplex(source, duplex);
203
- return duplex;
204
- }
205
- // If it's a Writable
206
- if (source instanceof Writable) {
207
- return new Duplex({
208
- objectMode: source.writableObjectMode,
209
- write(chunk, encoding, callback) {
210
- source.write(chunk, encoding, callback);
211
- },
212
- final(callback) {
213
- source.end(callback);
214
- }
215
- });
216
- }
217
- throw new StreamTypeError("Duplex-compatible source", typeof source);
218
- }
219
- /**
220
- * Create a Duplex from a Web ReadableWritablePair
221
- */
222
- static fromWeb(pair, options) {
223
- const duplex = new Duplex(options);
224
- const newReadable = new Readable({
225
- stream: pair.readable,
226
- objectMode: duplex.readableObjectMode
227
- });
228
- const newWritable = new Writable({
229
- stream: pair.writable,
230
- objectMode: duplex.writableObjectMode
231
- });
232
- if (duplex._sideForwardingCleanup) {
233
- duplex._sideForwardingCleanup();
234
- duplex._sideForwardingCleanup = null;
235
- }
236
- duplex._readable = newReadable;
237
- duplex._writable = newWritable;
238
- // Re-wire event forwarding (data forwarding remains lazy via Duplex.on)
239
- duplex._setupSideForwarding();
240
- return duplex;
241
- }
242
- /**
243
- * Convert a Node.js Duplex to Web ReadableWritablePair
244
- */
245
- static toWeb(duplex) {
246
- return {
247
- readable: Readable.toWeb(duplex._readable),
248
- writable: Writable.toWeb(duplex._writable)
249
- };
250
- }
251
- /**
252
- * Detect a subclass-defined implementation hook (e.g. _read/_write/_writev/_final).
253
- *
254
- * Node.js allows implementing Duplex by subclassing and defining _read/_write on the
255
- * subclass prototype. Since the browser Duplex composes internal Readable/Writable
256
- * instances, we must explicitly forward these prototype hooks.
257
- *
258
- * The return type is an open function signature because the hooks it resolves
259
- * (`_read`/`_write`/`_writev`/`_final`) have different arities and arguments.
260
- */
261
- _getSubclassHook(name) {
262
- let proto = Object.getPrototypeOf(this);
263
- while (proto && proto !== Duplex.prototype && proto !== Object.prototype) {
264
- if (Object.prototype.hasOwnProperty.call(proto, name)) {
265
- const fn = this[name];
266
- if (typeof fn === "function") {
267
- return fn.bind(this);
268
- }
269
- return undefined;
270
- }
271
- proto = Object.getPrototypeOf(proto);
272
- }
273
- return undefined;
274
- }
275
- constructor(options) {
276
- super();
277
- // Track if we've already set up data forwarding
278
- this._dataForwardingSetup = false;
279
- this._destroyed = false;
280
- this._errored = null;
281
- this._closed = false;
282
- this._sideForwardingCleanup = null;
283
- this._constructed = true;
284
- this.allowHalfOpen = options?.allowHalfOpen ?? true;
285
- this._emitClose = options?.emitClose ?? true;
286
- this._autoDestroy = options?.autoDestroy ?? true;
287
- // Support shorthand objectMode option
288
- const objectMode = options?.objectMode ?? false;
289
- const readableObjMode = options?.readableObjectMode ?? objectMode;
290
- const writableObjMode = options?.writableObjectMode ?? objectMode;
291
- // HWM: if highWaterMark is explicitly provided it overrides per-side (matching Node)
292
- const hasGeneralHwm = options != null && Object.prototype.hasOwnProperty.call(options, "highWaterMark");
293
- const readableHwm = hasGeneralHwm ? options.highWaterMark : options?.readableHighWaterMark;
294
- const writableHwm = hasGeneralHwm ? options.highWaterMark : options?.writableHighWaterMark;
295
- // Store user-provided destroy function
296
- if (options?.destroy) {
297
- this._destroy = options.destroy.bind(this);
298
- }
299
- // Store user-provided construct function
300
- if (options?.construct) {
301
- this._constructFunc = options.construct.bind(this);
302
- }
303
- // When Duplex has a construct hook, propagate delay to child streams
304
- // so that reads/writes are queued until the Duplex-level construct fires.
305
- let readableConstructCb;
306
- let writableConstructCb;
307
- const hasConstruct = this._hasConstructHook();
308
- const readHook = options?.read
309
- ? options.read.bind(this)
310
- : this._getSubclassHook("_read");
311
- // Prefer constructor options over subclass hooks (matches Node's behavior where
312
- // options.{read,write,final,writev} override prototype hooks).
313
- const writeHook = options?.write
314
- ? options.write.bind(this)
315
- : this._getSubclassHook("_write");
316
- const writevHook = options?.writev
317
- ? options.writev.bind(this)
318
- : this._getSubclassHook("_writev");
319
- const finalHook = options?.final
320
- ? options.final.bind(this)
321
- : this._getSubclassHook("_final");
322
- this._readable = new Readable({
323
- highWaterMark: readableHwm,
324
- objectMode: readableObjMode,
325
- read: readHook,
326
- encoding: options?.encoding,
327
- // Suppress child-level close/error — Duplex itself is the authority
328
- emitClose: false,
329
- autoDestroy: false,
330
- // Propagate construct delay to child readable
331
- construct: hasConstruct
332
- ? cb => {
333
- readableConstructCb = cb;
334
- }
335
- : undefined
336
- });
337
- this._writable = new Writable({
338
- highWaterMark: writableHwm,
339
- objectMode: writableObjMode,
340
- write: writeHook,
341
- writev: writevHook,
342
- final: finalHook,
343
- decodeStrings: options?.decodeStrings,
344
- defaultEncoding: options?.defaultEncoding,
345
- // Suppress child-level close/error — Duplex itself is the authority
346
- emitClose: false,
347
- autoDestroy: false,
348
- // Propagate construct delay to child writable
349
- construct: hasConstruct
350
- ? cb => {
351
- writableConstructCb = cb;
352
- }
353
- : undefined
354
- });
355
- // Prevent unhandled error throws on child streams.
356
- // Errors are forwarded to the Duplex via _setupSideForwarding; these
357
- // noop listeners act as safety nets after forwarding cleanup.
358
- const noop = () => { };
359
- this._readable.on("error", noop);
360
- this._writable.on("error", noop);
361
- this._setupSideForwarding();
362
- // signal option — destroy the Duplex when signal aborts (matching Node)
363
- if (options?.signal) {
364
- this._setupAbortSignal(options.signal);
365
- }
366
- // R5-1: _construct hook — if provided, delay reads/writes until constructed
367
- if (hasConstruct) {
368
- this._constructed = false;
369
- deferTask(() => {
370
- const fn = this._constructFunc ?? this._construct.bind(this);
371
- fn(err => {
372
- if (err) {
373
- readableConstructCb?.(err);
374
- writableConstructCb?.(err);
375
- this.destroy(err);
376
- return;
377
- }
378
- this._constructed = true;
379
- // Unblock child streams by firing their construct callbacks
380
- readableConstructCb?.();
381
- writableConstructCb?.();
382
- });
383
- });
384
- }
385
- }
386
- _setupAbortSignal(signal) {
387
- if (signal.aborted) {
388
- this.destroy(createAbortError(signal.reason));
389
- return;
390
- }
391
- const onAbort = () => {
392
- this.destroy(createAbortError(signal.reason));
393
- };
394
- const cleanup = () => {
395
- signal.removeEventListener("abort", onAbort);
396
- };
397
- signal.addEventListener("abort", onAbort, { once: true });
398
- this.once("close", cleanup);
399
- }
400
- _setupSideForwarding() {
401
- if (this._sideForwardingCleanup) {
402
- this._sideForwardingCleanup();
403
- this._sideForwardingCleanup = null;
404
- }
405
- // Ensure the pipe source identity is always the outer Duplex,
406
- // including after fromWeb() replaces the internal _readable.
407
- this._readable._pipes?.setSource(this);
408
- const registry = createListenerRegistry();
409
- // Deduplicate error forwarding: when destroy(err) tears down both sides,
410
- // both _readable and _writable emit "error". Node.js Duplex only emits
411
- // one "error" event, so we guard against duplicate forwarding.
412
- let errorForwarded = false;
413
- const forwardError = (err) => {
414
- if (errorForwarded) {
415
- return;
416
- }
417
- errorForwarded = true;
418
- this.emit("error", err);
419
- };
420
- // Auto-destroy: when both sides finish, destroy the Duplex (matching Node.js).
421
- let readableEnded = false;
422
- let writableFinished = false;
423
- const maybeAutoDestroy = () => {
424
- if (this._autoDestroy && readableEnded && writableFinished && !this._destroyed) {
425
- this.destroy();
426
- }
427
- };
428
- // Forward non-data events (data forwarding is lazy to avoid premature flowing)
429
- registry.once(this._readable, "end", () => {
430
- this.emit("end");
431
- readableEnded = true;
432
- if (!this.allowHalfOpen) {
433
- this._writable.end();
434
- }
435
- maybeAutoDestroy();
436
- });
437
- registry.add(this._readable, "error", forwardError);
438
- // Use EventEmitter.prototype.on directly to register "readable" forwarding,
439
- // bypassing Readable's on() override which sets readableFlowing = false.
440
- const readableForwarder = () => {
441
- this.emit("readable");
442
- };
443
- EventEmitter.prototype.on.call(this._readable, "readable", readableForwarder);
444
- registry.add(this._readable, "pause", () => this.emit("pause"));
445
- registry.add(this._readable, "resume", () => this.emit("resume"));
446
- registry.add(this._writable, "error", forwardError);
447
- registry.once(this._writable, "prefinish", () => this.emit("prefinish"));
448
- registry.once(this._writable, "finish", () => {
449
- this.emit("finish");
450
- writableFinished = true;
451
- maybeAutoDestroy();
452
- });
453
- registry.add(this._writable, "drain", () => this.emit("drain"));
454
- // Forward "pipe"/"unpipe" from the internal writable so that
455
- // source.pipe(duplex) triggers "pipe" on the Duplex itself.
456
- registry.add(this._writable, "pipe", source => this.emit("pipe", source));
457
- registry.add(this._writable, "unpipe", source => this.emit("unpipe", source));
458
- // Node.js: when allowHalfOpen is false and the writable side finishes,
459
- // gracefully end the readable side with push(null) — NOT destroy().
460
- // The check is dynamic (inside the handler) so runtime changes to
461
- // allowHalfOpen are respected, matching Node.js behaviour.
462
- registry.once(this._writable, "finish", () => {
463
- if (!this.allowHalfOpen && !this._readable.readableEnded) {
464
- this._readable.push(null);
465
- }
466
- });
467
- // Node.js parity: when the internal _readable is destroyed independently
468
- // (e.g. by a higher-order method like map/filter/forEach that uses the
469
- // async iterator and calls _readable.destroy() on error or early exit),
470
- // propagate the destruction to the outer Duplex. Without this, only the
471
- // readable side would be torn down, leaving the writable side open — a
472
- // resource leak that doesn't happen in Node.js where Duplex IS the
473
- // Readable (same object, so destroy() hits both sides).
474
- const origReadableDestroy = this._readable.destroy.bind(this._readable);
475
- this._readable.destroy = (err) => {
476
- const result = origReadableDestroy(err);
477
- if (!this._destroyed) {
478
- this.destroy(err);
479
- }
480
- return result;
481
- };
482
- this._sideForwardingCleanup = () => {
483
- registry.cleanup();
484
- this._readable.off("readable", readableForwarder);
485
- // Restore original destroy to avoid leaking the closure after cleanup.
486
- this._readable.destroy = origReadableDestroy;
487
- };
488
- }
489
- /**
490
- * Override on() to set up data forwarding lazily
491
- */
492
- on(event, listener) {
493
- // Register the listener FIRST so that when _readable.on("data") triggers
494
- // resume() and synchronously drains buffered data, the forwarding handler
495
- // can find the listener already in place on this Duplex.
496
- super.on(event, listener);
497
- // Set up data forwarding when first external data listener is added
498
- if (event === "data" && !this._dataForwardingSetup) {
499
- this._dataForwardingSetup = true;
500
- this._readable.on("data", chunk => this.emit("data", chunk));
501
- }
502
- else if (event === "readable") {
503
- // Node.js: adding a 'readable' listener sets readableFlowing to false
504
- this._readable._setReadableFlowing(false);
505
- }
506
- return this;
507
- }
508
- /**
509
- * Push data to readable side
510
- */
511
- push(chunk, encoding) {
512
- return this._readable.push(chunk, encoding);
513
- }
514
- /**
515
- * Put a chunk back at the front of the buffer (readable side)
516
- */
517
- unshift(chunk, encoding) {
518
- this._readable.unshift(chunk, encoding);
519
- }
520
- /**
521
- * Read from readable side
522
- */
523
- read(size) {
524
- return this._readable.read(size);
525
- }
526
- write(chunk, encodingOrCallback, callback) {
527
- const encoding = typeof encodingOrCallback === "string" ? encodingOrCallback : undefined;
528
- const cb = typeof encodingOrCallback === "function" ? encodingOrCallback : callback;
529
- return encoding !== undefined
530
- ? this._writable.write(chunk, encoding, cb)
531
- : this._writable.write(chunk, cb);
532
- }
533
- end(chunkOrCallback, encodingOrCallback, callback) {
534
- const { chunk, encoding, cb } = parseEndArgs(chunkOrCallback, encodingOrCallback, callback);
535
- // Node invokes the end() callback with an error in some paths (write-after-
536
- // end / already-finished). `parseEndArgs` types it `() => void`, so view it
537
- // through an error-accepting signature for those Node-parity invocations.
538
- const endCb = cb;
539
- // Repeated end() protection (matches Node.js Writable.end() behavior)
540
- if (this._writable.writableEnded) {
541
- // If a chunk was provided, this is a write-after-end error.
542
- if (chunk !== undefined) {
543
- this.write(chunk, encoding, err => {
544
- endCb?.(err ?? null);
545
- });
546
- return this;
547
- }
548
- // If we've already finished, callback receives ERR_STREAM_ALREADY_FINISHED.
549
- if (this.writableFinished && cb) {
550
- const err = new Error("Cannot call end after a stream was finished");
551
- err.code = "ERR_STREAM_ALREADY_FINISHED";
552
- deferTask(() => endCb(err));
553
- }
554
- else if (cb) {
555
- // Redundant end() is a no-op; callback called with no error.
556
- deferTask(() => endCb(null));
557
- }
558
- return this;
559
- }
560
- if (cb) {
561
- // Node.js fires the end() callback on 'finish', but also on 'close'
562
- // (which is emitted after destroy). This ensures the callback fires
563
- // even when the stream is destroyed before finishing.
564
- let called = false;
565
- const onceCb = () => {
566
- if (!called) {
567
- called = true;
568
- cb();
569
- }
570
- };
571
- this.once("finish", onceCb);
572
- this.once("close", onceCb);
573
- }
574
- if (chunk !== undefined) {
575
- // Propagate write errors through destroy (matching Node.js)
576
- const onWriteError = (err) => {
577
- if (err && !this.destroyed) {
578
- this.destroy(err);
579
- }
580
- };
581
- if (encoding !== undefined) {
582
- this._writable.write(chunk, encoding, onWriteError);
583
- }
584
- else {
585
- this._writable.write(chunk, onWriteError);
586
- }
587
- }
588
- this._writable.end();
589
- return this;
590
- }
591
- /**
592
- * Cork the writable side
593
- */
594
- cork() {
595
- this._writable.cork();
596
- }
597
- /**
598
- * Uncork the writable side
599
- */
600
- uncork() {
601
- this._writable.uncork();
602
- }
603
- /**
604
- * Set encoding for readable side
605
- */
606
- setEncoding(encoding) {
607
- this._readable.setEncoding(encoding);
608
- return this;
609
- }
610
- /**
611
- * Set default encoding for writable side
612
- */
613
- setDefaultEncoding(encoding) {
614
- this._writable.setDefaultEncoding(encoding);
615
- return this;
616
- }
617
- /**
618
- * Pipe readable side to destination.
619
- * Accepts any writable-like object (duck-typed, matching Node.js behavior).
620
- */
621
- pipe(destination, options) {
622
- this._readable.pipe(destination, options);
623
- return destination;
624
- }
625
- /**
626
- * Unpipe from destination
627
- */
628
- unpipe(destination) {
629
- this._readable.unpipe(destination);
630
- return this;
631
- }
632
- /**
633
- * Pause the readable side
634
- */
635
- pause() {
636
- this._readable.pause();
637
- return this;
638
- }
639
- /**
640
- * Resume the readable side
641
- */
642
- resume() {
643
- this._readable.resume();
644
- return this;
645
- }
646
- /**
647
- * Check if paused
648
- */
649
- isPaused() {
650
- return this._readable.isPaused();
651
- }
652
- /**
653
- * Destroy both sides
654
- */
655
- destroy(error) {
656
- if (this._destroyed) {
657
- return this;
658
- }
659
- this._destroyed = true;
660
- if (this._sideForwardingCleanup) {
661
- this._sideForwardingCleanup();
662
- this._sideForwardingCleanup = null;
663
- }
664
- const afterDestroy = (finalError) => {
665
- // Node.js: _destroy's callback determines whether an error is emitted.
666
- // cb(null)/cb()/cb(undefined) all suppress the original error.
667
- // Only cb(new Error(...)) replaces and emits the error.
668
- const err = finalError || null;
669
- if (err) {
670
- this._errored = err;
671
- }
672
- this._closed = true;
673
- // Destroy internal streams without their own error/close emission — the
674
- // Duplex itself is the authority for those events.
675
- this._readable.destroy();
676
- this._writable.destroy();
677
- const doEmit = () => {
678
- if (err) {
679
- this.emit("error", err);
680
- }
681
- if (this._emitClose) {
682
- this.emit("close");
683
- }
684
- };
685
- if (inDeferredContext() &&
686
- !this._hasDestroyHook() &&
687
- this.readableEnded &&
688
- this.writableFinished) {
689
- doEmit();
690
- }
691
- else {
692
- deferTask(doEmit);
693
- }
694
- };
695
- if (this._hasDestroyHook()) {
696
- try {
697
- this._destroy(error ?? null, afterDestroy);
698
- }
699
- catch (err) {
700
- afterDestroy(err instanceof Error ? err : new Error(String(err)));
701
- }
702
- }
703
- else {
704
- afterDestroy(error);
705
- }
706
- return this;
707
- }
708
- /**
709
- * Override in subclass to customise destroy behaviour.
710
- * Call `callback(err)` when cleanup is complete.
711
- */
712
- _destroy(error, callback) {
713
- callback(error);
714
- }
715
- /**
716
- * Reverse the effects of destroy() so the stream can potentially be reused.
717
- * Matches Node.js _undestroy() which resets destroyed and closed flags.
718
- */
719
- _undestroy() {
720
- this._readable._undestroy();
721
- this._writable._undestroy();
722
- this._destroyed = false;
723
- this._closed = false;
724
- this._errored = null;
725
- this._setupSideForwarding();
726
- }
727
- /** Check if _destroy has been overridden by a subclass or constructor option. */
728
- _hasDestroyHook() {
729
- return (Object.prototype.hasOwnProperty.call(this, "_destroy") ||
730
- Object.getPrototypeOf(this)._destroy !== Duplex.prototype._destroy);
731
- }
732
- /**
733
- * Check if a subclass defines _construct on its own prototype.
734
- * Node.js does NOT have _construct on any stream prototype — it only exists
735
- * when provided via constructor options or defined by a subclass.
736
- */
737
- _hasConstructHook() {
738
- if (this._constructFunc) {
739
- return true;
740
- }
741
- let proto = Object.getPrototypeOf(this);
742
- while (proto && proto !== Duplex.prototype && proto !== Object.prototype) {
743
- if (Object.prototype.hasOwnProperty.call(proto, "_construct")) {
744
- return true;
745
- }
746
- proto = Object.getPrototypeOf(proto);
747
- }
748
- return false;
749
- }
750
- /**
751
- * Synchronous dispose — destroys the stream.
752
- * Matches Node.js Symbol.dispose support (v20+, experimental).
753
- */
754
- [Symbol.dispose]() {
755
- if (!this._destroyed) {
756
- this.destroy();
757
- }
758
- }
759
- /**
760
- * Async dispose support (using await).
761
- * Destroys the stream and resolves after the 'close' event.
762
- */
763
- async [Symbol.asyncDispose]() {
764
- // Match Node.js behavior:
765
- // 1. If not yet destroyed, destroy the stream (always resolves)
766
- // 2. If already destroyed by someone else, reject with "Premature close"
767
- // unless the stream ended gracefully (writableFinished)
768
- const selfInitiated = !this._destroyed;
769
- if (selfInitiated) {
770
- this.destroy();
771
- }
772
- return new Promise((resolve, reject) => {
773
- const settle = () => {
774
- if (selfInitiated || this.writableFinished) {
775
- resolve();
776
- }
777
- else {
778
- reject(new Error("Premature close"));
779
- }
780
- };
781
- if (this._closed) {
782
- settle();
783
- }
784
- else {
785
- this.once("close", settle);
786
- }
787
- });
788
- }
789
- get readable() {
790
- return this._readable.readable;
791
- }
792
- set readable(val) {
793
- this._readable.readable = val;
794
- }
795
- get writable() {
796
- return this._writable.writable;
797
- }
798
- set writable(val) {
799
- this._writable.writable = val;
800
- }
801
- get readableEnded() {
802
- return this._readable.readableEnded;
803
- }
804
- get writableEnded() {
805
- return this._writable.writableEnded;
806
- }
807
- get writableFinished() {
808
- return this._writable.writableFinished;
809
- }
810
- get readableLength() {
811
- return this._readable.readableLength;
812
- }
813
- get writableLength() {
814
- return this._writable.writableLength;
815
- }
816
- get readableHighWaterMark() {
817
- return this._readable.readableHighWaterMark;
818
- }
819
- get writableHighWaterMark() {
820
- return this._writable.writableHighWaterMark;
821
- }
822
- get destroyed() {
823
- return this._destroyed;
824
- }
825
- set destroyed(val) {
826
- this._destroyed = val;
827
- // Propagate to internal streams so their state stays consistent with
828
- // the Duplex — matches Node.js where Duplex/Readable/Writable share
829
- // a single destroyed flag via the prototype chain.
830
- this._readable.destroyed = val;
831
- this._writable.destroyed = val;
832
- }
833
- get writableCorked() {
834
- return this._writable.writableCorked;
835
- }
836
- get writableNeedDrain() {
837
- return this._writable.writableNeedDrain;
838
- }
839
- get readableObjectMode() {
840
- return this._readable.readableObjectMode;
841
- }
842
- get writableObjectMode() {
843
- return this._writable.writableObjectMode;
844
- }
845
- get readableFlowing() {
846
- return this._readable.readableFlowing;
847
- }
848
- get readableAborted() {
849
- return this._readable.readableAborted;
850
- }
851
- get readableDidRead() {
852
- return this._readable.readableDidRead;
853
- }
854
- get readableEncoding() {
855
- return this._readable.readableEncoding;
856
- }
857
- get errored() {
858
- return this._errored ?? this._readable.errored ?? this._writable.errored;
859
- }
860
- get closed() {
861
- return this._closed;
862
- }
863
- get readableBuffer() {
864
- return this._readable.readableBuffer;
865
- }
866
- get writableBuffer() {
867
- return this._writable.writableBuffer;
868
- }
869
- /**
870
- * Wrap a legacy stream
871
- */
872
- wrap(stream) {
873
- this._readable.wrap(stream);
874
- return this;
875
- }
876
- /**
877
- * Create an async iterator with options.
878
- *
879
- * Node.js parity: when `destroyOnReturn` is true (the default) and the
880
- * iterator exits early (break/return), the entire Duplex is destroyed —
881
- * not just the readable side. The inner `_readable`'s iterator would only
882
- * destroy `_readable` (which has `autoDestroy: false`, `emitClose: false`),
883
- * leaving the writable side open. We wrap the iterator so that `return()`
884
- * propagates destruction to the outer Duplex.
885
- */
886
- iterator(options) {
887
- const destroyOnReturn = options?.destroyOnReturn !== false;
888
- if (!destroyOnReturn) {
889
- // No destruction needed on return — delegate directly.
890
- return this._readable.iterator(options);
891
- }
892
- return this._wrapAsyncIterator(this._readable[Symbol.asyncIterator]());
893
- }
894
- /**
895
- * Async iterator support.
896
- * Wraps the inner readable's iterator so that early exit destroys the
897
- * entire Duplex (both readable and writable sides), matching Node.js.
898
- */
899
- [Symbol.asyncIterator]() {
900
- return this._wrapAsyncIterator(this._readable[Symbol.asyncIterator]());
901
- }
902
- /**
903
- * Wrap an inner readable iterator so that return()/throw() destroy the
904
- * outer Duplex, not just the inner readable.
905
- */
906
- _wrapAsyncIterator(inner) {
907
- // oxlint-disable-next-line no-this-alias -- needed for object literal method closures
908
- const duplex = this;
909
- return {
910
- next() {
911
- return inner.next();
912
- },
913
- async return() {
914
- const result = await inner.return?.();
915
- if (!duplex.destroyed) {
916
- duplex.destroy();
917
- }
918
- return result ?? { value: undefined, done: true };
919
- },
920
- async throw(err) {
921
- const result = await inner.throw?.(err);
922
- if (!duplex.destroyed) {
923
- duplex.destroy(err instanceof Error ? err : undefined);
924
- }
925
- return result ?? { value: undefined, done: true };
926
- },
927
- [Symbol.asyncIterator]() {
928
- return this;
929
- }
930
- };
931
- }
932
- // =============================================================================
933
- // Functional / Higher-order Methods (forwarded to readable side)
934
- // =============================================================================
935
- map(fn, options) {
936
- return this._readable.map(fn, options);
937
- }
938
- filter(fn, options) {
939
- return this._readable.filter(fn, options);
940
- }
941
- async forEach(fn, options) {
942
- return this._readable.forEach(fn, options);
943
- }
944
- async toArray(options) {
945
- return this._readable.toArray(options);
946
- }
947
- async some(fn, options) {
948
- return this._readable.some(fn, options);
949
- }
950
- async find(fn, options) {
951
- return this._readable.find(fn, options);
952
- }
953
- async every(fn, options) {
954
- return this._readable.every(fn, options);
955
- }
956
- flatMap(fn, options) {
957
- return this._readable.flatMap(fn, options);
958
- }
959
- drop(limit, options) {
960
- return this._readable.drop(limit, options);
961
- }
962
- take(limit, options) {
963
- return this._readable.take(limit, options);
964
- }
965
- async reduce(fn, initial, options) {
966
- if (arguments.length >= 2) {
967
- return this._readable.reduce(fn, initial, options);
968
- }
969
- return this._readable.reduce(fn);
970
- }
971
- compose(stream, options) {
972
- return this._readable.compose(stream, options);
973
- }
974
- }
975
- // Node.js: `Duplex.prototype.addListener === Duplex.prototype.on` (same function).
976
- // Duplex overrides `on` from EventEmitter, so we must re-alias `addListener`.
977
- Duplex.prototype.addListener = Duplex.prototype.on;
978
- // Node.js: Duplex.prototype._writev === null (copied from Writable).
979
- Duplex.prototype._writev = null;