Best JavaScript code snippet using puppeteer
Fetcher.ts
Source:Fetcher.ts
...97 if (value) {98 values.push(value);99 receivedLength += value.length;100 if (onProgress) {101 onProgress(receivedLength, Math.max(receivedLength, contentLength), path);102 }103 }104 }105 const buffer = new ArrayBuffer(receivedLength);106 const array = new Uint8Array(buffer);107 receivedLength = 0;108 for (const value of values) {109 array.set(value, receivedLength);110 receivedLength += value.length;111 }112 if (onProgress) {113 onProgress(1, 1, path);114 }115 return { buffer, contentType };116 }117 protected async _getBuffer(path: string, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<getPartsReturnType> {118 onProgress = this.normalizeOnProgress(headerMap, onProgress);119 headerMap = this.normalizeHeaderMap(headerMap);120 const response = await this.getResponse(path, headerMap);121 return await this.readResponseBuffer(path, response, onProgress);122 }123 async getBuffer(path: string): Promise<getPartsReturnType>;124 async getBuffer(path: string, onProgress?: progressCallback): Promise<getPartsReturnType>;125 async getBuffer(path: string, headerMap?: Map<string, string>): Promise<getPartsReturnType>;126 async getBuffer(path: string, headerMap?: Map<string, string>, onProgress?: progressCallback): Promise<getPartsReturnType>;127 async getBuffer(path: string, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<getPartsReturnType> {128 return await this._getBuffer(path, headerMap, onProgress);129 }130 protected async _postObjectForBuffer<T>(path: string, obj: T, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<getPartsReturnType> {131 onProgress = this.normalizeOnProgress(headerMap, onProgress);132 headerMap = this.normalizeHeaderMap(headerMap);133 const response = await this.postObjectForResponse(path, obj, headerMap);134 return await this.readResponseBuffer(path, response, onProgress);135 }136 async postObjectForBuffer<T>(path: string, obj: T): Promise<getPartsReturnType>;137 async postObjectForBuffer<T>(path: string, obj: T, onProgress?: progressCallback): Promise<getPartsReturnType>;138 async postObjectForBuffer<T>(path: string, obj: T, headerMap?: Map<string, string>): Promise<getPartsReturnType>;139 async postObjectForBuffer<T>(path: string, obj: T, headerMap?: Map<string, string>, onProgress?: progressCallback): Promise<getPartsReturnType>;140 async postObjectForBuffer<T>(path: string, obj: T, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<getPartsReturnType> {141 return await this._postObjectForBuffer(path, obj, headerMap, onProgress);142 }143 protected async _getBlob(path: string, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<Blob> {144 onProgress = this.normalizeOnProgress(headerMap, onProgress);145 headerMap = this.normalizeHeaderMap(headerMap);146 const { buffer, contentType } = await this._getBuffer(path, headerMap, onProgress);147 return new Blob([buffer], { type: contentType });148 }149 async getBlob(path: string): Promise<Blob>;150 async getBlob(path: string, onProgress?: progressCallback): Promise<Blob>;151 async getBlob(path: string, headerMap?: Map<string, string>): Promise<Blob>;152 async getBlob(path: string, headerMap?: Map<string, string>, onProgress?: progressCallback): Promise<Blob>;153 async getBlob(path: string, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<Blob> {154 return this._getBlob(path, headerMap, onProgress);155 }156 protected async _postObjectForBlob<T>(path: string, obj: T, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback) {157 onProgress = this.normalizeOnProgress(headerMap, onProgress);158 headerMap = this.normalizeHeaderMap(headerMap);159 const { buffer, contentType } = await this._postObjectForBuffer(path, obj, headerMap, onProgress);160 return new Blob([buffer], { type: contentType });161 }162 async postObjectForBlob<T>(path: string, obj: T): Promise<Blob>;163 async postObjectForBlob<T>(path: string, obj: T, onProgress?: progressCallback): Promise<Blob>;164 async postObjectForBlob<T>(path: string, obj: T, headerMap?: Map<string, string>): Promise<Blob>;165 async postObjectForBlob<T>(path: string, obj: T, headerMap?: Map<string, string>, onProgress?: progressCallback): Promise<Blob>;166 async postObjectForBlob<T>(path: string, obj: T, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback) {167 return this._postObjectForBlob(path, obj, headerMap, onProgress);168 }169 protected async _getFile(path: string, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<string> {170 onProgress = this.normalizeOnProgress(headerMap, onProgress);171 headerMap = this.normalizeHeaderMap(headerMap);172 const blob = await this._getBlob(path, headerMap, onProgress);173 return URL.createObjectURL(blob);174 }175 async getFile(path: string): Promise<string>;176 async getFile(path: string, onProgress?: progressCallback): Promise<string>;177 async getFile(path: string, headerMap?: Map<string, string>): Promise<string>;178 async getFile(path: string, headerMap?: Map<string, string>, onProgress?: progressCallback): Promise<string>;179 async getFile(path: string, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<string> {180 return await this._getFile(path, headerMap, onProgress);181 }182 protected async _postObjectForFile<T>(path: string, obj: T, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<string> {183 onProgress = this.normalizeOnProgress(headerMap, onProgress);184 headerMap = this.normalizeHeaderMap(headerMap);185 const blob = await this._postObjectForBlob(path, obj, headerMap, onProgress);186 return URL.createObjectURL(blob);187 }188 async postObjectForFile<T>(path: string, obj: T): Promise<string>;189 async postObjectForFile<T>(path: string, obj: T, onProgress?: progressCallback): Promise<string>;190 async postObjectForFile<T>(path: string, obj: T, headerMap?: Map<string, string>): Promise<string>;191 async postObjectForFile<T>(path: string, obj: T, headerMap?: Map<string, string>, onProgress?: progressCallback): Promise<string>;192 async postObjectForFile<T>(path: string, obj: T, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<string> {193 return await this._postObjectForFile(path, obj, headerMap, onProgress);194 }195 private readBufferText(buffer: ArrayBuffer): string {196 const decoder = new TextDecoder("utf-8");197 const text = decoder.decode(buffer);198 return text;199 }200 protected async _getText(path: string, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<string> {201 onProgress = this.normalizeOnProgress(headerMap, onProgress);202 headerMap = this.normalizeHeaderMap(headerMap);203 const { buffer } = await this._getBuffer(path, headerMap, onProgress);204 return this.readBufferText(buffer);205 }206 async getText(path: string): Promise<string>;207 async getText(path: string, onProgress?: progressCallback): Promise<string>;208 async getText(path: string, headerMap?: Map<string, string>): Promise<string>;209 async getText(path: string, headerMap?: Map<string, string>, onProgress?: progressCallback): Promise<string>;210 async getText(path: string, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<string> {211 return await this._getText(path, headerMap, onProgress);212 }213 private async _postObjectForText<T>(path: string, obj: T, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<string> {214 onProgress = this.normalizeOnProgress(headerMap, onProgress);215 headerMap = this.normalizeHeaderMap(headerMap);216 const { buffer } = await this._postObjectForBuffer(path, obj, headerMap, onProgress);217 return this.readBufferText(buffer);218 }219 async postObjectForText<T>(path: string, obj: T): Promise<string>;220 async postObjectForText<T>(path: string, obj: T, onProgress?: progressCallback): Promise<string>;221 async postObjectForText<T>(path: string, obj: T, headerMap?: Map<string, string>): Promise<string>;222 async postObjectForText<T>(path: string, obj: T, headerMap?: Map<string, string>, onProgress?: progressCallback): Promise<string>;223 async postObjectForText<T>(path: string, obj: T, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<string> {224 return await this._postObjectForText(path, obj, headerMap, onProgress);225 }226 private setDefaultAcceptType(headerMap: Map<string, string> | undefined, type: string): Map<string, string> {227 if (!headerMap) {228 headerMap = new Map<string, string>();229 }230 if (!headerMap.has("Accept")) {231 headerMap.set("Accept", type);232 }233 return headerMap;234 }235 protected async _getObject<T>(path: string, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<T> {236 onProgress = this.normalizeOnProgress(headerMap, onProgress);237 headerMap = this.normalizeHeaderMap(headerMap);238 headerMap = this.setDefaultAcceptType(headerMap, "application/json");239 const text = await this._getText(path, headerMap, onProgress);240 return JSON.parse(text) as T;241 }242 async getObject<T>(path: string): Promise<T>;243 async getObject<T>(path: string, onProgress?: progressCallback): Promise<T>;244 async getObject<T>(path: string, headerMap?: Map<string, string>): Promise<T>;245 async getObject<T>(path: string, headerMap?: Map<string, string>, onProgress?: progressCallback): Promise<T>;246 async getObject<T>(path: string, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<T> {247 return await this._getObject<T>(path, headerMap, onProgress);248 }249 protected async _postObjectForObject<T, U>(path: string, obj: T, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<U> {250 onProgress = this.normalizeOnProgress(headerMap, onProgress);251 headerMap = this.normalizeHeaderMap(headerMap);252 headerMap = this.setDefaultAcceptType(headerMap, "application/json");253 const text = await this._postObjectForText(path, obj, headerMap, onProgress);254 return JSON.parse(text) as U;255 }256 async postObjectForObject<T, U>(path: string, obj: T): Promise<U>;257 async postObjectForObject<T, U>(path: string, obj: T, onProgress?: progressCallback): Promise<U>;258 async postObjectForObject<T, U>(path: string, obj: T, headerMap?: Map<string, string>): Promise<U>;259 async postObjectForObject<T, U>(path: string, obj: T, headerMap?: Map<string, string>, onProgress?: progressCallback): Promise<U>;260 async postObjectForObject<T, U>(path: string, obj: T, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<U> {261 return await this._postObjectForObject<T, U>(path, obj, headerMap, onProgress);262 }263 async postObject<T>(path: string, obj: T): Promise<void>;264 async postObject<T>(path: string, obj: T, headerMap?: Map<string, string>): Promise<void>;265 async postObject<T>(path: string, obj: T, onProgress?: progressCallback): Promise<void>;266 async postObject<T>(path: string, obj: T, headerMap?: Map<string, string>, onProgress?: progressCallback): Promise<void>;267 async postObject<T>(path: string, obj: T, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<void> {268 onProgress = this.normalizeOnProgress(headerMap, onProgress);269 headerMap = this.normalizeHeaderMap(headerMap);270 if (onProgress instanceof Function) {271 const [upProg, downProg] = splitProgress(onProgress, 2);272 let headers: Map<string, string> | undefined = headerMap;273 const xhr = new XMLHttpRequest();274 function makeTask(name: string, target: (XMLHttpRequest | XMLHttpRequestUpload), onProgress: progressCallback, skipLoading: boolean, prevTask: Promise<void>): Promise<void> {275 return new Promise((resolve: () => void, reject: (status: number) => void) => {276 let done = false;277 let loaded = skipLoading;278 function maybeResolve() {279 if (loaded && done) {280 resolve();281 }282 }283 async function onError() {284 await prevTask;285 reject(xhr.status);286 }287 target.addEventListener("loadstart", async () => {288 await prevTask;289 onProgress(0, 1, name);290 });291 target.addEventListener("progress", async (ev: Event) => {292 const evt = ev as ProgressEvent<XMLHttpRequestEventTarget>;293 await prevTask;294 onProgress(evt.loaded, evt.total, name);295 if (evt.loaded === evt.total) {296 loaded = true;297 maybeResolve();298 }299 });300 target.addEventListener("load", async () => {301 await prevTask;302 onProgress(1, 1, name);303 done = true;304 maybeResolve();305 });306 target.addEventListener("error", onError);307 target.addEventListener("abort", onError);308 });309 }310 const upload = makeTask("uploading", xhr.upload, upProg, false, Promise.resolve());311 const download = makeTask("saving", xhr, downProg, true, upload);312 xhr.open("POST", path);313 if (headers) {314 for (const [key, value] of headers) {315 xhr.setRequestHeader(key, value);316 }317 }318 if (obj instanceof FormData) {319 xhr.send(obj);320 }321 else {322 const json = JSON.stringify(obj);323 xhr.send(json);324 }325 await upload;326 await download;327 }328 else {329 await this.postObjectForResponse(path, obj, headerMap);330 }331 }332 private readTextXml(text: string): HTMLElement {333 const parser = new DOMParser();334 const xml = parser.parseFromString(text, "text/xml");335 return xml.documentElement;336 }337 protected async _getXml(path: string, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<HTMLElement> {338 onProgress = this.normalizeOnProgress(headerMap, onProgress);339 headerMap = this.normalizeHeaderMap(headerMap);340 const text = await this._getText(path, headerMap, onProgress);341 return this.readTextXml(text);342 }343 async getXml(path: string): Promise<HTMLElement>;344 async getXml(path: string, onProgress?: progressCallback): Promise<HTMLElement>;345 async getXml(path: string, headerMap?: Map<string, string>): Promise<HTMLElement>;346 async getXml(path: string, headerMap?: Map<string, string>, onProgress?: progressCallback): Promise<HTMLElement>;347 async getXml(path: string, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<HTMLElement> {348 return await this._getXml(path, headerMap, onProgress);349 }350 async postObjectForXml<T>(path: string, obj: T): Promise<HTMLElement>;351 async postObjectForXml<T>(path: string, obj: T, onProgress?: progressCallback): Promise<HTMLElement>;352 async postObjectForXml<T>(path: string, obj: T, headerMap?: Map<string, string>): Promise<HTMLElement>;353 async postObjectForXml<T>(path: string, obj: T, headerMap?: Map<string, string>, onProgress?: progressCallback): Promise<HTMLElement>;354 async postObjectForXml<T>(path: string, obj: T, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<HTMLElement> {355 const text = await this._postObjectForText(path, obj, headerMap, onProgress);356 return this.readTextXml(text);357 }358 async loadScript(path: string, test: () => boolean, onProgress?: progressCallback): Promise<void> {359 if (!test()) {360 const scriptLoadTask = waitFor(test);361 const file = await this.getFile(path, onProgress);362 createScript(file);363 await scriptLoadTask;364 }365 else if (onProgress) {366 onProgress(1, 1, "skip");367 }368 }...
zip-fs.js
Source:zip-fs.js
1/*2 Copyright (c) 2013 Gildas Lormeau. All rights reserved.3 Redistribution and use in source and binary forms, with or without4 modification, are permitted provided that the following conditions are met:5 1. Redistributions of source code must retain the above copyright notice,6 this list of conditions and the following disclaimer.7 2. Redistributions in binary form must reproduce the above copyright 8 notice, this list of conditions and the following disclaimer in 9 the documentation and/or other materials provided with the distribution.10 3. The names of the authors may not be used to endorse or promote products11 derived from this software without specific prior written permission.12 THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,13 INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND14 FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,15 INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,16 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT17 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,18 OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF19 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING20 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,21 EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.22 */23(function() {24 var CHUNK_SIZE = 512 * 1024;25 var TextWriter = zip.TextWriter, //26 BlobWriter = zip.BlobWriter, //27 Data64URIWriter = zip.Data64URIWriter, //28 Reader = zip.Reader, //29 TextReader = zip.TextReader, //30 BlobReader = zip.BlobReader, //31 Data64URIReader = zip.Data64URIReader, //32 createReader = zip.createReader, //33 createWriter = zip.createWriter;34 function ZipBlobReader(entry) {35 var that = this, blobReader;36 function init(callback) {37 this.size = entry.uncompressedSize;38 callback();39 }40 function getData(callback) {41 if (that.data)42 callback();43 else44 entry.getData(new BlobWriter(), function(data) {45 that.data = data;46 blobReader = new BlobReader(data);47 callback();48 }, null, that.checkCrc32);49 }50 function readUint8Array(index, length, callback, onerror) {51 getData(function() {52 blobReader.readUint8Array(index, length, callback, onerror);53 }, onerror);54 }55 that.size = 0;56 that.init = init;57 that.readUint8Array = readUint8Array;58 }59 ZipBlobReader.prototype = new Reader();60 ZipBlobReader.prototype.constructor = ZipBlobReader;61 ZipBlobReader.prototype.checkCrc32 = false;62 function getTotalSize(entry) {63 var size = 0;64 function process(entry) {65 size += entry.uncompressedSize || 0;66 entry.children.forEach(process);67 }68 process(entry);69 return size;70 }71 function initReaders(entry, onend, onerror) {72 var index = 0;73 function next() {74 index++;75 if (index < entry.children.length)76 process(entry.children[index]);77 else78 onend();79 }80 function process(child) {81 if (child.directory)82 initReaders(child, next, onerror);83 else {84 child.reader = new child.Reader(child.data, onerror);85 child.reader.init(function() {86 child.uncompressedSize = child.reader.size;87 next();88 });89 }90 }91 if (entry.children.length)92 process(entry.children[index]);93 else94 onend();95 }96 function detach(entry) {97 var children = entry.parent.children;98 children.forEach(function(child, index) {99 if (child.id == entry.id)100 children.splice(index, 1);101 });102 }103 function exportZip(zipWriter, entry, onend, onprogress, totalSize) {104 var currentIndex = 0;105 function process(zipWriter, entry, onend, onprogress, totalSize) {106 var childIndex = 0;107 function exportChild() {108 var child = entry.children[childIndex];109 if (child)110 zipWriter.add(child.getFullname(), child.reader, function() {111 currentIndex += child.uncompressedSize || 0;112 process(zipWriter, child, function() {113 childIndex++;114 exportChild();115 }, onprogress, totalSize);116 }, function(index) {117 if (onprogress)118 onprogress(currentIndex + index, totalSize);119 }, {120 directory : child.directory,121 version : child.zipVersion122 });123 else124 onend();125 }126 exportChild();127 }128 process(zipWriter, entry, onend, onprogress, totalSize);129 }130 function addFileEntry(zipEntry, fileEntry, onend, onerror) {131 function getChildren(fileEntry, callback) {132 if (fileEntry.isDirectory)133 fileEntry.createReader().readEntries(callback);134 if (fileEntry.isFile)135 callback([]);136 }137 function process(zipEntry, fileEntry, onend) {138 getChildren(fileEntry, function(children) {139 var childIndex = 0;140 function addChild(child) {141 function nextChild(childFileEntry) {142 process(childFileEntry, child, function() {143 childIndex++;144 processChild();145 });146 }147 if (child.isDirectory)148 nextChild(zipEntry.addDirectory(child.name));149 if (child.isFile)150 child.file(function(file) {151 var childZipEntry = zipEntry.addBlob(child.name, file);152 childZipEntry.uncompressedSize = file.size;153 nextChild(childZipEntry);154 }, onerror);155 }156 function processChild() {157 var child = children[childIndex];158 if (child)159 addChild(child);160 else161 onend();162 }163 processChild();164 });165 }166 if (fileEntry.isDirectory)167 process(zipEntry, fileEntry, onend);168 else169 fileEntry.file(function(file) {170 zipEntry.addBlob(fileEntry.name, file);171 onend();172 }, onerror);173 }174 function getFileEntry(fileEntry, entry, onend, onprogress, onerror, totalSize, checkCrc32) {175 var currentIndex = 0;176 function process(fileEntry, entry, onend, onprogress, onerror, totalSize) {177 var childIndex = 0;178 function addChild(child) {179 function nextChild(childFileEntry) {180 currentIndex += child.uncompressedSize || 0;181 process(childFileEntry, child, function() {182 childIndex++;183 processChild();184 }, onprogress, onerror, totalSize);185 }186 if (child.directory)187 fileEntry.getDirectory(child.name, {188 create : true189 }, nextChild, onerror);190 else191 fileEntry.getFile(child.name, {192 create : true193 }, function(file) {194 child.getData(new zip.FileWriter(file, zip.getMimeType(child.name)), nextChild, function(index) {195 if (onprogress)196 onprogress(currentIndex + index, totalSize);197 }, checkCrc32);198 }, onerror);199 }200 function processChild() {201 var child = entry.children[childIndex];202 if (child)203 addChild(child);204 else205 onend();206 }207 processChild();208 }209 if (entry.directory)210 process(fileEntry, entry, onend, onprogress, onerror, totalSize);211 else212 entry.getData(new zip.FileWriter(fileEntry, zip.getMimeType(entry.name)), onend, onprogress, checkCrc32);213 }214 function resetFS(fs) {215 fs.entries = [];216 fs.root = new ZipDirectoryEntry(fs);217 }218 function bufferedCopy(reader, writer, onend, onprogress, onerror) {219 var chunkIndex = 0;220 function stepCopy() {221 var index = chunkIndex * CHUNK_SIZE;222 if (onprogress)223 onprogress(index, reader.size);224 if (index < reader.size)225 reader.readUint8Array(index, Math.min(CHUNK_SIZE, reader.size - index), function(array) {226 writer.writeUint8Array(new Uint8Array(array), function() {227 chunkIndex++;228 stepCopy();229 });230 }, onerror);231 else232 writer.getData(onend);233 }234 stepCopy();235 }236 function getEntryData(writer, onend, onprogress, onerror) {237 var that = this;238 if (!writer || (writer.constructor == that.Writer && that.data))239 onend(that.data);240 else {241 if (!that.reader)242 that.reader = new that.Reader(that.data, onerror);243 that.reader.init(function() {244 writer.init(function() {245 bufferedCopy(that.reader, writer, onend, onprogress, onerror);246 }, onerror);247 });248 }249 }250 function addChild(parent, name, params, directory) {251 if (parent.directory)252 return directory ? new ZipDirectoryEntry(parent.fs, name, params, parent) : new ZipFileEntry(parent.fs, name, params, parent);253 else254 throw "Parent entry is not a directory.";255 }256 function ZipEntry() {257 }258 ZipEntry.prototype = {259 init : function(fs, name, params, parent) {260 var that = this;261 if (fs.root && parent && parent.getChildByName(name))262 throw "Entry filename already exists.";263 if (!params)264 params = {};265 that.fs = fs;266 that.name = name;267 that.id = fs.entries.length;268 that.parent = parent;269 that.children = [];270 that.zipVersion = params.zipVersion || 0x14;271 that.uncompressedSize = 0;272 fs.entries.push(that);273 if (parent)274 that.parent.children.push(that);275 },276 getFileEntry : function(fileEntry, onend, onprogress, onerror, checkCrc32) {277 var that = this;278 initReaders(that, function() {279 getFileEntry(fileEntry, that, onend, onprogress, onerror, getTotalSize(that), checkCrc32);280 }, onerror);281 },282 moveTo : function(target) {283 var that = this;284 if (target.directory) {285 if (!target.isDescendantOf(that)) {286 if (that != target) {287 if (target.getChildByName(that.name))288 throw "Entry filename already exists.";289 detach(that);290 that.parent = target;291 target.children.push(that);292 }293 } else294 throw "Entry is a ancestor of target entry.";295 } else296 throw "Target entry is not a directory.";297 },298 getFullname : function() {299 var that = this, fullname = that.name, entry = that.parent;300 while (entry) {301 fullname = (entry.name ? entry.name + "/" : "") + fullname;302 entry = entry.parent;303 }304 return fullname;305 },306 isDescendantOf : function(ancestor) {307 var entry = this.parent;308 while (entry && entry.id != ancestor.id)309 entry = entry.parent;310 return !!entry;311 }312 };313 ZipEntry.prototype.constructor = ZipEntry;314 var ZipFileEntryProto;315 function ZipFileEntry(fs, name, params, parent) {316 var that = this;317 ZipEntry.prototype.init.call(that, fs, name, params, parent);318 that.Reader = params.Reader;319 that.Writer = params.Writer;320 that.data = params.data;321 that.getData = params.getData || getEntryData;322 }323 ZipFileEntry.prototype = ZipFileEntryProto = new ZipEntry();324 ZipFileEntryProto.constructor = ZipFileEntry;325 ZipFileEntryProto.getText = function(onend, onprogress, checkCrc32, encoding) {326 this.getData(new TextWriter(encoding), onend, onprogress, checkCrc32);327 };328 ZipFileEntryProto.getBlob = function(mimeType, onend, onprogress, checkCrc32) {329 this.getData(new BlobWriter(mimeType), onend, onprogress, checkCrc32);330 };331 ZipFileEntryProto.getData64URI = function(mimeType, onend, onprogress, checkCrc32) {332 this.getData(new Data64URIWriter(mimeType), onend, onprogress, checkCrc32);333 };334 var ZipDirectoryEntryProto;335 function ZipDirectoryEntry(fs, name, params, parent) {336 var that = this;337 ZipEntry.prototype.init.call(that, fs, name, params, parent);338 that.directory = true;339 }340 ZipDirectoryEntry.prototype = ZipDirectoryEntryProto = new ZipEntry();341 ZipDirectoryEntryProto.constructor = ZipDirectoryEntry;342 ZipDirectoryEntryProto.addDirectory = function(name) {343 return addChild(this, name, null, true);344 };345 ZipDirectoryEntryProto.addText = function(name, text) {346 return addChild(this, name, {347 data : text,348 Reader : TextReader,349 Writer : TextWriter350 });351 };352 ZipDirectoryEntryProto.addBlob = function(name, blob) {353 return addChild(this, name, {354 data : blob,355 Reader : BlobReader,356 Writer : BlobWriter357 });358 };359 ZipDirectoryEntryProto.addData64URI = function(name, dataURI) {360 return addChild(this, name, {361 data : dataURI,362 Reader : Data64URIReader,363 Writer : Data64URIWriter364 });365 };366 ZipDirectoryEntryProto.addFileEntry = function(fileEntry, onend, onerror) {367 addFileEntry(this, fileEntry, onend, onerror);368 };369 ZipDirectoryEntryProto.addData = function(name, params) {370 return addChild(this, name, params);371 };372 ZipDirectoryEntryProto.importBlob = function(blob, onend, onerror) {373 this.importZip(new BlobReader(blob), onend, onerror);374 };375 ZipDirectoryEntryProto.importText = function(text, onend, onerror) {376 this.importZip(new TextReader(text), onend, onerror);377 };378 ZipDirectoryEntryProto.importData64URI = function(dataURI, onend, onerror) {379 this.importZip(new Data64URIReader(dataURI), onend, onerror);380 };381 ZipDirectoryEntryProto.exportBlob = function(onend, onprogress, onerror) {382 this.exportZip(new BlobWriter("application/zip"), onend, onprogress, onerror);383 };384 ZipDirectoryEntryProto.exportText = function(onend, onprogress, onerror) {385 this.exportZip(new TextWriter(), onend, onprogress, onerror);386 };387 ZipDirectoryEntryProto.exportFileEntry = function(fileEntry, onend, onprogress, onerror) {388 this.exportZip(new zip.FileWriter(fileEntry, "application/zip"), onend, onprogress, onerror);389 };390 ZipDirectoryEntryProto.exportData64URI = function(onend, onprogress, onerror) {391 this.exportZip(new Data64URIWriter("application/zip"), onend, onprogress, onerror);392 };393 ZipDirectoryEntryProto.importZip = function(reader, onend, onerror) {394 var that = this;395 createReader(reader, function(zipReader) {396 zipReader.getEntries(function(entries) {397 entries.forEach(function(entry) {398 var parent = that, path = entry.filename.split("/"), name = path.pop();399 path.forEach(function(pathPart) {400 parent = parent.getChildByName(pathPart) || new ZipDirectoryEntry(that.fs, pathPart, null, parent);401 });402 if (!entry.directory)403 addChild(parent, name, {404 data : entry,405 Reader : ZipBlobReader406 });407 });408 onend();409 });410 }, onerror);411 };412 ZipDirectoryEntryProto.exportZip = function(writer, onend, onprogress, onerror) {413 var that = this;414 initReaders(that, function() {415 createWriter(writer, function(zipWriter) {416 exportZip(zipWriter, that, function() {417 zipWriter.close(onend);418 }, onprogress, getTotalSize(that));419 }, onerror);420 }, onerror);421 };422 ZipDirectoryEntryProto.getChildByName = function(name) {423 var childIndex, child, that = this;424 for (childIndex = 0; childIndex < that.children.length; childIndex++) {425 child = that.children[childIndex];426 if (child.name == name)427 return child;428 }429 };430 function FS() {431 resetFS(this);432 }433 FS.prototype = {434 remove : function(entry) {435 detach(entry);436 this.entries[entry.id] = null;437 },438 find : function(fullname) {439 var index, path = fullname.split("/"), node = this.root;440 for (index = 0; node && index < path.length; index++)441 node = node.getChildByName(path[index]);442 return node;443 },444 getById : function(id) {445 return this.entries[id];446 },447 importBlob : function(blob, onend, onerror) {448 resetFS(this);449 this.root.importBlob(blob, onend, onerror);450 },451 importText : function(text, onend, onerror) {452 resetFS(this);453 this.root.importText(text, onend, onerror);454 },455 importData64URI : function(dataURI, onend, onerror) {456 resetFS(this);457 this.root.importData64URI(dataURI, onend, onerror);458 },459 exportBlob : function(onend, onprogress, onerror) {460 this.root.exportBlob(onend, onprogress, onerror);461 },462 exportText : function(onend, onprogress, onerror) {463 this.root.exportText(onend, onprogress, onerror);464 },465 exportFileEntry : function(fileEntry, onend, onprogress, onerror) {466 this.root.exportFileEntry(fileEntry, onend, onprogress, onerror);467 },468 exportData64URI : function(onend, onprogress, onerror) {469 this.root.exportData64URI(onend, onprogress, onerror);470 }471 };472 zip.fs = {473 FS : FS,474 ZipDirectoryEntry : ZipDirectoryEntry,475 ZipFileEntry : ZipFileEntry476 };477 zip.getMimeType = function() {478 return "application/octet-stream";479 };...
ImageFetcher.ts
Source:ImageFetcher.ts
1import { once } from "../events/once";2import { CubeMapFace } from "../graphics2d/CubeMapFace";3import type { InterpolationType } from "../graphics2d/InterpolationType";4import {5 renderCanvasFace,6 renderCanvasFaces,7 renderImageBitmapFace,8 renderImageBitmapFaces9} from "../graphics2d/renderFace";10import { sliceCubeMap } from "../graphics2d/sliceCubeMap";11import {12 CanvasTypes,13 createUtilityCanvas,14 createUtilityCanvasFromImage,15 createUtilityCanvasFromImageBitmap,16 hasImageBitmap,17 MemoryImageTypes18} from "../html/canvas";19import type { progressCallback } from "../tasks/progressCallback";20import { splitProgress } from "../tasks/splitProgress";21import { using, usingAsync } from "../using";22import { Fetcher } from "./Fetcher";23import { IImageFetcher } from "./IImageFetcher";24export class ImageFetcher25 extends Fetcher26 implements IImageFetcher {27 constructor() {28 super();29 this.__getCanvas = hasImageBitmap30 ? this._getCanvasViaImageBitmap31 : this._getCanvasViaImage;32 this.__getImageData = hasImageBitmap33 ? this._getImageDataViaImageBitmap34 : this._getImageDataViaImage;35 this.__getCubes = hasImageBitmap36 ? this._getCubesViaImageBitmaps37 : this._getCubesViaImage;38 this.__getEquiMaps = hasImageBitmap39 ? this._getEquiMapViaImageBitmaps40 : this._getEquiMapViaImage;41 }42 private async readFileImage(file: string): Promise<HTMLImageElement> {43 const img = new Image();44 img.src = file;45 if (!img.complete) {46 await once(img, "load", "error");47 }48 return img;49 }50 private readImageData(img: HTMLImageElement | ImageBitmap): ImageData {51 const canv = createUtilityCanvas(img.width, img.height);52 const g = canv.getContext("2d");53 if (!g) {54 throw new Error("Couldn't create a 2D canvas context");55 }56 g.drawImage(img, 0, 0);57 return g.getImageData(0, 0, canv.width, canv.height);58 }59 protected async _getImageBitmap(path: string, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<ImageBitmap> {60 onProgress = this.normalizeOnProgress(headerMap, onProgress);61 headerMap = this.normalizeHeaderMap(headerMap);62 const blob = await this._getBlob(path, headerMap, onProgress);63 return await createImageBitmap(blob);64 }65 async getImageBitmap(path: string): Promise<ImageBitmap>;66 async getImageBitmap(path: string, onProgress?: progressCallback): Promise<ImageBitmap>;67 async getImageBitmap(path: string, headerMap?: Map<string, string>): Promise<ImageBitmap>;68 async getImageBitmap(path: string, headerMap?: Map<string, string>, onProgress?: progressCallback): Promise<ImageBitmap>;69 async getImageBitmap(path: string, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<ImageBitmap> {70 return await this._getImageBitmap(path, headerMap, onProgress);71 }72 protected async _getImage(path: string, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<HTMLImageElement> {73 onProgress = this.normalizeOnProgress(headerMap, onProgress);74 headerMap = this.normalizeHeaderMap(headerMap);75 const file = await this._getFile(path, headerMap, onProgress);76 return await this.readFileImage(file);77 }78 async getImage(path: string): Promise<HTMLImageElement>;79 async getImage(path: string, onProgress?: progressCallback): Promise<HTMLImageElement>;80 async getImage(path: string, headerMap?: Map<string, string>): Promise<HTMLImageElement>;81 async getImage(path: string, headerMap?: Map<string, string>, onProgress?: progressCallback): Promise<HTMLImageElement>;82 async getImage(path: string, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<HTMLImageElement> {83 return await this._getImage(path, headerMap, onProgress);84 }85 protected async _postObjectForImageBitmap<T>(path: string, obj: T, headerMap?: progressCallback | Map<string, string>, onProgress?: progressCallback): Promise<ImageBitmap> {86 onProgress = this.normalizeOnProgress(headerMap, onProgress);87 headerMap = this.normalizeHeaderMap(headerMap);88 const blob = await this._postObjectForBlob(path, obj, headerMap, onProgress);89 return await createImageBitmap(blob);90 }91 async postObjectForImageBitmap<T>(path: string, obj: T): Promise<ImageBitmap>;92 async postObjectForImageBitmap<T>(path: string, obj: T, onProgress?: progressCallback): Promise<ImageBitmap>;93 async postObjectForImageBitmap<T>(path: string, obj: T, headerMap?: Map<string, string>): Promise<ImageBitmap>;94 async postObjectForImageBitmap<T>(path: string, obj: T, headerMap?: Map<string, string>, onProgress?: progressCallback): Promise<ImageBitmap>;95 async postObjectForImageBitmap<T>(path: string, obj: T, headerMap?: progressCallback | Map<string, string>, onProgress?: progressCallback): Promise<ImageBitmap> {96 return await this._postObjectForImageBitmap(path, obj, headerMap, onProgress);97 }98 protected async _postObjectForImage<T>(path: string, obj: T, headerMap?: progressCallback | Map<string, string>, onProgress?: progressCallback): Promise<HTMLImageElement> {99 onProgress = this.normalizeOnProgress(headerMap, onProgress);100 headerMap = this.normalizeHeaderMap(headerMap);101 const file = await this._postObjectForFile(path, obj, headerMap, onProgress);102 return await this.readFileImage(file);103 }104 async postObjectForImage<T>(path: string, obj: T): Promise<HTMLImageElement>;105 async postObjectForImage<T>(path: string, obj: T, onProgress?: progressCallback): Promise<HTMLImageElement>;106 async postObjectForImage<T>(path: string, obj: T, headerMap?: Map<string, string>): Promise<HTMLImageElement>;107 async postObjectForImage<T>(path: string, obj: T, headerMap?: Map<string, string>, onProgress?: progressCallback): Promise<HTMLImageElement>;108 async postObjectForImage<T>(path: string, obj: T, headerMap?: progressCallback | Map<string, string>, onProgress?: progressCallback): Promise<HTMLImageElement> {109 return await this._postObjectForImage(path, obj, headerMap, onProgress);110 }111 private async _getCanvasViaImageBitmap(path: string, headerMap?: progressCallback | Map<string, string>, onProgress?: progressCallback): Promise<CanvasTypes> {112 onProgress = this.normalizeOnProgress(headerMap, onProgress);113 headerMap = this.normalizeHeaderMap(headerMap);114 return using(await this._getImageBitmap(path, headerMap, onProgress), (img: ImageBitmap) => {115 return createUtilityCanvasFromImageBitmap(img);116 });117 }118 private async _getCanvasViaImage(path: string, headerMap?: progressCallback | Map<string, string>, onProgress?: progressCallback): Promise<CanvasTypes> {119 onProgress = this.normalizeOnProgress(headerMap, onProgress);120 headerMap = this.normalizeHeaderMap(headerMap);121 const img = await this._getImage(path, headerMap, onProgress);122 return createUtilityCanvasFromImage(img);123 }124 private async _getImageDataViaImageBitmap(path: string, headerMap?: progressCallback | Map<string, string>, onProgress?: progressCallback): Promise<ImageData> {125 onProgress = this.normalizeOnProgress(headerMap, onProgress);126 headerMap = this.normalizeHeaderMap(headerMap);127 return using(await this._getImageBitmap(path, headerMap, onProgress), (img: ImageBitmap) => {128 return this.readImageData(img);129 });130 }131 private async _getImageDataViaImage(path: string, headerMap?: progressCallback | Map<string, string>, onProgress?: progressCallback): Promise<ImageData> {132 onProgress = this.normalizeOnProgress(headerMap, onProgress);133 headerMap = this.normalizeHeaderMap(headerMap);134 const img = await this._getImage(path, headerMap, onProgress);135 return this.readImageData(img);136 }137 async _getCubesViaImageBitmaps(path: string, headerMap?: progressCallback | Map<string, string>, onProgress?: progressCallback): Promise<ImageBitmap[]> {138 onProgress = this.normalizeOnProgress(headerMap, onProgress);139 headerMap = this.normalizeHeaderMap(headerMap);140 return await usingAsync(await this._getImageBitmap(path, headerMap, onProgress), async (img: ImageBitmap) => {141 const canvs = sliceCubeMap(img);142 return await Promise.all(canvs.map((canv) => createImageBitmap(canv)));143 });144 }145 private async _getCubesViaImage(path: string, headerMap?: progressCallback | Map<string, string>, onProgress?: progressCallback): Promise<CanvasTypes[]> {146 onProgress = this.normalizeOnProgress(headerMap, onProgress);147 headerMap = this.normalizeHeaderMap(headerMap);148 const img = await this._getImage(path, headerMap, onProgress);149 return sliceCubeMap(img);150 }151 private async _getEquiMapViaImageBitmaps(path: string, interpolation: InterpolationType, maxWidth: number, headerMap?: progressCallback | Map<string, string>, onProgress?: progressCallback): Promise<ImageBitmap[]> {152 onProgress = this.normalizeOnProgress(headerMap, onProgress);153 headerMap = this.normalizeHeaderMap(headerMap);154 const splits = splitProgress(onProgress, [1, 6]);155 const imgData = await this._getImageDataViaImageBitmap(path, headerMap, splits.shift());156 return await renderImageBitmapFaces(renderImageBitmapFace, imgData, interpolation, maxWidth, splits.shift());157 }158 private async _getEquiMapViaImage(path: string, interpolation: InterpolationType, maxWidth: number, headerMap?: progressCallback | Map<string, string>, onProgress?: progressCallback): Promise<CanvasTypes[]> {159 onProgress = this.normalizeOnProgress(headerMap, onProgress);160 headerMap = this.normalizeHeaderMap(headerMap);161 const splits = splitProgress(onProgress, [1, 6]);162 const imgData = await this._getImageDataViaImage(path, headerMap, splits.shift());163 return await renderCanvasFaces(renderCanvasFace, imgData, interpolation, maxWidth, splits.shift());164 }165 private __getCanvas: (path: string, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback) => Promise<CanvasTypes>;166 protected async _getCanvas(path: string, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<CanvasTypes> {167 onProgress = this.normalizeOnProgress(headerMap, onProgress);168 headerMap = this.normalizeHeaderMap(headerMap);169 return await this.__getCanvas(path, headerMap, onProgress);170 }171 async getCanvas(path: string): Promise<CanvasTypes>;172 async getCanvas(path: string, onProgress?: progressCallback): Promise<CanvasTypes>;173 async getCanvas(path: string, headerMap?: Map<string, string>): Promise<CanvasTypes>;174 async getCanvas(path: string, headerMap?: Map<string, string>, onProgress?: progressCallback): Promise<CanvasTypes>;175 async getCanvas(path: string, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<CanvasTypes> {176 return await this._getCanvas(path, headerMap, onProgress);177 }178 private __getImageData: (path: string, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback) => Promise<ImageData>;179 protected async _getImageData(path: string, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<ImageData> {180 onProgress = this.normalizeOnProgress(headerMap, onProgress);181 headerMap = this.normalizeHeaderMap(headerMap);182 return await this.__getImageData(path, headerMap, onProgress);183 }184 async getImageData(path: string): Promise<ImageData>;185 async getImageData(path: string, onProgress?: progressCallback): Promise<ImageData>;186 async getImageData(path: string, headerMap?: Map<string, string>): Promise<ImageData>;187 async getImageData(path: string, headerMap?: Map<string, string>, onProgress?: progressCallback): Promise<ImageData>;188 async getImageData(path: string, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<ImageData> {189 return await this._getImageData(path, headerMap, onProgress);190 }191 private __getCubes: (path: string, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback) => Promise<MemoryImageTypes[]>;192 protected async _getCubes(path: string, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<MemoryImageTypes[]> {193 onProgress = this.normalizeOnProgress(headerMap, onProgress);194 headerMap = this.normalizeHeaderMap(headerMap);195 return await this.__getCubes(path, headerMap, onProgress);196 }197 async getCubes(path: string): Promise<MemoryImageTypes[]>;198 async getCubes(path: string, onProgress?: progressCallback): Promise<MemoryImageTypes[]>;199 async getCubes(path: string, headerMap?: Map<string, string>): Promise<MemoryImageTypes[]>;200 async getCubes(path: string, headerMap?: Map<string, string>, onProgress?: progressCallback): Promise<MemoryImageTypes[]>;201 async getCubes(path: string, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<MemoryImageTypes[]> {202 return await this._getCubes(path, headerMap, onProgress);203 }204 private __getEquiMaps: (path: string, interpolation: InterpolationType, maxWidth: number, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback) => Promise<MemoryImageTypes[]>;205 protected async _getEquiMaps(path: string, interpolation: InterpolationType, maxWidth: number, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<MemoryImageTypes[]> {206 onProgress = this.normalizeOnProgress(headerMap, onProgress);207 headerMap = this.normalizeHeaderMap(headerMap);208 return await this.__getEquiMaps(path, interpolation, maxWidth, headerMap, onProgress);209 }210 async getEquiMaps(path: string, interpolation: InterpolationType, maxWidth: number): Promise<MemoryImageTypes[]>;211 async getEquiMaps(path: string, interpolation: InterpolationType, maxWidth: number, onProgress?: progressCallback): Promise<MemoryImageTypes[]>;212 async getEquiMaps(path: string, interpolation: InterpolationType, maxWidth: number, headerMap?: Map<string, string>): Promise<MemoryImageTypes[]>;213 async getEquiMaps(path: string, interpolation: InterpolationType, maxWidth: number, headerMap?: Map<string, string>, onProgress?: progressCallback): Promise<MemoryImageTypes[]>;214 async getEquiMaps(path: string, interpolation: InterpolationType, maxWidth: number, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<MemoryImageTypes[]> {215 return await this._getEquiMaps(path, interpolation, maxWidth, headerMap, onProgress);216 }217 async renderImageBitmapFace(readData: ImageData, faceName: CubeMapFace, interpolation: InterpolationType, maxWidth: number, onProgress?: progressCallback): Promise<ImageBitmap> {218 return await renderImageBitmapFace(readData, faceName, interpolation, maxWidth, onProgress);219 }...
ImageFetcherWorkerClient.ts
Source:ImageFetcherWorkerClient.ts
1import { CubeMapFace } from "../graphics2d/CubeMapFace";2import { InterpolationType } from "../graphics2d/InterpolationType";3import { renderImageBitmapFaces } from "../graphics2d/renderFace";4import { hasImageBitmap, hasOffscreenCanvasRenderingContext2D, MemoryImageTypes } from "../html/canvas";5import { progressCallback } from "../tasks/progressCallback";6import { splitProgress } from "../tasks/splitProgress";7import { isNullOrUndefined, isNumber, isString } from "../typeChecks";8import { WorkerClient } from "../workers/WorkerClient";9import { getPartsReturnType } from "./getPartsReturnType";10import { ImageFetcher } from "./ImageFetcher";11export class ImageFetcherWorkerClient extends ImageFetcher {12 worker: WorkerClient;13 /**14 * Creates a new pooled worker method executor.15 * @param scriptPath - the path to the unminified script to use for the worker16 * @param minScriptPath - the path to the minified script to use for the worker (optional)17 * @param workerPoolSize - the number of worker threads to create for the pool (defaults to 1)18 */19 constructor(scriptPath: string);20 constructor(scriptPath: string, minScriptPath: string);21 constructor(scriptPath: string, workerPoolSize: number);22 constructor(scriptPath: string, minScriptPath: string, workerPoolSize: number);23 constructor(scriptPath: string, minScriptPath?: number | string, workerPoolSize: number = 1) {24 super();25 if (isNumber(minScriptPath)) {26 workerPoolSize = minScriptPath;27 minScriptPath = undefined;28 }29 if (isNullOrUndefined(workerPoolSize)) {30 workerPoolSize = 1;31 }32 if (isString(minScriptPath)) {33 this.worker = new WorkerClient(scriptPath, minScriptPath, workerPoolSize);34 }35 else {36 this.worker = new WorkerClient(scriptPath, workerPoolSize);37 }38 }39 protected async _getBuffer(path: string, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<getPartsReturnType> {40 onProgress = this.normalizeOnProgress(headerMap, onProgress);41 headerMap = this.normalizeHeaderMap(headerMap);42 if (this.worker.enabled) {43 return await this.worker.execute("getBuffer", [path, headerMap], onProgress);44 }45 else {46 return await super._getBuffer(path, headerMap, onProgress);47 }48 }49 protected async _postObjectForBuffer<T>(path: string, obj: T, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<getPartsReturnType> {50 onProgress = this.normalizeOnProgress(headerMap, onProgress);51 headerMap = this.normalizeHeaderMap(headerMap);52 if (this.worker.enabled) {53 return await this.worker.execute("postObjectForBuffer", [path, obj, headerMap], onProgress);54 }55 else {56 return await super._postObjectForBuffer(path, obj, headerMap, onProgress);57 }58 }59 protected async _getObject<T>(path: string, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<T> {60 onProgress = this.normalizeOnProgress(headerMap, onProgress);61 headerMap = this.normalizeHeaderMap(headerMap);62 if (this.worker.enabled) {63 return await this.worker.execute("getObject", [path, headerMap], onProgress);64 }65 else {66 return await super._getObject(path, headerMap, onProgress);67 }68 }69 protected async _postObjectForObject<T, U>(path: string, obj: T, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<U> {70 onProgress = this.normalizeOnProgress(headerMap, onProgress);71 headerMap = this.normalizeHeaderMap(headerMap);72 if (this.worker.enabled) {73 return await this.worker.execute("postObjectForObject", [path, headerMap, obj], onProgress);74 }75 else {76 return await super._postObjectForObject(path, obj, headerMap, onProgress);77 }78 }79 protected async _getFile(path: string, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<string> {80 onProgress = this.normalizeOnProgress(headerMap, onProgress);81 headerMap = this.normalizeHeaderMap(headerMap);82 if (this.worker.enabled) {83 return await this.worker.execute("getFile", [path, headerMap], onProgress);84 }85 else {86 return await super._getFile(path, headerMap, onProgress);87 }88 }89 protected async _postObjectForFile<T>(path: string, obj: T, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<string> {90 onProgress = this.normalizeOnProgress(headerMap, onProgress);91 headerMap = this.normalizeHeaderMap(headerMap);92 if (this.worker.enabled) {93 return await this.worker.execute("postObjectForFile", [path, headerMap, obj], onProgress);94 }95 else {96 return await super._postObjectForFile(path, obj, headerMap, onProgress);97 }98 }99 protected async _getImageBitmap(path: string, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<ImageBitmap> {100 onProgress = this.normalizeOnProgress(headerMap, onProgress);101 headerMap = this.normalizeHeaderMap(headerMap);102 if (this.worker.enabled) {103 return await this.worker.execute("getImageBitmap", [path, headerMap], onProgress);104 }105 else {106 return await super._getImageBitmap(path, headerMap, onProgress);107 }108 }109 protected async _postObjectForImageBitmap<T>(path: string, obj: T, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<ImageBitmap> {110 onProgress = this.normalizeOnProgress(headerMap, onProgress);111 headerMap = this.normalizeHeaderMap(headerMap);112 if (this.worker.enabled && hasImageBitmap) {113 return await this.worker.execute("postObjectForImageBitmap", [path, headerMap, obj], onProgress);114 }115 else {116 return await super._postObjectForImageBitmap(path, obj, headerMap, onProgress);117 }118 }119 protected async _getCubes(path: string, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<MemoryImageTypes[]> {120 onProgress = this.normalizeOnProgress(headerMap, onProgress);121 headerMap = this.normalizeHeaderMap(headerMap);122 if (this.worker.enabled123 && hasImageBitmap124 && hasOffscreenCanvasRenderingContext2D) {125 return await this.worker.execute("getCubes", [path, headerMap], onProgress);126 }127 else {128 return await super._getCubes(path, headerMap, onProgress);129 }130 }131 protected async _getEquiMaps(path: string, interpolation: InterpolationType, maxWidth: number, headerMap?: Map<string, string> | progressCallback, onProgress?: progressCallback): Promise<MemoryImageTypes[]> {132 onProgress = this.normalizeOnProgress(headerMap, onProgress);133 headerMap = this.normalizeHeaderMap(headerMap);134 if (this.worker.enabled135 && hasImageBitmap136 && hasOffscreenCanvasRenderingContext2D) {137 const splits = splitProgress(onProgress, [1, 6]);138 const imgData = await this._getImageData(path, headerMap, splits.shift());139 return await renderImageBitmapFaces(140 (readData: ImageData, faceName: CubeMapFace, interpolation: InterpolationType, maxWidth: number, onProgress?: progressCallback) =>141 this.worker.execute("renderFace", [readData, faceName, interpolation, maxWidth], onProgress),142 imgData, interpolation, maxWidth, splits.shift());143 }144 else {145 return await super.getEquiMaps(path, interpolation, maxWidth, onProgress);146 }147 }...
fetching.js
Source:fetching.js
...31export async function getBufferWithProgress(path, onProgress) {32 if (!isFunction(onProgress)) {33 throw new Error("progress callback is required");34 }35 onProgress(0, 1, path);36 const response = await getResponse(path);37 const contentLength = parseInt(response.headers.get("Content-Length"), 10);38 if (!contentLength) {39 throw new Error("Server did not provide a content length header.");40 }41 const contentType = response.headers.get("Content-Type");42 if (!contentType) {43 throw new Error("Server did not provide a content type");44 }45 const reader = response.body.getReader();46 const buffer = new Uint8Array(contentLength);47 let receivedLength = 0;48 while (true) {49 const { done, value } = await reader.read();50 if (done) {51 break;52 }53 if (receivedLength + value.length > contentLength) {54 throw new Error("Whoa! Recieved content exceeded expected amount");55 }56 buffer.set(value, receivedLength);57 receivedLength += value.length;58 onProgress(receivedLength, contentLength, path);59 }60 onProgress(1, 1, path);61 return { buffer, contentType };62}63/**64 * @param {string} path65 * @param {progressCallback} onProgress66 * @returns {Promise<any>}67 */68export async function getObjectWithProgress(path, onProgress) {69 const { buffer } = await getBufferWithProgress(path, onProgress);70 const decoder = new TextDecoder("utf-8");71 const text = decoder.decode(buffer);72 const obj = JSON.parse(text);73 return obj;74}75/**76 * @param {string} path77 * @param {progressCallback} onProgress78 * @returns {Promise<Blob>}79 */80export async function getBlobWithProgress(path, onProgress) {81 const { buffer, contentType } = await getBufferWithProgress(path, onProgress);82 const blob = new Blob([buffer], { type: contentType });83 return blob;84}85/** @type {Map<string, string>} */86const cache = new Map();87/**88 * @param {string} path89 * @param {progressCallback} onProgress90 * @returns {Promise<string>}91 */92export async function getFileWithProgress(path, onProgress) {93 const key = path;94 if (cache.has(key)) {95 onProgress(0, 1, path);96 const blobUrl = cache.get(key);97 onProgress(1, 1, path);98 return blobUrl;99 }100 else {101 const blob = await getBlobWithProgress(path, onProgress);102 const blobUrl = URL.createObjectURL(blob);103 cache.set(key, blobUrl);104 return blobUrl;105 }106}107/**108 * @param {string} path109 * @param {progressCallback?} onProgress110 * @returns {Promise<any>}111 */...
progressbar.js
Source:progressbar.js
...74 bar.animate({75 width: o.value + '%'76 }, ani_speed, function(){77 if (typeof o.onProgress === 'function') {78 o.onProgress(value);79 } else {80 if (typeof window[o.onProgress] === 'function') {81 window[o.onProgress](value);82 } else {83 var result = eval("(function(){"+o.onProgress+"})");84 result.call(value);85 }86 }87 });88 } else {89 bar.css({90 width: o.value + '%'91 });92 if (typeof o.onProgress === 'function') {93 o.onProgress(value);94 } else {95 if (typeof window[o.onProgress] === 'function') {96 window[o.onProgress](value);97 } else {98 var result = eval("(function(){"+o.onProgress+"})");99 result.call(value);100 }101 }102 }103 } else {104 return this.options.value;105 }106 },107 value: function(value){...
main.js
Source:main.js
1var chai = require('chai'),2 sinon = require('sinon'),3 SettledExt = require('../src/index');4require('promise-ext-delay')();5chai.should();6describe('Functional', function() {7 before(function() {8 this.clock = sinon.useFakeTimers();9 }),10 after(function() {11 this.clock.restore();12 }),13 it('should working correctly as static function and onProgress-function should be called', function(done) {14 var current = new Date(),15 promises = [],16 settled = 0;17 for (var i = 0; i < 10; i++) {18 var p = Promise.delay(500);19 if (!(i % 2)) {20 p = p.then(function() {21 throw new Error();22 });23 }24 promises.push(p);25 }26 this.clock.tick(500);27 SettledExt(promises, function() {28 settled++;29 }).then(function() {30 try {31 (new Date() - current).should.be.at.least(500);32 settled.should.be.equal(promises.length);33 done();34 } catch (e) {35 done(e);36 }37 });38 });39 it('should be fulfilled with correct value', function(done) {40 var promises = [],41 rejected = 0,42 resolved = 0;43 for (var i = 1; i <= 10; i++) {44 var p = new Promise(function(resolve) {45 resolve();46 });47 if (!(i % 2)) {48 p = p.then(function() {49 throw new Error();50 });51 }52 promises.push(p);53 }54 SettledExt(promises).then(function(result) {55 result.forEach(function(data) {56 if (data.status) {57 resolved++;58 } else {59 rejected++;60 }61 });62 try {63 resolved.should.be.equal(5);64 rejected.should.be.equal(5);65 done();66 } catch (e) {67 done(e);68 }69 });70 });71 it('should call onProgress with a correct status object when promise resolved', function(done) {72 var expectedValue = 1,73 expectedStatus = {value: expectedValue, status: true},74 promises = [Promise.resolve(expectedValue)],75 onProgress = sinon.spy();76 SettledExt(promises, onProgress).then(function() {77 try {78 onProgress.calledOnce.should.be.true;79 onProgress.args[0][0].should.be.deep.equal(expectedStatus);80 done();81 } catch(e) {82 done(e.message);83 }84 })85 });86 it('should call onProgress with a correct status object when promise rejected', function(done) {87 var expectedValue = 1,88 expectedStatus = {value: expectedValue, status: false},89 promises = [Promise.reject(expectedValue)],90 onProgress = sinon.spy();91 SettledExt(promises, onProgress).then(function() {92 try {93 onProgress.calledOnce.should.be.true;94 onProgress.args[0][0].should.be.deep.equal(expectedStatus);95 done();96 } catch(e) {97 done(e.message);98 }99 })100 });101 it('should call onProgress with a correct progress status', function(done) {102 var p1 = Promise.delay(500),103 p2 = new Promise(function(resolve, reject) { setTimeout(reject, 1000) }),104 p3 = Promise.delay(1500),105 promises = [p1, p2, p3],106 onProgress = sinon.spy(),107 expectedStatus = {total: promises.length, rejected: 0, resolved: 0};108 this.clock.tick(2000);109 SettledExt(promises, onProgress).then(function() {110 try {111 onProgress.calledThrice.should.be.true;112 expectedStatus.resolved++;113 onProgress.getCall(0).args[1].should.be.deep.equal(expectedStatus);114 expectedStatus.rejected++;115 onProgress.getCall(1).args[1].should.be.deep.equal(expectedStatus);116 expectedStatus.resolved++;117 onProgress.getCall(2).args[1].should.be.deep.equal(expectedStatus);118 done();119 } catch(e) {120 done(e.message);121 }122 })123 })...
Using AI Code Generation
1const puppeteer = require('puppeteer');2const fs = require('fs');3(async () => {4 const browser = await puppeteer.launch({ headless: true });5 const page = await browser.newPage();6 await page.pdf({path: 'hn.pdf', format: 'A4', printBackground: true, margin: {top: '0.5in', bottom: '0.5in', left: '0.5in', right: '0.5in'}});7 await browser.close();8})();9const puppeteer = require('puppeteer');10const fs = require('fs');11(async () => {12 const browser = await puppeteer.launch({ headless: true });13 const page = await browser.newPage();14 await page.pdf({path: 'hn.pdf', format: 'A4', printBackground: true, margin: {top: '0.5in', bottom: '0.5in', left: '0.5in', right: '0.5in'}});15 await browser.close();16})();17const puppeteer = require('puppeteer');18const fs = require('fs');19(async () => {20 const browser = await puppeteer.launch({ headless: true });21 const page = await browser.newPage();
Using AI Code Generation
1const puppeteer = require("puppeteer");2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 const downloadPath = "/Users/username/Downloads";6 await page._client.send("Page.setDownloadBehavior", {7 });8 await page.waitForSelector("a[aria-label='Download Chrome for Windows']");9 await Promise.all([10 page.waitForNavigation(),11 page.click("a[aria-label='Download Chrome for Windows']"),12 ]);13 await page.waitFor(10000);14 await browser.close();15})();
Using AI Code Generation
1const puppeteer = require("puppeteer");2const ProgressBar = require("progress");3(async () => {4 const browser = await puppeteer.launch();5 const page = await browser.newPage();6 const bar = new ProgressBar(":bar", { total: 100 });7 await page.pdf({8 onProgress: (progress) => {9 bar.tick(progress - bar.curr);10 },11 });12 await browser.close();13})();
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!