| 395 | } |
| 396 | |
| 397 | constructor(chunks: Array<BufferSource | DataView | Blob | string> = [], opts: { type?: string } = {}) { |
| 398 | const dataChunks: Uint8Array[] = []; |
| 399 | for (const chunk of chunks) { |
| 400 | if (chunk instanceof Blob) { |
| 401 | dataChunks.push(chunk._buffer); |
| 402 | } else if (typeof chunk === 'string') { |
| 403 | const textEncoder = new TextEncoder(); |
| 404 | dataChunks.push(textEncoder.encode(chunk)); |
| 405 | } else if (chunk instanceof DataView) { |
| 406 | dataChunks.push(new Uint8Array(chunk.buffer.slice(0))); |
| 407 | } else if (chunk instanceof ArrayBuffer || ArrayBuffer.isView(chunk)) { |
| 408 | dataChunks.push(new Uint8Array(ArrayBuffer.isView(chunk) ? chunk.buffer.slice(0) : chunk.slice(0))); |
| 409 | } else { |
| 410 | const textEncoder = new TextEncoder(); |
| 411 | dataChunks.push(textEncoder.encode(String(chunk))); |
| 412 | } |
| 413 | } |
| 414 | |
| 415 | const size = dataChunks.reduce((size, chunk) => size + chunk.byteLength, 0); |
| 416 | const buffer = new Uint8Array(size); |
| 417 | let offset = 0; |
| 418 | for (let i = 0; i < dataChunks.length; i++) { |
| 419 | const chunk = dataChunks[i]; |
| 420 | buffer.set(chunk, offset); |
| 421 | offset += chunk.byteLength; |
| 422 | } |
| 423 | |
| 424 | this._buffer = buffer; |
| 425 | this._size = this._buffer.byteLength; |
| 426 | |
| 427 | this._type = opts.type || ''; |
| 428 | if (/[^\u0020-\u007E]/.test(this._type)) { |
| 429 | this._type = ''; |
| 430 | } else { |
| 431 | this._type = this._type.toLowerCase(); |
| 432 | } |
| 433 | } |
| 434 | |
| 435 | public arrayBuffer() { |
| 436 | return Promise.resolve(this._buffer); |