"use strict";var t=require("crc-32");const e=Object.freeze({LE:827543618,BE:1112560433}),r=Object.freeze({SourceRead:0,TargetRead:1,SourceCopy:2,TargetCopy:3});function n(t){return{type:r.SourceRead,length:t}}function o(t){return{type:r.TargetRead,bytes:t,length:t.length}}function s(t,e){return{type:r.SourceCopy,offset:t,length:e}}function a(t,e){return{type:r.TargetCopy,offset:t,length:e}}function f(e){return t.buf(e)>>>0}function i(t,e){let r=0,n=1,o=0,s=e;for(;;){if(o=t.getUint8(s++),r+=(127&o)*n,128&o)return[r,s];n<<=7,r+=n}}function c(t,e){let r=t.getUint8(e);return ef&&(f=o,i=r)}return s(i-o,f)}function y(t,{word:e,outputOffset:r,targetRelativeOffset:n,targetWordTable:o}){let s=0,f=0;const i=o.getWordLocations(e);for(const e of i){let n=0,o=e,a=r;for(;as&&(s=n,f=e)}return a(f-n,s)}function p(...t){let e=t[0];for(let r=1,n=t.length;re.length&&(e=t[r]);return e}function d(t){let e=0,r=t;for(;;){if(e++,r>>=7,0===r)return e;r--}}function b(t,e,r){let n=r,o=e;for(;;){let e=127&n;if(n>>=7,0===n){t.setUint8(o++,128|e);break}t.setUint8(o++,e),n--}return o}function w(t,e,n){let o=b(t,e,(n.length-1<<2)+n.type);return n.type===r.TargetRead?n.bytes.forEach((e=>t.setUint8(o++,e))):n.type!==r.SourceCopy&&n.type!==r.TargetCopy||(o=b(t,o,(Math.abs(n.offset)<<1)+(n.offset<0?1:0))),o}exports.ActionType=r,exports.apply=function({sourceChecksum:t,targetSize:e,targetChecksum:n,actions:o},s){if(f(s)!==t)throw new Error("Source is not compatible with the patch, it does not have the expected checksum.");const a=new DataView(s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength)),i=new DataView(new ArrayBuffer(e));let c=0,u=0,g=0;for(const t of o)switch(t.type){case r.SourceRead:for(let e=0;e>2),3&t){case r.SourceRead:f=n(e);break;case r.TargetRead:{let t=new Array(e);for(let r=0;r>1),f=s(t,e)}break;case r.TargetCopy:{let t=0;[t,g]=i(c,g),t=(1&t?-1:1)*(t>>1),f=a(t,e)}}p.push(f)}if(d=c.getUint32(g+0,u),b=c.getUint32(g+4,u),w=c.getUint32(g+8,u),f(t.subarray(0,-4))!==w)throw new Error(`Patch is invalid, it does not have the expected checksum ${w}.`);return{instructions:{sourceSize:h,sourceChecksum:d,targetSize:l,targetChecksum:b,actions:p},checksum:w}},exports.serialize=function({sourceSize:t,sourceChecksum:n,targetSize:o,targetChecksum:s,actions:a}){const i=4+d(t)+d(o)+d(0)+a.reduce(((t,e)=>t+function(t){let e=d((t.length-1<<2)+t.type);return t.type===r.TargetRead?e+=t.length:t.type!==r.SourceCopy&&t.type!==r.TargetCopy||(e+=d((Math.abs(t.offset)<<1)+(t.offset<0?1:0))),e}(e)),0)+4+4+4,c=new DataView(new ArrayBuffer(i)),u=new Uint8Array(c.buffer);let g=0;c.setUint32(g,e.LE,!0),g=4,g=b(c,g,t),g=b(c,g,o),g=b(c,g,0);for(const t of a)g=w(c,g,t);c.setUint32(g,n,!0),c.setUint32(g+4,s,!0);const h=f(u.subarray(0,-4));return c.setUint32(g+8,h,!0),{buffer:u,checksum:h}};