Best JavaScript code snippet using cypress
libpatch.js
Source:libpatch.js
1/*2Copyright (C) 2018 hack64.net3Modified a lot by ComputerElite4*/5if(!Array.prototype.fill)6{7 var fill = function(v, start, end)8 {9 for(var i = start; i < end; i++)10 {11 this[i] = v;12 }13 }14 Array.prototype.fill = fill;15 Uint8Array.prototype.fill = fill;16}17(function(_this){18/*************/19const IN_WORKER = (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope);20var sitePath = ""21try {22 sitePath = window.location.href;23 if(sitePath.endsWith("/")) sitePath = sitePath.substring(0, sitePath.length - 1)24 sitePath = sitePath.substring(0, sitePath.lastIndexOf("/") + 1)25 console.log('current dir: ' + sitePath)26} catch {}27_this.applyPatch = applyPatch;28_this.applyPatchAsync = applyPatchAsync;29const ERR_PATCH_CHECKSUM = 'Patch checksum mismatch - patch file may be corrupt to downgrade';30const ERR_SOURCE_CHECKSUM = 'Source checksum mismatch - patch is not meant for this File. It may be meant for a other version of this file.';31const ERR_TARGET_CHECKSUM = 'Target checksum mismatch - something failed while downgrading';32const ERR_UNKNOWN_FORMAT = 'Unknown patch format';33const ERR_FORMAT_VERSION = 'Unhandled format version';34const ERR_GENERIC_DECODE = 'Decoding error';35const ERR_UNIMPLEMENTED = 'Unimplemented feature';36if(!_this.performance)37{38 _this.performance = {39 now: function()40 {41 console.log('performance object unavailable');42 return 1;43 }44 }45}46function adler32(arr, offs, size)47{48 var a = 1, b = 0;49 for(var i = 0; i < size; i++)50 {51 a = (a + arr[offs + i]) % 65521;52 b = (b + a) % 65521;53 }54 return ((b << 16) | a) >>> 0;55}56function strtest(u8arr, str)57{58 for(var i = 0; i < str.length; i++)59 {60 if(u8arr[i] != str.charCodeAt(i))61 {62 return false;63 }64 }65 return true;66}67function bytecopy(dst, dstOffs, src, srcOffs, size)68{69 var subsrc = src.subarray(srcOffs, srcOffs + size);70 dst.set(subsrc, dstOffs);71}72async function applyPatch(sourceData, patchData, ignoreChecksums, patchFilename, downgrades, isSync = false)73{74 ignoreChecksums = ignoreChecksums || false;75 var header = new Uint8Array(patchData);76 var decrReg = /.+_[0-9\.]+TO[0-9\.]+.*\.decr/g;77 78 var formats = [79 { sig: '\xD6\xC3\xC4', name: 'vcdiff', applyPatch: applyPatchVCD }80 ];81 for(var i in formats)82 {83 var fmt = formats[i];84 if(strtest(header, fmt.sig))85 {86 var timeStart, timeEnd;87 var targetData;88 console.log('libpatch: test applying ' + fmt.name + ' patch...');89 timeStart = _this.performance.now();90 91 if(!ignoreChecksums) {92 var downgrade = extractDowngrade(patchFilename, false, downgrades, true)93 if(downgrade != null) {94 console.log("Calculating SSHA256")95 var SSHA256 = await GetSHA256(sourceData)96 console.log("finished: " + SSHA256)97 if(SSHA256 != downgrade["SSHA256"]) {98 console.log("SSHA256 mismatch")99 throw new Error(ERR_SOURCE_CHECKSUM)100 }101 console.log("Calculating DSHA256")102 var DSHA256 = await GetSHA256(patchData)103 console.log("finished: " + DSHA256)104 if(DSHA256 != downgrade["DSHA256"]) {105 console.log("DSHA256 mismatch")106 throw new Error(ERR_PATCH_CHECKSUM)107 }108 console.log("Hashes match.")109 } else {110 console.log("Downgrade not found. Continuing without hash validation.")111 }112 113 }114 115 targetData = fmt.applyPatch(sourceData, patchData, ignoreChecksums);116 timeEnd = _this.performance.now();117 console.log('libpatch: took ' + (timeEnd - timeStart).toFixed(3) + 'ms');118 return targetData119 }120 }121 if(decrReg.test(patchFilename)) {122 console.log("old decr patch detected.")123 timeStart = _this.performance.now();124 var patcher = new DecrPatcher();125 patcher.sourceData = sourceData126 patcher.patchData = patchData127 var downgrade = extractDowngrade(patchFilename, true, downgrades, false)128 if(downgrade == null) throw new Error()129 var result = await patcher.applyDecr(ignoreChecksums, downgrade, isSync)130 console.log(result)131 timeEnd = _this.performance.now();132 console.log('libpatch: took ' + (timeEnd - timeStart).toFixed(3) + 'ms');133 delete patcher134 return result;135 } else {136 throw new Error(ERR_UNKNOWN_FORMAT);137 }138}139function extractDowngrade(patchFilename, abortOnNotFound, downgrades, isXdelta3) {140 var versionRegex = /[0-9a-f\.]+TO[0-9a-f\.]+/g141 var vers = patchFilename.match(versionRegex)[0].split("TO")142 var SV = vers[0]143 var TV = vers[1]144 var appid = patchFilename.substring(0, versionRegex.exec(patchFilename).index - 1)145 console.log(`extracted infos from FileName: SV: ${SV}, TV: ${TV}, appid: ${appid}`)146 var patcher = new DecrPatcher();147 var downgrade = patcher.GetVersion(downgrades, SV, TV, appid, isXdelta3)148 if(downgrade == null && abortOnNotFound) {149 console.log("Entry not found.")150 alert(`Version ${SV} to ${TV} of ${appid} doesn't seem to exist. Aborting due to lack of information.`)151 return null152 }153 console.log("Downgrade found: ")154 console.log(downgrade)155 return downgrade156}157async function GetSHA256(input) {158 var x = await crypto.subtle.digest('SHA-256', input)159 const hashArray = Array.from(new Uint8Array(x)); // convert buffer to byte array160 const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join(''); // convert bytes to hex string 161 console.log("SHA256: " + hashHex)162 return hashHex163}164class DecrPatcher {165 sourceData = null166 patchData = null167 targetData = null168 async applyDecr(ignoreChecksums, downgrade, isSync) {169 if(!ignoreChecksums) {170 console.log("Calculating SSHA256")171 if(isSync) this.updateProgress(0.03)172 var SSHA256 = await this.GetSHA256(this.sourceData)173 console.log("finished: " + SSHA256)174 if(SSHA256 != downgrade["SSHA256"]) {175 console.log("SSHA256 mismatch")176 throw new Error(ERR_SOURCE_CHECKSUM)177 }178 console.log("Calculating DSHA256")179 this.updateProgress(0.08)180 var DSHA256 = await this.GetSHA256(this.patchData)181 console.log("finished: " + DSHA256)182 if(DSHA256 != downgrade["DSHA256"]) {183 console.log("DSHA256 mismatch")184 throw new Error(ERR_PATCH_CHECKSUM)185 }186 console.log("Hashes match.")187 188 }189 console.log("downgrading")190 this.XOR(downgrade["TargetByteSize"], isSync);191 if(isSync) this.updateProgress(0.98)192 if(!ignoreChecksums) {193 var TSHA256 = await this.GetSHA256(this.targetData)194 if(TSHA256 != downgrade["TSHA256"]) {195 console.log("TSHA256 mismatch")196 throw new Error(ERR_TARGET_CHECKSUM)197 }198 }199 if(isSync) this.updateProgress(1)200 return this.targetData201 }202 updateProgress(ratio)203 {204 document.querySelector('#progress-bar').style.width = (ratio * 100) + '%';205 }206 207 XOR(targetLength, isSync) {208 var tmp = new Uint8Array(targetLength)209 var sourceTmp = new Uint8Array(this.sourceData)210 var patchTmp = new Uint8Array(this.patchData)211 console.log("XORing")212 for (let i = 0; i < targetLength; i++) {213 if(i%10000000 == 0) {214 if(isSync) this.updateProgress(0.1 + i / targetLength * 0.85);215 console.log(i + " / " + targetLength + " (" + (i / targetLength * 100) + " %)")216 }217 tmp[i] = sourceTmp[i]^patchTmp[i];218 }219 this.targetData = tmp.buffer220 console.log("XORed")221 }222 223 async GetSHA256(input) {224 var x = await crypto.subtle.digest('SHA-256', input)225 const hashArray = Array.from(new Uint8Array(x)); // convert buffer to byte array226 const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join(''); // convert bytes to hex string 227 console.log("SHA256: " + hashHex)228 return hashHex229 }230 231 GetVersion(downgrades, SV, TV, appid, isXDelta3) {232 var outp = null233 downgrades.forEach(element => {234 if (element["SV"] == this.SV && element["TV"] == this.TV && appid == element["appid"] && element["isXDelta3"] == isXDelta3) { outp = element; return false;}235 else if (element["SV"] == this.TV && element["TV"] == this.SV && element["SourceByteSize"] == element["TargetByteSize"] && appid == element["appid"] && element["isXDelta3"] == isXDelta3) { outp = element; return false;}236 });237 return outp238 }239}240function applyPatchAsync(sourceData, patchData, config, patchFilename, downgrades)241{242 var patchWorker = new Worker(applyPatchAsync.WORKER_URL);243 var ignoreChecksums = config.ignoreChecksums || false;244 var onpatchend = config.onpatchend || null;245 var onprogress = config.onprogress || null;246 var onerror = config.onerror || null;247 248 var callbacks = {249 'patchend': onpatchend,250 'progress': onprogress,251 'error': onerror252 };253 patchWorker.onmessage = function(e)254 {255 var msg = e.data;256 if(callbacks[msg.evtType])257 {258 callbacks[msg.evtType](msg.param);259 }260 }261 var msg = {262 sourceData: sourceData,263 patchData: patchData,264 ignoreChecksums: ignoreChecksums,265 patchFilename: patchFilename,266 downgrades: downgrades267 };268 patchWorker.postMessage(msg);269}270applyPatchAsync.WORKER_URL = (function()271{272 if(IN_WORKER)273 {274 return null;275 }276 var WORKER_SOURCE = [277 'importScripts("' + sitePath + 'libpatch.js", "' + sitePath + 'lzma.js");',278 '',279 'self.onmessage = function(e)',280 '{',281 ' var sourceData = e.data.sourceData;',282 ' var patchData = e.data.patchData;',283 ' var ignoreChecksums = e.data.ignoreChecksums;',284 ' var patchFilename = e.data.patchFilename;',285 ' var downgrades = e.data.downgrades;',286 ' ',287 ' try',288 ' {',289 ' applyPatch(sourceData, patchData, ignoreChecksums, patchFilename, downgrades).then(function(result) {',290 ' self.postMessage({ evtType: \'patchend\', param: result });',291 ' self.close();',292 ' })',293 ' ',294 ' }',295 ' catch(e)',296 ' {',297 ' console.log(e);',298 ' self.postMessage({ evtType: \'error\', param: e.message });',299 ' }',300 '}'].join('');301 302 var workerURL = URL.createObjectURL(new Blob([WORKER_SOURCE]));303 return workerURL;304})();305function ProgressBroadcaster()306{307 this.ratio = 0.0;308}309ProgressBroadcaster.prototype.update = function(ratio)310{311 if(IN_WORKER && (ratio - this.ratio) >= 0.01)312 {313 // post progress update to the main thread if ratio has increased by 1+%314 self.postMessage({ evtType: 'progress', param: ratio });315 this.ratio = ratio;316 }317}318function PatchStream(ab, littleEndian)319{320 this.ab = ab;321 this.u8 = new Uint8Array(ab);322 this.dv = new DataView(ab);323 this.offset = 0;324 this.littleEndian = littleEndian || false;325}326PatchStream.prototype = {327 seek: function(offset)328 {329 this.offset = offset;330 },331 skip: function(numBytes)332 {333 this.offset += numBytes;334 },335 isEOF: function()336 {337 return (this.offset >= this.ab.byteLength);338 },339 readBytes: function(dst, dstOffs, numBytes)340 {341 // read bytes into a u8 array342 bytecopy(dst, dstOffs, this.u8, this.offset, numBytes);343 this.skip(numBytes);344 },345 _readInt: function(dvType, numBytes)346 {347 var val = this.dv[dvType](this.offset, this.littleEndian);348 this.offset += numBytes;349 return val;350 },351 readU8: function()352 {353 return this._readInt('getUint8', 1);354 },355 readU16: function()356 {357 return this._readInt('getUint16', 2);358 },359 readU24: function()360 {361 if(!this.littleEndian)362 {363 return (this.readU16() << 8) | this.readU8();364 }365 return this.readU16() | (this.readU8() << 16);366 },367 readU32: function()368 {369 return this._readInt('getUint32', 4);370 },371 readU64: function()372 {373 var a = this.readU32();374 var b = this.readU32();375 if(this.littleEndian)376 {377 return ((b * 0x100000000) + a);378 }379 return ((a * 0x100000000) + b);380 }381};382// VCDiff (xdelta)383// https://tools.ietf.org/html/rfc3284384// hdrIndicator385const VCD_DECOMPRESS = (1 << 0);386const VCD_CODETABLE = (1 << 1);387const VCD_APPHEADER = (1 << 2); // nonstandard?388// winIndicator389const VCD_SOURCE = (1 << 0);390const VCD_TARGET = (1 << 1);391const VCD_ADLER32 = (1 << 2);392// COPY address modes393const VCD_SELF = 0;394const VCD_HERE = 1;395// deltaIndicator - secondary compression396const VCD_DATACOMP = (1 << 0);397const VCD_INSTCOMP = (1 << 2);398const VCD_ADDRCOMP = (1 << 3);399const VCD_NOOP = 0, VCD_ADD = 1, VCD_RUN = 2, VCD_COPY = 3;400const VCDDefaultCodeTable = (function()401{402 var table = [];403 var empty = {inst: VCD_NOOP, size: 0, mode: 0};404 // 0405 table.push([{inst: VCD_RUN, size: 0, mode: 0}, empty]);406 // 1,18407 for(var size = 0; size <= 17; size++)408 {409 table.push([{inst: VCD_ADD, size: size, mode: 0}, empty]);410 }411 // 19,162412 for(var mode = 0; mode <= 8; mode++)413 {414 table.push([{inst: VCD_COPY, size: 0, mode: mode}, empty]);415 416 for(var size = 4; size <= 18; size++)417 {418 table.push([{inst: VCD_COPY, size: size, mode: mode}, empty]);419 }420 }421 // 163,234422 for(var mode = 0; mode <= 5; mode++)423 {424 for(var addSize = 1; addSize <= 4; addSize++)425 {426 for(var copySize = 4; copySize <= 6; copySize++)427 {428 table.push([{inst: VCD_ADD, size: addSize, mode: 0},429 {inst: VCD_COPY, size: copySize, mode: mode}]);430 }431 }432 }433 // 235,246434 for(var mode = 6; mode <= 8; mode++)435 {436 for(var addSize = 1; addSize <= 4; addSize++)437 {438 table.push([{inst: VCD_ADD, size: addSize, mode: 0},439 {inst: VCD_COPY, size: 4, mode: mode}]);440 }441 }442 // 247,255443 for(var mode = 0; mode <= 8; mode++)444 {445 table.push([{inst: VCD_COPY, size: 4, mode: mode},446 {inst: VCD_ADD, size: 1, mode: 0}]); 447 }448 return table;449})();450function VCDStream(arrayBuffer, offset)451{452 PatchStream.call(this, arrayBuffer);453 this.offset = offset;454}455VCDStream.prototype = Object.create(PatchStream.prototype);456VCDStream.prototype.readnum = function()457{458 var num = 0, bits = 0;459 do {460 bits = this.readU8();461 num = (num << 7) + (bits & 0x7F); 462 } while(bits & 0x80);463 return num;464}465function VCDCache(config)466{467 this.near = new Array(config.nearSize);468 this.nearSize = config.nearSize;469 this.nextSlot = 0;470 this.same = new Array(config.sameSize * 256);471 this.sameSize = config.sameSize;472 473 this.reset();474}475VCDCache.prototype.reset = function()476{477 this.nextSlot = 0;478 this.near.fill(0);479 this.same.fill(0);480}481VCDCache.prototype.update = function(addr)482{483 if(this.nearSize > 0)484 {485 this.near[this.nextSlot] = addr;486 this.nextSlot = (this.nextSlot + 1) % this.nearSize;487 }488 if(this.sameSize > 0)489 {490 this.same[addr % (this.sameSize * 256)] = addr;491 }492}493VCDCache.prototype.decodeAddress = function(copyAddrStream, mode, here)494{495 var addr = 0;496 var m = 0;497 if(mode == VCD_SELF)498 {499 addr = copyAddrStream.readnum();500 }501 else if(mode == VCD_HERE)502 {503 addr = here - copyAddrStream.readnum();504 }505 else if((m = (mode - 2)) >= 0 && m < this.nearSize) // near cache506 {507 addr = this.near[m] + copyAddrStream.readnum();508 }509 else // same cache510 {511 m = mode - (2 + this.nearSize);512 addr = this.same[m*256 + copyAddrStream.readU8()];513 }514 515 this.update(addr);516 return addr;517}518function VCDHeader(patchStream)519{520 patchStream.skip(4); // skip over the magic number521 this.indicator = patchStream.readU8();522 this.secDecompressorId = 0;523 this.codeTableDataLength = 0;524 this.appDataLength = 0;525 if(this.indicator & VCD_DECOMPRESS)526 {527 this.secDecompressorId = patchStream.readU8();528 console.log("secondary decompressor:" + this.secDecompressorId);529 }530 if(this.indicator & VCD_CODETABLE)531 {532 this.codeTableDataLength = patchStream.readnum();533 console.log("code table is used");534 }535 if(this.indicator & VCD_APPHEADER)536 {537 // ignore app header data538 this.appDataLength = patchStream.readnum();539 patchStream.skip(this.appDataLength);540 }541}542function VCDWindowHeader(patchStream)543{544 this.indicator = patchStream.readU8();545 this.sourceSegmentLength = 0;546 this.sourceSegmentPosition = 0;547 this.adler32 = 0;548 this.haveChecksum = false;549 if(this.indicator & (VCD_SOURCE | VCD_TARGET))550 {551 this.sourceSegmentLength = patchStream.readnum();552 this.sourceSegmentPosition = patchStream.readnum();553 }554 this.deltaLength = patchStream.readnum();555 this.targetWindowLength = patchStream.readnum();556 this.deltaIndicator = patchStream.readU8(); // secondary compression557 558 this.dataLength = patchStream.readnum();559 this.instrsLength = patchStream.readnum();560 this.copysLength = patchStream.readnum();561 if(this.indicator & VCD_ADLER32) 562 {563 this.adler32 = patchStream.readU32();564 this.haveChecksum = true;565 }566 //if(this.deltaIndicator != 0)567 //{568 // // deltaIndicator":7,569 // console.log(JSON.stringify(this));570 // throw new Error(ERR_UNIMPLEMENTED);571 //}572}573function vcdPrecalculateTargetSize(patchStream)574{575 var targetSize = 0;576 var header = new VCDHeader(patchStream);577 while(!patchStream.isEOF())578 {579 var winHeader = new VCDWindowHeader(patchStream);580 targetSize += winHeader.targetWindowLength;581 patchStream.skip(winHeader.dataLength + winHeader.copysLength + winHeader.instrsLength);582 }583 patchStream.offset = 0;584 return targetSize;585}586function applyPatchVCD(sourceData, patchData, ignoreChecksums)587{588 var sourceU8 = new Uint8Array(sourceData);589 var patchStream = new VCDStream(patchData, 0);590 var targetSize = vcdPrecalculateTargetSize(patchStream);591 var targetData = new ArrayBuffer(targetSize);592 var targetU8 = new Uint8Array(targetData);593 var progress = new ProgressBroadcaster();594 var header = new VCDHeader(patchStream);595 var cache = null;596 var codeTable = null;597 if(header.secDecompressorId != 0)598 {599 console.log("sec decompressor " + header.secDecompressorId);600 throw new Error(ERR_UNIMPLEMENTED); // secondary decompressor601 }602 if(header.codeTableDataLength == 0)603 {604 cache = new VCDCache({ nearSize: 4, sameSize: 3 });605 codeTable = VCDDefaultCodeTable;606 }607 else608 {609 console.log("code table");610 throw new Error(ERR_UNIMPLEMENTED); // custom code table611 }612 var targetWindowPosition = 0;613 while(!patchStream.isEOF())614 {615 var winHeader = new VCDWindowHeader(patchStream);616 var dataStream, instructionStream, copyAddrStream;617 if(winHeader.deltaIndicator & VCD_DATACOMP)618 {619 // TODO: secondary decompressor implementation here620 }621 else622 {623 dataStream = new VCDStream(patchData, patchStream.offset);624 }625 if(winHeader.deltaIndicator & VCD_INSTCOMP)626 {627 }628 else629 {630 instructionStream = new VCDStream(patchData, dataStream.offset + winHeader.dataLength);631 }632 if(winHeader.deltaIndicator & VCD_ADDRCOMP)633 {634 }635 else636 {637 copyAddrStream = new VCDStream(patchData, instructionStream.offset + winHeader.instrsLength);638 }639 var instructionStreamEndOffs = copyAddrStream.offset;640 var targetWindowOffs = 0; // offset within the current target window641 var copySourceU8 = null;642 if(winHeader.indicator & VCD_SOURCE)643 {644 copySourceU8 = sourceU8;645 }646 else if(winHeader.indicator & VCD_TARGET)647 {648 copySourceU8 = targetU8;649 }650 cache.reset();651 while(instructionStream.offset < instructionStreamEndOffs)652 {653 var codeTableIndex = instructionStream.readU8();654 var code = codeTable[codeTableIndex];655 for(var i = 0; i <= 1; i++)656 {657 var op = code[i].inst;658 if(op == VCD_NOOP)659 {660 continue;661 }662 var length = code[i].size || instructionStream.readnum();663 switch(op)664 {665 case VCD_ADD:666 dataStream.readBytes(targetU8, targetWindowPosition + targetWindowOffs, length);667 targetWindowOffs += length;668 break;669 case VCD_RUN:670 var runByte = dataStream.readU8();671 var offs = targetWindowPosition + targetWindowOffs;672 targetU8.fill(runByte, offs, offs + length);673 targetWindowOffs += length;674 break;675 case VCD_COPY:676 var addr = cache.decodeAddress(copyAddrStream, code[i].mode, winHeader.sourceSegmentLength + targetWindowOffs);677 var absAddr = 0;678 // source segment and target segment are treated as if they're concatenated679 if(addr >= winHeader.sourceSegmentLength)680 {681 absAddr = targetWindowPosition + (addr - winHeader.sourceSegmentLength);682 copySourceU8 = targetU8;683 }684 else685 {686 absAddr = winHeader.sourceSegmentPosition + addr;687 if(winHeader.indicator & VCD_SOURCE)688 {689 copySourceU8 = sourceU8;690 }691 }692 while(length--)693 {694 targetU8[targetWindowPosition + targetWindowOffs++] = copySourceU8[absAddr++];695 }696 break;697 }698 }699 progress.update((targetWindowPosition + targetWindowOffs) / targetSize);700 }701 if(winHeader.haveChecksum && !ignoreChecksums)702 {703 var testAdler32 = adler32(targetU8, targetWindowPosition, winHeader.targetWindowLength);704 if(winHeader.adler32 != testAdler32)705 {706 throw new Error(ERR_TARGET_CHECKSUM);707 }708 }709 patchStream.skip(winHeader.dataLength + winHeader.copysLength + winHeader.instrsLength);710 targetWindowPosition += winHeader.targetWindowLength;711 }712 delete codeTable713 delete cache714 delete header715 delete progress716 delete targetU8717 delete targetSize718 delete patchStream719 delete sourceU8720 return targetData;721}...
patch.spec.js
Source:patch.spec.js
1var streams = helper.requireSource('streams');2describe('streams.patch', function() {3 var patches;4 before(function(done) {5 helper.loadFixture('users', done);6 });7 describe('create patch for single user', function() {8 before(function(done) {9 var worker = function(user, callback) {10 callback(null, { $set: { associates: ['user_2'] } });11 };12 var patchStream = streams.patch(13 helper.db.collection('users'),14 { name: 'user_1' },15 worker);16 helper.readStream(patchStream, function(err, result) {17 patches = result;18 done(err);19 });20 });21 it('should only patch one user', function() {22 chai.expect(patches.length).to.equal(1);23 });24 it('should contain passed modifier', function() {25 chai.expect(patches[0]).to.have.property('modifier').to.deep.equal({ $set: { associates: ['user_2'] } });26 });27 it('should contain matched user document', function() {28 chai.expect(patches[0])29 .to.have.property('before')30 .to.contain.subset({31 name: 'user_1',32 associates: [],33 location: {34 city: 'Copenhagen',35 address: 'Wildersgade'36 }37 });38 });39 it('should contain passed query', function() {40 chai.expect(patches[0]).to.have.property('query').to.deep.equal({ name: 'user_1' });41 });42 it('should contain collection being a mongojs object', function() {43 chai.expect(patches[0]).to.have.property('collection').to.be.an('object');44 });45 it('should contain collection having users as name', function() {46 chai.expect(patches[0].collection.toString()).to.equal('users');47 });48 });49 describe('create patch for all users', function() {50 before(function(done) {51 var worker = function(user, callback) {52 callback(null, { $rename: { 'name': 'username' } });53 };54 var patchStream = streams.patch(helper.db.collection('users'), {}, worker);55 helper.readStream(patchStream, function(err, result) {56 patches = result;57 done(err);58 });59 });60 it('should patch three users', function() {61 chai.expect(patches.length).to.equal(3);62 });63 describe('patch for user_1', function() {64 var patch;65 before(function() {66 patch = patches.filter(function(p) {67 return (p.before && p.before.name === 'user_1');68 })[0];69 });70 it('should be defined', function() {71 chai.expect(patch).to.be.defined;72 });73 it('should contain passed modifier', function() {74 chai.expect(patch).to.have.property('modifier').to.deep.equal({ $rename: { 'name': 'username' } });75 });76 it('should contain matched user document', function() {77 chai.expect(patch).to.have.property('before').to.have.property('name', 'user_1');78 });79 it('should contain passed query', function() {80 chai.expect(patch).to.have.property('query').to.deep.equal({});81 });82 it('should contain collection being a mongojs object', function() {83 chai.expect(patch).to.have.property('collection').to.be.an('object');84 });85 });86 describe('patch for user_2', function() {87 var patch;88 before(function() {89 patch = patches.filter(function(p) {90 return (p.before && p.before.name === 'user_2');91 })[0];92 });93 it('should be defined', function() {94 chai.expect(patch).to.be.defined;95 });96 it('should contain passed modifier', function() {97 chai.expect(patch).to.have.property('modifier').to.deep.equal({ $rename: { 'name': 'username' } });98 });99 it('should contain matched user document', function() {100 chai.expect(patch).to.have.property('before').to.have.property('name', 'user_2');101 });102 it('should contain passed query', function() {103 chai.expect(patch).to.have.property('query').to.deep.equal({});104 });105 it('should contain collection being a mongojs object', function() {106 chai.expect(patch).to.have.property('collection').to.be.an('object');107 });108 });109 describe('patch for user_3', function() {110 var patch;111 before(function() {112 patch = patches.filter(function(p) {113 return (p.before && p.before.name === 'user_3');114 })[0];115 });116 it('should be defined', function() {117 chai.expect(patch).to.be.defined;118 });119 it('should contain passed modifier', function() {120 chai.expect(patch).to.have.property('modifier').to.deep.equal({ $rename: { 'name': 'username' } });121 });122 it('should contain matched user document', function() {123 chai.expect(patch).to.have.property('before').to.have.property('name', 'user_3');124 });125 it('should contain passed query', function() {126 chai.expect(patch).to.have.property('query').to.deep.equal({});127 });128 it('should contain collection being a mongojs object', function() {129 chai.expect(patch).to.have.property('collection').to.be.an('object');130 });131 });132 });133 describe('worker skipped documents', function() {134 before(function(done) {135 var worker = function(user, callback) {136 if (user.name === 'user_2') {137 return callback(null, { $set: { name: 'user_4' } });138 }139 callback();140 };141 var patchStream = streams.patch(helper.db.collection('users'), {}, worker);142 helper.readStream(patchStream, function(err, result) {143 patches = result;144 done(err);145 });146 });147 it('should only contain one user', function() {148 chai.expect(patches.length).to.be.equal(1);149 });150 it('should contain matched user document', function() {151 chai.expect(patches[0])152 .to.have.property('before')153 .to.contain.subset({154 name: 'user_2',155 associates: ['user_1', 'user_3'],156 location: {157 city: 'Aarhus',158 address: 'Niels Borhs Vej'159 }160 });161 });162 });163 describe('worker updates whole document', function() {164 before(function(done) {165 var worker = function(user, callback) {166 user.name = 'me';167 callback(null, user);168 };169 var patchStream = streams.patch(170 helper.db.collection('users'),171 { name: 'user_1' },172 worker);173 helper.readStream(patchStream, function(err, result) {174 patches = result;175 done(err);176 });177 });178 it('should only contain one user', function() {179 chai.expect(patches.length).to.be.equal(1);180 });181 it('should contain modified user as modifier', function() {182 chai.expect(patches[0])183 .to.have.property('modifier')184 .to.contain.subset({185 name: 'me',186 associates: [],187 location: {188 city: 'Copenhagen',189 address: 'Wildersgade'190 }191 });192 });193 it('should not have modified document', function() {194 chai.expect(patches[0])195 .to.have.property('before')196 .to.contain.subset({197 name: 'user_1',198 associates: [],199 location: {200 city: 'Copenhagen',201 address: 'Wildersgade'202 }203 });204 });205 });206 describe('worker performs async update', function() {207 before(function(done) {208 var worker = function(user, callback) {209 setTimeout(function() {210 callback(null, { $set: { location: { city: 'Esbjerg' } } });211 }, 10);212 };213 var patchStream = streams.patch(214 helper.db.collection('users'),215 { name: 'user_2' },216 worker);217 helper.readStream(patchStream, function(err, result) {218 patches = result;219 done(err);220 });221 });222 it('should only contain one user', function() {223 chai.expect(patches.length).to.equal(1);224 });225 it('should contain matched user document', function() {226 chai.expect(patches[0])227 .to.have.property('before')228 .to.contain.subset({229 name: 'user_2',230 associates: ['user_1', 'user_3'],231 location: {232 city: 'Aarhus',233 address: 'Niels Borhs Vej'234 }235 });236 });237 it('should contain passed modifier', function() {238 chai.expect(patches[0]).to.have.property('modifier').to.deep.equal({ $set: { location: { city: 'Esbjerg' } } });239 });240 });241 describe('worker calls with an error', function() {242 var err;243 before(function(done) {244 var worker = function(user, callback) {245 callback(new Error('User error'));246 };247 var patchStream = streams.patch(248 helper.db.collection('users'),249 { name: 'user_3' },250 worker);251 patchStream.on('error', function(result) {252 err = result;253 done();254 });255 });256 it('should emit an error', function() {257 chai.expect(err).to.be.defined;258 });259 it('should have patch data with user document', function() {260 chai.expect(err)261 .to.have.property('patch')262 .to.have.property('before').to.contain.subset({263 name: 'user_3',264 associates: ['user_2'],265 location: {266 city: 'Aarhus',267 address: 'Hovedgade'268 }269 });270 });271 });...
index.js
Source:index.js
1var extend = require('xtend')2module.exports = function (db, opts) {3 opts = opts || {}4 opts.separator = opts.separator || '\xff'5 opts.timestampField = opts.timestampField || 'ts'6 opts.keyField = opts.keyField || 'key'7 opts.patchField = opts.patchField || 'patch'8 opts.key = opts.key || function (meta, namespace, opts) {9 return [namespace, meta[opts.timestampField]].join(opts.separator)10 }11 return {12 addPatch: addPatch,13 add: addPatch,14 patchStream: patchStream,15 readStream: patchStream,16 createReadStream: patchStream17 }18 function addPatch (namespace, patch, meta, cb) {19 if (!cb) {20 cb = meta21 meta = {}22 }23 var meta = ts(meta, opts.timestampField)24 var key = opts.key(meta, namespace, opts)25 var props = {}26 props[opts.keyField] = key27 props[opts.patchField] = patch28 var value = extend(meta, props)29 db.put(key, value, function (err) {30 if (err) return cb(err)31 cb(null, value)32 })33 }34 function patchStream (namespace, start) {35 var range = {36 start: (start || namespace+opts.separator)+'\x00',37 end: namespace+opts.separator+'\xff'38 }39 return db.valueStream(range)40 }41}42function ts (meta, field) {43 var obj = {}44 obj[field] = new Date().toISOString()45 return extend(meta, obj)...
tty.js
Source:tty.js
...34 }35 // else pass through36 return isatty.call(tty, fd)37 }38 if (process.env.FORCE_STDIN_TTY === '1') patchStream(patched, 'stdin')39 if (process.env.FORCE_STDOUT_TTY === '1') patchStream(patched, 'stdout')40 if (process.env.FORCE_STDERR_TTY === '1') patchStream(patched, 'stderr')41 return42}43module.exports = {44 override,45 getWindowSize,...
xdelta3.js
Source:xdelta3.js
1module.exports = {2 DiffStream: DiffStream,3 PatchStream: PatchStream4};5var stream = require('stream');6var fs = require('fs');7var util = require('util');8var xdelta = require('./build/Release/node_xdelta3.node');9for (var aOpt in xdelta.constants)10 module.exports[aOpt] = xdelta.constants[aOpt];11function DiffStream(src, dst, opt) {12 stream.Readable.call(this, opt || {});13 this.diffObj = new xdelta.XdeltaDiff(src, dst, opt || {});14}15util.inherits(DiffStream, stream.Readable);16DiffStream.prototype._read = function(size) {17 var that = this;18 that.diffObj.diffChunked(size, function(err, data) {19 if (err)20 that.emit('error', err);21 else22 that.push(data);23 });24};25function PatchStream(src, dst, opt) {26 stream.Writable.call(this, opt || {});27 this.patchObj = new xdelta.XdeltaPatch(src, dst, opt || {});28 this.on('finish', function () { 29 var that = this;30 that.patchObj.patchChunked(function(err) {31 if (err)32 that.emit('error', err);33 else34 that.emit('close');35 }); 36 });37}38util.inherits(PatchStream, stream.Writable);39PatchStream.prototype._write = function (chunk, encoding, callback) {40 this.patchObj.patchChunked(chunk, callback);...
createpatch
Source:createpatch
1#! /usr/bin/env node2var fs = require('fs'),3 chalk = require('chalk'),4 diffutils = require('../diffutils'),5 diff = require('diff'),6 argv = require('yargs')7 .usage('Usage: $0 --file1 <path> --file2 <path> -o <path>')8 .option('file1', { demand: true, describe: 'Path to original file.' })9 .option('file2', { demand: true, describe: 'Path to updated file.' })10 .option('o', { alias: 'output', demand: true, describe: 'Path to write patch file.' })11 .argv;12var content1 = diffutils.getContents(argv.file1),13 content2 = diffutils.getContents(argv.file2),14 patch;15var hasDiff = diffutils.hasDiff(argv.file1, argv.file2);16if (hasDiff) {17 patch = diff.createTwoFilesPatch(18 argv.file1,19 argv.file2,20 content1,21 content222 );23}24var patchStream = fs.createWriteStream(argv.output);25patchStream.on('finish', function() {26 console.log(patch ? 'Differences found.\n' : 'No differences found.\n');27 console.log(chalk.green('Patch written to ' + argv.output + '.'));28 process.exit(0);29});30if (patch) {31 patchStream.write(patch);32}...
Using AI Code Generation
1describe('test', () => {2 it('test', () => {3 cy.fixture('test.png').then((image) => {4 Cypress.Blob.patchStream(image, (stream, next) => {5 next(stream)6 })7 })8 })9})10describe('test', () => {11 it('test', () => {12 cy.fixture('test.png').then((image) => {13 Cypress.Blob.patchStream(image, (stream, next) => {14 next(stream)15 })16 })17 })18})19describe('test', () => {20 it('test', () => {21 cy.fixture('test.png').then((image) => {22 Cypress.Blob.patchStream(image, (stream, next) => {23 next(stream)24 })25 })26 })27})28describe('test', () => {29 it('test', () => {30 cy.fixture('test.png').then((image) => {31 Cypress.Blob.patchStream(image, (stream, next) => {32 next(stream)33 })34 })35 })
Using AI Code Generation
1describe('My First Test', function() {2 it('Does not do much!', function() {3 cy.pause()4 cy.get('.network-btn').click()5 cy.get('.network-post').should('have.length', 1)6 cy.get('.network-post').then((response) => {7 console.log(response)8 cy.request({9 body: {
Using AI Code Generation
1import { patchStream } from 'cy-file-upload';2describe('Upload File', () => {3 it('upload file', () => {4 cy.get('input[type="file"]').then((subject) => {5 patchStream(subject);6 cy.fixture('test.txt', 'binary').then((fileContent) => {7 subject[0].files = [new File([fileContent], 'test.txt')];8 subject[0].dispatchEvent(new Event('change', { bubbles: true }));9 });10 });11 });12});
Using AI Code Generation
1describe('test', () => {2 it('test', () => {3 cy.get('input[type="text"]').type('hello');4 });5});6at Object.patchStream (cypress/plugins/index.js:4:40)7at Object.<anonymous> (cypress/integration/test.js:5:5)8at Object.invoke (node_modules/cypress/types/lodash/index.js:3279:23)9at Object.<anonymous> (node_modules/cypress/types/lodash/index.js:3013:27)10at Object.<anonymous> (node_modules/cypress/types/lodash/index.js:3013:27)11at Object.invoke (node_modules/cypress/types/lodash/index.js:3279:23)12at Object.<anonymous> (node_modules/cypress/types/lodash/index.js:3013:27)13at Object.<anonymous> (node_modules/cypress/types/lodash/index.js:3013:27)14at Object.invoke (node_modules/cypress/types/lodash/index.js:3279:23)15at Object.<anonymous> (node_modules/cypress/types/lodash/index.js:3013:27)16at Object.patchStream (cypress/plugins/index.js:4:40)17at Object.<anonymous> (cypress/integration/test.js:5:5)18at Object.invoke (node_modules/cypress/types/lodash/index.js:3279:23)19at Object.<anonymous> (node_modules/cypress/types/lodash/index.js:3013:27)20at Object.<anonymous> (node_modules
Using AI Code Generation
1cy.patchStream('/api/v1/streams/1', {2})3cy.patchStream('/api/v1/streams/1', {4})5cy.deleteStream('/api/v1/streams/1')6cy.deleteStream('/api/v1/streams/1')7cy.getStreamSubscriptions('/api/v1/streams/1/subscriptions')8cy.getStreamSubscriptions('/api/v1/streams/1/subscriptions')9cy.getStreamEvents('/api/v1/streams/1/events')10cy.getStreamEvents('/api/v1/streams/1/events')
Using AI Code Generation
1 headers: {2 }3}).as('request')4 headers: {5 },6}).as('request')7 headers: {8 },9}).as('request')10 headers: {11 },12}).as('request')13 headers: {14 },15}).as('request')16 headers: {17 },18}).as('request')19 headers: {20 },21}).as('
Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.
You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.
Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.
Get 100 minutes of automation test minutes FREE!!