From a8d8821e818503133d9d015b3a7e232f8f4a4239 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jimmy=20W=C3=A4rting?= Date: Wed, 17 Apr 2019 19:47:12 +0200 Subject: [PATCH 01/11] Standardjs format --- Blob.js | 293 +++++++++++++++++++++++++++----------------------------- 1 file changed, 143 insertions(+), 150 deletions(-) diff --git a/Blob.js b/Blob.js index 100fefb..5ad1801 100644 --- a/Blob.js +++ b/Blob.js @@ -8,8 +8,7 @@ * See https://github.com/eligrey/Blob.js/blob/master/LICENSE.md */ -;(function(){ - +;(function () { var global = typeof window === 'object' ? window : typeof self === 'object' ? self : this @@ -17,9 +16,9 @@ var BlobBuilder = global.BlobBuilder || global.WebKitBlobBuilder || global.MSBlobBuilder - || global.MozBlobBuilder; + || global.MozBlobBuilder - global.URL = global.URL || global.webkitURL || function(href, a) { + global.URL = global.URL || global.webkitURL || function (href, a) { a = document.createElement('a') a.href = href return a @@ -34,7 +33,7 @@ var arrayBufferSupported = !!global.ArrayBuffer var blobBuilderSupported = BlobBuilder && BlobBuilder.prototype.append - && BlobBuilder.prototype.getBlob; + && BlobBuilder.prototype.getBlob try { // Check if Blob constructor is supported @@ -42,151 +41,149 @@ // Check if Blob constructor supports ArrayBufferViews // Fails in Safari 6, so we need to map to ArrayBuffers there. - blobSupportsArrayBufferView = new Blob([new Uint8Array([1,2])]).size === 2 - } catch(e) {} + blobSupportsArrayBufferView = new Blob([new Uint8Array([1, 2])]).size === 2 + } catch (e) {} /** * Helper function that maps ArrayBufferViews to ArrayBuffers * Used by BlobBuilder constructor and old browsers that didn't * support it in the Blob constructor. */ - function mapArrayBufferViews(ary) { - return ary.map(function(chunk) { + function mapArrayBufferViews (ary) { + return ary.map(function (chunk) { if (chunk.buffer instanceof ArrayBuffer) { - var buf = chunk.buffer; + var buf = chunk.buffer // if this is a subarray, make a copy so we only // include the subarray region from the underlying buffer if (chunk.byteLength !== buf.byteLength) { - var copy = new Uint8Array(chunk.byteLength); - copy.set(new Uint8Array(buf, chunk.byteOffset, chunk.byteLength)); - buf = copy.buffer; + var copy = new Uint8Array(chunk.byteLength) + copy.set(new Uint8Array(buf, chunk.byteOffset, chunk.byteLength)) + buf = copy.buffer } - return buf; + return buf } - return chunk; - }); + return chunk + }) } - function BlobBuilderConstructor(ary, options) { - options = options || {}; + function BlobBuilderConstructor (ary, options) { + options = options || {} - var bb = new BlobBuilder(); - mapArrayBufferViews(ary).forEach(function(part) { - bb.append(part); - }); + var bb = new BlobBuilder() + mapArrayBufferViews(ary).forEach(function (part) { + bb.append(part) + }) - return options.type ? bb.getBlob(options.type) : bb.getBlob(); - }; + return options.type ? bb.getBlob(options.type) : bb.getBlob() + } - function BlobConstructor(ary, options) { - return new origBlob(mapArrayBufferViews(ary), options || {}); - }; + function BlobConstructor (ary, options) { + return new origBlob(mapArrayBufferViews(ary), options || {}) + } if (global.Blob) { - BlobBuilderConstructor.prototype = Blob.prototype; - BlobConstructor.prototype = Blob.prototype; + BlobBuilderConstructor.prototype = Blob.prototype + BlobConstructor.prototype = Blob.prototype } - function FakeBlobBuilder() { - function toUTF8Array(str) { - var utf8 = []; - for (var i=0; i < str.length; i++) { - var charcode = str.charCodeAt(i); - if (charcode < 0x80) utf8.push(charcode); + function FakeBlobBuilder () { + function toUTF8Array (str) { + var utf8 = [] + for (var i = 0; i < str.length; i++) { + var charcode = str.charCodeAt(i) + if (charcode < 0x80) utf8.push(charcode) else if (charcode < 0x800) { - utf8.push(0xc0 | (charcode >> 6), - 0x80 | (charcode & 0x3f)); - } - else if (charcode < 0xd800 || charcode >= 0xe000) { - utf8.push(0xe0 | (charcode >> 12), - 0x80 | ((charcode>>6) & 0x3f), - 0x80 | (charcode & 0x3f)); + utf8.push(0xc0 | (charcode >> 6), + 0x80 | (charcode & 0x3f)) + } else if (charcode < 0xd800 || charcode >= 0xe000) { + utf8.push(0xe0 | (charcode >> 12), + 0x80 | ((charcode >> 6) & 0x3f), + 0x80 | (charcode & 0x3f)) } // surrogate pair else { - i++; + i++ // UTF-16 encodes 0x10000-0x10FFFF by // subtracting 0x10000 and splitting the // 20 bits of 0x0-0xFFFFF into two halves - charcode = 0x10000 + (((charcode & 0x3ff)<<10) - | (str.charCodeAt(i) & 0x3ff)); - utf8.push(0xf0 | (charcode >>18), - 0x80 | ((charcode>>12) & 0x3f), - 0x80 | ((charcode>>6) & 0x3f), - 0x80 | (charcode & 0x3f)); + charcode = 0x10000 + (((charcode & 0x3ff) << 10) + | (str.charCodeAt(i) & 0x3ff)) + utf8.push(0xf0 | (charcode >> 18), + 0x80 | ((charcode >> 12) & 0x3f), + 0x80 | ((charcode >> 6) & 0x3f), + 0x80 | (charcode & 0x3f)) } } - return utf8; + return utf8 } - function fromUtf8Array(array) { - var out, i, len, c; - var char2, char3; - - out = ""; - len = array.length; - i = 0; + function fromUtf8Array (array) { + var out, i, len, c + var char2, char3 + + out = '' + len = array.length + i = 0 while (i < len) { - c = array[i++]; - switch (c >> 4) - { + c = array[i++] + switch (c >> 4) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: // 0xxxxxxx - out += String.fromCharCode(c); - break; + out += String.fromCharCode(c) + break case 12: case 13: // 110x xxxx 10xx xxxx - char2 = array[i++]; - out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F)); - break; + char2 = array[i++] + out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F)) + break case 14: // 1110 xxxx 10xx xxxx 10xx xxxx - char2 = array[i++]; - char3 = array[i++]; - out += String.fromCharCode(((c & 0x0F) << 12) | + char2 = array[i++] + char3 = array[i++] + out += String.fromCharCode(((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | - ((char3 & 0x3F) << 0)); - break; + ((char3 & 0x3F) << 0)) + break } - } - return out; + } + return out } - function isDataView(obj) { + function isDataView (obj) { return obj && DataView.prototype.isPrototypeOf(obj) } - function bufferClone(buf) { + function bufferClone (buf) { var view = new Array(buf.byteLength) var array = new Uint8Array(buf) var i = view.length - while(i--) { + while (i--) { view[i] = array[i] } return view } - function encodeByteArray(input) { - var byteToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + function encodeByteArray (input) { + var byteToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' - var output = []; + var output = [] for (var i = 0; i < input.length; i += 3) { - var byte1 = input[i]; - var haveByte2 = i + 1 < input.length; - var byte2 = haveByte2 ? input[i + 1] : 0; - var haveByte3 = i + 2 < input.length; - var byte3 = haveByte3 ? input[i + 2] : 0; + var byte1 = input[i] + var haveByte2 = i + 1 < input.length + var byte2 = haveByte2 ? input[i + 1] : 0 + var haveByte3 = i + 2 < input.length + var byte3 = haveByte3 ? input[i + 2] : 0 - var outByte1 = byte1 >> 2; - var outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4); - var outByte3 = ((byte2 & 0x0F) << 2) | (byte3 >> 6); - var outByte4 = byte3 & 0x3F; + var outByte1 = byte1 >> 2 + var outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4) + var outByte3 = ((byte2 & 0x0F) << 2) | (byte3 >> 6) + var outByte4 = byte3 & 0x3F if (!haveByte3) { - outByte4 = 64; + outByte4 = 64 if (!haveByte2) { - outByte3 = 64; + outByte3 = 64 } } @@ -199,11 +196,11 @@ } var create = Object.create || function (a) { - function c() {} - c.prototype = a; - return new c + function c () {} + c.prototype = a + return new c() } - + if (arrayBufferSupported) { var viewClasses = [ '[object Int8Array]', @@ -217,17 +214,15 @@ '[object Float64Array]' ] - var isArrayBufferView = ArrayBuffer.isView || function(obj) { + var isArrayBufferView = ArrayBuffer.isView || function (obj) { return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1 } } - - /********************************************************/ /* Blob constructor */ /********************************************************/ - function Blob(chunks, opts) { + function Blob (chunks, opts) { chunks = chunks || [] for (var i = 0, len = chunks.length; i < len; i++) { var chunk = chunks[i] @@ -249,54 +244,52 @@ this.type = opts ? opts.type || '' : '' } - Blob.prototype.slice = function(start, end, type) { + Blob.prototype.slice = function (start, end, type) { var slice = this._buffer.slice(start || 0, end || this._buffer.length) return new Blob([slice], {type: type}) } - Blob.prototype.toString = function() { + Blob.prototype.toString = function () { return '[object Blob]' } - - /********************************************************/ /* File constructor */ /********************************************************/ - function File(chunks, name, opts) { + function File (chunks, name, opts) { opts = opts || {} var a = Blob.call(this, chunks, opts) || this a.name = name - a.lastModifiedDate = opts.lastModified ? new Date(opts.lastModified) : new Date + a.lastModifiedDate = opts.lastModified ? new Date(opts.lastModified) : new Date() a.lastModified = +a.lastModifiedDate - + return a } - File.prototype = create(Blob.prototype); - File.prototype.constructor = File; + File.prototype = create(Blob.prototype) + File.prototype.constructor = File - if (Object.setPrototypeOf) - Object.setPrototypeOf(File, Blob); - else { - try {File.__proto__ = Blob} catch (e) {} + if (Object.setPrototypeOf) { + Object.setPrototypeOf(File, Blob) + } else { + try { File.__proto__ = Blob } catch (e) {} } - File.prototype.toString = function() { + File.prototype.toString = function () { return '[object File]' } - /********************************************************/ /* FileReader constructor */ /********************************************************/ - function FileReader() { - if (!(this instanceof FileReader)) - throw new TypeError("Failed to construct 'FileReader': Please use the 'new' operator, this DOM object constructor cannot be called as a function.") + function FileReader () { + if (!(this instanceof FileReader)) { + throw new TypeError("Failed to construct 'FileReader': Please use the 'new' operator, this DOM object constructor cannot be called as a function.") + } var delegate = document.createDocumentFragment() this.addEventListener = delegate.addEventListener - this.dispatchEvent = function(evt) { + this.dispatchEvent = function (evt) { var local = this['on' + evt.type] if (typeof local === 'function') local(evt) delegate.dispatchEvent(evt) @@ -304,13 +297,14 @@ this.removeEventListener = delegate.removeEventListener } - function _read(fr, blob, kind) { - if (!(blob instanceof Blob)) - throw new TypeError("Failed to execute '" + kind + "' on 'FileReader': parameter 1 is not of type 'Blob'.") - + function _read (fr, blob, kind) { + if (!(blob instanceof Blob)) { + throw new TypeError("Failed to execute '" + kind + "' on 'FileReader': parameter 1 is not of type 'Blob'.") + } + fr.result = '' - setTimeout(function(){ + setTimeout(function () { this.readyState = FileReader.LOADING fr.dispatchEvent(new Event('load')) fr.dispatchEvent(new Event('loadend')) @@ -328,34 +322,33 @@ FileReader.prototype.onloadstart = null FileReader.prototype.onprogress = null - FileReader.prototype.readAsDataURL = function(blob) { + FileReader.prototype.readAsDataURL = function (blob) { _read(this, blob, 'readAsDataURL') this.result = 'data:' + blob.type + ';base64,' + encodeByteArray(blob._buffer) } - FileReader.prototype.readAsText = function(blob) { + FileReader.prototype.readAsText = function (blob) { _read(this, blob, 'readAsText') this.result = fromUtf8Array(blob._buffer) } - FileReader.prototype.readAsArrayBuffer = function(blob) { + FileReader.prototype.readAsArrayBuffer = function (blob) { _read(this, blob, 'readAsText') this.result = blob._buffer.slice() } - FileReader.prototype.abort = function() {} + FileReader.prototype.abort = function () {} - /********************************************************/ /* URL */ /********************************************************/ - URL.createObjectURL = function(blob) { - return blob instanceof Blob + URL.createObjectURL = function (blob) { + return blob instanceof Blob ? 'data:' + blob.type + ';base64,' + encodeByteArray(blob._buffer) : createObjectURL.call(URL, blob) } - - URL.revokeObjectURL = function(url) { + + URL.revokeObjectURL = function (url) { revokeObjectURL && revokeObjectURL.call(URL, url) } @@ -364,7 +357,7 @@ /********************************************************/ var _send = global.XMLHttpRequest && global.XMLHttpRequest.prototype.send if (_send) { - XMLHttpRequest.prototype.send = function(data) { + XMLHttpRequest.prototype.send = function (data) { if (data instanceof Blob) { this.setRequestHeader('Content-Type', data.type) _send.call(this, fromUtf8Array(data._buffer)) @@ -373,7 +366,7 @@ } } } - + global.FileReader = FileReader global.File = File global.Blob = Blob @@ -385,18 +378,18 @@ FileReader.prototype[strTag] = 'FileReader' } - function fixFileAndXHR() { + function fixFileAndXHR () { var isIE = !!global.ActiveXObject || ( - '-ms-scroll-limit' in document.documentElement.style && + '-ms-scroll-limit' in document.documentElement.style && '-ms-ime-align' in document.documentElement.style ) - // Monkey patched + // Monkey patched // IE don't set Content-Type header on XHR whose body is a typed Blob // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/6047383 var _send = global.XMLHttpRequest && global.XMLHttpRequest.prototype.send if (isIE && _send) { - XMLHttpRequest.prototype.send = function(data) { + XMLHttpRequest.prototype.send = function (data) { if (data instanceof Blob) { this.setRequestHeader('Content-Type', data.type) _send.call(this, data) @@ -408,34 +401,35 @@ try { new File([], '') - } catch(e) { + } catch (e) { try { - var klass = new Function('class File extends Blob {' + + var klass = new Function('class File extends Blob {' + 'constructor(chunks, name, opts) {' + 'opts = opts || {};' + 'super(chunks, opts || {});' + 'this.name = name;' + - 'this.lastModifiedDate = opts.lastModified ? new Date(opts.lastModified) : new Date;' + + 'this.lastModifiedDate = opts.lastModified ? new Date(opts.lastModified) : new Date();' + 'this.lastModified = +this.lastModifiedDate;' + '}};' + 'return new File([], ""), File' )() global.File = klass - } catch(e) { - var klass = function(b, d, c) { + } catch (e) { + var klass = function (b, d, c) { var blob = new Blob(b, c) - var t = c && void 0 !== c.lastModified ? new Date(c.lastModified) : new Date - + var t = c && void 0 !== c.lastModified ? new Date(c.lastModified) : new Date() + blob.name = d blob.lastModifiedDate = t blob.lastModified = +t - blob.toString = function() { + blob.toString = function () { return '[object File]' } - - if (strTag) + + if (strTag) { blob[strTag] = 'File' - + } + return blob } global.File = klass @@ -448,9 +442,8 @@ global.Blob = blobSupportsArrayBufferView ? global.Blob : BlobConstructor } else if (blobBuilderSupported) { fixFileAndXHR() - global.Blob = BlobBuilderConstructor; + global.Blob = BlobBuilderConstructor } else { FakeBlobBuilder() } - -})(); +})() From 04210bc55cd622e5a71e91427729ee618a84da23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jimmy=20W=C3=A4rting?= Date: Thu, 18 Apr 2019 00:21:36 +0200 Subject: [PATCH 02/11] Use TextEncoder and TextDecoder --- Blob.js | 244 +++++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 172 insertions(+), 72 deletions(-) diff --git a/Blob.js b/Blob.js index 5ad1801..d414e50 100644 --- a/Blob.js +++ b/Blob.js @@ -89,67 +89,166 @@ BlobConstructor.prototype = Blob.prototype } - function FakeBlobBuilder () { - function toUTF8Array (str) { - var utf8 = [] - for (var i = 0; i < str.length; i++) { - var charcode = str.charCodeAt(i) - if (charcode < 0x80) utf8.push(charcode) - else if (charcode < 0x800) { - utf8.push(0xc0 | (charcode >> 6), - 0x80 | (charcode & 0x3f)) - } else if (charcode < 0xd800 || charcode >= 0xe000) { - utf8.push(0xe0 | (charcode >> 12), - 0x80 | ((charcode >> 6) & 0x3f), - 0x80 | (charcode & 0x3f)) - } - // surrogate pair - else { - i++ - // UTF-16 encodes 0x10000-0x10FFFF by - // subtracting 0x10000 and splitting the - // 20 bits of 0x0-0xFFFFF into two halves - charcode = 0x10000 + (((charcode & 0x3ff) << 10) - | (str.charCodeAt(i) & 0x3ff)) - utf8.push(0xf0 | (charcode >> 18), - 0x80 | ((charcode >> 12) & 0x3f), - 0x80 | ((charcode >> 6) & 0x3f), - 0x80 | (charcode & 0x3f)) - } - } - return utf8 - } - function fromUtf8Array (array) { - var out, i, len, c - var char2, char3 - out = '' - len = array.length - i = 0 - while (i < len) { - c = array[i++] - switch (c >> 4) { - case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: - // 0xxxxxxx - out += String.fromCharCode(c) - break - case 12: case 13: - // 110x xxxx 10xx xxxx - char2 = array[i++] - out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F)) - break - case 14: - // 1110 xxxx 10xx xxxx 10xx xxxx - char2 = array[i++] - char3 = array[i++] - out += String.fromCharCode(((c & 0x0F) << 12) | - ((char2 & 0x3F) << 6) | - ((char3 & 0x3F) << 0)) - break + + /********************************************************/ + /* String Encoder fallback */ + /********************************************************/ + function stringEncode (string) { + var pos = 0 + var len = string.length + var out = [] + var Arr = global.Uint8Array || Array // Use byte array when possible + + var at = 0 // output position + var tlen = Math.max(32, len + (len >> 1) + 7) // 1.5x size + var target = new Arr((tlen >> 3) << 3) // ... but at 8 byte offset + + while (pos < len) { + var value = string.charCodeAt(pos++) + if (value >= 0xd800 && value <= 0xdbff) { + // high surrogate + if (pos < len) { + var extra = string.charCodeAt(pos) + if ((extra & 0xfc00) === 0xdc00) { + ++pos + value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000 + } + } + if (value >= 0xd800 && value <= 0xdbff) { + continue // drop lone surrogate } } - return out + + // expand the buffer if we couldn't write 4 bytes + if (at + 4 > target.length) { + tlen += 8 // minimum extra + tlen *= (1.0 + (pos / string.length) * 2) // take 2x the remaining + tlen = (tlen >> 3) << 3 // 8 byte offset + + const update = new Uint8Array(tlen) + update.set(target) + target = update + } + + if ((value & 0xffffff80) === 0) { // 1-byte + target[at++] = value // ASCII + continue + } else if ((value & 0xfffff800) === 0) { // 2-byte + target[at++] = ((value >> 6) & 0x1f) | 0xc0 + } else if ((value & 0xffff0000) === 0) { // 3-byte + target[at++] = ((value >> 12) & 0x0f) | 0xe0 + target[at++] = ((value >> 6) & 0x3f) | 0x80 + } else if ((value & 0xffe00000) === 0) { // 4-byte + target[at++] = ((value >> 18) & 0x07) | 0xf0 + target[at++] = ((value >> 12) & 0x3f) | 0x80 + target[at++] = ((value >> 6) & 0x3f) | 0x80 + } else { + // FIXME: do we care + continue + } + + target[at++] = (value & 0x3f) | 0x80 } + + return target.slice(0, at) + } + + /********************************************************/ + /* String Decoder fallback */ + /********************************************************/ + function stringDecode (buf) { + var end = buf.length + var res = [] + + var i = 0 + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + var len = res.length + var str = '' + var i = 0 + + while (i < len) { + str += String.fromCharCode.apply(String, res.slice(i, i += 0x1000)) + } + + return str + } + + // string -> buffer + var textEncode = typeof TextEncoder === 'object' + ? TextEncoder.prototype.encode.bind(new TextEncoder()) + : stringEncode + + // buffer -> string + var textDecode = typeof TextDecoder === 'object' + ? TextDecoder.prototype.decode.bind(new TextDecoder()) + : stringDecode + + function FakeBlobBuilder () { function isDataView (obj) { return obj && DataView.prototype.isPrototypeOf(obj) } @@ -162,7 +261,7 @@ } return view } - function encodeByteArray (input) { + function array2base64 (input) { var byteToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' var output = [] @@ -188,8 +287,9 @@ } output.push( - byteToCharMap[outByte1], byteToCharMap[outByte2], - byteToCharMap[outByte3], byteToCharMap[outByte4]) + byteToCharMap[outByte1], byteToCharMap[outByte2], + byteToCharMap[outByte3], byteToCharMap[outByte4] + ) } return output.join('') @@ -229,13 +329,13 @@ if (chunk instanceof Blob) { chunks[i] = chunk._buffer } else if (typeof chunk === 'string') { - chunks[i] = toUTF8Array(chunk) + chunks[i] = textEncode(chunk) } else if (arrayBufferSupported && (ArrayBuffer.prototype.isPrototypeOf(chunk) || isArrayBufferView(chunk))) { chunks[i] = bufferClone(chunk) } else if (arrayBufferSupported && isDataView(chunk)) { chunks[i] = bufferClone(chunk.buffer) } else { - chunks[i] = toUTF8Array(String(chunk)) + chunks[i] = textEncode(String(chunk)) } } @@ -283,9 +383,9 @@ /* FileReader constructor */ /********************************************************/ function FileReader () { - if (!(this instanceof FileReader)) { - throw new TypeError("Failed to construct 'FileReader': Please use the 'new' operator, this DOM object constructor cannot be called as a function.") - } + if (!(this instanceof FileReader)) { + throw new TypeError("Failed to construct 'FileReader': Please use the 'new' operator, this DOM object constructor cannot be called as a function.") + } var delegate = document.createDocumentFragment() this.addEventListener = delegate.addEventListener @@ -298,9 +398,9 @@ } function _read (fr, blob, kind) { - if (!(blob instanceof Blob)) { - throw new TypeError("Failed to execute '" + kind + "' on 'FileReader': parameter 1 is not of type 'Blob'.") - } + if (!(blob instanceof Blob)) { + throw new TypeError("Failed to execute '" + kind + "' on 'FileReader': parameter 1 is not of type 'Blob'.") + } fr.result = '' @@ -324,12 +424,12 @@ FileReader.prototype.readAsDataURL = function (blob) { _read(this, blob, 'readAsDataURL') - this.result = 'data:' + blob.type + ';base64,' + encodeByteArray(blob._buffer) + this.result = 'data:' + blob.type + ';base64,' + array2base64(blob._buffer) } FileReader.prototype.readAsText = function (blob) { _read(this, blob, 'readAsText') - this.result = fromUtf8Array(blob._buffer) + this.result = textDecode(blob._buffer) } FileReader.prototype.readAsArrayBuffer = function (blob) { @@ -344,7 +444,7 @@ /********************************************************/ URL.createObjectURL = function (blob) { return blob instanceof Blob - ? 'data:' + blob.type + ';base64,' + encodeByteArray(blob._buffer) + ? 'data:' + blob.type + ';base64,' + array2base64(blob._buffer) : createObjectURL.call(URL, blob) } @@ -360,7 +460,7 @@ XMLHttpRequest.prototype.send = function (data) { if (data instanceof Blob) { this.setRequestHeader('Content-Type', data.type) - _send.call(this, fromUtf8Array(data._buffer)) + _send.call(this, textDecode(data._buffer)) } else { _send.call(this, data) } From 99560939f793ac848ac83c5295c8532760de2661 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jimmy=20W=C3=A4rting?= Date: Thu, 18 Apr 2019 00:22:44 +0200 Subject: [PATCH 03/11] they are functions --- Blob.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Blob.js b/Blob.js index d414e50..14cb1f5 100644 --- a/Blob.js +++ b/Blob.js @@ -239,12 +239,12 @@ } // string -> buffer - var textEncode = typeof TextEncoder === 'object' + var textEncode = typeof TextEncoder === 'function' ? TextEncoder.prototype.encode.bind(new TextEncoder()) : stringEncode // buffer -> string - var textDecode = typeof TextDecoder === 'object' + var textDecode = typeof TextDecoder === 'function' ? TextDecoder.prototype.decode.bind(new TextDecoder()) : stringDecode From a3ec58c557b798cef3967fb576f125cacb657463 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jimmy=20W=C3=A4rting?= Date: Thu, 18 Apr 2019 00:56:10 +0200 Subject: [PATCH 04/11] added blob.stream(), blob.text(), blob.arrayBuffer() --- Blob.js | 103 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 103 insertions(+) diff --git a/Blob.js b/Blob.js index 14cb1f5..4805daf 100644 --- a/Blob.js +++ b/Blob.js @@ -546,4 +546,107 @@ } else { FakeBlobBuilder() } + + var blob = global.Blob.prototype + var stream + + function promisify(obj) { + return new Promise(function(resolve, reject) { + obj.onload = + obj.onerror = function(evt) { + obj.onload = + obj.onerror = null + + evt.type === 'load' + ? resolve(obj.result || obj) + : reject(new Error('Failed to read the blob/file')) + } + }) + } + + + try { + new ReadableStream({ type: 'bytes' }) + stream = function stream() { + var position = 0 + var blob = this + + return new ReadableStream({ + type: 'bytes', + autoAllocateChunkSize: 524288, + + pull: function (controller) { + var v = controller.byobRequest.view + var chunk = blob.slice(position, position + v.byteLength) + return chunk.arrayBuffer() + .then(function (buffer) { + var uint8array = new Uint8Array(buffer) + var bytesRead = uint8array.byteLength + + position += bytesRead + v.set(uint8array) + controller.byobRequest.respond(bytesRead) + + if(position >= blob.size) + controller.close() + }) + } + }) + } + } catch (e) { + try { + new ReadableStream({}) + stream = function stream(blob){ + var position = 0 + var blob = this + + return new ReadableStream({ + pull: function (controller) { + var chunk = blob.slice(position, position + 524288) + + return chunk.arrayBuffer().then(function (buffer) { + position += buffer.byteLength + var uint8array = new Uint8Array(buffer) + controller.enqueue(uint8array) + + if (position == blob.size) + controller.close() + }) + } + }) + } + } catch (e) { + try { + new Response('').body.getReader().read() + stream = function stream() { + return (new Response(this)).body + } + } catch (e) { + stream = function stream() { + throw new Error('Include https://github.com/MattiasBuelens/web-streams-polyfill') + } + } + } + } + + + if (!blob.arrayBuffer) { + blob.arrayBuffer = function arrayBuffer() { + var fr = new FileReader() + fr.readAsArrayBuffer(this) + return promisify(fr) + } + } + + if (!blob.text) { + blob.text = function text() { + var fr = new FileReader() + fr.readAsText(this) + return promisify(fr) + } + } + + if (!blob.stream) { + blob.stream = stream + } })() From 7f8c94e21055046d7c7cd1a2d4bf4fb4af0e3c71 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jimmy=20W=C3=A4rting?= Date: Thu, 18 Apr 2019 01:36:19 +0200 Subject: [PATCH 05/11] Blob not defined --- Blob.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Blob.js b/Blob.js index 4805daf..fabd941 100644 --- a/Blob.js +++ b/Blob.js @@ -472,12 +472,6 @@ global.Blob = Blob } - if (strTag) { - File.prototype[strTag] = 'File' - Blob.prototype[strTag] = 'Blob' - FileReader.prototype[strTag] = 'FileReader' - } - function fixFileAndXHR () { var isIE = !!global.ActiveXObject || ( '-ms-scroll-limit' in document.documentElement.style && @@ -547,6 +541,12 @@ FakeBlobBuilder() } + if (strTag) { + File.prototype[strTag] = 'File' + Blob.prototype[strTag] = 'Blob' + FileReader.prototype[strTag] = 'FileReader' + } + var blob = global.Blob.prototype var stream From 347f3d4f036519764d882a53adcfa08f66bd27ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jimmy=20W=C3=A4rting?= Date: Thu, 18 Apr 2019 02:10:09 +0200 Subject: [PATCH 06/11] concat to typed array when possible --- Blob.js | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/Blob.js b/Blob.js index fabd941..df7dd43 100644 --- a/Blob.js +++ b/Blob.js @@ -319,6 +319,21 @@ } } + function concatTypedarrays (chunks) { + var size = 0 + var i = chunks.length + while (i--) { size += chunks[i].length } + var b = new Uint8Array(size) + var offset = 0 + for (i = 0, l = chunks.length; i < l; i++) { + var chunk = chunks[i] + b.set(chunk, offset) + offset += chunk.byteLength || chunk.length + } + + return b + } + /********************************************************/ /* Blob constructor */ /********************************************************/ @@ -339,7 +354,9 @@ } } - this._buffer = [].concat.apply([], chunks) + this._buffer = global.Uint8Array + ? concatTypedarrays(chunks) + : [].concat.apply([], chunks) this.size = this._buffer.length this.type = opts ? opts.type || '' : '' } From 6682a51050840b05d898f6f6bc3d34640603c828 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jimmy=20W=C3=A4rting?= Date: Fri, 19 Apr 2019 16:50:22 +0200 Subject: [PATCH 07/11] discard bad mime types per spec --- Blob.js | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/Blob.js b/Blob.js index df7dd43..247a2a1 100644 --- a/Blob.js +++ b/Blob.js @@ -358,7 +358,14 @@ ? concatTypedarrays(chunks) : [].concat.apply([], chunks) this.size = this._buffer.length - this.type = opts ? opts.type || '' : '' + + this.type = opts.type || '' + if (/[^\u0020-\u007E]/.test(this.type)) { + this.type = '' + } else { + this.type = this.type.toLowerCase() + } + } Blob.prototype.slice = function (start, end, type) { From 5735017461fc3a1180b61b8a30d034a75a0e1c28 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jimmy=20W=C3=A4rting?= Date: Fri, 19 Apr 2019 16:50:55 +0200 Subject: [PATCH 08/11] Slash should be converted to colon --- Blob.js | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Blob.js b/Blob.js index 247a2a1..41c23f7 100644 --- a/Blob.js +++ b/Blob.js @@ -339,6 +339,7 @@ /********************************************************/ function Blob (chunks, opts) { chunks = chunks || [] + opts = opts == null ? {} : opts for (var i = 0, len = chunks.length; i < len; i++) { var chunk = chunks[i] if (chunk instanceof Blob) { @@ -383,7 +384,7 @@ function File (chunks, name, opts) { opts = opts || {} var a = Blob.call(this, chunks, opts) || this - a.name = name + a.name = name.replace(/\//g, ':') a.lastModifiedDate = opts.lastModified ? new Date(opts.lastModified) : new Date() a.lastModified = +a.lastModifiedDate @@ -525,7 +526,7 @@ 'constructor(chunks, name, opts) {' + 'opts = opts || {};' + 'super(chunks, opts || {});' + - 'this.name = name;' + + 'this.name = name.replace(/\//g, ":");' + 'this.lastModifiedDate = opts.lastModified ? new Date(opts.lastModified) : new Date();' + 'this.lastModified = +this.lastModifiedDate;' + '}};' + @@ -537,7 +538,7 @@ var blob = new Blob(b, c) var t = c && void 0 !== c.lastModified ? new Date(c.lastModified) : new Date() - blob.name = d + blob.name = d.replace(/\//g, ':') blob.lastModifiedDate = t blob.lastModified = +t blob.toString = function () { From eb14683b06fdde1554a078a84de08bee8a6d863b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jimmy=20W=C3=A4rting?= Date: Fri, 19 Apr 2019 17:26:07 +0200 Subject: [PATCH 09/11] added arrayBuffer and text methods to blob --- Blob.js | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Blob.js b/Blob.js index 41c23f7..5789e80 100644 --- a/Blob.js +++ b/Blob.js @@ -366,7 +366,14 @@ } else { this.type = this.type.toLowerCase() } + } + Blob.prototype.arrayBuffer = function () { + return Promise.resolve(this._buffer) + } + + Blob.prototype.text = function () { + return Promise.resolve(textDecode(this._buffer)) } Blob.prototype.slice = function (start, end, type) { From 107ede17899906e16b149ed1e44dc62936f64972 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jimmy=20W=C3=A4rting?= Date: Fri, 19 Apr 2019 17:26:24 +0200 Subject: [PATCH 10/11] Return array buffer when possible --- Blob.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Blob.js b/Blob.js index 5789e80..164e42d 100644 --- a/Blob.js +++ b/Blob.js @@ -465,8 +465,9 @@ } FileReader.prototype.readAsArrayBuffer = function (blob) { - _read(this, blob, 'readAsText') - this.result = blob._buffer.slice() + _read(this, blob, 'readAsText') + // return ArrayBuffer when possible + this.result = (blob._buffer.buffer || blob._buffer).slice() } FileReader.prototype.abort = function () {} From ecf7fe0eb4ee6dc8f4cf62f0c5196b425d6ee5b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jimmy=20W=C3=A4rting?= Date: Fri, 19 Apr 2019 18:10:29 +0200 Subject: [PATCH 11/11] updated the date --- Blob.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Blob.js b/Blob.js index 164e42d..27608cc 100644 --- a/Blob.js +++ b/Blob.js @@ -1,6 +1,6 @@ /* Blob.js * A Blob, File, FileReader & URL implementation. - * 2018-08-09 + * 2019-04-19 * * By Eli Grey, http://eligrey.com * By Jimmy Wärting, https://github.com/jimmywarting