|
1 | | -// Copyright 2020-2021 by David Sherret. All rights reserved. |
2 | | -// This work is licensed under the terms of the MIT license. |
3 | | -// For a copy, see <https://opensource.org/licenses/MIT>. |
4 | | - |
5 | 1 | /** Formats code. */ |
6 | 2 | export interface Formatter { |
7 | 3 | /** |
@@ -89,17 +85,40 @@ export function createImportObject(): WebAssembly.Imports { |
89 | 85 | }; |
90 | 86 | } |
91 | 87 |
|
| 88 | +export interface ResponseLike { |
| 89 | + arrayBuffer(): Promise<BufferSource>; |
| 90 | +} |
| 91 | + |
92 | 92 | /** |
93 | 93 | * Creates a formatter from the specified streaming source. |
94 | 94 | * @remarks This is the most efficient way to create a formatter. |
95 | 95 | * @param response - The streaming source to create the formatter from. |
96 | 96 | */ |
97 | 97 | export function createStreaming( |
98 | | - response: Promise<Response>, |
| 98 | + response: Promise<ResponseLike>, |
99 | 99 | ): Promise<Formatter> { |
100 | | - return WebAssembly |
101 | | - .instantiateStreaming(response,createImportObject()) |
102 | | - .then((obj) => createFromInstance(obj.instance)); |
| 100 | + if (typeof WebAssembly.instantiateStreaming === "function") { |
| 101 | + return WebAssembly |
| 102 | + // deno-lint-ignore no-explicit-any |
| 103 | + .instantiateStreaming(response as any, createImportObject()) |
| 104 | + .then((obj) => createFromInstance(obj.instance)); |
| 105 | + } else { |
| 106 | + // fallback for node.js |
| 107 | + return getArrayBuffer() |
| 108 | + .then((buffer) => createFromBuffer(buffer)); |
| 109 | + } |
| 110 | + |
| 111 | + function getArrayBuffer() { |
| 112 | + if (isResponse(response)) { |
| 113 | + return response.arrayBuffer(); |
| 114 | + } else { |
| 115 | + return response.then((response) => response.arrayBuffer()); |
| 116 | + } |
| 117 | + |
| 118 | + function isResponse(response: unknown): response is ResponseLike { |
| 119 | + return (response as Response).arrayBuffer != null; |
| 120 | + } |
| 121 | + } |
103 | 122 | } |
104 | 123 |
|
105 | 124 | /** |
|
0 commit comments