UNPKG

nstdlib-nightly

Version:

Node.js standard library converted to runtime-agnostic ES modules.

68 lines (57 loc) 2.16 kB
// Source: https://github.com/nodejs/node/blob/65eff1eb/lib/internal/wasm_web_api.js import { codes as __codes__ } from "nstdlib/lib/internal/errors"; import * as __hoisted_internal_deps_undici_undici__ from "nstdlib/stub/internal/deps/undici/undici"; const { ERR_INVALID_ARG_TYPE, ERR_WEBASSEMBLY_RESPONSE } = __codes__; let undici; function lazyUndici() { return (undici ??= __hoisted_internal_deps_undici_undici__); } // This is essentially an implementation of a v8::WasmStreamingCallback, except // that it is implemented in JavaScript because the fetch() implementation is // difficult to use from C++. See lib/internal/process/pre_execution.js and // src/node_wasm_web_api.cc that interact with this function. function wasmStreamingCallback(streamState, source) { (async () => { const response = await Promise.resolve(source); if (!(response instanceof lazyUndici().Response)) { throw new ERR_INVALID_ARG_TYPE( "source", ["Response", "Promise resolving to Response"], response, ); } const contentType = response.headers.get("Content-Type"); if (contentType !== "application/wasm") { throw new ERR_WEBASSEMBLY_RESPONSE( `has unsupported MIME type '${contentType}'`, ); } if (!response.ok) { throw new ERR_WEBASSEMBLY_RESPONSE(`has status code ${response.status}`); } if (response.bodyUsed !== false) { throw new ERR_WEBASSEMBLY_RESPONSE("body has already been used"); } if (response.url) { streamState.setURL(response.url); } // Pass all data from the response body to the WebAssembly compiler. const { body } = response; if (body != null) { for await (const chunk of body) { streamState.push(chunk); } } })().then( () => { // No error occurred. Tell the implementation that the stream has ended. streamState.finish(); }, (err) => { // An error occurred, either because the given object was not a valid // and usable Response or because a network error occurred. streamState.abort(err); }, ); } export { wasmStreamingCallback };