1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
//! Node `stream/consumers` module: read an entire stream to a single value.
//!
//! Each function (`text`/`json`/`arrayBuffer`/`buffer`/`bytes`/`blob`) returns a
//! Promise that settles once the stream ends. The reader is a small compiled JS
//! factory (same re-entrant `compile_completion` → `load_merged` → `run_chunk_on`
//! path `util.promisify` uses): it attaches `data`/`end`/`error` listeners on the
//! stream's real EventEmitter surface, accumulates chunks with `Buffer.concat`,
//! and resolves the Promise on `end` (rejecting on `error`). Building it in JS
//! means the genuine Promise + emitter machinery does the work — no bespoke
//! native listener/accumulator.
//!
//! Runtime byte container: this engine represents raw bytes as a `Buffer`, so
//! `arrayBuffer`/`bytes` resolve with a `Buffer` (matching `buffer::blob_call`,
//! which likewise resolves its `arrayBuffer`/`bytes` accessors with a `Buffer`
//! rather than a bare `ArrayBuffer`/`Uint8Array`). `blob` resolves a real `Blob`.
use cratewith_host;
use Value;
/// The free functions exported by `require('stream/consumers')`.
pub const METHODS: & = &;
/// The compiled reader factory: `(stream, kind) => Promise<value>`. A `data`
/// listener collects chunks (string chunks are wrapped to `Buffer`); the `end`
/// listener concatenates and finalizes per `kind`; `error` rejects.
const CONSUMER_SRC: &str = "(function (stream, kind) {\n\
var B = require('buffer');\n\
return new Promise(function (resolve, reject) {\n\
var chunks = [];\n\
stream.on('data', function (c) {\n\
chunks.push(typeof c === 'string' ? B.Buffer.from(c) : c);\n\
});\n\
stream.on('error', function (e) { reject(e); });\n\
stream.on('end', function () {\n\
try {\n\
var buf = B.Buffer.concat(chunks);\n\
if (kind === 'text') return resolve(buf.toString('utf8'));\n\
if (kind === 'json') return resolve(JSON.parse(buf.toString('utf8')));\n\
if (kind === 'blob') return resolve(new B.Blob([buf]));\n\
return resolve(buf);\n\
} catch (err) { reject(err); }\n\
});\n\
});\n\
})";
/// Compile a single JS expression and run it on the LIVE host, returning its
/// completion value. Delegates to the frontend's ONE runtime-source evaluator
/// (`crate::eval_in_global_scope`), which runs the factory in the program's
/// module scope rather than in the calling function's frame.
/// Module free-function dispatch (`consumers.text`, `consumers.json`, …).
/// Invoke the reader factory with `stream` and the `kind` selector, returning the
/// Promise it produces.