/** * Installs a UTF-8 `TextDecoder` on `g` when it has none, as the Hermes of * React Native before 0.88 doesn't. `withEffectUi` writes it out as a * script that runs before the bundle, so it uses nothing from outside, * not even the Babel helpers Metro would load with `require`. * * @internal */ export const installTextDecoder = (g: any): void => { if (g.TextDecoder !== undefined) return const replacement = 0xfffd // A function constructor, as a class or spread compiles to helpers. function TextDecoder( this: any, label = "utf-8", options?: { readonly fatal?: boolean; readonly ignoreBOM?: boolean } ) { if (!/^\s*(?:unicode-1-1-)?utf-?8\s*$/i.test(label)) { throw new RangeError(`The "${label}" encoding is not supported`) } this.encoding = "utf-8" this.fatal = options?.fatal === true this.ignoreBOM = options?.ignoreBOM === true this.pending = new Uint8Array(0) this.started = false } TextDecoder.prototype.decode = function( this: any, input?: ArrayBuffer | ArrayBufferView, options?: { readonly stream?: boolean } ): string { const { fatal, ignoreBOM } = this const view = input === undefined ? new Uint8Array(0) : ArrayBuffer.isView(input) ? new Uint8Array(input.buffer, input.byteOffset, input.byteLength) : new Uint8Array(input) const pending: Uint8Array = this.pending let bytes = view if (pending.length > 0) { bytes = new Uint8Array(pending.length + view.length) bytes.set(pending) bytes.set(view, pending.length) this.pending = new Uint8Array(0) } const stream = options?.stream === true const codes: Array = [] const n = bytes.length let i = 0 while (i < n) { const b = bytes[i]! if (b < 0x80) { codes.push(b) i++ continue } // The lead byte's length and its first continuation's bounds, as // the Encoding Standard sets them. const need = b >= 0xc2 && b <= 0xdf ? 1 : b >= 0xe0 && b <= 0xef ? 2 : b >= 0xf0 && b <= 0xf4 ? 3 : 0 let lower = b === 0xe0 ? 0xa0 : b === 0xf0 ? 0x90 : 0x80 let upper = b === 0xed ? 0x9f : b === 0xf4 ? 0x8f : 0xbf let code = b & (0x3f >> need) // Continuation bytes read, up to the first that doesn't fit. let j = 0 while (j < need && i + 1 + j < n) { const c = bytes[i + 1 + j]! if (c < lower || c > upper) break lower = 0x80 upper = 0xbf code = (code << 6) | (c & 0x3f) j++ } if (need > 0 && j === need) { codes.push(code) i += 1 + j continue } if (need > 0 && i + 1 + j === n && stream) { this.pending = bytes.slice(i) break } if (fatal) throw new TypeError("The encoded data was not valid") codes.push(replacement) i += 1 + j } const any = codes.length > 0 if (!this.started && !ignoreBOM && codes[0] === 0xfeff) codes.shift() this.started = stream && (this.started || any) let out = "" for (let k = 0; k < codes.length; k += 4096) { out += String.fromCodePoint.apply(null, codes.slice(k, k + 4096)) } return out } g.TextDecoder = TextDecoder }